text
stringlengths 8
267k
| meta
dict |
---|---|
Q: why should i use back_inserter in function generate_n? hi guys i will show three codes 1 and 2 makes same work but the third one doesnt work. I want to understand why doesnt work or why do work the other two ? (strrand function produces random string)
1.
int main(){
vector<string> svec(50);
randomize();
generate_n(svec.begin(), 20, strrand);
display(svec.begin(), svec.end());
return 0;
}
2.
int main() {
vector<string> svec;
randomize();
generate_n(back_inserter(svec), 20, strrand);
display(svec.begin(), svec.end());
return 0;
}
3.
int main(){
vector<string> svec;
randomize();
generate_n(svec.begin(), 20, strrand);
display(svec.begin(), svec.end());
return 0;
}
A: The third has undefined behavior. In the first, you specify the vector size where you define the vector. That means it starts as a vector of 50 default-initialized (empty) strings. You then overwrite those strings with your random strings.
In the second, you use a back_insert_iterator to add the strings to the vector individually.
In the third, you start with an empty vector, and you attempt to use the (invalid) iterator to its (nonexistent) beginning. You then write 20 strings starting at whatever spot in memory its (random) initial value happens to refer to. You have not, however, at any time actually inserted a string into the vector. A vector normally keeps a count of how many items it current contains; in your third case, that will start out 0, and remain 0 throughout. When you attempt to show the "contents", you should get nothing (though, since you've already had undefined behavior at that point, anything is possible -- especially if some of the data you wrote happened to overwrite part of the vector's internal data.
What you have is a marginally more subtle (but equally problematic) version of well known beginner mistakes like:
char *s;
strcpy(s, "This will give UB");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I get this to run. I keep on getting a cannot find symbol I saw this code on this stackoverflow question at Create Java console inside a GUI panel
Whenever I compile the code though I get an error saying it can't find the symbol TextAreaOutputStream. I really want to have this work. I would really appreciate an explanation for why I can't compile this.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class GUI{
public static void main( String [] args ) throws InterruptedException {
JFrame frame = new JFrame();
frame.add( new JLabel(" Outout" ), BorderLayout.NORTH );
JTextArea ta = new JTextArea();
TextAreaOutputStream taos = new TextAreaOutputStream( ta, 60 );
PrintStream ps = new PrintStream( taos );
System.setOut( ps );
System.setErr( ps );
frame.add( new JScrollPane( ta ) );
frame.pack();
frame.setVisible( true );
for( int i = 0 ; i < 100 ; i++ ) {
System.out.println( i );
Thread.sleep( 500 );
}
}
}
A: TextAreaOutputStream isn't a class included in the standard library. The code for it is in that other SO post you referenced. To use it, you'll have to copy/paste that code and compile it along with your class. You might be better off looking around for an existing library that does what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to reduce execution time? I have a facebook app where users can bet on a basketball game (guess the winner, the difference, the mvp and the top scorer).
I keep one table with the games, one with the IDs of the users and one with the bets.
If you guess the winner right, you get 1 point. If you guess the difference right, you get 5 points. If you guess the mvp right you get 3 points, and the same goes with the top scorer.
Now I have a file that makes a table with all the users and their points:
<table>
<tr>
<td></td>
<td>
Name
</td>
<td>
Points
</td>
</tr>
<?php
$selectusers = $db->query("SELECT * FROM `predictorusers`");
$c = 0;
while ($appuser = $db->fetchRows($selectusers))
{
try
{
$profile = $facebook->api('/'.$appuser['userid']);
} catch (FacebookApiException $e) {
continue;
}
$c++;
$points = 0;
$selectbets = $db->query("SELECT * FROM `predictor` WHERE `userid`='{$profile['id']}'");
while ($bet = $db->fetchRows($selectbets))
{
$selectgame = $db->query("SELECT * FROM `schedule` WHERE `id`='{$bet['gameid']}'");
$game = $db->fetchRows($selectgame);
if ($bet['winner'] == 1 && $game['homescore'] > $game['awayscore'])
{
$points = $points + 1;
if (($game['homescore'] - $game['awayscore']) == $bet['diff'])
$points = $points + 5;
}
elseif ($bet['winner'] == 2 && $game['awayscore'] > $game['homescore'])
{
$points = $points + 1;
if (($game['awayscore'] - $game['homescore']) == $bet['diff'])
$points = $points + 5;
}
$selectmvprkg = $db->query("SELECT MAX(`rkg`) FROM `boxscore` WHERE `game`='{$game['id']}'");
$mvprgk = $db->fetchRows($selectmvprkg);
$selectmvp = $db->query("SELECT * FROM `boxscore` WHERE `rkg`='{$mvprkg['rkg']}'");
while ($mvp = $db->countRows($selectmvp))
{
if ($mvp['player'] == $bet['mvp'])
$points = $points + 3;
}
$selecttopscorerpts = $db->query("SELECT MAX(`pts`) FROM `boxscore` WHERE `game`='{$game['id']}'");
$topscorerpts = $db->fetchRows($selecttopscorerpts);
$selecttopscorer = $db->query("SELECT * FROM `boxscore` WHERE `pts`='{$topscorerpts['pts']}'");
while ($topscorer = $db->fetchRows($selecttopscorer))
{
if ($topscorer['player'] == $bet['topscorer'])
$points = $points + 5;
}
}
?>
<tr>
<td>
<?php echo $c; ?>
</td>
<td>
<?php echo $profile['name']; ?>
</td>
<td>
<?php echo $points; ?>
</td>
</tr>
<?php
}
?>
</table>
The only problem, is that the script takes more than 30 seconds to be fully executed, so the server stops it's execution and sends an erro:
Fatal error: Maximum execution time of 30 seconds exceeded in * on line 37
Does anyone know how can I prevent this from happening?
Edit:
Take a look on this file that contains 0 api calls:
<table>
<tr>
<td></td>
<td>
Name
</td>
<td>
Points
</td>
</tr>
<?php
$selectusers = $db->query("SELECT * FROM `predictorusers`");
$c = 0;
while ($appuser = $db->fetchRows($selectusers))
{
$c++;
$points = 0;
$selectbets = $db->query("SELECT * FROM `predictor` WHERE `userid`='{$appuser['userid']}'");
while ($bet = $db->fetchRows($selectbets))
{
$selectgame = $db->query("SELECT * FROM `schedule` WHERE `id`='{$bet['gameid']}'");
$game = $db->fetchRows($selectgame);
if ($bet['winner'] == 1 && $game['homescore'] > $game['awayscore'])
{
$points = $points + 1;
if (($game['homescore'] - $game['awayscore']) == $bet['diff'])
$points = $points + 5;
}
elseif ($bet['winner'] == 2 && $game['awayscore'] > $game['homescore'])
{
$points = $points + 1;
if (($game['awayscore'] - $game['homescore']) == $bet['diff'])
$points = $points + 5;
}
$selectmvprkg = $db->query("SELECT MAX(`rkg`) FROM `boxscore` WHERE `game`='{$game['id']}'");
$mvprgk = $db->fetchRows($selectmvprkg);
$selectmvp = $db->query("SELECT * FROM `boxscore` WHERE `rkg`='{$mvprkg['rkg']}'");
while ($mvp = $db->countRows($selectmvp))
{
if ($mvp['player'] == $bet['mvp'])
$points = $points + 3;
}
$selecttopscorerpts = $db->query("SELECT MAX(`pts`) FROM `boxscore` WHERE `game`='{$game['id']}'");
$topscorerpts = $db->fetchRows($selecttopscorerpts);
$selecttopscorer = $db->query("SELECT * FROM `boxscore` WHERE `pts`='{$topscorerpts['pts']}'");
while ($topscorer = $db->fetchRows($selecttopscorer))
{
if ($topscorer['player'] == $bet['topscorer'])
$points = $points + 5;
}
}
?>
<tr>
<td>
<?php echo $c; ?>
</td>
<td>
<?php echo $app['userid']; ?>
</td>
<td>
<?php echo $points; ?>
</td>
</tr>
<?php
}
?>
</table>
The same thing happens.
A: I'd suggest caching the results of your API calls in some fashion, so that you don't have to make a call to the API for each user every single time the page loads.
You may also want to look into the Facebook API functions that allow you to request data for more than a single user at a time - making one API call for all of the users in your result set would be much faster than making individual API calls for each user.
Also in general, nesting queries in loops multiple levels deep is a bad idea - try to reduce the total number of queries you're running.
A: You have nested queries 3 deep. Nested queries in code is always a red flag (on rare occasions necessary). For every record in predictorusers you are querying records in predictor. Then for every query in predictor you are running queries against schedule and boxscore (3 times).
That's where your problem is, you have way too many queries running. You should be using JOINs and narrowing the data down to specific information. It seems like you are querying every piece of data you have. You can probably get it down to 1 query per user, or even just 1 query with a userid filter.
A: *
*Please dont use select * , instead use specific column names.
*Please avoid nested sql statements by using single fetch and save data in an array for traversing.
*Try using XDebug Profiler to figure out which part of script is taking more time to load.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Deleting list elements based on condition I have a list of lists: [word, good freq, bad freq, change_status]
list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0],['change', 1, 2, 2]]
I would like to delete from the list all elements which don't satisfy a condition.
So if change_status > 0.3 and bad_freq < 5 then I would like to delete that the elements corresponding to it.
So the list_1 would be modified as,
list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0]]
How do I selective do that?
A: list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0],['change', 1, 2, 2]]
list_1 = [item for item in list_1 if item[2] >= 5 or item[3] >= 0.3]
You can also use if not (item[2] < 5 and item[3] < 0.3) for the condition if you want.
A: Use the filter function with an appropriate function.
list_1 = filter(lambda x: x[3] <= 0.3 and x[2] < 5, list_1)
Demo:
In [1]: list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0],['change', 1, 2, 2]]
In [2]: filter(lambda x: x[3] <= 0.3 and x[2] < 5, list_1)
Out[2]: [['bad', 10, 0, 0.0]]
Note that good doesn't satisfy your condition (20 < 5 is false) even though you said so in your question!
If you have many elements you might want to use the equivalent function from itertools:
from itertools import ifilter
filtered = ifilter(lambda x: x[3] <= 0.3 and x[2] < 5, list_1)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "62"
} |
Q: Amazon Red Price On Amazon store there are many prices and I'm trying to get what is referred as Amazon Price that is in red and Large. When I try
$pxml = aws_signed_request("com", array("Operation"=>"ItemLookup","ItemId"=>$itemId,"ResponseGroup"=>"Large"), $public_key, $private_key);
$pxml->Items->Item->Offers->Offer->OfferListing->Price->FormattedPrice;
I get a price that's higher than the red price.
If I use
$pxml->Items->Item->OfferSummary->LowestNewPrice->FormattedPrice;
I get a price lower than the red price that shows up where is say xx new from $5.49 (for example). Does anybody know how to get this value?
Thanks,
A: Look for the red price here:
$pxml->Items->Item->Offers->Offer->OfferListing->Price->Amount;
A: I found out the answer. The prices weren't matching because the items are sold by 3rd party vendors. When the items are sold by Amazon the above outlined method worked fine. From what I gather you can't get the 3rd party price info through Amazon api.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Rewrite file extension BUT deny direct access to file I am looking for a way to hide the file extension via .htaccess and deny direct access. Let's consider the following:
http://www.xyz.zyx/index.php
gets converted to
http://www.xyz.zyx/index OR http://www.xyz.zyx/
All good till now. What I want to do next is block or redirect when the user tries a direct access. Example, if the user types in the URL bar the following (extension), block or redirect:
http://www.xyz.zyx/index.php
I checked the other answers from other questions, but non seemed to be exactly it.
Thanks in advance for helping a newbie like me.
A: Although one may question the usefulness of such a thing, it's feasible, so here's how to do it in a .htaccess using mod_rewrite:
RewriteEngine On
# Sets your index script
RewriteRule ^$ index.php [L]
# Condition prevents redirect loops (when script is not found)
RewriteCond %{ENV:REDIRECT_STATUS} !^$
RewriteCond %{REQUEST_FILENAME} !-f
# Stop here if the file is not found after a redirect
RewriteRule ^(.*)$ notfound.php [L]
# Condition prevents redirect loops (when script is found)
RewriteCond %{ENV:REDIRECT_STATUS} ^$
# Forbid access directly to PHP files
RewriteRule ^.*?\.php$ forbidden [F,L]
# Make sure the filename does not actually exist (images, etc.)
RewriteCond %{REQUEST_FILENAME} !-f
# Append the .php extension to the URI
RewriteRule ^(.*)$ $1.php [L]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Fluid MovieClip with mouse pan at AS3 In fact, all I want to have is getting this pan effect and to be able to add buttons inside fluidly resizing main MovieClip.
See this example: www.avmevsimifilm.com
Do you have a good idea to make something working like this?
Thanks
A: Parallax scrolling for the parallax effect
and the "fluid" pan effect is probably just:
smoothCoeficitent = 0.2;
x = x + (targetX-x)*smoothCoeficient;
where targetX would be some future position based on mouseX (say targetX = mouseX; or similar);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Are WebSockets not supported in Firefox I'm running Firefox 7 in Ubuntu 11.04, and I noticed socket.io was falling back from web sockets to xhr-polling, so I typed WebSocket in Firefox's console, and got
[00:48:21.224] ReferenceError: WebSocket is not defined
On Google Chrome 14 I got
WebSocket
function WebSocket() { [native code] }
According to this, WebSockets is partly supported since firefox 4 and fully supported since firefox 6.
Is it only different in firefox on linux ?
A: In Firefox 4/5, WebSockets support is present but disabled (activated via about:config). In Firefox 6, Mozilla enabled WebSockets by default but added the "Moz" prefix. Also, note that Firefox 6 uses the newer HyBi protocol and W3C API. Chrome added the HyBi protocol in Chrome 14 although Chrome has never used a prefix.
The protocol is effectively complete and the official first version is expected to be published in about 6 weeks (the wire format has not changed significantly in months). The API has also been quite stable for months and Chrome 14+ and Firefox 6+ basically have the same implementation of the API. For some reason Mozilla has chosen to be even more cautious than normal with WebSockets prefixing. Perhaps it is a reaction to Google not being careful enough about prefixing unstable APIs.
Unless you are interested in binary message support, specific error and close condition handling or sub-protocol selection, then the WebSockets API has been essentially the same since Chrome introduced it a couple of years ago. If you are implementing a WebSockets server then you will need to know about the various versions of the protocol which has seen significant changes in the past 2 years.
A: Try MozWebSocket instead.
https://developer.mozilla.org/en/WebSockets#AutoCompatibilityTable
A: Firefox 7 supports hybi-10 "straight out of the box." I've been running it against my Firefox 7 supports hybi-10 "straight out of the box." I've been running it against my websocket server. You can try my online demo with Firefox 7 and let me know if you have any problem. I've tested it from Ubuntu 11. I have that set up right now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Error initializer element is not constant I am having trouble with my code, and I can not solve ....
the code snippet where the error is reported:
static FILE *debugOut = stderr;
static FILE *infoOut = stdout;
The error that the gcc return is:
initializer element is not constant
A: try doing it in main for example:
static FILE *debugOut;
static FILE *infoOut;
main(){
debugOut = stderr;
infoOut = stdout;
}
A: The ANSI C standard does not demand that stderr/stdout have to be constant expressions.
Thus, depending on the used standard C library code like this
static FILE *debugOut = stderr;
compiles or yields the error message you have asked about.
For example, the GNU C library defines stderr/stdout/stdin as non-constant expressions.
You have basically two options to deal with this situation, i.e. to make such code portable.
Initialization from main
static FILE *debugOut = NULL;
static FILE *infoOut = NULL;
int main(int argc, char **argv)
{
debugOut = stderr;
infoOut = stdout;
// [..]
return 0;
}
Initialization from a constructor function
On many platforms you can declare a function as constructor, meaning that it is called on startup before main() is called. For example when using GCC you can implement it like this:
static FILE *debugOut = NULL;
static FILE *infoOut = NULL;
static void init_streams(void) __attribute__((constructor));
static void init_streams(void)
{
debugOut = stderr;
infoOut = stdout;
}
This constructor attribute syntax is not standardized, but since GCC is very widespread and other compilers strive for GCC compatibility this is actually quite portable.
In case you need to make this portable to other compilers that does not have a similar declaration feature you can guard this code with macros like __GNU_LIBRARY__ and/or __GNUC__.
A: From the C99 standard:
6.7.8 Initialization
Constraints
4 All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
Hence,
static FILE *debugOut = stderr;
static FILE *infoOut = stdout;
is not legal code if compiler does not think stderr and stdout are constant expressions.
This is what the standard has to say about stderr and stdout.
7.19 Input/output <stdio.h>
7.19.1 Introduction
...
stderr
stdin
stdout
which are expressions of type ‘‘pointer to FILE’’ that point to the FILE objects associated, respectively, with the standard error, input, and output streams.
Solution
The standard compliant way to deal with this is to initialize the variables to NULL and set their values in main.
static FILE *debugOut = NULL;
static FILE *infoOut = NULL;
int main()
{
debugOut = stderr;
infoOut = stdout;
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: jquery hover hides on child element
live example: http://jsbin.com/axaqoc/2
when i try to select the child select box, the dropDown menu hides away, thinking the mouse went away from parent element.
js code: (complete code: http://pastie.org/2624436)
$('.dropOption').hover(function(e) {
e.stopPropagation();
$(this).trigger('dropOption', 'show'); // show the parent element
return false;
},function(e) {
e.stopPropagation();
$(this).trigger('dropOption', 'hide'); // hide the parent on mouse out
return false;
});
how can i stop the bubbling on select drop down menu? (btw this works fine on chrome, but does not on any other browser.)
html code:
<ul><li id="repeat" class="dropOption active"><a href="#" class="dropLink active tips" data-tips-position="right center"><span class="icon repeat">Repeat Off</span></a>
<ul class="repeatOptions active">
<li><label>Repeat Each</label> <select class="repeatEach" name="repeatEach"><option value="ayah">Ayah</option><option value="page">Page</option><option value="surah">Surah</option><option value="Juz">Juz</option></select></li>
<li><label>Repeat Times</label> <select class="repeatTimes" name="repeatTimes"><option value="1">x1</option><option value="2">x2</option><option value="3">x3</option><option value="4">x4</option><option value="5">x5</option><option value="6">x6</option><option value="7">x7</option><option value="8">x8</option><option value="9">x9</option><option value="0">∞</option></select></li>
<li><label>Delay</label> <select class="repeatDelay" name="repeatDelay"><option value="0">0 sec</option><option value="1">1 sec</option><option value="2">2 sec</option><option value="3">3 sec</option><option value="4">4 sec</option><option value="5">5 sec</option><option value="5">5 sec</option><option value="6">6 sec</option><option value="7">7 sec</option><option value="8">8 sec</option><option value="9">9 sec</option><option value="ayah">Ayah Duration</option></select></li>
</ul>
</li>
</ul>
A: e.relatedTarget = null if mouse is over select box
$('.dropOption').hover(function(e) {
$(this).trigger('dropOption', 'show');
},function(e) {
if (e.relatedTarget != null) // drop down select box fix
$(this).trigger('dropOption', 'hide');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: passing this from constructor to other constructor yields undefined reference on linking I am trying to compile code with the following structure under codeblocks:
class a : public cppcms::application (has virtual members) {
public:
a() : b_inst(this) {}
...
b b_inst;
}
class b {
public:
b(a* ptr) : a_ptr(ptr) {}
private:
a* a_ptr;
...
}
I am trying to put this together with codeblocks/g++ and get the following error message (at the linking stage):
undefined reference to `vtable for b (In function b: ...)
I tried pulling of the same thing with a reference, same result. I tried to change a::b_inst to a pointer and creating an instance of b with new in the constructor (codepart), same result.
What is the right way to do this?
By the way, if I do not add the pointer passing on construction, the code works, so i think it is not resolved by the answer here
A:
undefined reference to `vtable for b (In function b: ...)
That means probably you haven't implemented all of b's virtual methods. gcc emits the vtable when the first one is defined AFAIK.
That means it has nothing to do with the implementation of your constructor.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Resizing the content of UIWebView? A noob here so it might take a while to understand what's the wrong, just follow along ..
the key purpose of my app is to download an xml file from rss feed then parse it and pass it as html file to a webview with this method: [webView loadHTMLString:aString baseURL:nil]
after the content took place in the webview it doesn't fit nice and neat instead there's some photos in the content that has a width larget than what it can be displayed at once without scrolling horizontally,as well as the attachments at the end of the webview you have to scroll a bit right or left to read the full name of it, it'd be nice if the content stretched so it can be seen without scrolling horizontally.
Notice that I adjusted webview property scalesPageToFit to be YES, but that scaled the content to very small size to the point that you can't read what it contains!
any solution around this?
A: You need to use a meta/viewport tag and se the content width. See documentation, here:
https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting specific things from a site in android So i'm working on a track and trace app.
And i need to pull information from this site:
http://www.postdanmark.dk/tracktrace/TrackTrace.do?i_stregkode=RA076673982CN
My problem is that i dont know how to pick this part:
*
*september 2011 09:47 Ankommet til DANMARK
*september 2011 07:17 Ankommet til omdeling 6710 Esbjerg V Posthus
*september 2011 11:57 Udleveret til privat
and only that part.
Here's my code that downloads the whole html page:
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://www.postdanmark.dk/tracktrace/TrackTrace.do?i_stregkode=RA076673982CN";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
e.printStackTrace();
}
I have looked at several links and i cant seem to find anything that shows how to get a certain part of a html site like the:
<tbody>
<tr>
<td valign="top">19. september 2011</td>
<td valign="top">09:47</td>
<td valign="top">Ankommet til DANMARK</td>
</tr>
<tr>
<td valign="top">20. september 2011</td>
<td valign="top">07:17</td>
<td valign="top">Ankommet til omdeling 6710 Esbjerg V Posthus</td>
</tr>
<tr>
<td valign="top">20. september 2011</td>
<td valign="top">11:57</td>
<td valign="top">Udleveret til privat</td>
</tr>
</tbody>
I need my parser to get that part, but i haven't found or understood how :(
Can any of you show me an example on how to do it? :-/
A: You need to parse the HTML and pull out the data you want using something like TagSoup/etc. (not sure if that works on Android). You could try to pull it out using regex, but...
RegEx match open tags except XHTML self-contained tags
A: try using the sax parser
http://developer.android.com/reference/javax/xml/parsers/SAXParser.html
you just give it an input stream to the site page and then you can select which tags to keep
here is an example:
http://about-android.blogspot.com/2010/02/sample-saxparser-in-android.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Memcached on NodeJS - node-memcached or node-memcache, which one is more stable? I need to implement a memory cache with Node, it looks like there are currently two packages available for doing this:
*
*node-memcached (https://github.com/3rd-Eden/node-memcached)
*node-memcache (https://github.com/vanillahsu/node-memcache)
Looking at both Github pages it looks like both projects are under active development with similar features.
Can anyone recommend one over the other? Does anyone know which one is more stable?
A: Since this is an old question/answer (2 years ago), and I got here by googling and then researching, I feel that I should tell readers that I definitely think 3rd-eden's memcached package is the one to go with. It seems to work fine, and based on the usage by others and recent updates, it is the clear winner. Almost 20K downloads for the month, 1300 just today, last update was made 21 hours ago. No other memcache package even comes close. https://npmjs.org/package/memcached
A: The best way I know of to see which modules are the most robust is to look at how many projects depend on them. You can find this on npmjs.org's search page. For example:
*
*memcache has 3 dependent projects
*memcached has 31 dependent projects
... and in the latter, I see connect-memcached, which would seem to lend some credibility there. Thus, I'd go with the latter barring any other input or recommenations.
A: At the moment of writing this, the project 3rd-Eden/node-memcached doesn't seem to be stable, according to github issue list. (e.g. see issue #46) Moreover I found it's code quite hard to read (and thus hard to update), so I wouldn't suggest using it in your projects.
The second project, elbart/node-memcache, seems to work fine , and I feel good about the way it's source code is written. So If I were to choose between only this two options, I would prefer using the elbart/node-memcache.
But as of now, both projects suffer from the problem of storing BLOBs. There's an opened issue for the 3rd-Eden/node-memcached project, and the elbart/node-memcache simply doesn't support the option. (it would be fair to add that there's a fork of the project that is said to add option of storing BLOBs, but I haven't tried it)
So if you need to store BLOBs (e.g. images) in memcached, I suggest using overclocked/mc module. I'm using it now in my project and have no problems with it. It has nice documentation, it's highly-customizable, but still easy-to-use. And at the moment it seems to be the only module that works fine with BLOBs storing and retrieving.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How do android "app lock" applications work? I've tried googling, and looking on stackoverflow as well, but I can't seem to find any satisfying answer as to how the "App lock" applications(eg: ZDBox, App Lock, etc..) work.
Is there a service that runs in the background continuously polling to see if the app is launched and tries to kill it? Or is there a way to intercept launch intents for new activities?
A: they are watching logcat output. whenever you start an activity, you can find specific logcat. like this,
I/ActivityManager( 585): Starting activity: Intent { action=android.intent.action...}
if this logcat printed by locked app, locker service starts password screen.
A: there is a service running in the background to read the activity stack. if find new activity, will start the passwordActivity
A: MORE MODERN ANSWER (Nov 2022):
This can be handled by the new app usage API
The system collects the usage data on a per-app basis, aggregating the data over daily, weekly, monthly, and yearly intervals. The maximum duration that the system keeps this data is as follows:
Daily data: 7 days
Weekly data: 4 weeks
Monthly data: 6 months
Yearly data: 2 years
For each app, the system records the following data:
The last time the app was used
The total length of time the app was in the foreground for that time interval (by > day, week, month, or year)
Timestamp capturing when a component (identified by a package and activity name) ?> moved to the foreground or background during a day
Timestamp capturing when a device configuration changed (such as when the device orientation changed because of rotation)
A background service can be used to constantly watch for updates to timestamps for specific apps regarding when they moved to the foreground with the API above.
note: It seems that starting from Android 5/6/7 and higher you cannot read info about other apps, including their status and logs. I believe this makes looking in logcat no longer work. If anyone can confirm this please comment below! Also, the getRunningTasks function to view active activities is now deprecated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: 404 errors with Codeigniter on nginx when accessing controller I'm using Codeigniter for my website, the root website works just fine which has a landing page, however I have a development section located /var/www/domain.com/www/dev/ which /var/www/domain.com/www/ is the root (landing page is stored there).
Now, when I go to domain.com/dev, my codeigniter website works fine, but when I load an controller, e.g. domain.com/index.php/search it gives me an 404 error.
In the error logs of domain.com it shows this:
2011/10/02 02:03:37 [error] 17042#0: *568 open() "/var/www/domain.com/www/dev/index.php/search" failed (20: Not a directory), client: xx.xx.xx.xx, server: domain.com, request: "GET /dev/$
Now I have no complete idea why it's doing this and how to resolve this issue. How can I stop this and also remove the "index.php" remove the URL because Codeigniter tutorials only contain apache's rewriterule which isn't valid on nginx.
A: I believe that codeigniter uses the front-controller pattern, which will redirect all requests to index.php using a rewrite rule.
As the rewrite rules are for apache and not nginx, the server is actually looking for a directory called search which lives under another directory called index.php and so on.
I don't have much experience when it comes to nginx, but I believe this blog post can help you come up with rewrite rules on nginx.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to detect that animation has ended on UITableView beginUpdates/endUpdates? I am inserting/deleting table cell using insertRowsAtIndexPaths/deleteRowsAtIndexPaths wrapped in beginUpdates/endUpdates. I am also using beginUpdates/endUpdates when adjusting rowHeight. All these operations are animated by default.
How can I detect that animation has ended when using beginUpdates/endUpdates?
A: If you're targeting iOS 11 and above, you should use UITableView.performBatchUpdates(_:completion:) instead:
tableView.performBatchUpdates({
// delete some cells
// insert some cells
}, completion: { finished in
// animation complete
})
A: A possible solution could be to inherit from the UITableView on which you call endUpdates and overwrite its setContentSizeMethod, since UITableView adjusts its content size to match the added or removed rows. This approach should also work for reloadData.
To ensure that a notification is sent only after endUpdates is called, one could also overwrite endUpdates and set a flag there.
// somewhere in header
@private BOOL endUpdatesWasCalled_;
-------------------
// in implementation file
- (void)endUpdates {
[super endUpdates];
endUpdatesWasCalled_ = YES;
}
- (void)setContentSize:(CGSize)contentSize {
[super setContentSize:contentSize];
if (endUpdatesWasCalled_) {
[self notifyEndUpdatesFinished];
endUpdatesWasCalled_ = NO;
}
}
A: You can enclose your operation(s) in UIView animation block like so:
- (void)tableView:(UITableView *)tableView performOperation:(void(^)())operation completion:(void(^)(BOOL finished))completion
{
[UIView animateWithDuration:0.0 animations:^{
[tableView beginUpdates];
if (operation)
operation();
[tableView endUpdates];
} completion:^(BOOL finished) {
if (completion)
completion(finished);
}];
}
Credits to https://stackoverflow.com/a/12905114/634940.
A: Swift Version
CATransaction.begin()
CATransaction.setCompletionBlock({
do.something()
})
tableView.beginUpdates()
tableView.endUpdates()
CATransaction.commit()
A: What about this?
[CATransaction begin];
[CATransaction setCompletionBlock:^{
// animation has finished
}];
[tableView beginUpdates];
// do some work
[tableView endUpdates];
[CATransaction commit];
This works because the tableView animations use CALayer animations internally. That is, they add the animations to any open CATransaction. If no open CATransaction exists (the normal case), then one is implicitly began, which is ended at the end of the current runloop. But if you begin one yourself, like is done here, then it will use that one.
A: Haven't found a good solution yet (short of subclassing UITableView). I've decided to use performSelector:withObject:afterDelay: for now. Not ideal, but gets the job done.
UPDATE: It looks like I can use scrollViewDidEndScrollingAnimation: for this purpose (this is specific to my implementation, see comment).
A: You can use tableView:willDisplayCell:forRowAtIndexPath: like:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"tableView willDisplay Cell");
cell.backgroundColor = [UIColor colorWithWhite:((indexPath.row % 2) ? 0.25 : 0) alpha:0.70];
}
But this will also get called when a cell that is already in the table moves from off the screen to on the screen so it may not be exactly what you are looking for. I just looked through all the UITableView and UIScrollView delegate methods and there doesnt appear to be anything to handle just after a cell is inserted animation.
Why not just call the method you want to be called when the animation ends after the endUpdates?
- (void)setDownloadedImage:(NSMutableDictionary *)d {
NSIndexPath *indexPath = (NSIndexPath *)[d objectForKey:@"IndexPath"];
[indexPathDelayed addObject:indexPath];
if (!([table isDragging] || [table isDecelerating])) {
[table beginUpdates];
[table insertRowsAtIndexPaths:indexPathDelayed withRowAnimation:UITableViewRowAnimationFade];
[table endUpdates];
// --> Call Method Here <--
loadingView.hidden = YES;
[indexPathDelayed removeAllObjects];
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "120"
} |
Q: Is there a open-source forum that I can integrate my current members database with? So what im trying to do is save myself coding a forum... I've got a members table already with their passwords, username etc etc... and I want a forum system that can possibly be linked with my members table.
So then they don't have to re-signup if they want to use the forum? Ive used PHPBB before but again, that doesn't allow me to link my members table & forum members table.
Site uses PHP/MySQL
Thanks :)
A: Vanilla Forums pioneered the Proxy Connect method for single sign on -
http://vanillaforums.org/docs/singlesignon
I think an SSO bridge is better than syncing/maintaining two separate user tables (one for the main site and one for the forum). If you can map the existing table to the new one you still might run into encryption problems when it comes to encoding or deciphering user passwords.
I've studied forums with SSO and with a separate log in. The perfectionist in me loves the clean bridge that SSO can provide. However, practically speaking, I've found that a forum's popularity hinges on (1) the number of unique visitors per day; (2) the freshness of the content; and (3) the quality of the content. In other words, SSO is way less of a factor than you might expect.
If you run a popular, high quality site, users will sign up even if it means jumping through an extra hoop to register. I know that seems counter intuitive but that's been my experience. My recommendation is to launch your forum without SSO --- and once you confirm that it will succeed and remain popular, then consider merging the user tables using Proxy Connect.
A: There is a community contributed code snippet which can be used to authenticate users against an external database: http://www.phpbb.com/community/viewtopic.php?t=1598865 (It is an abandoned thread, so not sure whether it will work)
You can also write own authentication plugins using PHPBB API: http://wiki.phpbb.com/Authentication_plugins
A: I don't think you'll be able to simply "plug" your current, bespoke user table into some existing forum.
Perhaps I'm misunderstanding the question, but it sounds like you're going to need to write some sort of script that transfers the information out of your database and into a new database in the format that the forum software understands.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: scala simple while loop error object JDWhileLoop
{
def main(args: Array[String])
{
var index:Int = 0
while( index<=10)
{
println("index="+index)
index= index+1
}
}
}
here is the error
JDWhileLoop.scala:3: error: only classes can have declared but
undefined members
def main(args: Array[String])
^
I got this simple code and try to make work,but is not ,I dont know why.please help me. thanks
A: That's formatting error. This should be fine:
object JDWhileLoop
{
def main(args: Array[String])
{
var index:Int = 0
while( index<=10) {
println("index="+index)
index= index+1
}
}
}
In your code def main(args: Array[String]) treated as an abstract method (without body) followed by some code block in object inner body definition.
Note that in scala the following braces style is preffered
def foo (args: Bar) {
//some work
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add and subtract 16 bit floating point half precision numbers? How do I add and subtract 16 bit floating point half precision numbers?
Say I need to add or subtract:
1 10000 0000000000
1 01111 1111100000
2’s complement form.
A: The OpenEXR library defines a half-precision floating point class. It's C++, but the code for casting between native IEEE754 float and half should be easy to adapt. see: Half/half.h as a start.
A: Assuming you are using a denormalized representation similar to that of IEEE single/double precision, just compute the sign = (-1)^S, the mantissa as 1.M if E != 0 and 0.M if E == 0, and the exponent = E - 2^(n-1), operate on these natural representations, and convert back to the 16-bit format.
sign1 = -1
mantissa1 = 1.0
exponent1 = 1
sign2 = -1
mantissa2 = 1.11111
exponent2 = 0
sum:
sign = -1
mantissa = 1.111111
exponent = 1
Representation: 1 10000 1111110000
Naturally, this assumes excess encoding of the exponent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Prevent firefox from resetting scroll position when overflow element changes I am trying to implement a modal popup like the way facebook does it for previewing photos. From what I've inspected, the body becomes overflow:hidden and the modal box becomes overflow-y:scroll.
However, I have a bug in my website for firefox where when I change the overflow element from auto to hidden, it resets the scroll position of the page. This does not happen in Chrome. Any workaround/fix for this? Thanks!
EDIT:
Thanks for your help. Please look at the jsfiddle http://jsfiddle.net/k3evQ/7/.
Greatly appreciate it!!!
A: Ended up scrapping the idea of changing the overflow to hidden. Thanks for all your help anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How does std::endl not use any brackets if it is a function? The question is pretty much in the title. According to C++ Reference, std::endl is actually a function. Looking at its declaration in <iostream>, this can be verified.
However, when you use std::endl, you don't use std::endl(). Instead, you use:
std::cout << "Foo" << std::endl;
In fact, if you use std::endl(), the compiler demands more parameters, as noted on the link above.
Would someone care to explain this? What is so special about std::endl? Can we implement functions that do not require any brackets when calling too?
A: std::endl is a function template declared (27.7.3.8):
template <class charT, class traits>
basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);
The reason that you can "stream" it to std::cout is that the basic_ostream class template has a member declared:
basic_ostream<charT,traits>& operator<<
( basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&) );
which is defined to have the effect of returning pf(*this) (27.7.3.6.3).
std::endl without parentheses refers to a set of overload functions - all possible specializations of the function template, but used in a context where a function pointer of one particular type is acceptable (i.e. as an argument to operator<<), the correct specialization can be unambiguously deduced.
A: std::endl is an object of some type (not really important) that is supplied as an argument to operator<<( std::ostream &, decltype(std::endl)).
EDIT
Reading the other question would lead me to think that endl is a function template and that we most likely select the ostream& operator<<(ostream&(*)(ostream&)) member function overload.
A: Though it's a function [template], standard stream manipulators are designed to be sent to streams as function pointers (or functor object references). Inserting the result of a function call won't give you anything but the value that results from that function call.
This means that you stream the functor itself (f), rather than the result of calling it (f()).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: diff on two program with same input? #!bin/sh
i=0;
while read inputline
do
array[$i]=$inputline;
i=`expr $i + 1`
done
j=i;
./a.out > test/temp;
while [$i -gt 0]
do
echo ${array[$i]}
i=`expr $i - 1`;
done
./test > test/temp1;
while [$j -gt 0]
do
echo ${array[$j]}
j=`expr $j - 1`;
done
diff test/temp1 test/temp
What's wrong with the above code? Essentially what it's meant to do is take some input from stdin and then provide the same input to two separate programs and then put their output into another file and then diff them. How come it doesn't work?
A: I see a few things that could be problems.
First, usually the path to sh is /bin/sh. I would expect the shebang line to be something like this:
#!/bin/sh
This may not be causing an error, however, if you're calling sh on the command line.
Second, the output from your while loops needs to be redirected to your executables:
{
while [ $i -lt $lines ]
do
echo ${array[$i]}
i=`expr $i + 1`;
done
} | ./a.out > test/temp;
Note: I tested this on Mac OS X and Linux, and sh is aliased to bash on both operating systems. I'm not entirely sure that this construct works in plain old sh.
Third, the indexing is off in your while loops: it should go from 0 to $i - 1 (or from $i - 1 to 0). As written in your example, it goes from $i to 1.
Finally, "test" is used as both your executable name and the output directory name. Here's what I ended up with:
#!/bin/sh
lines=0;
while read inputline
do
array[$lines]=$inputline;
lines=`expr $lines + 1`
done
i=0
{
while [ $i -lt $lines ]
do
echo ${array[$i]}
i=`expr $i + 1`;
done
} | ./a.out > test/temp;
i=0
{
while [ $i -lt $lines ]
do
echo ${array[$i]}
i=`expr $i + 1`;
done
} | ./b.out > test/temp1;
diff test/temp1 test/temp
Another way to do what you want would be to store your test input in a file and just use piping to feed the input to the programs. For example, if your input is stored in input.txt then you can do this:
cat input.txt | a.out > test/temp
cat input.txt | b.out > test/temp1
diff test/temp test/temp1
A: Another approach is to capture stdin like this:
#!/bin/sh
input=$(cat -)
printf "%s" "$input" | ./a.out > test/temp
printf "%s" "$input" | ./test > test/temp1
diff test/temp test/temp1
or, using bash process substitution and here-strings:
#!/bin/bash
input=$(cat -)
diff <(./a.out <<< "$input") <(./test <<< "$input")
A: What's wrong?
The semi-colons are not necessary, though they do no harm.
The initial input loop looks OK.
The assignment j=i is quite different from j=$i.
You run the program ./a.out without supplying it any input.
You then have a loop that was meant to echo the input. It provides the input backwards compared with the way it was read.
You repeat the program execution of ./test without supplying any input, followed by a repeat loop that was meant to echo the input, but this one fails because of the misassignment.
You then run diff on the two outputs produced from uncertain inputs.
You do not clean up the temporary files.
How to do it
This script is simple - except that it ensures that temporary files are cleaned up.
tmp=${TMPDIR:-/tmp}/tester.$$
trap "rm -f $tmp.?; exit 1" 0 1 2 3 13 15
cat - > $tmp.1
./a.out < $tmp.1 > $tmp.2
./test < $tmp.1 > $tmp.3
diff $tmp.2 $tmp.3
rm -f $tmp.?
trap 0
exit 0
The first step is to capture the input in a file $tmp.1. Then run the two test programs, capturing the output in files $tmp.2 and $tmp.3. Then take the difference of the two files.
The first trap line ensures that the temporary files are removed when the shell exits, or if it receives a signal from the set { HUP, INT, QUIT, PIPE, TERM }. The second trap line cancels the 'exit' trap, so that the script can exit successfully. (You can relay the exit status of diff to the calling program (shell) by capturing its exit status status=$? and then using exit $status.)
A: If all you want to do is supply the same stdin to two programs you might like to use process substitution together with tee. Assuming you can cat your input from a file (or just using the tee part, if you want it interactive-ish) you could use something like this:
cat input | tee >(./p1 > p1.out) >(./p2 > p2.out) && diff p1.out p2.out
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NUnit vs Manual Unit Testing Background
I have recently tried to develop a suite of tests for regression testing of a particular application. I have been using NUnit and have had no problems.
I ran into the issue of sending parameters to NUnit tests, for which no satisfactory answer seems to exist.
Question
Say I implement a simple unit tester that loads a class, runs the Startup, Test, and Teardown methods in order, catching exceptions and then unloads the assembly. What are the downsides of doing this versus using NUnit?
In this scenario, I can easily pass parameters to my test cases, or do any other crazy thing I might come up with. But my concern is what I lose from abandoning NUnit.
A: What do you lose? Your time.
If you're working for a customer or business, they are (presumably) paying you to solve business problems, not to write infrastructure code. Some infrastructure may be necessary in order to address the business needs. In this case it's clearly not. You're reinventing the wheel.
Don't fall into the Not Invented Here trap. Use NUnit. It supports parameterized tests. If NUnit doesn't meet your needs, investigate MbUnit or xUnit.net. Or look at SpecFlow, etc. for BDD-style. Or FitNesse for acceptance testing. And this is only a partial list!
If you're writing a test framework on your own for learning purposes, great! If not, you are wasting your time and/or your company's money.
Addressing the technical aspects
JUnit was originally created during a long airplane trip. Back then there weren't a lot of alternatives. Writing a testing framework is not a huge project. Writing a robust one that is full-featured and easy to use is more difficult. Writing test runners, IDE integration, CI integration, code coverage integration, etc. is significantly more difficult. And it's been done. Unless you're Ayende Rahien, don't do it!
In addition to the integration, you also lose any features of NUnit you don't implement (and there are a lot). I don't use all of these, but I do rely on many of them.
(Moved from my comments)
A: Two parts mainly independent parts in this question:
*
*What are the pros/cons of create our own implementation
*Why this use case does not reason even to play with the idea of create our own
implementation
1) Because this falls to the "reinvent of the wheel" all pros/cons are identical and more general than this question, and all that reasoning apply to this case.
*
*We do not utilize an existing stable implementation
*We probably underestimate the effort hours invested in the existing implementation
*We lose all the surrounding ecosystem what are built around and on the existing implementation
*We lose the common accumulated community knowledge
*Probably we will not achieve the required minimum quality expectations within acceptable timeframe
(in the 1990s I've met a guy who were writing his RDBMS because neither Oracle Database neither SQL Server 6.5 "was not capable" to do what he wanted to do... btw this was a pageable cursor)
2) To send parameters to NUnit tests is just like any other configuration/parameter setting task. You can read your config/parameters from the format your choice (say: XML, json, RDBMS) and do this both in setup, teardown and "test" methods.
You can create your
*
*a) completely custom implementation (I mean read your config in
setup, test and teardown)
*b) or you can rely on [TestCaseSource] or
some related attribute
*c) or extend NUnit
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Remove/change Internal styles sheet styles with JavaScript/jQuery I want to be able to remove/change the internal style sheets values through JavasScript. It has to be through JS because I cannot edit the html since I am using an application that does not allow me to, but I can use JS. How can I change the value for the background or remove it completely? Or is there another way to accomplish this?
<body>
<head>
<style type="text/css">
#company-header{background:#000 !important;}
</style>
</head>
<div id="company-header"></div>
</body>
A: If your just going to change small bits of css, using jQuery's css() is your best option, but it does not always recognize !important, for that you would probably need cssText, like this:
$('#id').css('cssText', 'height: 200px !important');
This replaces all the css, so everything needs to be defined in the new css rules that are added.
If you are changing a lot of css, or just want to make it easier for the next time, you could remove all inline css and add an external stylesheet instead.
To remove all inline styles you would do something like this:
$(document).removeAttr('style');
or for div's only
$('div').removeAttr('style');
Depending on how many styles there are, this could take som time to process.
Then to add a new stylesheet do:
(function() {
var myCSS = document.createElement('link');
myCSS.rel = 'stylesheet';
myCSS.type = 'text/css';
myCSS.src = '/styles/mystylesheet.css';
var place = document.getElementsByTagName('script')[0];
place.parentNode.insertBefore(myCSS, place);
})();
Edit:
function removeCSS() {
var badCSS = document.getElementsByTagName('style')[0];
$(badCSS).remove();
});
This will remove all the markup in the internal stylesheet, but since the styles are already loaded it will make absolutely no difference.
Internal styles will always override external styles, but for one exeption, if the external style is !important. If both the external and internal styles are !important, the internal style will be used.
Loading an external stylesheet dynamicly with javascript will only work if everything you are trying to override is set to !important in the external stylesheet, and not set to !important in the internal stylesheet.
Changing the styles directly in the DOM with jQuery's css() and using the cssText option to override the !important set in the internal stylesheet may be your only viable option if there is absolutely no way to alter the html file and remove the internal stylesheet.
A: EDIT: OK, now that we understand that this question is really just about how to override the !important style declaration when setting styles via javascript, this is a duplicate of this posting: Overriding !important style.
The two possible answers there are to set a whole style string on the object or to create a new stylesheet that refers to this object.
Previous answer before question was edited:
You can just set some style directly on the object if you want like this. This will override anything that comes from a style sheet so you don't have to mess with the style sheet.
$("#company-header").css("background-color", "#FFFFFF");
or
$("#company-header").css("background", "none");
A more extensible way of modifying the look of an object or groups of objects is to based the style settings on class names and then add/remove class names using jQuery. This has the effect of switching which style sheet rules apply to a given object without having to directly manipulate the style sheets themselves:
$("#company-header").removeClass("oldClass").addClass("newClass");
A: $(document).ready(function(){
$('style').remove();
});
This code will remove the all internal css from the site. I used this but style tag will be visible in the page source.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Form Action with Relative Path Not Working I am using PHP and MySql and running inside of VS.PHP. I have written the following:
<form action="../register.php" method="post">
<input type="button" value="Submit" id="submit" />
</form>
But when I click, nothing actually happens. Am I not allowed to use relative paths for actions?
A: You need to change
<input type="button" value="Submit" id="submit" />
to
<input type="submit" value="Submit" id="submit" />
The button input type is mostly used with javascript, but will not submit your form automatically.
EDIT:
Here is a reference on the input button tag
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Operator '^' cannot be applied to operands of type 'double' and 'double' I have this code:
private void t_Tick(object source, EventArgs e)
{
double anInteger;
anInteger = Convert.ToDouble(label1.Text);
anInteger = double.Parse(label1.Text);
double val1;
double val2;
double answer;
double previous_val;
previous_val = Convert.ToDouble(label1.Text);
previous_val = double.Parse(label1.Text);
val1 = anInteger;
val2 = ((((((previous_val ^ 1.001)) / 24) - ((previous_val / 24) / 60)) / 10));
answer = val1 + val2;
label1.Text = answer.ToString();
}
I am getting the error "Operator '^' cannot be applied to operands of type 'double' and 'double'" at the line:
val2 = ((((((previous_val ^ 1.001)) / 24) - ((previous_val / 24) / 60)) / 10));
Does anyone have any solutions?
A: ^ is bitwise operator XOR. It makes no sense on double type.
What was your intent?
A: If you are looking to raise a Value1 to the power of Value2
Use:
Math.Pow(Value1,Value2)
In your example:
Math.Pow(previous_val,1.001)
A: Math.Pow(previous_val, 1.001);
will solve your problem. this is the way how to use powers in .net
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Removing indent in PYDEV I am using pydev for python development. I am facing issue while removing indentation for a block of statement.
If I have to add indentation I used to press SHIFT + down arrow key until I reach the end of block of statements which I want to indent and then press the TAB key.This is how i used to add indent for a block of statements in one step.
The issue now I am facing is to remove indent in one step for a block of statement.For example I have a for loop and i have a block of statement with in that for loop. Now I dont want to have the for loop any more and want to remove the indent underlying the for loop statement block. At present I am going each line and press backspace to remove that indentation. Is there any easy way to do this for the entire statement block?
A: I don't know Pydev, but in most editors Shift+Tab will do the trick.
A: From pydev.org, their page:
Block indent (and dedent) Tab / Shift-Tab
Smart indent (and dedent) Enter / Backspace
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do you setup relationships with many foreign keys from the same table in PHP ActiveRecord? I am building a real estate related website that real estate agents and investors can use to track properties submitted in the system and keep track of who is owed what profits. I have the following tables that I am having trouble figuring out how to setup the relationships for in my models using PHP ActiveRecord:
properties
*
*id
*primary_profit_sharing
*secondary_profit_sharing
*commission
*referral_payment
users
*
*id
*name
*email
payments
*
*id
*type (commission, referral_payment, etc.)
*property_id
*user_id
What is the proper way to setup these relationships using PHP ActiveRecord? I would like to be able to access the user information for each payment by something like $property->commission and $property->referral_payment but I can't figure out how to setup the relationships in the models to allow that.
I currently have payments belonging to users and properties, and users/payments have many payments. All the information I was is returned in the query, but not in an accessible ways. I have $property->users but no way of getting the user information for a particular payment type.
The only way I can think of to accomplish what I'm looking for is to setup a table for each payment type, but that doesn't seem like the best way to do it.
A: In the payments table, instead of using property_id and user_id, maybe you should use fk_object as the foreign key and do your joins using that field. fk_object represents the id of the user or the id of the property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Wait for Swing to finish updating JProgressBar before continuing I have a JFrame with a CardLayout set as its layout manager. This has two JPanel subclasses in it. One is a panel, WordsLoadingPanel, which displays the text "Loading words..." and has a JProgressBar. The other has to actually load the words. This takes a while (about 10-14 seconds for 100 words; it's a pretty selective algorithm), so I want to assure the user that the program is still working. I made the loading algorithm in the panel fire a property change with firePropertyChange(String, int, int), and the WordsLoadingPanel is catching the change just fine - I know this because I added a listener for this event to perform a println, and it works. However, when I change the println to actually changing the JProgressBar's value, it doesn't do anything. I know I'm changing the value right, because if I set the value before the algorithm starts, it works, and it works on the last iteration of the loop. I'm guessing this is because my algorithm is eating the computing power and won't let JProgressBar update.
So, my question is: How do I make my algorithm wait for Swing (would this be the AWT Dispatching Thread?) to finish updating the progress bar before continuing? I've tried:
*
*Thread.yield in each iteration of the loop
*Thread.sleep(1000L) in each iteration of the loop, in a try/catch
*putting everything in the loop in a SwingUtilities.invokeLater(Runnable)
*putting only the CPU-intensive algorithm in a SwingUtilities.invokeLater(Runnable)
EDIT: To further support my hypothesis of the CPU-eating algorithm (sounds like a children's story…), when I set the JProgressBar to indeterminate, it only starts moving after the algorithm finishes.
Does anyone have any suggestions?
Thanks!
A: To do expensive operations in background, consider using the SwingWorker class. The documentation has examples on how to use it to do tasks that interact with the user interface in a separate thread, including progress display in JProgressBars.
If you have trouble understanding how the class works, consider:
*
*SwingWorker is a generic class that takes two parameters: T, and V
*The doInBackground method returns T and is executed in a separate thread.
*Since Swing may only be manipulated in the Event Dispatch Thread, you may not manipulate Swing in doInBackground.
*The process method takes a List<V> as a parameter and is called asynchronously on the Event Dispatch Thread.
*The publish method takes V... arguments and sends them for processing in the process method.
In conclusion:
*
*T is the type of the result of the computation, if any.
*V is the type of the data needed to manipulate the user interface.
*Your algorithm should run entirely in doInBackground.
*The user interface should be manipulated in the process method.
*Your algorithm should use publish to send data to the process method.
A: OK, I've solved it. For anyone who may have a similar problem, my solution was to change the method which begun the algorithm from executing it synchonously to asynchronously (with new Thread(Runnable).start). So, my code is now
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Thread(new Runnable () {
public void run () {
window.keyboardTrainingPanel.initialize();
}
}).start();
}
});
I hope this can help someone! However, if there is a better way to do this, feel free to notify me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: WebView - WebPage not available I (like many others) followed the webview tutorial, but I can't get pages to load. Everything comes up as 'Webpage not Available'
I have ensured that the emulator does have internet access, and just to rule out a problem with the emulator I tried installing it on my phone, which resulted in the same behavior.
I have read that the biggest issue is people not putting the INTERNET permission in my manifest file, which I have tried putting as a child of different elements in the manifest to no avail. Does anyone know why I can't get this to load?
Here is my code:
Manifest:
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidTestActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<uses-permission android:name="android.permission.INTERNET" />
</activity>
</application>
</manifest>
AndroidTestActivity
public class AndroidTestActivity extends Activity {
WebView webview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.google.com/m");
Intent intent = getIntent();
// To get the action of the intent use
System.out.println(intent.getAction());
// We current open a hard-coded URL
try {
webview.setWebViewClient(new AndroidTestClient());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private class AndroidTestClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
Thanks!
A: Your internet permission should be an immediate child of "manifest" - shouldn't be under "application".
e.g.
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mypackage.name"
android:installLocation="auto"
android:versionCode="3210" android:versionName="1.1.0">
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="6" android:targetSdkVersion="10"/>
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
<!-- activities go here -->
</application>
</manifest>
Hope this helps
-serkan
A: If you use VPN, it can lead to this error. I connected to VPN and started an emulator, then WebView showed an error:
I disconnected from the VPN, restarted the emulator, and web page loaded. Of course, I wrote <uses-permission android:name="android.permission.INTERNET" /> in AndroidManifest.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Java can't find the 'equal' method I tried to check if a property was equal to a string but I keep getting this error
Code:
if (prop.getProperty("quit").equal("true")) {
}
Error:
cannot find symbol
symbol: method equal(java.lang.String)
location: class java.lang.String
A: The method name is equals not equal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-8"
} |
Q: SDL Surface with a menu and status bar How can I add a menu, and a status toolbar to SDL? I can not find any reference to this online... I think it might be an SDL limitation?
If so, what portable library can I use which would allow me to add an SDL surface to it, and a status bar and menu?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python if statement doesn't work as expected I currently have the code:
fleechance = random.randrange(1,5)
print fleechance
if fleechance == 1 or 2:
print "You failed to run away!"
elif fleechance == 4 or 3:
print "You got away safely!"
fleechance is constantly printing as 3 or 4, but I continue to get the result "You failed to run away!" ,can anyone tell me why this is happening?
A: The expression fleechance == 1 or 2 is equivalent to (fleechance == 1) or (2). The number 2 is always considered “true”.
Try this:
if fleechance in (1, 2):
EDIT: In your situation (only 2 possibilities), the following will be even better:
if fleechance <= 2:
print "You failed to run away!"
else:
print "You got away safely!"
A: Try
if fleechance == 1 or fleechance == 2:
print "You failed to run away!"
elif fleechance == 4 or fleechance == 3:
print "You got away safely!"
Alternatively, if those are the only possibilites, you can do
if fleechance <= 2:
print "You failed to run away!"
else:
print "You got away safely!"
A: The if statement is working as designed, the problem is that order of operations is causing this code to do something other than that you want.
The easiest fix would be to say:
if fleechance == 1 or fleechance == 2:
print "You failed to run away!"
elif fleechance == 3 or fleechance == 4:
print "You got away safely!"
A: Because you're not asking whether fleechance is 1 or fleechance is 2; you're asking whether
*
*fleechance is 1, or
*2 is non-zero.
Of course, that second part of the condition is always true. Try
if fleechance == 1 or fleechance == 2:
...
A: The way you wrote your if statements is wrong.
You tell python to check if fleechance equals 1 is true or if 2 is true.
A non-zero integer always means true in a condition.
You should wrote :
fleechance = random.randrange(1,5)
print fleechance
if fleechance == 1 or fleechance == 2:
print "You failed to run away!"
elif fleechance == 4 or fleechance == 3:
print "You got away safely!"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Looking for a javascript solution to reorder divs I have some divs in the page that show different things of the same kind, for example offers, now offers have ending time, and also posted time, if the user wants to order by ending time, or posted time, they should be re ordered.
I'm looking for a javascript solution that could do that, any particular libraries under Ext JS , or JQuery would work
Here is how these divs look like
<div data-sortunit="1" data-sort1="40" data-sort2="156" data-sort3="1"
data-sort4="1317620220" class="item">
</div>
<div data-sortunit="2" data-sort1="30" data-sort2="116" data-sort3="5"
data-sort4="1317620220" class="item">
</div>
<div data-sortunit="3" data-sort1="10" data-sort2="157" data-sort3="2"
data-sort4="1317620220" class="item">
</div>
So I wanna be able to sort these divs based on data-sortN, N being an integer
A: Edit: OK, now that you've supplied some HTML, here's javascript code that will sort that specific HTML by the desired column number:
function sortByDataItem(containerID, dataNum) {
var values = [];
$("#" + containerID + " .item").each(function(index) {
var item = {};
item.index = index;
item.obj = this;
item.value = $(this).data("sort" + dataNum);
values.push(item);
});
values.sort(function(a, b) {return(b.value - a.value);});
var container = $("#" + containerID);
for (var i = 0; i < values.length; i++) {
var self = $(values[i].obj);
self.detach();
container.prepend(self);
}
return;
}
$("#sort").click(function() {
var sortValue = $("#sortColumn").val();
if (sortValue) {
sortValue = parseInt(sortValue, 10);
if (sortValue && sortValue > 0 && sortValue <= 3) {
sortByDataItem("container", sortValue);
return;
}
}
$("#msg").show(1).delay(5000).fadeOut('slow');
});
You can see it work here in a jsFiddle: http://jsfiddle.net/jfriend00/JG32X/
Since you've given us no HTML to go on, I've made my own HTML and shown you how you can use jQuery to sort:
HTML:
<button id="sort">Sort</button><br>
<div id="productList">
<div class="row"><div class="productName">Popcorn</div><div class="price">$5.00</div></div>
<div class="row"><div class="productName">Peanuts</div><div class="price">$4.00</div></div>
<div class="row"><div class="productName">Cookie</div><div class="price">$3.00</div></div>
<div class="row"><div class="productName">Beer</div><div class="price">$5.50</div></div>
<div class="row"><div class="productName">Soda</div><div class="price">$4.50</div></div>
</div>
Javascript (run after page is loaded):
$("#sort").click(function() {
var prices = [];
// find all prices
$("#productList .price").each(function(index) {
var str = $(this).text();
var item = {};
var matches = str.match(/\d+\.\d+/);
if (matches && matches.length > 0) {
// parse price and add it to the prices array
item.price = parseFloat(matches[0]);
item.row = $(this).closest(".row").get(0);
item.index = index;
prices.push(item);
}
});
// now the prices array has all the prices in it
// sort it using a custom sort function
prices.sort(function(a, b) {
return(a.price - b.price);
});
// now pull each row out and put it at the beginning
// starting from the end of the prices list
var productList = $("#productList");
for (var i = prices.length - 1; i >= 0; i--) {
var self = $(prices[i].row);
self.detach();
productList.prepend(self);
}
});
And, a jsFiddle that shows it in action: http://jsfiddle.net/jfriend00/vRdrA/.
A: I made a tiny jqueryPlugin out of jfriend00's answer:
(function($){
$.fn.sortChildrenByDataKey = function(key, desc){
var i, els = this.children().sort(function(a, b) {return (desc?1:-1)*($(a).data(key) - $(b).data(key));});
for (i = 0; i < els.length; i++) {
this.prepend($(els[i]).detach());
}
return this;
};
})(jQuery);
Your HTML:
<div id="myContainer">
<div data-myKey="4"> ... </div>
<div data-myKey="2"> ... </div>
...
</div>
Usage:
$('div#myContainer').sortChildrenByDataKey('myKey', true_or_false);
The children of the container can be any Elements. Its only important, that they are immediate children and have data-X key.
Thank you, jfriend00!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How set cursor inside textbox after page load with jquery Alright i have a asp.net textbox and i want to set cursor inside textbox after page loaded like when you open google.
I only need set cursor inside textbox code.
I tried this but not working
$('txtSendTo').focus();
A: If txtSendTo is an id, you need a #
$('#txtSendTo').focus();
If txtSendTo is a class, you need a .
$('.txtSendTo').focus();
Or, if there is only one textbox on the page
$('textbox').focus();
Also make sure the page is fully loaded before you try to search the dom:
$(document).ready(function () {
`$('textbox').focus();`
});
A: I was not able to set cursor inside an input field when a link is clicked. However adding event.preventDefault() at the start of the function and returning false fixed it. Here is the code if someone is having the same issue
$("#search-button").click(function (event) {
event.preventDefault();
$("#textbox").focus();
return false;
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: JQuery hover addclass not working I am trying to use JQuery to change a picture inside of a nested li with an id of "logotest"
The classes I want applied are logotest1 and logotest2. Basically when the user hovers over the button, the picture is changed to a different one so the colors match. Here's a fiddle. Obviously the pictures aren't there, but maybe I am doing something wrong.
http://jsfiddle.net/b9XHe/
I don't have the classes logotest1 and 2 in the fiddle - can it not dynamically changed the background image of the li?
A: It's working because there is a :hover in the css that kicks in, and you should read up on correct css syntax.
Here is an example of changing classes with backgrounds : http://jsfiddle.net/b9XHe/28/
Another way to do it in jQuery is directly thru the .css() function, something like this:
$("#logotest").css("background", "url(/images/newBG.jpg)");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Submitting form data through a jQuery command I have an MVC project I'm working on, and am creating a set of different submit buttons, each which pass a different value to the controller on submission.
In my current code, I have the call to the submit function first create hidden input elements to pass the data I want, something like this:
$('#btnCreate').live('click', function () {
$('#formIndex').submit(function (event) {
$('#actions').append('<input type="hidden" name="objectId" value="' + $('input[name="objectList"]').val() + '" />');
$('#actions').append('<input type="hidden" name="choice" value="create" />');
});
});
I'm wondering if I can just pass the values of those hidden inputs as a set of parameters in the submit call, like you can do with the $.get, $.post, and $.ajax functions. I've experimented but haven't seemed to hit on the right formula yet.
Thanks for your help!
A: If you have to just submit data in the form to the backend, you can use
serialize() function of jquery.
Usage:
$('form').submit(function() {
var yourdata = $(this).serialize();
$.ajax({
type: "POST",
url: "check.php",
data: yourdata,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});
A: I think you are on the right track by adding hidden input parameters. I don't know of any other way to append data to your non-ajax form submit.
You might want to change a few things about your code though:
*
*Build your hidden inputs using jquery (as seen here on SO)
var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val("bla");
$('#form1').append($(input));
*For better performance, use delegate() instead of live(). The performance benefit really depends on how deep your DOM is. However, delegate supports chaining where live does not. (In jquery 1.7, all these problems go away with the on() method...):
$('body').delegate('#btnCreate', 'click', function () { ... });
Note that instead of using body as the container element, you could instead use something lower in the DOM which wraps your btnCreate element.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Massage model data before save in Django I'm not sure if this is the best way to do this, but I have some data that is being sent by a form. I have a ModelForm that takes the the request.POST of that form data. All the data that is being sent is a description, amount and deposit (boolean).
When the person submits the data, the amount will be a positive number, but I would like to store it in the database as a negative number if deposit is False.
I was thinking of doing this in either the Model or the ModelForm and sort of massage that amount before saving... So, somewhere in one of those classes, I'd like to have something like:
if not deposit:
amount = -amount
... and then save it as such.
Is there a way to handle this in the ModelForm or Model that would keep me from having to do all that logic inside of the view?
A: ModelForm's save() method is a good place for this:
class MyForm(models.ModelForm):
...
def save(self):
instance = super(MyForm, self).save(commit=False)
if not self.deposit:
self.amount = -self.amount
instance.save()
return instance
A: Overwrite model save method is a solution. But I prefear make this operations in clean method and mix it with business rules:
models.py:
from django.db import models
class Issue(models.Model):
....
def clean(self):
rules.Issue_clean(self)
from issues import rules
rules.connect()
rules.py:
from issues.models import Issue
def connect():
from django.db.models.signals import post_save, pre_save, pre_delete
#issues
pre_delete.connect(Issue_pre_delete, sender= Incidencia)
pre_save.connect(Issue_pre_save, sender = Incidencia )
post_save.connect(Issue_post_save, sender = Incidencia )
def Incidencia_clean( instance ):
#pre save:
if not instance.deposit:
instance.amount *= -1
#business rules:
errors = {}
#dia i hora sempre informats
if not instance.account.enoughCredit:
errors.append( 'No enough money.' )
if len( errors ) > 0:
raise ValidationError(errors)
def Issue_pre_save(sender, instance, **kwargs):
instance.clean()
At this way rules are binded to model and you don't need to write code on each form that this model appears (here, you can see this on more detail)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I tell IE to add the class 'Selected' to my LI on scroll? I was hoping to get a little help with my code. This works in moz/webkit but not in ie. I don't quite understand why :(
$(window).trigger('hashchange');
// Add .selected class to nav on page scroll
var $sections = $('section');
var $navs = $('nav > ul > li');
var topsArray = $sections.map(function() {
return $(this).position().top - 50;
}).get();
var len = topsArray.length;
var currentIndex = 0;
var getCurrent = function( top ) {
for( var i = 0; i < len; i++ ) {
if( top > topsArray[i] && topsArray[i+1] && top < topsArray[i+1] ) {
return i;
}
}
};
$(document).scroll(function(e) {
var scrollTop = $(this).scrollTop();
var secondSection = topsArray[1];
if(scrollTop <= 200) { // moved past the header
$navs.eq(0).removeClass("selected")
} else if(scrollTop >= 205 && scrollTop <= secondSection ) { // between header and 2nd section
$navs.eq(0).addClass("selected")
}
var checkIndex = getCurrent( scrollTop );
if( checkIndex !== currentIndex ) {
currentIndex = checkIndex;
$navs.eq( currentIndex ).addClass("selected").siblings(".selected").removeClass("selected");
}
});
A: IE is not very forgiving of javascript errors. Try adding some missing semicolons:
if(scrollTop <= 200) { // moved past the header
$navs.eq(0).removeClass("selected"); //missing semicolon
} else if(scrollTop >= 205 && scrollTop <= secondSection ) { // between header and 2nd section
$navs.eq(0).addClass("selected"); //missing semicolon
}
If it is IE only, then IE is having trouble parsing the js. Try running your js through a debugger like JsLint if you run into issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I get pianobarfly to compile correctly on OS X? I'm trying to get pianobarfly working on OS X and can't get it to compile correctly.
Selected text from the install document:
Dependencies
------------
gmake
libao http://www.xiph.org/ao/
libfaad2 http://www.audiocoding.com/downloads.html
AND/OR libmad http://www.underbit.com/products/mad/
pthreads
libid3tag http://www.underbit.com/products/mad/
UTF-8 console/locale!
Building
--------
If you have all of the dependencies listed above just type
make clean && make
NOTE: The above won't work on Mac OS X (Snow Leopard) since c99 targets i386
and cc (gcc4.2) targets x86_64. If you've built supporting libraries
(libao, etc.) using gcc, you'll be unable to link. You can work around
this issue by overriding CFLAGS[1]
make clean && make CFLAGS="-O2 -DNDEBUG -W64" && make DISABLE_FAAD=1
I think I have all the dependencies, except I'm not sure if I have pthreads or not, and I'm assuming my system default is UTF-8 console/locale!
I have used homebrew to install the dependencies I didn't have, like faad2 and libid3tag, but I haven't been to turn up anything on google about installing pthreads or how to tell if I have that already or not.
Anyhow, when I try to complile pianobarfly, this is what I get:
####:pianobarfly user$ make clean && make CFLAGS="-O2 -DNDEBUG -W64" && make DISABLE_FAAD=1
rm -f src/main.o src/player.o src/settings.o src/terminal.o src/ui_act.o src/ui.o\
src/ui_readline.o src/ui_dispatch.o src/fly.o src/fly_id3.o src/fly_mp4.o\
src/libpiano/crypt.o src/libpiano/piano.o src/libpiano/xml.o\
src/libwaitress/waitress.o src/libwaitress/waitress.o/test.o \
src/libezxml/ezxml.o src/libpiano/crypt.lo src/libpiano/piano.lo\
src/libpiano/xml.lo src/libwaitress/waitress.lo \
src/libezxml/ezxml.lo pianobarfly libpiano.so* libpiano.a waitress-test
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/main.o src/main.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/player.o src/player.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/settings.o src/settings.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/terminal.o src/terminal.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/ui_act.o src/ui_act.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/ui.o src/ui.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/ui_readline.o src/ui_readline.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/ui_dispatch.o src/ui_dispatch.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/fly.o src/fly.c
src/fly.c: In function ‘_BarFlyParseCoverArtURL’:
src/fly.c:733: warning: implicit declaration of function ‘strndup’
src/fly.c:734: warning: assignment makes pointer from integer without a cast
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/fly_id3.o src/fly_id3.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/fly_mp4.o src/fly_mp4.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/libpiano/crypt.o src/libpiano/crypt.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/libpiano/piano.o src/libpiano/piano.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/libpiano/xml.o src/libpiano/xml.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/libwaitress/waitress.o src/libwaitress/waitress.c
c99 -O2 -DNDEBUG -W64 -I src/libpiano -I src/libwaitress \
-I src/libezxml -DENABLE_FAAD \
-DENABLE_MAD -DENABLE_ID3TAG -c -o src/libezxml/ezxml.o src/libezxml/ezxml.c
c99 -O2 -DNDEBUG -W64 src/main.o src/player.o src/settings.o src/terminal.o src/ui_act.o\
src/ui.o src/ui_readline.o src/ui_dispatch.o src/fly.o src/fly_id3.o src/fly_mp4.o\
src/libpiano/crypt.o src/libpiano/piano.o src/libpiano/xml.o \
src/libwaitress/waitress.o src/libezxml/ezxml.o -lao -lpthread -lm \
-lfaad -lmad -lid3tag -o pianobarfly
Undefined symbols for architecture x86_64:
"_strndup", referenced from:
_BarFlyOpen in fly.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make: *** [pianobarfly] Error 1
####:pianobarfly user$
A: This has been resolved within the master and development branch of pianobarfly. Please be aware that there is an issue/patch available for homebrew which resolves a issue where pkg-config was not being generated for id3tag.pc. This patch has not (yet) been integrated into homebrew.
See: https://github.com/mxcl/homebrew/pull/7973
Also see: https://github.com/ghuntley/pianobarfly/issues/3
A: This is a portability bug in the program you are trying to build: it assumes that strndup() is available, and it isn't.
Fortunately, it's trivial to implement your own strndup replacement, given a description of what it does.
Or you may check fly.c: perhaps replacing strndup with strdup also works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to tell which Facebook Page my Page Tab App is installed on
Possible Duplicate:
How can I find out what Page has installed my Facebook Canvas App?
I have a facebook app and I have installed this app to a page tab through the graph api. It worked fine so far.
Once this app may be installed to a lot of pages, what do I need is, within my app, to be able to get the ID of the page whom is holding the app.
Is it possible?
A: it is passed as a part of a signed_request to your app, it is called "page":
A JSON object containing the page id string, the liked boolean if the
user has liked the page, the admin boolean if the user is an admin.
Only available if your app is an iframe loaded in a Page tab.
https://developers.facebook.com/docs/authentication/signed_request/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery onclick run I need to run all onclick events on page load.
how can I do something like this:
$('.upload').foreach(function(){
//execute onclick for found element (ex: test(this, 'var') )
});
<div class="upload" onclick="test(this, 'var')">text</div>
A: You can use the click() or trigger() methods to do that.
$('.upload').each(function(){
$(this).click();
});
A demo of it work.
A: I hate to give you a 'this will take some work' answer, but it is considered bad practice to use onclick events these days. Since you are already using jQuery, I would recommend using one of jQuery's event binding utilities to replace your onclicks.
.click(), .delegate(), .live() and .bind() will all be helpful in this.
However...
Also since you're using jQuery, you just need to fire .click() on them if you're really not interested in bringing your code up to current standards. ;-)
A: This should do the job:
$('.upload').each(function(){
$(this).click();
});
But there is probably a better solution to whatever you are trying to achieve.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ContentFlow javascript - reloading images after filtering I am using the following "Coverflow" javascript, ContentFlow
and have a filter function to search the Contentflow for image titles and filter them. I need the Contentflow to reload with the filtered images after the search function. I have the following code which works for filtering and reloading the "flow" but it reloads all the images, not the filtered images. Obviously, I don't have the right code to do this and I need a bit of help to get the filtered images loaded.
$("#filter").keyup(function(){
global.canChangeImage = true;
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
// Loop through the comment list
$("a.item").each(function(){
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
var contentFlow = new ContentFlow('contentFlow');
contentFlow._init();
count++;
}
});
// Update the count
var numberItems = count;
$("#filter-count").text(count+" Images Found");
});
Any help would be appreciated!
A: You may use an array to store all your images' info and then use ContentFlow's addItem() and rmItem() functions depending on the filter condition and the array.
With this approach you could reload the flow dynamically from the array items.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there any loss of functionality with streaming jobs in hbase/hadoop versus using java? Sorry in advance if this is a basic question. I'm reading a book on hbase and learing but most of the examples in the book(and well as online) tend to be using Java(I guess because hbase is native to java). There are a few python examples and I know I can access hbase with python(using thrift or other modules), but I'm wondering about additional functions?
For example, hbase has a 'coprocessors' function that pushs the data to where your doing your computing. Does this type work with python or other apps that are using streaming hadoop jobs? It seems with java, it can know what your doing and manage the data flow accordingly but how does this work with streaming? If it doesn't work, is there a way to get this type of functionality(via streaming without switching to another language)?
Maybe another way of asking this is..what can a non-java programmer do to get all the benefits of the features of hadoop when streaming?
Thanks in advance!
A: As far as I know, you are talking about 2(or more) totally different concepts.
"Hadoop Streaming" is there to stream data through your executable (independent from your choice of programming language). When using streaming there can't be any loss of functionality, since the functionality is basicly map/reduce the data you are getting from hadoop stream.
For hadoop part you can even use pig or hive big data query languages to get things done efficiently. With the newest versions of pig you can even write custom functions in python and use them inside your pig scripts.
Although there are tools to make you use the language you are comfortable with never forget that hadoop framework is mostly written in java. There could be times when you would need to write a specialized InputFormat; or a UDF inside pig, etc. Then a decent knowledge in java would come handy.
Your "Hbase coprocessors" example is kinda unrelated with streaming functionality of hadoop. Hbase coproccessors consists of 2 parts : server-side part, client-side part. I am pretty sure there would be some useful server-side coprocessors embedded inside hbase with release; but other than that you would need to write your own coprocessor (and bad news: its java). For client side I am sure you would be able to use them with your favorite programming language through thrift without too much problem.
So as an answer to your question: you can always dodge learning java; still using hadoop to it's potential (using 3rd party libraries/applications). But when shit hits the fan its better to understand the underlaying content; to be able to develop with java. Knowing java would give you a full control over hadoop/hbase enviroment.
Hope you would find this helpful.
A: Yes, you should get data local code execution with streaming. You do not push the data to where the program is, you push the program to where the data is. Streaming simply takes the local input data and runs it through stdin to your python program. Instead of each map running inside of a java task, it spins up and instance of your python program and just pumps the input through that.
If you really want to do fast processing you really should learn java though. Having to pipe everything through stdin and stout is a lot of overhead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Printing numbered nested lists on separate lines using enumerate in python I've come to some grief in trying to achieve the following though I suspect it has a simple fix that has temporarily leaked from my brain. I need to be able to to print a grid of variable dimensions that has numbers down the left-hand side like below
1 - + -
2 + - +
3 - + -
the grid is composed in nested lists, using enumerate with i+1 like below
for i, line in enumerate(grid):
return i+1, line
I can get those numbers on the left hand side however the output appears as lists which is untidy and not quite what I'm after, at the moment I'm printing the grid (with no numbers) using
def print_grid(grid):
for line in grid:
for char in line:
print char,
print
Is there something else that I ought to be using instead of enumerate to get those numbers along the side? Because the grid can be set up with variable parameters I was really hoping there would be a way of achieving this in printing it, rather than modifying the code I used to construct the grid which I'm desperate not to tamper with least it break? I've had a search around the internet and have found instances where people have had numbers appearing at the base of whatever picture they are drawing but not down the left hand side like that. No matter where I stick the enumerate statement in the print_grid function it messes up the output.
A: You can join each list into a single string:
for i, line in enumerate(grid, 1):
print i, ' '.join(line)
A: Are you looking for this?
for i, line in enumerate(grid):
print i,
for char in line:
print char,
print
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java Swing - set opacity for all children components? I've got some Swing components with children. When I setOpaque(false) on the parent, the children still have opacity.
So I hacked up this function (thanks SOF users):
Component[] comps = this.getComponents();
for(Component c : comps) { if(c instanceof JComponent) {
((JComponent)c).setOpaque(false); }
}
But now I'm plagued with self-doubt - this seems sort of clunky, is there a better way to do it?
A: You could add a ContainerListener to the panel and the set the opacity of the children as they are added.
However neither this solution or yours will handle nested panels.
There is no easy solution that I'm aware of.
A: Your way is OK. A little bit better is:
public void setOpaqueForAll(JComponent aComponent, boolean isOpaque) {
aComponent.setOpaque(isOpaque);
Component[] comps = aComponent.getComponents();
for (Component c : comps) {
if (c instanceof JComponent) {
setOpaqueForAll((JComponent) c, isOpaque);
}
}
}
But you need to call this method each time if your component tree changed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Alternative select box with jquery I'm trying to make the a selectable list like a select-box, so when you click on the li a, change the label for the selected li a.
First of all, this is possible?
Here is the code: http://jsfiddle.net/dcalixto/h8esW/10/
Thank's for any hint :)
A: Definitely possible using the text() method.
$(".genero-box li").click(function() {
$genero = $('.genero'); /* Get the <label> */
$genero.text($(this).text()); /* Set <label>'s text to clicked <li>'s text */
$genero.click(); /* Trigger a click on the label to close the selection */
});
Here's an update to your code.
A: This probably is what you're looking for:
$(".genero-box li").click(function(e) {
$("label.genero").text($(this).text());
$(".genero-box").fadeOut();
});
Check kthis jsFiddle - http://jsfiddle.net/FloydPink/tyHSx/1/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Zero width inline element moves justified text node contents I have a justified text node into which I want to insert an inline placeholder ( element if you like) whose only content is a "‍" that shouldn't have any width (and chrome inspector says as much too). I have noticed that when I insert this node inline into the text node, the whole line "jiggles" as if recalculating the layout, although this should not affect it.
I have also tested that if the text node I insert it into is left-aligned, this slight movement does not happen. Is this just inherent to the way the browser calculates text placement in a justified text element or could there be any workaround for this?
A: As I suspected, the issue, rather no issue, is due to the way "justify" works. First to confirm that "justify" text-align is causing this, check the jsffidle : http://jsfiddle.net/e7Ne2/29/
Both divs are same -> except that First div has text-align: justify and the other does not.
You will see that first div shows that behaviour but not second div.
This is because "justify" works this way (from wiki):
In justified text, the spaces between words, and, to a lesser extent, between glyphs or letters (kerning), are stretched or sometimes compressed in order to make the text align with both the left and right margins.
So, when we introduct a &zwb;, the text gets reorganized. This behaviour not consistent because not all characters are modified with &zwb;. So, when &zwb; alters the text, few letters "may be" stretched/compressed leading to the seemingly weird behaviour
A: The best I can find on it is that support for the zwj is not complete in all browsers. Your code is taking the inserted span tag and removing it with that .text() call, so it's unwrapping the zwj and causing display issues wherever it lands between letters.
I'm not sure what the end application is supposed to be, but using the jQuery .html() function would probably be better (you'll just need to check and make sure you're not writing inside of a tag), because the .text() function strips tags.
Reference:
http://api.jquery.com/text/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How can I ask ocamlopt to link against glibc 2.5? Is there a way to ask ocamlopt to link against glibc 2.5 such that I can run the resulting binary on machines that have only that that version of the library?
If this were possible, are there additional packages I would have to install on my machine? My machine does not have glibc 2.5. Is there a package for that?
Thanks in advance.
A: You can use the following ocamlopt flags to specify flags for compiling and linking:
-cc <comp> Use <comp> as the C compiler and linker
-cclib <opt> Pass option <opt> to the C linker
-ccopt <opt> Pass option <opt> to the C compiler and linker
As long as you know how to ask your C compiler to link in the way you want, you can use these flags to do it. In fact, I'd suggest solving the problem in this order. Get it working with a (trivial) C program first, then work with ocamlopt next.
Yes, you'll need to have the library installed for the linker to do its thing. In essence, you'll want your system to look like the target system (the one where you want your code to run). For suggestions on how to install the library on your system, I'd suggest asking in a forum dedicated to that system.
A: From my experience, it is better to get chroot or vm with glibc-2.5 based system and compile distributable binary there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Threaded programming - ties to asynchronous programming? Useful for web apps? Aside from AJAX, I don't know much about asynchronous programming, and certainly nothing about threads aside from the basic idea behind them. So, needless to say, I was a bit perplexed when I saw in a MSDN blog that the newest version of Visual Studio/C# will have asynchrony baked into the language itself.
So, as a beginner to the whole C#/MVC world, should I start learning about threads? Would they be useful to me? Are threads and asynchronous programming similar?
A: Threads are one of the OS features that enable asynchronous operation. You can program directly with threads, but the upcoming C# language features are at a higher level of abstraction and likely easier to deal with without causing concurrency bugs.
Concurrency is useful if you're either modelling a concurrent problem domain, or when you need to respond to requests (e.g. a user clicking a button) before the action the request initiates completes. A canonical example would be a file copy operation in a file manager - the copy takes a long time, but you need to tell the user about the progress of the operation, and the rest of the file manager needs to remain responsive. So, the file copy isn't processed synchronously with the user request - you finish responding to the drag-and-drop itself before the file copy completes, and finish the rest of it in a separate thread.
This is also what the "asynchronous" in AJAX means. If XHRs were synchronous, it would mean the HTTP request would have to return with data before the browser could process further user input, and the browser would "freeze".
In web development, an example would be generating a complex report over a database. Instead of having the report result page load for two minutes, you could generate the report in the background, and show a page with a list of report requests where the user can download the report once it's finished.
A: The first thing you should learn is that asynchrony and threading are two different things. Threading is about concurrency, not about asynchrony. More specifically: concurrency is a strategy for managing asynchrony.
We need to manage asynchrony because computer programs increasingly are manipulating high latency data sources. That is, the gap between when you need to get the information and when the information becomes available to the processor is large enough that the processor ought to be doing something else in that time. The source of that latency could be anything -- it could be that another thread is doing the work and the current thread is waiting. It could be that another computer in this cluster is doing the work, or it could be that you're waiting for a disk to spin or data to arrive over a network, or whatever. Latency is everywhere these days.
The typical way to deal with this is to synchronously wait for the information to become available; that is, block. What if you don't want to stall your processor waiting for the information? You need to wait asynchronously. That is, do something else while you're waiting.
Threads are one solution to this, but they're not a great solution. Neither blocking nor doing a lot of work on the UI thread is a good idea, and dealing with threading in general makes you have to reason globally about your program in order to avoid deadlocks. Another solution is to break up the work into tiny little pieces; as soon as one piece of work has to wait, you queue its continuation up, go do something else, and come back to it later, all on the same thread. The async work that will be done in the next version of C# uses a combination of various techniques to achieve better support for asynchrony without blocking the UI.
If this subject interests you, I have an article on it for beginners in October 2011's issue of MSDN magazine which you can read online here. My colleagues Mads and Stephen also have articles that go into more depth.
A: No... you don't need to learn multi-therading. If you're working with web applications (ASP.NET, MVC, etc) then you generally don't have to use multi-threading yourself, although your application may implicitly run in a multi-threaded environmet. Multi-therading is rarely (if ever) used in web applications, rather, it's used in desktop applications, services and libraries built (in this case) with C#.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: merging arrays and word frequency So I'm cycling through a document with 41 paragraphs. For each paragraph I'm trying to [1] first break the string into an array, and then get the word frequency of the paragraph. I then want to combine the data from all paragraphs and get the word frequency of the whole document.
I'm able to get array that gives me the "word" and its "frequency" for a given pargraph but I'm having trouble merging the results from each paragraph so as to get the "word frequency of the whole document. Here is what I have:
function sectionWordFrequency($sectionFS)
{
$section_frequency = array();
$filename = $sectionFS . ".xml";
$xmldoc = simplexml_load_file('../../editedtranscriptions/' . $filename);
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
$paraArray = $xmldoc->xpath("//tei:p");
foreach ($paraArray as $p)
{
$para_frequency = (array_count_values(str_word_count(strtolower($p), 1)));
$section_frequency[] = $para_frequency;
}
return array_merge($section_frequency);
}
/// now I call the function, sort it, and try to display it
$section_frequency = sectionWordFrequency($fs);
ksort($section_frequency);
foreach ($section_frequency as $word=>$frequency)
{
echo $word . ": " . $frequency . "</br>";
}
Right now the result I get is:
1: Array
2: Array
3: Array
4: Array
Any help is greatly appreciated.
A: Try to replace this line
$section_frequency[] = $para_frequency;
with this
$section_frequency = array_merge($section_frequency, $para_frequency);
and then
return $section_frequency
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sign out has to be clicked twice in asp.net In my master page I have the signout. When I click the sign out button the below code is executed
protected void singout_Click(object sender, EventArgs e)
{
Session.Abandon();
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
FormsAuthentication.SignOut();
Response.Redirect("Home.aspx");
}
}
and in the same master page my load is
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
Menu Items..
}
When I click the signout the menu disappears as I do it in the page load based on role, so it means the role permission is stored in session so it gets cleared but the page has to redirect to Home.aspx but it remains in the same page, I have to click the sign out again for the page to redirect to home.aspx. WHere am I going wrong
A: A logout operation can be facilitated solely by using FormsAuthentication without touching the cookie in your code, and without the if statement. Forms Authentication will automatically take care of the cookie state for you.
This will also solve the problem of double sign-out because you are redirecting the user away from the protected page the first time the sign-out button is clicked.
protected void singout_Click(object sender, EventArgs e)
{
Session.Abandon();
//Removes the forms-authentication ticket from the browser:
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
// ...or redirect the user to any place of choice outside the protected files.
}
A: Try the under mentioned code.
protected void singout_Click(object sender, EventArgs e)
{
Session.Abandon();
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
FormsAuthentication.SignOut();
}
Response.Redirect("Home.aspx");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Zend and google fusion table I have a fusion table containing postcodes.
I'm trying to access it using PHP.
After hours, I've managed to get something display (Select) using Zend.
I'm now able to display the body of the Http response.
But I can't find a way to do a 'foreach' for each postcode (I need to update another column for each postcode).
My code:
$data = $gdata->get($url);
$postcodes = $data->getRawBody();
foreach ($postcodes as $codes)
{
echo "postcode: ". $codes. "<br/>";
}
echo "<pre>";
var_dump($postcodes);
echo "</pre>\n";
So, the foreach returns an error:
Warning: Invalid argument supplied for foreach() in
And the dump:
string(147555) "name
AB10 1
AB10 6
AB10 7
AB11 5
AB11 6
AB11 7
AB11 8
AB11 9
AB12 3
A: Managed to solve it
$postcodes = $data->getRawBody();
$codes = split ( "\n", $postcodes);
foreach ($codes as $entry)
{
echo "postcode:" . $entry . "<br/>";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails can't see my controller Given:
Two controllers under /app/controllers named:
*
*customers_controller.rb (CustomersController)
*home_controller.rb (HomeController)
Problem:
When I run rails command (i.e. rails c) this is what I get:
ruby-1.9.2-p290 :001 > CustomersController
=> CustomersController
ruby-1.9.2-p290 :002 > HomeController
NameError: uninitialized constant HomeController
from /home/aaron/.rvm/gems/ruby-1.9.2-p290/gems/rake-0.8.7/lib/rake.rb:2503:in `const_missing'
from (irb):2
from /home/aaron/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.9/lib/rails/commands/console.rb:44:in `start'
from /home/aaron/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.9/lib/rails/commands/console.rb:8:in `start'
from /home/aaron/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.9/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
So whats the deal? Why isn't HomeController being recognized by my application?
Edit:
My home_controller.rb file:
class HomeController < ApplicationController
def index
end
def sign_up
end
def faq
end
def terms
end
def privacy
end
def feedback
end
end
Theres not much in it.
A: works for me with Rails 3.0.7 ... which version of Rails are you using?
There was a problem with old versions of Rake in the newer Rails versions, and I noticed that you're using a really old version of Rake..
Try to put this in your Gemfile:
gem 'rake' , '>= 0.9.1'
then do a "bundle update"
and try to do "rails c" again..
does it work for you afterwards?
See also:
Confused with rake error in Rails 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Whitespace detector returning errors I created a method to basically detect white space characters. I go through a string and check each character for white space. If it is a white space character, I return true, and if it's not, I return false. However, I get a compilation error, stating "missing return statement". As I already have two return statements "true" and "false", I can't see why there is an error. Can you help me out or point me in the right direction? Thanks in advance.
public boolean isWhitespace()
{
for (int i=0; i<string.length(); i++)
{
if (Character.isWhitespace(i))
{
return true;
}
else
{
return false;
}
}
}
A: Imagine if string.length() were 0. What would get returned?
Also, note that this doesn't do what you stated, which is to go through a string and check each character. It actually isn't checking anything about the string at all because of your use of i. If it were checking the string, it still would only check the first character of the string. If that character is whitespace, true is immediately returned, and if not, false is immediately returned.
A: You are looping over the length of the String, yet trying to return inside that loop. The logic doesn't make sense.
Think about the problem you are trying to solve - do you want to test if a character is a whitespace, or if an entire String contains at least one whitespace character? For the latter:
boolean hasWhite = false;
for(int i=0; i < string.length(); i++)
{
if(Character.isWhitespace(string.charAt(i)))
{
hasWhite = true;
break;
}
}
return hasWhite;
EDIT: A much simpler approach, if you're into that sorta thing ;-) -
return string.contains(" ");
A: Here is what your code should look like:
public boolean isWhitespace(String string) { // NOTE: Passing in string
if (string == null) { // NOTE: Null checking
return true; // You may consider null to be not whitespace - up to you
}
for (int i=0; i < string.length(); i++) {
if (!Character.isWhitespace(string.charAt(i))) { // NOTE: Checking char number i
return false; // NOTE: Return false at the first non-whitespace char found
}
}
return true; // NOTE: Final "default" return when no non-whitespace found
}
Note that this caters for the edge cases of a blank (zero-length) string and a null string
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use method in different context, instance_eval adds unwanted argument I'm trying to call a method of an object foo as if it was an method of object bar. I tried two approaches:
1. unbind and bind - fails because of different classes
class Foo
def initialize
@name = "John"
end
end
class Bar
def out
puts @name
end
end
foo = Foo.new
bar = Bar.new
m = bar.method :out
foo.instance_eval m.unbind.bind(foo)
2. instance_eval on proc made from method
This fails on the fact that instance_eval passes a reciever as an additional argument instead of the real reciever (afaik)
class Foo
def initialize
@name = "John"
end
end
class Bar
def out
puts @name
end
end
foo = Foo.new
bar = Bar.new
m = bar.method :out
proc = m.to_proc
foo.instance_eval &proc
It says: in `out': wrong number of arguments (1 for 0) (ArgumentError) in the stacktrace.
However when I use this instead of the last line it works fine:
foo.instance_eval {
puts @name
}
A: The problem is that #instance_eval sends to the block a parameter that is the object it self. So you can do it:
# ...
class Bar
def out(foo_object)
[@name, foo_object, self]
end
end
# ...
m = bar.method :out
foo.instance_eval &m # => ["John", #<Foo:0x1c11b10>, #<Bar:0x1bb2470>]
The argument is place where the method is called and self is from here the method is. I don't know how to call the method without parsing this extra argument.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java Swing Components - why deprecated HTML markup? I'm learning Java from a webdev background. I've been using some HTML inside Swing components, but a little part of me dies every time I see or write
<p color=red>Two<br>Lines</p>
So I can sleep at night, what's the reason for this poor, deprecated markup? And, if I use XHTML and inline styling, is my program at risk of being unsupported?
A: Swing supports only limited CSS without a third-party package; that's just the way it is :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Silverlight Grid Layout When I have Grid in Silverlight, and I provide Column Definitions like below
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
For some reason the items that get placed in those columns get cut off.
That is I only see half the control.
But when I do
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
and put items in those respected rows I can see the entire items with their proper respective widths and heights.
What could I be overlooking?
Thanks
A: <Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
is actually just a short cut for
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*"/>
<ColumnDefinition Width="0.5*"/>
</Grid.ColumnDefinitions>
which means, you have two columns in this Grid, each takes 50% of the width.
Same way,
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
is the same as
<Grid.RowDefinitions>
<RowDefinition Height="0.5*"/>
<RowDefinition Height="0.5*"/>
</Grid.RowDefinitions>
Hope this helps. :)
A: Look for following link. It should help you:
Using the Grid control in Silverlight
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multi-dimensional array to JSON java / android gson In my web service I'm making a query to a database, and I would like to return 2 columns of the database and put these columns in a 2d array.
Also I would like to convert the array to JSON and send it to the client. The client using gson parses the message from the server in a 2d array. Is it possible?
I have tried a lot but no luck till now. Thank you in advance.
The last version i've tried is this:
private static String[][] db_load_mes (String u){
ArrayList<String> array1 = new ArrayList<String>();
ArrayList<String> array2 = new ArrayList<String>();
JSONObject messages = new JSONObject();
Connection c = null;
try{
// Load the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c = DriverManager.getConnection("jdbc:odbc:dsn1","mymsg","mymsg");
Statement s = c.createStatement();
// SQL code:
ResultSet r;
r = s.executeQuery("select * from accounts ");
int i = 0, j = 0;
int k = 0;
String x,y;
while(r.next()) {
x = r.getString("username");
array1.add(x);
y = r.getString("password");
array2.add(y);
k = k + 1;
}
int count = array1.size();
String[][] row = new String[count][2];
Iterator<String> iter = array1.iterator();
while (iter.hasNext()) {
row[i][0]=iter.next();
i++;
}
Iterator<String> iter2 = array2.iterator();
while (iter2.hasNext()) {
row[j][1]=iter2.next();
j++;
}
for(int z=0;z<count;z++)
System.out.println(row[z][0] + "\t" + row[z][1] + "\n");
if (k == 0)
System.err.println("no accounts!");
c.close();
s.close();
}
catch(SQLException se)
{
System.err.println(se);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ...;
}
With the above code I can create the 2d array but how can I send this array to the client.
A: Here is how I made it using Gson from google...
Download gson from here
include it in your project.
package javaapplication1;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JavaApplication1 {
public static void main(String[] args) {
int rows = 3;
String records[][] = new String[][]{{"bob", "123-pass"},
{"erika", "abc123"},
{"richard", "123123123"}
};
Gson gson = new Gson();
String recordsSerialized = gson.toJson(records);
System.out.println(recordsSerialized);
/* prints this
[["bob","123-pass"],["erika","abc123"],["richard","123123123"]]
*/
// if you want a better output import com.google.gson.GsonBuilder;
Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
String recordsSerializedPretty = gsonPretty.toJson(records);
System.out.println(recordsSerializedPretty);
/* PRINTS IN different lines.. I can't paste it here */
// for retrieval
String retrievedArray[][] = gsonPretty.fromJson(recordsSerializedPretty, String[][].class);
for (int i = 0; i < retrievedArray.length; i++) {
for (int j = 0; j < retrievedArray[0].length; j++) {
System.out.print(retrievedArray[i][j]+" ");
}
System.out.println("");
}
// PRINTS THIS
/*
bob 123-pass
erika abc123
richard 123123123
*/
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Property binding in MVVM my cpde in ModelView :
public Boolean EnableTextBox { get; set; }
public CustomerAccountVM()
{
this.EnableTextBox = false;
//...
}
code in View:
XAML :
<TextBox Text="{Binding Path=IdCustomer, Mode=Default}" IsEnabled="{Binding Path=EnableTextBox,Mode=Default}" />
Why the code does not work?
no answer ?
A: You're not publishing the fact that the Enable property has been updated.
You need to implement the INotifyPropertyChanged interface and change your property to be:
private Boolean _enableTextBox;
public Boolean EnableTextBox
{
get { return _enableTextBox; }
set
{
_enableTextBox = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
You should wrap the PropertyChanged code in a method so you're not repeating yourself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I fix this FS00003 error? This is my code:
module RTX
open System
open System.Text.RegularExpressions
let input = "Line 1: Num allocs:3 New:2 Delete:1
Line 2: Num allocs:3 New:2 Delete:1
Line 3: Num allocs:3 New:2 Delete:1"
type AllocResult = { lineNo:string; numAllocs:string; news:string; frees:string }
let matches = Regex.Matches(input,@"Line (\d+): Num allocs:(\d+) New:(\d+) Delete:(\d+)",RegexOptions.Singleline)
let matchCollection = [ for m in matches do if m.Success then yield [for l in m.Groups -> l.Value]]
let allocCreator (e: string list) = { lineNo = e.[0]; numAllocs = e.[1]; news = e.[2]; frees = e.[3] }
let wfirst = List.map allocCreator List.map List.tail matchCollection
List.iter (fun e -> printfn "%s\n") wfirst
//List.iter (printfn "%s\n") matchCollection
Console.ReadLine()
The error I receive is: This value is not a function and cannot be applied (FS0003), and it appears at the List.map allocCreator part. Basically, I want to remove the string that matched from the Match, and keep only the captures in a record.
EDIT: I will try to explain a little more what I wanted to achieve.The Match result will be something like this:
[ "Line 1: Num allocs:3 New:2 Delete:1"; "1"; "3"; "2"; "1"; ]
By using
let matchCollection = [ for m in matches do if m.Success then yield [for l in m.Groups -> l.Value]] I was trying to get a list of lists ,something like this:
[["Line 1: Num allocs:3 New:2 Delete:1"; "1"; "3"; "2"; "1"; ];["Line 2: Num allocs:3 New:2 Delete:1";"2"; "3"; "2"; "1"; ]; ["Line 3: Num allocs:3 New:2 Delete:1";"3"; "3"; "2"; "1"]]
By using List.map List.tail matchCollection, I was trying to get from the above list, to this:
[["1"; "3"; "2"; "1"; ];["2"; "3"; "2"; "1"; ]; [;"3"; "3"; "2"; "1"]]
And by using List.map allocCreator I was trying to turn the above list into a list of records. I'm kinda new at F# and I probably my logic is wrong, but I don't understand why/where.
EDIT 2: It seems like a precedence issue. If I do this:
let wfirst = List.map allocCreator (List.map List.tail matchCollection);;
Then I get what I needed.
A: Not sure what you are trying to achieve with that line, but lets look at the types to try and figure it out
first
List.map allocCreater
this is already incorrect, the first argument to map needs to have type 'a -> 'b but you have given a list
List.map List.tail matchCollection
this is a string list list
I have no idea what you are actually trying to get at here, but you seem to be short a function or have too many lists
A: let wfirst = List.map allocCreator <| List.map List.tail matchCollection
List.iter (printfn "%A\n") wfirst
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Find zeros for solutions to differential equations in Mathematica Given the following code:
s := NDSolve[{x''[t] == -x[t], x[0] == 1, x'[0] == 1}, x, {t, 0, 5 }]
Plot[Evaluate[{x[t]} /. s], {t, 0, 3}]
This plots the solution to the differential equation. How would I numerically solve for a zero of x[t] where t ranges between 0 and 3?
A: The original question was answered by @rcollyer. I am answering the question you posted in your first comment to rcollyer's answer:
But what if instead our s is "s := NDSolve[{x'[t]^2 == -x[t]^3 - x[t] + 1, x[0] == 0.5}, x, {t, 0, 5}]" Then the FindRoot function just gives back an error while the plot shows that there is a zero around 0.6 or so.
So:
s = NDSolve[{x'[t]^2 == -x[t]^3 - x[t] + 1, x[0] == 0.5},
x, {t, 0, 1}, Method -> "StiffnessSwitching"];
Plot[Evaluate[{x[t]} /. s], {t, 0, 1}]
FindRoot[x[t] /. s[[1]], {t, 0, 1}]
{t -> 0.60527}
Edit
Answering rcollyer's comment, the "second line" comes from the squared derivative, as in:
s = NDSolve[{x'[t]^2 == Sin[t], x[0] == 0.5}, x[t], {t, 0, Pi}];
Plot[Evaluate[{x[t]} /. s], {t, 0, Pi}]
Coming from:
DSolve[{x'[t]^2 == Sin[t]}, x[t], t]
(*
{{x[t] -> C[1] - 2 EllipticE[1/2 (Pi/2 - t), 2]},
{x[t] -> C[1] + 2 EllipticE[1/2 (Pi/2 - t), 2]}}
*)
A: FindRoot works
In[1]:= FindRoot[x[t] /. s, {t, 0, 3}]
Out[1]:= {t -> 2.35619}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: "Don't ask again before sending requests to" checked or not I tried this using "Test user" and random friend , it seems "Test user" continue to appear even previous I cheched "Don't ask again before sending requests to Test user and rand user".
Is sending apprequests only available through fb.ui and no POST method (and if post method exist - example appreciated)
A: Facebook app requests are not available via POST, only the plugin. If the frictionless requests are not working, I would log a bug with Facebook.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding a new page to a website sorry if this question seems a bit open ended, but I'm often wanting to add new pages to my website. As my website grows, this means I'm having go back and add a link to the new page on all of my previous pages, which is becoming increasingly time consuming. Is there any way around this? An automatic method? Obviously in an ideal world you'd get the template page correct first, but this doesn't seem to allow for easy expansion. How do the big sites cope? Thanks.
A: You user server-side includes.
In PHP there are include() and require()
include('filename.php') will add the contents of 'filename.php' to the page it was included on. Require does the same thing, but the script stops if it can't locate or use the file.
Instead of doing:
<div id="navbar" >
<ul>
<li>Menu</li>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>
Put it in a file called "navbar.html" and just do:
<?PHP include('navbar.html'); ?>
In your include file you could have:
<div id="navbar" >
<ul>
<li id="1" class="<?PHP echo $m1class ?>">Menu</li>
<li id="2" class="<?PHP echo $m2class ?>">item</li>
<li id="3" class="<?PHP echo $m3class ?>">item</li>
<li id="4" class="<?PHP echo $m4class ?>">item</li>
</ul>
</div>
And then in the PHP file:
<?PHP
$m1class=$m2class=$m4class="notCurrent";
$m3class="current";
include('navbar.php');
?>
It would be the same as doing:
<?PHP
$m1class=$m2class=$m4class="notCurrent";
$m3class="current";
include('navbar.php');
?>
<div id="navbar" >
<ul>
<li id="1" class="<?PHP echo $m1class ?>">Menu</li>
<li id="2" class="<?PHP echo $m2class ?>">item</li>
<li id="3" class="<?PHP echo $m3class ?>">item</li>
<li id="4" class="<?PHP echo $m4class ?>">item</li>
</ul>
</div>
...except that you can change the include file so that it changes every page. The output of either would be:
<div id="navbar">
<ul>
<li id="1" class="notCurrent">Menu</li>
<li id="2" class="notCurrent">item</li>
<li id="3" class="current">item</li>
<li id="4" class="notCurrent">item</li>
</ul>
</div>
Goodluck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: asp.net mvc 3 view for ef4 join how can i display a join from a entity framework model and then show it in an asp.net mvc 3 view?
The join is then based on more than 1 model?
A: Create a custom view model that will hold the contents of your EF join.
A: you can have a view model with all the properties you want in the presentation level. It will include all the properties from all the related models. In entity framework side you can have several options.
You can have views, can map several tables for one entity, You need to give more information to give some idea about the best method. Need to know about the relationships you have in your models in EF which you are going to join.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Web player not playing files with non-ASCII characters Our app allows users to upload video.
I noticed, as soon as someone uploads a video with "é" in the file name, the video doesn't play.
For example "fooébar.flv". Question is. Should I be saving file names with those characters or should I filter out those chars? Otherwise, should I find a way for my player to play file names with non-ASCII characters?
I am using JWPlayer, to play the media on our site by the way.
EDIT
I followed http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/16002/embedding-with-international-characters which seems to work with:
encodeURIComponent(encodeURI("path_to_file"))
A: As per ops request in the comments:
I would let them save with non-ascii characters, you don't want to make it harder for your users to upload.
A: We solved it this way:
file_path = <%= "http://localhost/#{CGI.escape( URI.escape( 'File name with extra charaters like & áéű' ) )}" %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Graph API - /apprequests seems to return an empty JSON array every time When I use
https://graph.facebook.com/(userid goes here)/apprequests?access_token=(user access_token goes here)
it returns an empty JSON array like so:
{
"data": [
]
}
Even though there ARE app requests.
These people were having the same problem, but didn't get their question answered either:
http://forum.developers.facebook.net/viewtopic.php?id=106693
http://forum.developers.facebook.net/viewtopic.php?id=88253
What am I doing wrong?
I tried POSTing and GETing requests with the Graph API Explorer, and THEY don't return an empty JSON array (however they only return the app requests POSTed by Graph API Explorer, not the requests for my app....I imagine this is to be expected however). Could this have something to do with my app being in sandbox mode? Does /apprequests work for anyone else's sandboxed app?
A: A few weeks back (around mid-september 2011), it was possible to get the requests with https://graph.facebook.com/me/apprequests?access_token={user_access_token}.
It does not seem possible today anymore. This call returns an empty data structure now.
Instead, calling https://graph.facebook.com/{user_id}/apprequests?access_token={app_access_token} does seem to work.
A: apprequests connection expect an app access token.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Dynamic CSS padding for Google +1 button I have several Google +1 buttons on my website and when a button is clicked a certain amount of times the plus one button on the page becomes wider and therefore moves out of its space given. How could I stop this from happening dynamically?
The CSS code for the button is as follows:
.news-plusone {
float: right;
margin: 2px -20px 0 10px;
}
The second parameter in the margin is the one that needs to change dynamically.
Example: http://www.nblackburn.me/index.php?section=news
The +1 button is included in this segment of HTML on my website (formatted here to remove scrolling):
<span class="news-plusone">
<g:plusone size="small" href="http://example.com/"></g:plusone>
</span>
A:
Publishers may not alter or obfuscate the +1 Button, and Publishers
may not associate the +1 Button with advertising content, such as
putting the +1 Button on or adjacent to an ad, or placing ads in
shared content, unless authorized to do so by Google. Publishers also
may not place in shared content any text, image, or other content that
violates the Google+ project's User Content and Conduct Policy.
+1 button policy
However if you were just changing the positioning of the button then possibly showing an example would help clarify your issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Backreference each character For the sake of simplicity & learning something new, please don't suggest using two separate replace functions. I know that's an option but I would rather also know how to do this (or if it's not possible).
'<test></test>'.replace(/<|>/g,'$&'.charCodeAt(0))
This is what I've got so far. This sample code is, as you can tell, for another piece of code to escape HTML entities while still using innerHTML (because I do intend to include a few HTML entities such as small images, so again please don't suggest textContent).
Since I'm trying to replace both < and >, the problem is converting each individual one to their respective character codes. Since regular expressions allow for this "OR" condition as well as backreferences to each one, I'm hoping there's a way to get the reference of each individual character as they're replaced. $& will return <><> (because they're replaced in that order), but I don't know how to get them as they're replaced and take their character codes for the HTML entities. The problem is, I don't know what to use in this case if anything.
If that explanation wasn't clear enough, I want it to be something like this (and this is obviously not going to work, it'll best convey what I mean):
Assuming x is the index of the character being replaced,
'<test></test>'.replace(/<|>/g,'$&'.charCodeAt(x))
Hopefully that makes more sense. So, is this actually possible in some way?
A: '<test></test>'.replace(/[<>]/g,function(a) {return '&#'+a.charCodeAt(0)+';';});
I've put the characters in a square-bracket-thing (don't know it's proper name). That way you can add whatever characters you want.
The above will return:
<test></test>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Updating Apple g++/gcc What is the difference between Apple gcc and GNU gcc? Is Apple gcc a superset of the standard one?
The g++ version information in my OSX shows:
$ g++ --version
i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)
Some of the latest features of C++11 are in gcc 4.3/4.4 as per this. Is there any newer version of Apple gcc I can upgrade to. if so, how can i do it? I have Xcode 4.1
A: Well, for the first part, Apple in this case is using the LLVM backend for g++ as the default g++. Apple also installs the wonderfully named clang and clang++ front-ends for LLVM. However, there is absolutely nothing stopping you from installing newer branches of GCC; MacPorts has packages for everything up to 4.6. If you look for "APPLE ONLY" in the gcc man page, you can see what won't be available outside of Apple branches.
A: Beside the already mentioned llvm-gcc and clang, there is also an Apple-supplied gcc-4.2 (without LLVM backend) at /usr/bin/gcc-4.2 in Xcode 4.1. But do not overwrite the Apple-supplied versions in /usr/bin. All three support a superset of features include multi-arch support and multi-abi support not found in the vanilla GNU distributions and many third-party packages depend on these features in OS X. If you install something via MacPorts or from source, it will be installed to a different path, like /opt/local/bin or /usr/local/bin. Use PATHs or environment variables to manage which compiler you use.
A: You can use macport to install newer versions. You can download it here. Once you have installed gcc with macport, you can use it with xcode by adding an user-defined setting to your build :
- Go to the build setting of your project
- Click on the add build setting button
- Choose user-defined setting
- Name it CC
- In the value field, put the path of the gcc version installed by macport.
A: One thing that definitely is present in the Apple GCC branch but not in GNU GCC is blocks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: CSS: #id .class VS .class performance. Which is better? I'd assume that this would be faster:
#dialog .videoContainer { width:100px; }
than:
.videoContainer { width:100px; }
Of course disregarding that .videoContainer in the first example would only be styled under the #dialog tag.
A: CSS selectors are matched from right to left.
Therefore, .videoContainer should be "faster" than #dialog .videoContainer because it misses out testing for #dialog.
However, this is all irrelevant at best - you'll never notice the difference. For normally sized pages, the amount of time we're talking about is so insignificant as to be nonexistent.
Here's a relevant answer by an expert that you should read: Why do browsers match CSS selectors from right to left?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Android & OpenId4Java Any special tricks/gotchas for building an OpenId app for Android using OpenId4Java? Haven't found info on others that have made this combo work.
I have a simple app that compiles fine in Eclipse & command line, but when I install the apk, I get a bunch of debug messages indicating there are codec classes with earlier definitions.
E.g.:
D/dalvikvm(11571): DexOpt: 'Lorg/apache/commons/codec/Decoder;' has an earlier definition; blocking out
NOTE: I'm using the xerces, guice, nekohtml, commons-codec that came with the openid4java-0.9.6.jar
These are followed by debug messages that those classes aren't being verified, and some info messages sprinkled about ambiguous other codec classes.
Starting the app gives another bunch of messages:
I/dalvikvm(11582): Failed resolving Lorg/apache/xerces/dom/NodeImpl; interface 1983 'Lorg/w3c/dom/events/EventTarget;'
W/dalvikvm(11582): Link of class 'Lorg/apache/xerces/dom/NodeImpl;' failed
The main activity comes up fine, but when I attempt to call consumerManager.discover with an id for yahoo or google, I get an IllegalArgumentException:
I/Discovery(11582): Starting discovery on URL identifier: https://www.google.com/accounts/o8/id
W/System.err(11582): java.lang.IllegalArgumentException: http://java.sun.com/xml/jaxp/properties/schemaLanguage
W/System.err(11582): at org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl.setAttribute(DocumentBuilderFactoryImpl.java:86)
W/System.err(11582): at org.openid4java.discovery.xrds.XrdsParserImpl.parseXmlInput(XrdsParserImpl.java:168)
W/System.err(11582): at org.openid4java.discovery.xrds.XrdsParserImpl.parseXrds(XrdsParserImpl.java:50)
W/System.err(11582): at org.openid4java.discovery.yadis.YadisResolver.retrieveXrdsDocument(YadisResolver.java:301)
W/System.err(11582): at org.openid4java.discovery.yadis.YadisResolver.discover(YadisResolver.java:256)
W/System.err(11582): at org.openid4java.discovery.yadis.YadisResolver.discover(YadisResolver.java:232)
W/System.err(11582): at org.openid4java.discovery.yadis.YadisResolver.discover(YadisResolver.java:166)
W/System.err(11582): at org.openid4java.discovery.Discovery.discover(Discovery.java:147)
W/System.err(11582): at org.openid4java.discovery.Discovery.discover(Discovery.java:129)
W/System.err(11582): at org.openid4java.consumer.ConsumerManager.discover(ConsumerManager.java:542)
Suggestions? Insights?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: php - which is faster call mysql connection + query OR call a data file? good evening,
i have a mysql table that contain the users data
and i use mysql_connect, mysql_query, mysql_fetch_array to fetch user data
this query should run on every page load and for thousands of users
so which is better and faster ? using mysql for every page load ?
OR cache all of the user data results in a file and include it ?
A: I think the right answer is mix. You should cache the most common query result and retry the other "on the fly"
A: If it is user data for logged in users, I would store their user info in the session rather than fetching it over and over again.
If it will be changing frequently and you are worried about database performance, a good option would be to cache the data using something like memcached to cache the data in memory. You could request the data from cache on each request, and if user information changes, simply update the cache and the next time it is fetched it will get the new data and there is no need to hit the database unless the cache entry doesn't exist.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: quickfix: how to convert FIX::Account to a c_string or other types I am using quickfixengine to build a FIX application. quickfix almost has no documentation, pretty much like a blackhole. I have a variable which is a FIX::Account type. I know it is a FIX string type, but how do I get the string out (to be a c-string). I tried something like this, it does not pass the compilation.
FIX::Account acct;
// populate acct somewhere else
printf(acct.c_str());
Compiler error is error: ‘class FIX::Account’ has no member named ‘c_str’
basically, I'd like to know how to get to know the constructor, interface of every FIX types? which files contain these?
thank you
A: I assume you're using the C++ API. In this case, all fields inherit from FIX::FieldBase which has a convenient getString() method (see here).
I agree that is not easy to understand at a glance the declarations of FIX fields. That's because all classes related to FIX messages are directly generated from the XML specifications of the FIX protocol.
A: getValue() method should be used for getting string fields.
printf(acct.getValue().c_str());
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Naming a relation in Doctrine 2 ORM? How can i set the name of the foreign key (edit: not the name of the attribute itself) for the many-to-one relation "region" using YAML?
SWA\TestBundle\Entity\Province:
type: entity
table: province
uniqueConstraints:
UNIQUE_PROVINCE_CODE:
columns: code
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
code:
type: integer
name:
type: string
length: 255
short_name:
type: string
length: 2
manyToOne:
region:
targetEntity: Region
inversedBy: provinces
A: Due to @JakubZalas answer, I had taken a look to the code in Github, and have seen that changing the framework code for doing what you want is really easy.
If you check the folder where AbstractPlatform class is, you'll see that there is a ForeignKeyConstraint class. In it you'll see it inherits from AbstractAsset.
Now AbstractAsset class has a _generateIdentifierName method. If you check this method in github you'll see that it has a commented part that does just what you want. You just uncomment this part, comment the actual active part, change the $prefix parameter to $postfix and you're done. The constraint name will be generated using the table and column names with a corresponding postfix.
The AbstractAsset.php file is the the this folder: Symfony/vendor/doctrine/dbal/lib/Doctrine/DBAL/Schema
I tried in my project ant it worked fine.
One final information: at least for my project the commented part I mention above is only in github, not in the file at my local machine.
A: Look at the getCreateConstraintSQL method in the AbstractPlatform class to see how the name of the foreign key is chosen (line 1088).
It is taken directly from the constraint name. Influencing constraint name will influence the foreign key name.
As a workaround you could drop the constraint and re-create it with a new name in a doctrine migration.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: std::vectors in classes I'm building a c++ program, and I need to store an indefinite (i.e., dynamic) number of images within a class. I also have an indefinite number of sprite objects which can display those images.
Right now I have something like this:
class Hud {
std::vector<Image> images;
std::vector<Sprite> sprites;
}
In order to avoid duplication of the images (thereby taking up excessive ram), I re-use them by putting a pointer to the image in the Sprite object.
Obviously, when an Image is added to the std::vector, these pointers are no longer any good. There's probably something wrong with my approach, but I'm not sure how to fix this. Rendering is being done in OpenGL. Any suggestions would be helpful.
How can I store a dynamic array of images that can be accessed by my sprite objects, and that will allow me to avoid duplicate images in memory (which can be extremely taxing for particle effects)? Alternate methods would be welcome, but I can't afford to spend more than a day or two rewriting my code.
Thanks.
A: You should be storing a list of shared_ptr, not a list of Image objects. That way, the list and Sprite classes can share ownership. Indeed, if you don't want the Sprite to actually own the image, they could store a weak_ptr instead of a shared_ptr. Though it's more likely that you would want the list itself to be a list of weak_ptr.
If you're not using a compiler with TR1 or C++11 support, then you can get these smart pointers from Boost.
Alternatively, you can use a std::list. That way, you can insert and remove from the list to your heart's content without invalidating pointers.
A: You can store pointers to the objects in your vectors, making sure to delete the objects before erasing them from the vector. Boost's shared pointer library might make this easier.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create an interval of times in PHP based on a start time? I'm wondering how given a start time, I can calculate a series of time spans in intervals and execute code during that time.
For example: I start at 3:30pm and have 4, 45 minute intervals that need to be calculated based on the start time. Then between 3:00pm and 3:45pm I want to be able to check if the current time is between that span and then execute a block of code if it is.
The gist: A company wants to give out 20 gift cards during a 3 hour span. They want to give out only 5 every 45 minutes.
Any thoughts would be appreciated.
A: As Walkerneo said, the best way to do this is to use a cron job on the server and maybe store the data for the gift cards in a MySQL that will be checked when the cron runs the php with the funcions...
The other (very bad way) to do this is keep a loop inside your php file to check if it's time to give out the gift cards, but this is a VERY VERY BAD idea because of the high CPU usage in the server...
If you want to give the the gift cards when the user opens a page or buys something, it's easy, just setup a table in MySQL with the time spans where the user can get the gift cards and then when we submits the form to buy or check it's PHP should go the table and check if you're in any of the time spans.
Hope it helps...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Boost requires compiled libraries like libboost_date_time for even basic things. How do I eliminate dependencies on building those libraries? I want a header-only BOOST.
Using boost::bind and boost::ptr_set, it seems unnecessary to depend on libboost_date_time and libboost_regex. But I get a linker error for those libraries when I build.
LINK : fatal error LNK1104: cannot open file 'libboost_date_time-vc90-mt-s-1_47.lib'
A: #define BOOST_DATE_TIME_NO_LIB in your compiler Makefile to exclude the datetime library. #define BOOST_REGEX_NO_LIB to exclude the regex library, for example.
A: Geenrally you can #define BOOST_ALL_NO_LIB to disable the auto-linking of the MSVC compiler you are using as documented (see Boost.Config). But of course you still have to compile and link the libraries you do use. Which if you are getting those errors it means that you are likely using the libraries.
A: You can use the bcp utility to copy the specific portions of Boost that you actually use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to get the content of a tag inside a label How can get the content of the b tag?
<label for="onde">
<b>qua qua text</b>
<textarea name="onde"></textarea>
</label>
I am trying this with no success:
$('textarea[name=onde]').prev().val();
A: $('label[for="onde"] b').text();
should do it
A: You were close:
$( 'textarea[name="onde"]' ).prev().text()
Live demo: http://jsfiddle.net/5Y3Q8/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: IntelliSense: cannot open source file "curl.h" in C++ I am unable to compile my C++ project.
IntelliSense: cannot open source file "curl.h" in C++
I tried adding that file to the "Header Files" folder in Solution Explorer: no change. I was unable to add it to the "Source Files" folder.
How can I fix this?
A: Under Visual Studio 2010/2012/2013
*
*Right click on your project
*select Properties
*Expand Configuration Properties
*Click on the VC++ Directories
*Add the path to your file, as well as $(ProjectDir), into the "Reference Directories" item
A: *
*Right click on your project
*select Properties
*Expand Configuration Properties
*Click on the VC++ Directories
*Add $(ProjectDir) into the "Reference Directories" item
A: If you've added the header file correctly, then sometimes intellisense can be corrupted and you will need to delete the .ncb file in you project. Once this is done, restart VS and see if this works. The .ncb file is the intellisense database file so if you delete this, VS will rebuild it.
A: *
*Under Visual Studio 2010/2012/2013
*Right click on your project select
*Properties Expand Configuration
*Properties Click on the VC++
*Directories Add the path to your file,as well as $(VCInstallDir)lib;, into the "Reference Directories" item
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Intersecting sets of custom variables in Google Analytics This question refers to both the iOS SDK and JS API for Google Analytics.
Let's say a mobile device opens my application or views my webpage, and I want to note certain things, for example, the device's model, firmware version, and application version. It sets these as custom variables with the visitor scope.
I know I can find out how many devices of one model there are, or how many devices on one firmware version there are, but can I determine how many devices are of a specific model and on a specific firmware version? Or how many devices are on a specific firmware version with a certain version of my application?
I know this should technically be possible (cookies in mobile web, and UDIDs on devices), but I have not seen this anywhere and would like to confirm that it is in fact possible, and before I commit to using Google Analytics for statistic collecting. Please note, I am not looking for any other solution that can do this, there are plenty, I am asking if Google Analytics can do it in its current state. I think Google Analytics would be cool, because in order to buy my application, users have to view a webpage that I host. I could then compare the webpage's statistics to the application's statistics and gain some sort of useful data, all in one place.
A: The feature to do this with is Advanced Segmentation.
Basically, you can create an advanced segment for the particular custom variable values you're interested in. ie, create a segment for visitors that match, say, customVariableSlot2 value = iPhone AND customVariableSlot3 value = 4. The resulting set of visits will be the intersection of visits those 2 custom variable values.
That's the best you can do with the interface, as far as I know.
If you'd like to create a better view of this data, you can utilize the Google Analytics Export API to model the data in the views you're interested in. You can fiddle with the Google Analytics Data Feed Query Explorer to try that with your Google Analytics data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: rake undefined method `[]' for nil:NilClass I just installed a Rails 3.1 app to my deployment server.
When I tried to run
sudo rake db:setup RAILS_ENV=“production”
I got an error message saying
rake aborted!
undefined method `[]' for nil:NilClass
With --trace it says:
** Invoke db:setup (first_time)
** Invoke db:create (first_time)
** Invoke db:load_config (first_time)
** Invoke rails_env (first_time)
** Execute rails_env
** Execute db:load_config
** Execute db:create
rake aborted!
undefined method '[]' for nil:NilClass
/usr/local/lib/ruby/gems/1.9.1/gems/activerecord-3.1.0/lib/active_record/railties/databases.rake:74:in 'rescue in create_database'
/usr/local/lib/ruby/gems/1.9.1/gems/activerecord-3.1.0/lib/active_record/railties/databases.rake:54:in 'create_database'
/usr/local/lib/ruby/gems/1.9.1/gems/activerecord-3.1.0/lib/active_record/railties/databases.rake:44:in 'block (2 levels) in <top (required)>'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:205:in 'call'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:205:in 'block in execute'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:200:in 'each'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:200:in 'execute'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:158:in 'block in invoke_with_call_chain'
/usr/local/lib/ruby/1.9.1/monitor.rb:201:in 'mon_synchronize'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:151:in 'invoke_with_call_chain'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:176:in 'block in invoke_prerequisites'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:174:in 'each'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:174:in 'invoke_prerequisites'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:157:in 'block in invoke_with_call_chain'
/usr/local/lib/ruby/1.9.1/monitor.rb:201:in 'mon_synchronize'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:151:in 'invoke_with_call_chain'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:144:in 'invoke'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:112:in 'invoke_task'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:90:in 'block (2 levels) in top_level'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:90:in 'each'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:90:in 'block in top_level'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:129:in 'standard_exception_handling'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:84:in 'top_level'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:62:in 'block in run'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:129:in 'standard_exception_handling'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:59:in 'run'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/bin/rake:32:in '<top (required)>'
/usr/local/bin/rake:19:in 'load'
/usr/local/bin/rake:19:in '<main>'
Tasks: TOP => db:setup => db:create
My database.yml says
production:
adapter: mysql2
encoding: utf8
reconnect: false
database: t_production
pool: 5
username: deploy
password: V
host: localhost
There is only 1 migration and it says this:
class CreateDeals < ActiveRecord::Migration
def change
create_table :deals do |t|
t.string :title
t.text :description
t.string :image_url
t.decimal :price, :precision => 8, :scale => 2
t.timestamps
end
end
end
What should I try to fix this? I'm not even sure where to begin.
A: You should fix your statement, the double quotes are wrong. They need to be regular " quotes. It probably tries to load a setting for the “production” environment, which obviously doesn't exist.
If you are using the correct quotes, make sure your identation is correct, the definition should look something like the following:
production:
adapter: mysql2
encoding: utf8
reconnect: false
database: t_production
pool: 5
username: deploy
password: V
host: localhost
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: load data local infile ERROR 2 file not found I've been ramming my face against this sql error for about 45 minutes, and I have a feeling it's going to be something silly.
I'm trying to load a .txt file into my database, which is on a server elsewhere. I'm using putty on windows 7.
The sql call I am using is the following:
LOAD DATA LOCAL INFILE "C:/Users/Sam/Desktop/students_data.txt" INTO TABLE students;
The response I get is ERROR 2 (HYOOO): File 'C:/Users/Sam/Desktop/students_data.txt' not found (Errcode:2)
If anyone could shed some light on this that'd be extravagant. I already tried switching the / to \ and using single quotes, etc., but nothing seems to work. The file path is copied by shift+clicking the actual file and pasting it.
A: I have found a solution. First delete the word LOCAL from the sql statement. Second - place your file into MySQL DATA folder usually - bin/mysql/msql5.5.8/data/and your DB with which you are working. It worked for me. You might want to check your MAX_FILE upload number in php.ini file if file is large.
A: Removing the word LOCAL seemed to work for me; try it out!
A: Try to type path as C:\\mydir\\myfile.csv i.e. use \\ instead of \
A: I had this problem too, then I read this:
The file name must be given as a literal string. On Windows, specify
backslashes in path names as forward slashes or doubled backslashes
(from http://dev.mysql.com/doc/refman/5.1/en/load-data.html)
I did use the LOCAL keyword, but escaped the file path like this: str_replace('\\','/',$file), then it worked like a charm!
A: Had this too and solved it by using cmd.exe and found that the filename was mistakenly in the form filename.txt.txt and fixed it.
A: just replace "\" by "/" as the path directory before the filename.txt in (""). it will be better if u just keep the file in mysql data folder and do the thing i mentioned above.it will definitely work.
A: Sorry my previous answer is wrong.
In my case, I connect to a proxy, not the real physical mysql instance, so of course it could not get my local file.
To solve this, figure out the true physical mysql instance IP, connect it directly. You need help from the DBA.
A: LOAD DATA LOCAL INFILE 'C:\\cygwin\\home\\jml58z\\e_npv\\Fn_awk2010.mysql' INTO TABLE mydata
with the double \ it worked
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Plugging a sortedArrayUsingSelector and/or initWithArray Memory Leak Between Classes I've been struggling to solve this memory leak for awhile now, so I'm hoping the community can provide some help. Memory Management is still an issue I'm working to understand (and yes I have the memory management guide).
According to the Instruments Leak tool, I'm leaking an NSArray as soon as I navigate backward (back button w/ Nav Controller) off of the pertinent screen. I'm show all the relevant code I can think of, below, and can share more if needed.
I know that I'm alloc/initing an array in the ordered array function. This is because, to the best of my understanding, sortedArrayUsingSelector returns only pointers to the old array, not a true copy, so if I want to keep the array, I need to copy the values.
The problem is then how do I pass this sorted array to a different class while still properly managing my ownership of it? I release it in the dealloc, and I release it if the function is going to assign a new value, etc. But tbh I don't know if I'm doing this correctly.
Like I said, I'm really struggling still to properly understand how to correctly juggle all the memory management stuff, so any help would be much appreciated.
.h file of the relevant model class
@interface InstalledDataTracker : NSObject {
...other code...
NSArray *orderedZonesArray;
...other code...
}
@property (nonatomic, retain) NSArray *orderedZonesArray;
.m file of the relevant model class
@synthesize orderedZonesArray;
...other code...
- (NSArray *)orderedZonesArray {
if (!orderedZonesArray || installedDataChangedSinceLastRead) {
if (orderedZonesArray) {
[orderedZonesArray release];
}
NSArray *unorderedZones = [NSArray arrayWithArray:[self.installedAreas allKeys]];
orderedZonesArray = [[NSArray alloc] initWithArray:[unorderedZones sortedArrayUsingSelector:@selector(localizedCompare:)]];
}
return orderedZonesArray;
}
- (void) dealloc {
...other code...
[orderedZonesArray release], orderedZonesArray = nil;
[super dealloc];
}
.h in View Controller
#import <UIKit/UIKit.h>
@class InstalledDataTracker;
@interface SBVC_LSC01_ZoneSelect : UIViewController <UITableViewDataSource, UITableViewDelegate> {
... other stuff...
InstalledDataTracker *_dataTracker;
}
@property (nonatomic, retain) InstalledDataTracker *dataTracker;
.m init in View Controller
@synthesize dataTracker = _dataTracker;
- (id)initWithPerson:(NSString *)person {
if (self = [super init]) {
...other stuff...
self.dataTracker = [[InstalledDataTracker alloc] init];
}
return self;
}
- (void)dealloc
{
...other stuff...
[self.dataTracker release];
[super dealloc];
}
Leaking Method in View Controller
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
AbbreviationLookup *lookup = [[AbbreviationLookup alloc] init];
NSString *abbreviatedZone = [self.dataTracker.orderedZonesArray objectAtIndex:[indexPath section]];
cell.textLabel.text = [lookup zoneForAbbreviation:abbreviatedZone];
[lookup release];
return cell;
}
Instruments Leak Trace:
0 libSystem.B.dylib calloc
1 libobjc.A.dylib class_createInstance
2 CoreFoundation __CFAllocateObject2
3 CoreFoundation +[__NSArrayI __new::]
4 CoreFoundation -[NSArray initWithArray:range:copyItems:]
5 CoreFoundation -[NSArray initWithArray:]
6 -[InstalledDataTracker orderedZonesArray]
7 -[SBVC_LSC01_ZoneSelect tableView:cellForRowAtIndexPath:]
Things I've tried
orderedZonesArray = [[[NSArray alloc] initWithArray:[unorderedZones sortedArrayUsingSelector:@selector(localizedCompare:)]] autorelease];
return [orderedZonesArray autorelease];
And a bunch of other stuff I can't remember. Many attempts I've made to properly "release" the ownership created by alloc/init result in some sort of crash/bad access in the view controller. This is contributing to my confusion over where to properly release the array...
Detailed replies very welcome. I still have a great deal to learn!
Thanks a bunch. (Also, I've had to change some class and methods names for project security, so if something doesn't seem to match please mention it and I'll recheck for a typo)
Edit:
@Daniel Hicks, when I remove the initWithArray copy of the sorted array, as follows:
orderedZonesArray = [unorderedZones sortedArrayUsingSelector:@selector(localizedCompare:)];
, I get an EXC_BAD_ACCESS crash when the class tries to access the array from within the View Controller didSelectRowAtIndexPath method (likely the next time the array is accessed, I believe). Here's the method. It crashes on the second NSLog line, so I've left that in for good measure:
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"indexPath = %@", indexPath);
NSLog(@"self.dataTracker.orderedZonesArray = %@", self.dataTracker.orderedZonesArray);
NSString *abbreviatedZone = [self.dataTracker.orderedZonesArray objectAtIndex:[indexPath section]];
SBVC_LSC02_ZoneSelect *slz2 = [[SBVC_LSC02_ZoneSelect alloc] initWithPerson:self.selectedPerson andZone:abbreviatedZone];
[self.navigationController pushViewController:slz2 animated:YES];
[slz2 release];
}
A: In your viewController code, you allocate an InstalledDataTracker object, and then pass it to a retain property. This results in a retain count of 2, not 1. Later, when you release the dataTracker object, you only reduce the retain count by one.
The easiest way to fix it would be to remove the self. prefix so that you are not invoking the automatic retain that is performed by the property accessor. In fact, I would recommend not using the dot syntax at all in your init and dealloc methods. There is some debate on the matter, but in general I think it is best to avoid calling your property accessors unless you have a very good reason to do so.
Here is how I would write it:
- (id)initWithPerson:(NSString *)person {
if (self = [super init]) {
...other stuff...
dataTracker = [[InstalledDataTracker alloc] init];
}
return self;
}
- (void)dealloc {
...other stuff...
[dataTracker release];
[super dealloc];
}
A:
This is because, to the best of my understanding, sortedArrayUsingSelector returns only pointers to the old array, not a true copy, so if I want to keep the array, I need to copy the values.
This is a misinterpretation. sortedArrayUsing..., similar other such functions, returns an array which contains the same pointer VALUES as in the original array. And, as the sorted array copy was made, the reference counts of the OBJECTS pointed to were incremented (ie, retain was done on each copied pointer). So the sorted array and the original are both "equals", and neither "owns" the objects more than the other one does. (In fact, examining the innards of the two arrays you'd not be able to tell which was copied from which, other than if you noticed that one is sorted and the other isn't.)
So there's absolutely no need to make the additional copy of the sorted array.
When you make that additional copy, you're using an [[alloc] init...] operation which returns a retained array. You then return that array to your caller without doing autorelease on it, meaning that it will leak if your caller does not explicitly release it, and meaning that the Analyzer will complain about it (since you can only return a retained object from copy... et al).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Scheme, lists, and graph theory I'm trying to develop a Scheme function that will take a graph as defined:
(define aGraph
'{{USA {Canada Mexico}}
{Mexico {USA}}
{Canada {USA}}})
and find the number of nodes bordering the specified node of the graph. I believe I am approaching this problem the wrong way; here is what I have done so far:
(define (nodes n graph)
(cond ((null? n) '())
(else
(cond ((eqv? n (first graph)) (length (first graph)))
(else (nodes n (rest graph)))))))
Needless to say, it doesn't work (The function can be called like this: (nodes 'USA aGraph), which in theory should return 2). What advice do you have to offer so that I may get on the right track?
A: Let's examine this line:
(cond ((eqv? n (first graph)) (length (first graph)))
You are treating (first graph) as both the node key in (eqv? n (first graph)) and as the bordering nodes in (length (first graph)) -- perhaps this will work better:
(cond ((eqv? n (first (first graph))) (length (second (first graph))))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Looping moving background objective-C I am testing a background-loop animation where there will be to images both 1024x768 pixels in dimension, move leftwards, go offscreen, then jump back to the other side, and repeat.
I was able to do this by creating a constant speed for both background image to move (successful), and then I tried the following code to make it jump, but there was a problem:
if((background.center.x) < -511){
background.center = CGPointMake(1536, background.center.y);
}
if((background2.center.x) < -511){
background2.center = CGPointMake(1536, background2.center.y);
}
Somehow this is not working the way I expected. It leaves a few pixels of gap every time, and I am confused why. Does anyone know what's causing this to happen and how to fix it? Thanks!
A: It seems like you have forgotten to take into account the distance moved. The greater than expression might have been triggered because you moved to far. I guess your movement is larger than 1 pixel/frame.
I am not sure what kind of values that are feeding your movement but I think to take into account the movement you should do something like...
if ((background.center.x) < -511){
CGFloat dist = background.center.x + 512;
background.center = CGPointMake(1536+dist, background.center.y);
}
if ((background2.center.x) < -511){
CGFloat dist = background2.center.x + 512;
background2.center = CGPointMake(1536+dist, background2.center.y);
}
A: Rather than have the two images move (sort of) independently, I would keep track of a single backgroundPosition variable and then constantly update the position of both images relative to that one position. This should keep everything nice and tidy:
CGFloat const backgroundWidth = 1024;
CGFloat const backgroundSpeed = 2;
- (void)animateBackground {
backgroundPosition -= backgroundSpeed;
if (backgroundPosition < 0) {
backgroundPosition += backgroundWidth;
}
background1.center.x = backgroundPosition - backgroundWidth/2;
background2.center.x = backgroundPosition + backgroundWidth/2;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why do I get a seg fault? I want to put a char array pointer inside a struct consider the fallowing code:
typedef struct port * pport;
struct port
{
int a;
int b;
pport next;
pport prev;
char * port;
};
void addNewport(pport head)
{
pport newPort = (pport)malloc(sizeof(pport*));
newPort->prev=temp;
head->next=newPort;
}
int main()
{
pport head = (pport)malloc(sizeof(pport*));
addNewport(head);
}
This will result in seg fault if try to add a new port via a subroutine, but if I perform it the main, no seg fault will appear. Why is that?
A: Replace
malloc(sizeof(pport*))
with
malloc(sizeof(struct port))
because you don't want to allocate memory for a pointer, rather for the struct.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: No `while (!my_ifstream.eof()) { getline(my_ifstream, line) }` in C++? On this website, someone writes:
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
This is wrong, read carefully the documentation for the eof()
memberfunction. The correct code is this:
while( getline( myfile, line))
cout << line << endl;
Why is this?
A: There are two primary reasons. @Etienne has pointed out one: reading could fail for some reason other than reaching the end of the file, in which case your first version will go into an infinite loop.
Even with no other failures, however, the first won't work correctly. eof() won't be set until after an attempt at reading has failed because the end of the file was reached. That means the first loop will execute one extra iteration that you don't really want. In this case, that'll just end up adding an extra blank (empty) line at the end of the file. Depending on what you're working with, that may or may not matter. Depending on what you're using to read the data, it's also fairly common to see the last line repeated in the output.
A: A stream operation (such as reading) can fail for multiple reasons. eof() tests just one of them. To test them all, simply use the stream's void *conversion operator. That's what's done in the second snippet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can I speed up my Java text file parser? I am reading about 600 text files, and then parsing each file individually and add all the terms to a map so i can know the frequency of each word within the 600 files. (about 400MB).
My parser functions includes the following steps (ordered):
*
*find text between two tags, which is the relevant text to read in each file.
*lowecase all the text
*string.split with multiple delimiters.
*creating an arrayList with words like this: "aaa-aa", then adding to the string splitted above, and discounting "aaa" and "aa" to the String []. (i did this because i wanted "-" to be a delimiter, but i also wanted "aaa-aa" to be one word only, and not "aaa" and "aa".
*get the String [] and map to a Map = new HashMap ... (word, frequency)
*print everything.
It is taking me about 8min and 48 seconds, in a dual-core 2.2GHz, 2GB Ram. I would like advice on how to speed this process up. Should I expect it to be this slow? And if possible, how can I know (in netbeans), which functions are taking more time to execute?
unique words found: 398752.
CODE:
File file = new File(dir);
String[] files = file.list();
for (int i = 0; i < files.length; i++) {
BufferedReader br = new BufferedReader(
new InputStreamReader(
new BufferedInputStream(
new FileInputStream(dir + files[i])), encoding));
try {
String line;
while ((line = br.readLine()) != null) {
parsedString = parseString(line); // parse the string
m = stringToMap(parsedString, m);
}
} finally {
br.close();
}
}
EDIT: Check this:
![enter image description here][1]
I don't know what to conclude.
EDIT: 80% TIME USED WITH THIS FUNCTION
public String [] parseString(String sentence){
// separators; ,:;'"\/<>()[]*~^ºª+&%$ etc..
String[] parts = sentence.toLowerCase().split("[,\\s\\-:\\?\\!\\«\\»\\'\\´\\`\\\"\\.\\\\\\/()<>*º;+&ª%\\[\\]~^]");
Map<String, String> o = new HashMap<String, String>(); // save the hyphened words, aaa-bbb like Map<aaa,bbb>
Pattern pattern = Pattern.compile("(?<![A-Za-zÁÉÍÓÚÀÃÂÊÎÔÛáéíóúàãâêîôû-])[A-Za-zÁÉÍÓÚÀÃÂÊÎÔÛáéíóúàãâêîôû]+-[A-Za-zÁÉÍÓÚÀÃÂÊÎÔÛáéíóúàãâêîôû]+(?![A-Za-z-])");
Matcher matcher = pattern.matcher(sentence);
// Find all matches like this: ("aaa-bb or bbb-cc") and put it to map to later add this words to the original map and discount the single words "aaa-aa" like "aaa" and "aa"
for(int i=0; matcher.find(); i++){
String [] tempo = matcher.group().split("-");
o.put(tempo[0], tempo[1]);
}
//System.out.println("words: " + o);
ArrayList temp = new ArrayList();
temp.addAll(Arrays.asList(parts));
for (Map.Entry<String, String> entry : o.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
temp.add(key+"-"+value);
if(temp.indexOf(key)!=-1){
temp.remove(temp.indexOf(key));
}
if(temp.indexOf(value)!=-1){
temp.remove(temp.indexOf(value));
}
}
String []strArray = new String[temp.size()];
temp.toArray(strArray);
return strArray;
}
600 files, each file about 0.5MB
EDIT3#- The pattern is no longer compiling each time a line is read. The new images are:
2:
A: Be sure to increase your heap size, if you haven't already, using -Xmx. For this app, the impact may be striking.
The parts of your code that are likely to have the largest performance impact are the ones that are executed the most - which are the parts you haven't shown.
Update after memory screenshot
Look at all those Pattern$6 objects in the screenshot. I think you're recompiling the pattern a lot - maybe for every line. That would take a lot of time.
Update 2 - after code added to question.
Yup - two patterns compiled on every line - the explicit one, and also the "-" in the split (much cheaper, of course). I wish they hadn't added split() to String without it taking a compiled pattern as an argument. I see some other things that could be improved, but nothing else like the big compile. Just compile the pattern once, outside this function, maybe as a static class member.
A: If you aren't already doing it, use BufferedInputStream and BufferedReader to read the files. Double-buffering like that is measurably better than using BufferedInputStream or BufferedReader alone. E.g.:
BufferedReader rdr = new BufferedReader(
new InputStreamReader(
new BufferedInputStream(
new FileInputStream(aFile)
)
/* add an encoding arg here (e.g., ', "UTF-8"') if appropriate */
)
);
If you post relevant parts of your code, there'd be a chance we could comment on how to improve the processing.
EDIT:
Based on your edit, here are a couple of suggestions:
*
*Compile the pattern once and save it as a static variable, rather than compiling every time you call parseString.
*Store the values of temp.indexOf(key) and temp.indexOf(value) when you first call them and then use the stored values instead of calling indexOf a second time.
A: Try to use to single regex that has a group that matches each word that is within tags - so a single regex could be used for your entire input and there would be not separate "split" stage.
Otherwise your approach seems reasonable, although I don't understand what you mean by "get the String [] ..." - I thought you were using an ArrayList. In any event, try to minimize the creation of objects, for both construction cost and garbage collection cost.
A: Is it just the parsing that's taking so long, or is it the file reading as well?
For the file reading, you can probably speed that up by reading the files on multiple threads. But first step is to figure out whether it's the reading or the parsing that's taking all the time so you can address the right issue.
A: Run the code through the Netbeans profiler and find out where it is taking the most time (right mouse click on the project and select profile, make sure you do time not memory).
A: Nothing in the code that you have shown us is an obvious source of performance problems. The problem is likely to be something to do with the way that you are parsing the lines or extracting the words and putting them into the map. If you want more advice you need to post the code for those methods, and the code that declares / initializes the map.
My general advice would be to profile the application and see where the bottlenecks are, and use that information to figure out what needs to be optimized.
@Ed Staub's advice is also sound. Running an application with a heap that is too small can result serious performance problems.
A: It looks like its spending most of it time in regular expressions. I would firstly try writing the code without using a regular expression and then using multiple threads as if the process still appears to be CPU bound.
For the counter, I would look at using TObjectIntHashMap to reduce the overhead of the counter. I would use only one map, not create an array of string - counts which I then use to build another map, this could be a significant waste of time.
A: Precompile the pattern instead of compiling it every time through that method, and rid of the double buffering: use new BufferedReader(new FileReader(...)).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to hide frag and refresh the activity to show this i have a button called ac and when i click on it, i want to hide my two fragment called a and b, but this is not happening, what do I need to do to make this work?
package cmsc436.lab5;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
public class Lab5Activity extends Activity implements button2interface, button1interface{
/** Called when the activity is first created. */
button1 a;
button2 b ;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
a= new button1();
b=new button2();
final LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setId(1);
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
//a.getActivity().findViewById(1);
fragmentTransaction.add(linearLayout.getId(), a);
fragmentTransaction.add(linearLayout.getId(), b);
fragmentTransaction.commit();
final Button ac =new Button(this);
ac.setText("c button");
linearLayout.addView(ac);
setContentView(linearLayout);
ac.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
fragmentTransaction.hide(a);
fragmentTransaction.hide(b);
}
});
}
@Override
public void buttonClick1() {
if (b.isHidden()) {
fragmentTransaction.show(b);
}
else {
fragmentTransaction.hide(b);
}
}
@Override
public void buttonClick2() {
if (a.isHidden()) {
fragmentTransaction.show(a);
}
else {
fragmentTransaction.hide(a);
}
}
}
A: I haven't really worked with fragments before, but it looks like you're trying to re-use a FragmentTransaction that's already been committed. You don't want a member variable for your FragmentTransaction; you should create a new one every time you need it:
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.hide(a);
fragmentTransaction.hide(b);
fragmentTransaction.commit();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Authentication with Windows Live ID issues I am trying to set up authentication with Windows LIve ID and followed this blog post. Everything is working but I have a problem logging into live INT web site. Whenever I try to log in (https://login.live-int.com/login.srf), after entering valid email/password I get redirected to the logout page. I tried two different accounts (one with existing email address, and other one with newly created @hotmail-int.com address) and three different browsers so I'm sure that neither account nor the browser are the cause of this. I also tried to enter wrong password, and in that case I get the message that the password is wrong.
If anyone has any hint about how to log in there It would be very, very helpful. I'm integrating SharePoint 2010 with Windows Live ID and instead of solving some real problems I'm stuck with this!
A: I have figured out myself and I have blogged it here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Batch: Running exe, copying file to appdata, and put it in startup For example, I have 2 exe's. Let's call them 1.exe and 2.exe, to keep it simple.
And I want to make a zip file, with 3 things in it, 1.exe, 2.exe and setup.bat.
First off, I want to know that the user is okay that we start the first exe (1.exe). So we type:
@echo off
cls
echo Are you sure you want to install 1.exe?
echo If not, click exit right now. If you are okay with it,
pause
Here comes the first question. So we want to start 1.exe. How do I start 1.exe, that is in the same folder as the bat file?
Okay, lets continue. When 1.exe is finished, I want to copy 2.exe, place it in %appdata%, and then add it to startup. And that's the second question. How do i do that.
So the questions are:
*
*How do I start 1.exe, which is in the same map as setup.bat
*How do I copy 2.exe which is in the same map as setup.bat to %appdata%
*How do I properly add 2.exe which is in %appdata% now to startup?
Note: Just using C:\documents and settings\all users\desktop\1.exe isn't going to work. I want it to work in all sorts of languages, and in some languages the folders might be called different.
A: 1.exe will run 1.exe, just like on the command line.
copy 2.exe %appdata% will copy 2.exe.
I don't know what question 3 means.
Define "work in all sorts of languages"? If you need to pass in an argument to the batch file, do so: http://commandwindows.com/batch.htm
A: You are right you should never hard code "Documents and Settings" or "Program Files" in a BAT file, because these folder names don't "work in all sorts of languages". You need to refer to them using special folder ids or environment variables.
In your case, you need to create a program shortcut (.LNK file) in the startup folder. There are two parts.
*
*creating a shortcut. Unfortunately there is no way to create a shortcut using only windows commands. You need to rely on a third party tool, there are many free command line tools that may do it; or write your own.
*locating the Startup folder and placing the shortcut there. There are two startup folders. The common startup and the user startup folder. Choose one. Then, you need to use either the %ALLUSERSPROFILE%\Start Menu\Programs\StartUp or the %USERPROFILE%\Start Menu\Programs\StartUp.
So putting all pieces together in your SETUP.BAT , it would look something like this...
@echo off
echo Are you sure you want to install 1.exe?
echo If not, click exit right now. If you are okay with it,
pause
1
copy 2.exe %appdata%
makelink %appdata%\2.exe %USERPROFILE%\Start Menu\Programs\StartUp\2.lnk
One suggestion. Avoid all this mess. It seems to me that you need to install a program. If so, I'd recommend you to try Inno Setup. http://www.jrsoftware.org/ .
Inno Setup is a free installer for Windows. First introduced in 1997, Inno Setup today rivals and even surpasses many commercial installers in feature set and stability.
...
*
*Supports creation of a single EXE to install your program for easy online distribution. Disk spanning is also supported.
*Standard Windows 2000/XP-style wizard interface.
*Customizable setup types, e.g. Full, Minimal, Custom.
*Complete uninstall capabilities.
*Installation of files: Includes integrated support for "deflate", bzip2, and 7-Zip LZMA/LZMA2 file compression. The installer has the ability to compare file version info, replace in-use files, use shared file counting, register DLL/OCX's and type libraries, and install fonts.
*Creation of shortcuts anywhere, including in the Start Menu and on the desktop.
*Creation of registry and .INI entries.
*Running other programs before, during or after install.
*...
A: This should do what you want.
@echo off
cls
echo Are you sure you want to install 1.exe?
echo If not, click exit right now. If you are okay with it,
pause
start /wait 1.exe
xcopy 2.exe %appdata% /y
reg add HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v "2" /d %appdata%\2.exe
The last line will make a reg entry instead of copying it to the startup folder which will not create a shortcut on the desktop and you don't need anything more than batch.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Load Files for Effeiency I was told there is a way to clean up my code to make it run faster. i should be able to reuse variables so i wont have to keyed them over and over again. Thus in return should make my reading of my files faster when load time comes, but i cant seem to figure out how to do this. My code works fine just not as effiecient.
InputStream in = myContext.getResources().openRawResource(R.raw.sql1);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String xmlFile = br.readLine();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(xmlFile);
NodeList statements = doc.getElementsByTagName("statement");
for (int i=0; i<statements.getLength(); i++) {
s = statements.item(i).getChildNodes().item(0).getNodeValue();
db.execSQL(s);
}
in.close();
doc = null;
statements = null;
in = null;
br.close();
br = null;
InputStream in2 = myContext.getResources().openRawResource(R.raw.sql2);
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String xmlFile2 = br2.readLine();
Document doc2 = builder.parse(xmlFile2);
NodeList statements2 = doc2.getElementsByTagName("statement");
for (int i=0; i<statements2.getLength(); i++) {
s = statements2.item(i).getChildNodes().item(0).getNodeValue();
db.execSQL(s);
}
in2.close();
doc2 = null;
statements2 = null;
in2 = null;
br2.close();
br2 = null;
InputStream in3 = myContext.getResources().openRawResource(R.raw.sql3);
BufferedReader br3 = new BufferedReader(new InputStreamReader(in3));
String xmlFile3 = br3.readLine();
Document doc3 = builder.parse(xmlFile3);
NodeList statements3 = doc3.getElementsByTagName("statement");
for (int i=0; i<statements3.getLength(); i++) {
s = statements3.item(i).getChildNodes().item(0).getNodeValue();
db.execSQL(s);
}
in3.close();
doc3 = null;
statements3 = null;
in3 = null;
br3.close();
br3 = null;
InputStream in4 = myContext.getResources().openRawResource(R.raw.sql4);
BufferedReader br4 = new BufferedReader(new InputStreamReader(in4));
String xmlFile4 = br4.readLine();
Document doc4 = builder.parse(xmlFile4);
NodeList statements4 = doc4.getElementsByTagName("statement");
for (int i=0; i<statements4.getLength(); i++) {
s = statements4.item(i).getChildNodes().item(0).getNodeValue();
db.execSQL(s);
}
in4.close();
doc4 = null;
statements4 = null;
in4 = null;
br4.close();
br4 = null;
InputStream in5 = myContext.getResources().openRawResource(R.raw.sql5);
BufferedReader br5 = new BufferedReader(new InputStreamReader(in5));
String xmlFile5 = br5.readLine();
Document doc5 = builder.parse(xmlFile5);
NodeList statements5 = doc5.getElementsByTagName("statement");
for (int i=0; i<statements5.getLength(); i++) {
s = statements5.item(i).getChildNodes().item(0).getNodeValue();
db.execSQL(s);
}
in5.close();
doc5 = null;
statements5 = null;
in5 = null;
br5.close();
br5 = null;
A: Your logic is a good candidate for factoring out into a subroutine, with the resource id as an argument.
That isn't going to improve the execution efficiency of the code. Things that are likely to help with efficiency are:
*
*Use SAX parsing (or pull parsing) instead of DOM parsing, and execute each statement as you get to its end.
*Turn on transaction mode, if applicable, and commit at the end of each file. (I don't know what SQL is being executed.)
In general, though, you need to profile your code to find out what's taking time. Then you can focus your optimization efforts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Using PHP pack() to Convert WKT into WKB I'm using prepared statements to insert data into my database, problem is I'm not able to use
INSERT INTO table (polygon) VALUES (GeomFromText(POLYGON((?,?,?,?,?,?))))
why? well, seems the GeomFromText itself is interpreted as text :/
so I figured I'd try pushing pure WKB strings into the db instead, problem is I can't really figure out how to pack a WKT into WKB.
Could someone help me do this with this format description: http://dev.mysql.com/doc/refman/5.0/en/gis-wkb-format.html
and the doc for pack() over at:
http://php.net/manual/en/function.pack.php
A: I see two problems. First, the GeomFromText function takes a string, so it should look like GeomFromText('POLYGON((0, 1, 2))') (note the quotation marks). Second, since the POLYGON... text is a string literal, it should be replaced with the wildcard, not the individual pieces. Your query should look like this:
INSERT INTO areas (name, polygon)
VALUES (?, GeomFromText(?))
You would then build the POLYGON((?, ?, ?, ?, ?, ?)) string in the application, not in the statement. Since PHP has safe string handling I would recommend using sprintf('POLYGON((%d, %d, %d, %d, %d, %d))', $var1, $var2, $var3, $var4, $var5, $var6) (sprintf is dangerous in C).
Alternatively, you can use MySQL's spatial functions to generate the points. I think this is what you were trying to do, but you don't pass them through GeomFromText. To build a polygon with MySQL's spatial functions, the documentation suggests you would need to do:
INSERT INTO areas (name, polygon)
VALUES (?, Polygon(LineString(Point(?, ?), Point(?, ?), Point(?, ?))))
Prior to MySQL 5.1.35 you would need to do:
INSERT INTO areas (name, polygon)
VALUES (?, GeomFromWKB(Polygon(LineString(Point(?, ?), Point(?, ?), Point(?, ?)))))
A: This is pretty straightforward. Grab a specification and use "C" for bytes, "V" for uint32's and "d" for doubles in your pack format strings. However, my advice is not to do that. First, rewriting a build-in function is a waste of time. Second, transferring binary data with sql is error prone (think of encoding issues for example). And third, according to http://dev.mysql.com/doc/refman/5.0/en/creating-spatial-values.html you don't even need GeomFromText, because mysql already treats unquoted wkt as binary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++0x : Storing any type of std::function in a std::map I'm trying to store a set of std::function in a map (under GCC 4.5)
I'd like to get 2 kind of things :
*
*storing functions with arguments already passed; then you just have
to call f()
*storing functions without arguments; then you have to call
f(...)
I think I achieved the first one with a class Command and a Manager :
class Command
{
std::function<void()> f_;
public:
Command() {}
Command(std::function<void()> f) : f_(f) {}
void execute() { if(f_) f_(); }
};
class CommandManager
{
typedef map<string, Command*> FMap;
public :
void add(string name, Command* cmd)
{
fmap1.insert(pair<string, Command*>(name, cmd));
}
void execute(string name)
{
FMap::const_iterator it = fmap1.find(name);
if(it != fmap1.end())
{
Command* c = it->second;
c->execute();
}
}
private :
FMap fmap1;
};
can be used like this :
class Print{
public:
void print1(string s, string s1){ cout<<"print1 : "<<"s : "<<s<<" s1 : "<<s1<<endl; }
int print2(){ cout<<"print2"<<endl; return 2;}
};
#include <string>
#include <functional>
int main()
{
Print p = Print();
function<void()> f1(bind(&Print::print1, &p, string("test1"), string("test2")));
function<int()> f2(bind(&Print::print2, &p));
CommandManager cmdMgr = CommandManager();
cmdMgr.add("print1", new Command(f1));
cmdMgr.execute("print1");
cmdMgr.add("print2", new Command(f2));
cmdMgr.execute("print2");
return 0;
}
Now I'd like to be able to do this :
int main()
{
Print p = Print();
function<void(string, string)> f1(bind(&Print::print1, &p, placeholders::_1, placeholders::_2));
CommandManager cmdMgr = CommandManager();
cmdMgr.add("print1", new Command(f1));
cmdMgr.execute("print1", string("test1"), string("test2"));
return 0;
}
Is there a way, using type-erasure for example ?
A: What you are trying to do is not possible without some serious runtime work and the associated cost. The simplest solution would of course to just store a boost::any (any_function never made it into boost) inside your map and do the necessary casts (or add some runtime data that tells you which cast to make), although you should avoid that at any cost and go with fixed arguments or no arguments.
Your users can then modify their functions using bind to match the signature you require.
Edit: In your current scheme I see no reason for CommandManager to store Command* in the map.
Edit2: Also you drop the return type. This could be OK for your use-case but makes this a lot less generic.
Edit3: I worked out some working example of your code using any. I feel that there is some flaw and I really don't see what this should achieve but here it goes:
#include <iostream>
#include <string>
#include <map>
#include <functional>
#include <boost/any.hpp>
class AnyCaller
{
std::map<std::string, boost::any> calls;
public:
AnyCaller() {}
void add(const std::string& name, const boost::any& fun) {
calls[name] = fun;
}
// we always use the throwing version of any_cast
// icbb by error checking
// no arg version
template<typename Ret>
Ret call(const std::string& s) {
const boost::any& a = calls[s];
return boost::any_cast< std::function<Ret(void)> >(a)();
}
// this should be a variadic template to be actually usable
template<typename Ret, typename T>
Ret call(const std::string& s, T&& arg) {
// we have to assume that our users know what we are actually returning here
const boost::any& a = calls[s];
return boost::any_cast< std::function<Ret(T)> >(a)(std::forward<T>(arg));
}
virtual ~AnyCaller() {}
};
int foo() { std::cout << "foo" << std::endl; return 1; }
double foo2(int i) { std::cout << "foo2" << std::endl; return double(i); }
int main()
{
AnyCaller c;
c.add("foo", std::function<int(void)>(foo));
c.add("foo2", std::function<double(int)>(foo2));
c.call<int>("foo");
c.call<double, int>("foo2", 1);
// this should throw
c.call<double, int>("foo", 1);
return 0;
}
As for the example using a fixed signature. Just think of what would be the most natural representation of a function you are going to store (looking at your Command example I'd assume it is std::function<void(void)>. Store functions of this type and whenever one your users tries to use it, he has to bind whatever function he wants to use, so it matches this signature.
A: Your Command class constructor needs a function<void()>. You are trying to feed it a function<void(string,string)>. This is not going to typecheck.
If you need functions that accept variable arguments (like printf), you will need function<> and execute() that accept variable arguments. You need to know how to work with that (in particular, you need a fixed first argument). You are then responsible for type safety, much like with printf.
If you just need a variable number of string arguments, use functions that accept e.g. vectors of strings.
All this has nothing to do whatsoever with std::map. Whatever you can store in a plain old variable, you can store in std::map too.
A: You could use dynamic cast to determine the type of the function in the list at runtime.
Please note that I added shared_ptr to remove the memory leak in the original sample. Perhaps you want to throw a exception if the execute method is called with the wrong arguments (if the dynamic_cast yields 0).
Usage:
void x() {}
void y(int ) {}
void main() {
CommandManager m;
m.add("print", Command<>(x));
m.add("print1", Command<int>(y));
m.execute("print");
m.execute("print1", 1);
}
Code (with variadic template support for example gcc-4.5):
#include <functional>
#include <map>
#include <string>
#include <memory>
using namespace std;
class BaseCommand
{
public:
virtual ~BaseCommand() {}
};
template <class... ArgTypes>
class Command : public BaseCommand
{
typedef std::function<void(ArgTypes...)> FuncType;
FuncType f_;
public:
Command() {}
Command(FuncType f) : f_(f) {}
void operator()(ArgTypes... args) { if(f_) f_(args...); }
};
class CommandManager
{
typedef shared_ptr<BaseCommand> BaseCommandPtr;
typedef map<string, BaseCommandPtr> FMap;
public :
template <class T>
void add(string name, const T& cmd)
{
fmap1.insert(pair<string, BaseCommandPtr>(name, BaseCommandPtr(new T(cmd))));
}
template <class... ArgTypes>
void execute(string name, ArgTypes... args)
{
typedef Command<ArgTypes...> CommandType;
FMap::const_iterator it = fmap1.find(name);
if(it != fmap1.end())
{
CommandType* c = dynamic_cast<CommandType*>(it->second.get());
if(c)
{
(*c)(args...);
}
}
}
private :
FMap fmap1;
};
without variadic template support (example VS2010):
#include <functional>
#include <map>
#include <string>
#include <memory>
using namespace std;
class Ignored;
class BaseCommand
{
public:
virtual ~BaseCommand() = 0 {};
};
template <class A1 = Ignored>
class Command : public BaseCommand
{
typedef std::function<void(A1)> FuncType;
FuncType f_;
public:
Command() {}
Command(FuncType f) : f_(f) {}
void operator()(const A1& a1) { if(f_) f_(a1); }
};
template <>
class Command<Ignored> : public BaseCommand
{
typedef std::function<void()> FuncType;
FuncType f_;
public:
Command() {}
Command(FuncType f) : f_(f) {}
void operator()() { if(f_) f_(); }
};
class CommandManager
{
typedef shared_ptr<BaseCommand> BaseCommandPtr;
typedef map<string, BaseCommandPtr> FMap;
public :
template <class T>
void add(string name, const T& cmd)
{
fmap1.insert(pair<string, BaseCommandPtr>(name, BaseCommandPtr(new T(cmd))));
}
template <class A1>
void execute(string name, const A1& a1)
{
typedef Command<A1> CommandType;
FMap::const_iterator it = fmap1.find(name);
if(it != fmap1.end())
{
CommandType* c = dynamic_cast<CommandType*>(it->second.get());
if(c)
{
(*c)(a1);
}
}
}
void execute(string name)
{
typedef Command<> CommandType;
FMap::const_iterator it = fmap1.find(name);
if(it != fmap1.end())
{
CommandType* c = dynamic_cast<CommandType*>(it->second.get());
if(c)
{
(*c)();
}
}
}
private :
FMap fmap1;
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Confusion with typedef and pointers in C
Possible Duplicate:
Typedef pointers a good idea?
I am confused with the following:
typedef struct body *headerptr;
Now, when I create something with type headptr that points to a struct body, to create a new headerptr would be as follows (I'm not sure if I'm doing this correctly):
headerptr newHeadptr;
Am I correct to assume that this would be a pointer that points to a struct body?
A: Yes. headerptr is now equivalent to struct body*.
A:
This would be a pointer that points to a struct body.
The way you've declared it, newHeadptr could point to a struct body. Remember, though, that you haven't allocated a struct body for it to point to. Initially, newHeadptr will just have some garbage value. To rectify that, you could to this:
headerptr newHeaderptr = malloc(sizeof(*newHeaderptr));
or:
struct body newBody;
headerptr newHeaderptr = &newBody;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why does error_log() always send exactly 3 emails? I'm using the error_log() function like so:
error_log($errorstring, 1, '[email protected]');
And it works fine, but every single time it is executed I get exactly 3 copies of the same email spaced about 1 or 2 seconds apart. There is no loop or anything that it's in, this is simply to notify me of a failed login attempt, so it is only called once before it die()s.
Anyone have any bright ideas on this?
EDIT: Sorry forgot to mention, this is in PHP using the error_log() function.
EDIT2: I have switched to using the custom error handler found here:
http://www.tonymarston.net/php-mysql/errorhandler.html
What I have discovered is that while MySQL errors generate only a single email as intended, non-MySQL errors generate the three emails. It's always three... never more or less, and they are spaced anywhere from 0 to 2 seconds apart, based on the timestamp sent in the emails.
Anyone have any other ideas why in the world this would be happening??
A: PHP MANUAL
error_log($errorstring, 1, '[email protected]',string $extra_header);
1 message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used.
extra_headers
The extra headers. It's used when the message_type parameter is set to 1. This message type uses the same internal function as mail() does.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ClassCastException at Gallery.setLayoutParams? I am create a base adapter for a Gallery.
I am using this method to override getView().
But i keep getting this error at the LayoutParam's code.
10-02 01:14:32.543: ERROR/AndroidRuntime(839): FATAL EXCEPTION: main
10-02 01:14:32.543: ERROR/AndroidRuntime(839): java.lang.ClassCastException: android.widget.Gallery$LayoutParams
10-02 01:14:32.543: ERROR/AndroidRuntime(839): at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:659)
10-02 01:14:32.543: ERROR/AndroidRuntime(839): at android.widget.LinearLayout.onMeasure(LinearLayout.java:311)
10-02 01:14:32.543: ERROR/AndroidRuntime(839): at android.view.View.measure(View.java:8313)
10-02 01:14:32.543: ERROR/AndroidRuntime(839): at android.view.ViewGroup.measureChild(ViewGroup.java:3109)
Here is my method..
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.lazyitemt, null);
ImageView image=(ImageView)vi.findViewById(R.id.image);
image.setLayoutParams(new Gallery.LayoutParams(250, 250));
imageLoader.DisplayImage(data[position], activity, image);
return vi;
}
A: Is the view child with id image inside of a Gallery? According to the stack trace, it looks like the child is trying to be positioned by a LinearLayout, which can not use the Gallery.LayoutParams params. Are you sure that there's only one View in your layout that is identified by id image, and are you sure that this view is not getting somehow moved from a Gallery into a LinearLayout?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: bjam can't find the boost libraries I've built boost from source because I need the latest version to build pyopencv with.
That all went fine.
However, bjam now can't find the boost libs or includes because now they're no longer in /usr/lib, now they're in /usr/local/lib and /usr/local/include.
(I did add /usr/local/lib to LD_LIBRARY_PATH)
Now bjam complains:
boost-build.jam:2: in module scope
rule using unknown in module
on the first line of my boost-build.jam which says:
using python;
How do I tell bjam where to look for includes? I've looked at the Boost.Build docs, but can't seem to make out how to set the include path.
A: It's not the Boost headers failing to find (yet), it's the BoostBuild2 sources it's failing to find. You either need to use the BBV2 sources from the Boost tree, or install BBv2 separately (the BBv2 install is explained here). Assuming you read the Boost Python documentation on how to get started using that library (see the BPL docs).. You need to also follow the instructions on how to modify the startup/template BBv2 project in those instructions to build your own Python extensions using BBv2 (see the Modifying the Example Project, Relocate the Project section).
Also note that the line above you have should be: using python ; -- I.e. the spaces are important.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624043",
"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.