text
stringlengths
8
267k
meta
dict
Q: Is the JavaScript operator === provably transitive? JavaScript's quirky weakly-typed == operator can easily be shown to be non-transitive as follows: var a = "16"; var b = 16; var c = "0x10"; alert(a == b && b == c && a != c); // alerts true I wonder if there are any similar tricks one can play with roundoff error, Infinity, or NaN that could should show === to be non-transitive, or if it can be proved to indeed be transitive. A: The === operator in Javascript seems to be as transitive as it can get. NaN is reliably different from NaN: >>> 0/0 === 0/0 false >>> 0/0 !== 0/0 true Infinity is reliably equal to Infinity: >>> 1/0 === 1/0 true >>> 1/0 !== 1/0 false Objects (hashes) are always different: >>> var a = {}, b = {}; >>> a === b false >>> a !== b true And since the === operator does not perform any type coercion, no value conversion can occur, so the equality / inequality semantics of primitive types will remain consistent (i.e. won't contradict one another), interpreter bugs notwithstanding. A: If you look at the spec (http://bclary.com/2004/11/07/#a-11.9.6) you will see that no type coercion is being made. Also, everything else is pretty straightforward, so maybe only implementation bugs will make it non-transitive. A: Assuming you have variable a,b, and c you can't be 100% certain as shown here. If someone is doing something as hackish as above in production, well then you probably have bigger problems ;) var a = 1; var b = 1; Object.defineProperty(window,"c",{get:function(){return b++;}}); alert(a === b && b === c && a !== c); // alerts true
{ "language": "en", "url": "https://stackoverflow.com/questions/7622671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Getting better performance using OpenCV? I need real time processing, but the internal functions of OpenCV are not providing this. I am doing hand gesture recognition, and it works almost perfectly, except for the fact that the resulting output is VERY laggy and slow. I know that this isn't because of my algorithm but the processing times of OpenCV. Is there anything I can do to speed it up? Ps: I don't want to use the IPP libraries so please don't suggest that. I need increased performance from OpenCV itself A: Traditional techniques for improving image analysis: * *Reduce the image to a monochrome sample. *Reduce the range of samples, e.g. from 8-bit monochrome to 4-bit monochrome. *Reduce the size of the image, e.g. 1024x1924 to 64x64. *Reduce the frame rate, e.g 60fps to 5fps. *Perform a higher level function to guess where the target area is with say a lower resolution, then perform the regular analysis on the cropped output, e.g. perform image recognition to locate the hand before determining the gesture. A: Steve-o's answer is good for optimizing your code efficiency. I recommend adding some logic to monitor execution times to help you identify where to spend efforts optimizing. OpenCV logic for time monitoring (python): startTime = cv.getTickCount() # your code execution time = (cv.getTickCount() - startTime)/ cv.getTickFrequency() Boost logic for time monitoring: boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time(); // do something time-consuming boost::posix_time::ptime end = boost::posix_time::microsec_clock::local_time(); boost::posix_time::time_duration timeTaken = end - start; std::cout << timeTaken << std::endl; How you configure your OpenCV build matters a lot in my experience. IPP isn't the only option to give you better performance. It really is worth kicking the tires on your build to get better hardware utilization. The other areas to look at are CPU and memory utilization. If you watch your CPU and/or memory utilization, you'll probably find that 10% of your code is working hard and the rest of the time things are largely idle. * *Consider restructuring your logic as a pipeline using threads so that you can process multiple images at once (if you're tracking and need the results of previous images, you need to break up your code into multiple segments such as preprocessing/analysis and use a std::queue to buffer between them, and imshow won't work from worker threads so you'll need to push result images into a queue and imshow from the main thread) *Consider using persistent/global objects for things like kernels/detectors that don't need to get recreated each time *Is your throughput slowing down the longer your program runs? You may need to look at how you are handling disposing of images/variables within the main loop's scope *Segmenting your code in functions makes it more readable, easier to benchmark, and descopes variables earlier (temporary Mat and results variables free up memory when descoped) *If you're doing low-level processing on Mat pixels where you iterate over a large portion of the image, use a single parallel for and avoid writing *Depending on how you are running your code, you may be able to disable debugging to get better performance *If you're streaming and dumping frames, prefer changing the camera settings to throttle the streaming rate instead of dumping frames *If you're converting from1 12 to 8 bits or only using a region of your image, prefer doing this at the camera hardware level Here's an example of a parallel for loop: cv::parallel_for_(cv::Range(0, img.rows * img.cols), [&](const cv::Range& range) { for (int r = range.start; r < range.end; r++) { int x = r / img.rows; int y = r % img.rows; uchar pixelVal = img.at<uchar>(y, x); //do work here } }); If you're hardware constrained (ie fully utilizing CPU and/or memory), then you need to look at priotizing your process/OS perfomance optimizations/freeing system resources/upgrading your hardware * *Increase the priority of the process to be more greedy with respect to other programs running on the computer (in linux you have nice(int inc) in unistd.h, in windows SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS) in windows.h) *Optimize your power settings for maximum performance in general *Disable CPU core parking *Optimize your acquisition hardware settings (increase rx/tx buffers, etc) to offload work from your CPU A: I'm using some approaches: * *[Application level] For hardware with OpenCL support: from cv::Mat to cv::UMat and set cv::ocl::setUseOpenCL(true) *[Library level] In OpenCV CMake use another parallel library: TBB may be better then openmp *[Library level] In OpenCV CMake enable IPP support in OpenCV *[Application level] Caching temporary results. Most functions in OpenCV makes check format and size of output arrays. So you can store all results as cv::Mat in privete members and on next frames OpenCV will not allocate and deallocate memory for they. *[Library -> Application level] Put sources of bottle-neck OpenCV functions and apply for it punkt [4].
{ "language": "en", "url": "https://stackoverflow.com/questions/7622672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Notepad++, Remember previous line folds on startup/file-open? How do I get Notepad++ to remember previous line folds when I start the program or re-open a file? Example: //I collapsed/folded my code [+] My code is collapsed/folded now ----------------------------------------- //Closed and re-opened file or Notepad++ [-] My code is no longer collapsed/folded, Notepad++ doesn't remember the previous file state | code | code | code ----------------------------------------- I would like it to behave just like Visual Studio does if possible. Thanks for any help!
{ "language": "en", "url": "https://stackoverflow.com/questions/7622677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a way to set file pointers equal to each other in C? For example, if I have FILE *fp, *tfp; fp = fopen (file, mode); tfp = fp; is this possible? A: Yes, it is possible and totally legal. Both fp and tfp are pointers to a variable of type FILE The statement tfp = fp; copies the address saved in fp into tfp. So, please keep in mind that you end up with two pointers to the same object. You aren't duplicating the "object" created in the fopen() call at all. A: Yes that it possible. These are just pointers after all. You can have as many variables as you like containing the same pointer and nobody can tell them apart. A: This is correct. But the best way to learn is to try. Launch this code under debugger and check that this works as you expect. A: Pointer variable (FILE * fp) simply contains an address (a number). You can see it: printf( "%p\n", fp ); So, assigning numbers of same type is perfectly legal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TCC and winsock.h I have already read Tiny C Compiler (TCC) and winsock?, but I still can't compile sockets with TCC, because when I try tiny_impdef winsock.dll -o winsock.def tiny_impdef responds: Not a PE file: C:\WINDOWS\system32\winsock.dll So how can I do to compile properly a program that use sockets? Any help will be appreciated A: I'm guessing that you have a 64 bit machine and TCC is 32 bit. In that situation C:\WINDOWS\system32\winsock.dll is the 64 bit version of winsock. Try it this way: tiny_impdef C:\WINDOWS\SysWOW64\winsock.dll -o winsock.def to pick up winsock from the 32 bit system directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: remove newline from shell script command I have the following shell script 'geturl.sh': wget -O /dev/null http://google.com/$1 wget -O /dev/null http://google.com/$1 When I run it with './geturl.sh news', it tries to wget http://google.com/news%0D on the first line, and http://google.com/news on the second. Why does it count the newline character and how do I fix it? Thanks A: if you created the file using a Unix editor, it wouldn't/shouldn't have the carriage return [chr(13), 0x0D, or ^M)] character. Unix newlines are linefeeds [chr(10), 0x0A, or ^J)] only. carriage returns don't have any special meaning to the shell and usually result in unwanted behavior. you can fix it using sed: sed -i 's/\r//' geturl.sh
{ "language": "en", "url": "https://stackoverflow.com/questions/7622686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery load fragment for several purposes once I am loading options for few select lists using load and fragment. This is what I have: $(document).ready(function(){ $("#select1").load("ts.xml #select1", function (responseText, textStatus, XMLHttpRequest) { if (textStatus == "success") { alert("Loaded select 1"); } $("#select2").load("ts.xml #select2", function (responseText, textStatus, XMLHttpRequest) { if (textStatus == "success") { alert("Loaded select 2"); } }); And my html looks like this: <li id="select1" class="left"></li> <li id="select2" class="left"></li> where the ts.xml looks like this: <select id="select1"> <option>Lorem</option> <option>Ipsum</option> <option>Lorem Ipsum</option> </select> <select id="select2"> <option>Lorem</option> <option>Ipsum</option> <option>Lorem Ipsum</option> </select> How can I load the ts.xml once and keep retrieving fragment out of it? Note that every time I retrieve a fragment I want to alert a success not on ts.xml load. Thanks alot A: Load once, cache, then use the cached version: $(document).ready(function(){ var response; $("#select1").load("ts.xml #select1", function (responseText, textStatus, XMLHttpRequest) { if (textStatus == "success") { response = responseText; // this will be your xml response // now you can use 'response' anywhere inside the doc.ready function } }); }); A: I think I would probably go back to the basic $.ajax function and do something like this. var xmlData; function getXML() { $.ajax({ type: "GET", url: "ts.xml", dataType: "xml", error: function() { $("#mydiv").append("<p>File Not Found!</p><br />"); }, success: function(xml){ xmlData = $(xml); } }); Now you can search the data anywhere, atleast I think so, not tested but can't see why not? var Searchvalue = "Lorem"; xmlData.find("select1").find("option:contains('" + Searchvalue + "')").each(function(){ // do something });
{ "language": "en", "url": "https://stackoverflow.com/questions/7622697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bcrypt - How many iterations/cost? I've read some articles saying you should set the cost to be at least 16 (216), yet others say 8 or so is fine. Is there any official standard for how high the cost should be set to? A: The cost should depend on your hardware. You should test your cost settings and aim for the 100 .. 500 ms interval. Of course, if you are working with highly sensitive information, the time could be 1000 ms or even more. A: The cost you should use depends on how fast your hardware (and implementation) is. Generally speaking a cost of 8 or 10 is fine -- there isn't any noticable delay. It's still a huge level of protection and far better than any home-grown solution using SHAs and salts. Once you upgrade your hardware you could increase the cost to 16. I would say that 16 is a little high at this time, and will probably result in noticeable (and annoying) delays. But if 16 works for you, by all means go for it! A: You must set the number of iterations at the maximum value which is still "tolerable" depending on the hardware you use and the patience of the users. Higher is better. The whole point of the iteration count is to make the password processing slow -- that is, to make it slow for the attacker who "tries" potential passwords. The slower the better. Unfortunately, raising the iteration count makes it slow for you too... As a rule of thumb, consider that an attacker will break passwords by trying, on average, about 10 millions (107) of potential passwords. If you set the iteration count so that password hashing takes 1 second for you, and you consider that the attacker can muster ten times more computing power than you, then it will take him 107*1/10 seconds, i.e. about 12 days. If you set the iteration count so that password hashing takes only 0.01 second on your PC, then the attacker is done in three hours.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: What is the ascii value of EOF in c.? Any one knows what is the ASCII value of i. I try printf("%d",EOF); but its print -1 and also try printf("%c",EOF); but its print blank screen. so anyone know which key for EOF. A: EOF (as defined in the C language) is not a character/not an ASCII value. That's why getc returns an int and not an unsigned char - because the character read could have any value in the range of unsigned char, and the return value of getc also needs to be able to represent the non-character value EOF (which is necessarily negative). A: there is not such thing as ascii value of EOF. There is a ASCII standard that includes 127 characters, EOF is not one of them. EOF is -1 because that's what they decided to #defined as in that particular compiler, it could be anything else. A: As Heffernan said, it's system defined. You can access it via the EOF constant (is it a constand?): #include <stdio.h> int main(void) { printf("%d\n", EOF); } After compiling: c:\>a.exe -1 c:\> A: The actual value of EOF is system defined and not part of the standard. EOF is an int with negative value and if you want to print it you should use the %d format string. Note that this will only tell you its value on your system. You should not care what its value is. A: EOF do not have ASCII value as they said .... no problem with this also you can avoid the strange character that appear in the end (which is the numeric representation of EOF ) by making if condition here is an example: #include <stdio.h> int main(void) { FILE *file = fopen("/home/abdulrhman/Documents/bash_history.log", "r"); FILE *file2 = fopen("/home/abdulrhman/Documents/result.txt", "w"); file = file2 = char hold = 'A'; while(hold != EOF) { hold = getc(file); if(hold == EOF) break; // to prevent EOF from print to the stream fputc(hold, file2); } fclose(file); return 0; } that is it A: EOF is not an ASCII character. Its size is not 1 byte as against size of a character and this can be checked by int main() { printf("%lu", sizeof(EOF)); return 0; } However, it is always defined to be -1. Try int main() { printf("%d",EOF); return 0; } The key combination for EOF is Crtl+D. The character equivalent of EOF is machine dependent. That can be checked by following: int main() { printf("%c", EOF) return 0; } A: for all intents and purposes 0x04 EOT (end of transmission as this will normaly signal and read function to stop and cut off file at that point.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: Edit the form css of a django form so the submit button looks like this: <input type="submit" id='register_submit' class= value="{% trans 'Submit' %}" /></div> and normall I would use a class to specify what the button looks like, but this has its own class that I cannot touch. What can I do here to give it a new class so I can customize the button? A: An option would be to override the existing rule with a specific rule. So, if your output HTML is: <input type="submit" class="django-submit" /> You could wrap it to end up with: <div class="my-button"> <input type="submit" class="django-submit" /> </div> And then use your .my-button class to create a more specific CSS rule: .my-button .django-submit { padding: 5px; color: #fff; background: #f00; } The following demo shows how the specific rule will override the generic rule. A: You could give the button a style attribute which will always take precedence over any class attribute.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: An array of elements in jQuery Markup code: <div id="elements"> <div> <a href="#">text</a> <a href="#">text</a> <a href="#">text</a> </div> <div> <a href="#">text</a> <a href="#">text</a> <a href="#">text</a> </div> <div> <a href="#">text</a> <a href="#">text</a> </div> </div> Please tell me how can I get an array of all elements of the div, so that later, it is possible to address an array of options? Such as: divs[0] links[1] A: Demo var divs = $('#elements div'); var links = $('#elements div a'); * *If you want the DOM elements, then you can access them with the array style like divs[0] or links[2]. *If you want to get the specific jQuery object, you can access them with divs.eq(0) or links.eq(1). A: $('#elements div').eq(0) // first div $('#elements div a').eq(1) // second anchor in group of divs Without the .eq() you have a collection of elements, the .eq just singles the elements out. A: See https://api.jquery.com/toArray/ $( "li" ).toArray() This works great in cases like $( "li" ).toArray().each( function(li) { console.log('do something with this list item', li); }) or if you really want $( "li" ).toArray()[0] A: wrapper = document.getElementById('elements'); divs = wrapper.getElementsByTagName('div'); links = []; for (i = 0; i < divs.length; i++) { links[i] = divs[i].getElementsByTagName('a'); } divs will now be an array of the divs inside of your "elements" div. Links is now a two dimensional array, where the first index refers to the div inside your "elements" div, and the second index refers to the "a" tags inside that div. links[2][1] will refer to the element denoted below: <div id="elements"> <div> <a href="#">text</a> <a href="#">text</a> <a href="#">text</a> </div> <div> <a href="#">text</a> <a href="#">text</a> <a href="#">text</a> </div> <div> <a href="#">text</a> <a href="#">text</a> //this one </div> </div> A: Or also, and I believe this is more accurately what you asked for: $("#elements div:eq(0) a:eq(1)") A: $("#elements a") $("div a") or $("a") jQuery Selectors
{ "language": "en", "url": "https://stackoverflow.com/questions/7622704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Declaring a Reference inside Function Parameter List I'm trying to do something funky with macros and to do it, I need to do something even funkier. To give an example of what I'm trying to do, consider the code below: #include <iostream> int set_to_three(int& n) { n = 3; return 0; } int main() { int s = set_to_three(int& t); // <-- Obviously this wouldn't compile t += 5; std::cout << t << std::endl; // <-- This should print 8 std::cout << s << std::endl; // <-- This should print 0 return 0; } So as you can see, I want to call a function, declare its parameter, and capture the return value of the function in exactly ONE expression. I tried using the comma operator in various funky ways, but no results. I was wondering if this is at all possible, and if so, how could I do it? I'm thinking it may be possible using comma operators, but I simply don't know how. I'm using Visual Studio 2010, in case you need to know which compiler I'm using. A: Since you only have two ints, this will work: int t, s = set_to_three(t); Note that this is not comma operator. Were the types of s and t different, it wouldn't be possible IMHO.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: running perl program from C++ program I have a C++ program to compute inventory and when it falls below a certain level I want to call my perl program that will write the order details into the DB. I read the documentation on calling Perl from C++ and I was trying this sample code #include <EXTERN.h> #include <perl.h> static PerlInterpreter *my_perl; int main(int argc, char **argv, char **env) { char *args[] = { NULL }; PERL_SYS_INIT3(&argc,&argv,&env); my_perl = perl_alloc(); perl_construct(my_perl); perl_parse(my_perl, NULL, argc, argv, NULL); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; /*** skipping perl_run() ***/ call_argv("showtime", G_DISCARD | G_NOARGS, args); perl_destruct(my_perl); perl_free(my_perl); PERL_SYS_TERM(); } I tried to compile but I get the following error g++ fn-test.cpp -o t 'perl -MExtUtils::Embed -e ccopts -e ldopts' g++: perl -MExtUtils::Embed -e ccopts -e ldopts: No such file or directory fn-test.cpp:2:24: fatal error: EXTERN.h: No such file or directory compilation terminated. I am working on ubuntu so I went into cpan and ran force install ExtUtils::Embed it did it's thing for a while and now when I try to compile again, I get the same error. This is my first time trying to call a Perl program from C++, so any tips would be helpful. A: The error you are seeing is because EXTERN.h is not in the include path. It looks like it's not on your g++ command line because the perl script is failing Can you run perl -MExtUtils::Embed -e ccopts -e ldopts by itself? This is the script that gives you the required g++ options. Are you using backticks () for quotes around the perl in your command line? That will cause the perl command to run. g++ fn-test.cpp -o t `perl -MExtUtils::Embed -e ccopts -e ldopts` The backticks will run what's inside the backticks then put the output of the command on the command-line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Understanding Moonlight; Is it a framework? I'm trying to understand if moonlight is a framework which is similar yet independent to the mono framework in exactly the same way as silverlight is similar yet independent for dot net framework. I'm trying to write a library that works for both moonlight and mono and I was wondering if I would need to target specific frameworks (as is the case with silverlight and dot net). A: Moonlight uses the Mono runtime but, like Silverlight, uses a subset of the available .NET framework. So yes, you'll need to target different frameworks for desktop vs Moonlight (Moonlight uses the 2.1 profile, same as Silverlight).
{ "language": "en", "url": "https://stackoverflow.com/questions/7622716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The type initializer for 'Facebook.FacebookApplication' threw an exception I am using Facebook APIs w/ oAuth using their Javascript SDK to sign in, and setting oAuth = true. I can from the SDK sign in successfully, and get my xfbml to render properly. I am using the Facebook C# sdk to retrieve the user ID and post to FB. I wrote a small test page that does this. HTML is: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="fbtest.aspx.cs" Inherits="fbtest" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> ID:<asp:label runat="server" text="Label" ID="Userid"></asp:label><div /> <asp:label runat="server" text="Label" ID="FacebookTokenLabel"></asp:label> </div> </form> </body> </html> The Code behind is: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Facebook; using Facebook.Web; public partial class fbtest : System.Web.UI.Page { private FacebookWebClient _facebookApp; protected void Page_Load(object sender, EventArgs e) { try { // FacebookWebContext fbWebContext = FacebookWebContext.Current; // FacebookTokenLabel.Text += fbWebContext.AccessToken; FacebookWebClient fb = new FacebookWebClient(); dynamic me = fb.Get("me"); FacebookTokenLabel.Text = me.name; Userid.Text = me.id; } catch (Exception ex) { FacebookTokenLabel.Text = ex.Message + ":" + ex.StackTrace; } } } I tried on all browsers (IE9, chrome 14.0.835.186 m and FF 6.0.2) and i get the same exception: ID:Label The type initializer for 'Facebook.FacebookApplication' threw an exception.: at Facebook.FacebookApplication.get_Current() in e:\Prabir\Documents\Projects\facebooksdk\v5.2.1\Source\Facebook\FacebookApplication.cs:line 48 at Facebook.Web.FacebookWebContext..ctor() in e:\Prabir\Documents\Projects\facebooksdk\v5.2.1\Source\Facebook.Web\FacebookWebContext.cs:line 48 at Facebook.Web.FacebookWebContext.get_Current() in e:\Prabir\Documents\Projects\facebooksdk\v5.2.1\Source\Facebook.Web\FacebookWebContext.cs:line 96 at fbtest.Page_Load(Object sender, EventArgs e) in c:\inetpub\vhosts\beirutna.com\subdomains\beta\httpdocs\fbtest.aspx.cs:line 16 You can try yourself: http://beta.beirutna.com and log in on the top right, it will show your user name and tile. Then go to: http://http://beta.beirutna.com/fbtest.aspx A: Check your inner exception In my case it revealed: Request for ConfigurationPermission failed while attempting to access configuration section 'facebookSettings'. To allow all callers to access the data for this section, set section attribute 'requirePermission' equal 'false' in the configuration file where this section is declared.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to permanently clear Output in Netbeans 7 I'm using Netbeans7. When I run my webapp I see a lot of info in Output tab. I doing Ctrl+L so tab getting blank. But when I run webapp one more time, all previous text appears again. Is there a way to clear Output permanently? A: Yes ... Probably it read from the log of the used server.Clean that and will solve your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Replacing value in datatable Scenario: App contains DataGridViews, I am populating the DataGridViews from a Database. All the data in the Database is encrypted so after I fill my DataTable I need to cycle through every entry in the DataTable through the decryption methods and place back in the same spot in the DataTable. How would I do such a task? Or is there a way I can decrypt the data as it is entering the dataTable? SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(query, conn); SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder(dataAdapter); DataTable dataTable = new DataTable(); dataTable.Locale = System.Globalization.CultureInfo.Invaria… dataAdapter.Fill(dataTable); //Decrypt cells int i; foreach (DataRow row in dataTable.Rows) { i = 0; foreach (var item in row.ItemArray) { //This doesn't work row.ItemArray[i] = Crypto.Decrypt(item.ToString()); i++; } } return dataTable; A: for (int i = 0; i < dataTable.Rows.Count; i++) { for (int j = 0; j < dataTable.Columns.Count; j++) { dataTable.Rows[i][j] = Crypto.Decrypt(dataTable.Rows[i][j].ToString()); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MS-Access query does not correctly interpret DBNull.Value using OLEDB.NET I am connecting to a MS-Access 2007 database using VB 2010 and OLEDB. Conducting the following test seems to suggest that MS-Access does not interpret DBNull.Value correctly when sent as a parameter from OLEDB: (The Hospital table contains 1 row with the "LatLong" column set to null) Dim cnt = Common.GetScalar(axsCon, "SELECT Count(*) FROM Hospitals WHERE LatLong = @LL ", _ New String() {"LL"}, New Object() {DBNull.Value}) This query returns cnt = 0 However: cnt = Common.GetScalar(axsCon, "SELECT Count(*) FROM Hospitals WHERE LatLong IS NULL ") returns cnt = 1 Any ideas are appreciated. p.s.: Common.GetScalar looks like: Public Shared Function GetScalar( _ ByRef OleCon As OleDbConnection, _ ByRef SQL As String, _ Optional ByRef Params() As String = Nothing, _ Optional ByRef Vals() As Object = Nothing, _ Optional IsQuery As Boolean = False) As Object Try Dim oleCmd As OleDbCommand = OleCon.CreateCommand oleCmd.CommandType = IIf(IsQuery, CommandType.StoredProcedure, CommandType.Text) oleCmd.CommandText = SQL If Not Params Is Nothing Then Dim pInx As Int16 For pInx = 0 To Params.Count - 1 oleCmd.Parameters.AddWithValue(Params(pInx), Vals(pInx)) Next End If Return oleCmd.ExecuteScalar() Catch ex As Exception Throw New Exception(ex.Message) End Try End Function TIA A: Change "SELECT Count(*) FROM Hospitals WHERE LatLong = @LL" to "SELECT Count(*) FROM Hospitals WHERE 1=     CASE         WHEN @LL IS null AND LatLong IS null THEN 1         WHEN LatLong = @LL THEN 1     END" This will then check for null or matching value. Nulls can be very very tricky. A: Your GetScalar will run the query: SELECT Count(*) FROM Hospitals WHERE LatLong = NULL but you want SELECT Count(*) FROM Hospitals WHERE LatLong IS NULL You need to switch out the = for IS if you're comparing to null.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why are instance variables in Java always private? I'm newbie to Java and I'm learning about encapsulation and saw an example where instance variables are declared as private in a class. http://www.tutorialspoint.com/java/java_encapsulation.htm I have 2 queries: * *Why are instance variables private? Why not public? *What if instance variables are made public and accessed directly? Do we see any constraints? Can you explain with an example as to what will go wrong in case the instance variables are declared as public in a class in Java? A: First, it is not true that all instance variables are private. Some of them are protected, which still preserves encapsulation. The general idea of encapsulation is that a class should not expose its internal state. It should only use it for performing its methods. The reason is that each class has a so-called "state space". That is, a set of possible values for its fields. It can control its state space, but if it exposes it, others might put it in an invalid state. For example, if you have two boolean fields, and the class can function properly only in 3 cases: [false, false], [false, true], and [true, false]. If you make the fields public, another object can set [true, true], not knowing the internal constraints, and the next method called on the original object will trigger unexpected results. A: Instance variables are made private to force the users of those class to use methods to access them. In most cases there are plain getters and setters but other methods might be used as well. Using methods would allow you, for instance, to restrict access to read only, i.e. a field might be read but not written, if there's no setter. That would not be possible if the field was public. Additionally, you might add some checks or conversions for the field access, which would not be possible with plain access to a public field. If a field was public and you'd later like to force all access through some method that performs additional checks etc. You'd have to change all usages of that field. If you make it private, you'd just have to change the access methods later on. If phone was private: Consider this case: class Address { private String phone; public void setPhone(String phone) { this.phone = phone; } } //access: Address a = new Address(); a.setPhone("001-555-12345"); If we started with the class like this and later it would be required to perform checks on the phoneNumber (e.g. some minimum length, digits only etc.) you'd just have to change the setter: class Address { private String phone; public void setPhone(String phone) { if( !isValid( phone) ) { //the checks are performed in the isValid(...) method throw new IllegalArgumentException("please set a valid phone number"); } this.phone = phone; } } //access: Address a = new Address(); a.setPhone("001-555-12345"); //access is the same If phone was public: Someone could set phone like this and you could not do anything about it: Address a = new Address(); a.phone="001-555-12345"; If you now want to force the validation checks to be performed you'd have to make it private and whoever wrote the above lines would have to change the second line to this: a.setPhone("001-555-12345"); Thus you couldn't just add the checks without breaking other code (it wouldn't compile anymore). Additionally, if you access all fields/properties of a class through methods you keep access consistent and the user would not have to worry about whether the property is stored (i.e. is a instance field) or calculated (there are just methods and no instance fields). A: Making instance variables public or private is a design tradeoff the designer makes when declaring the classes. By making instance variables public, you expose details of the class implementation, thereby providing higher efficiency and conciseness of expression at the possible expense of hindering future maintenance efforts. By hiding details of the internal implementation of a class, you have the potential to change the implementation of the class in the future without breaking any code that uses that class. Oracle White Paper A: Like has been pointed out by several answerers already, instance variables don't have to be private, but they are usually at the very least not made public, in order to preserve encapsulation. I saw an example in (I think) Clean Code, which very well illustrates this. If I recall correctly, it was a complex number (as in a+bi) type; in any case, something very much like that, I don't have the book handy. It exposed methods to get the value of the real and imaginary parts as well as a method to set the value of the instance. The big benefit of this is that it allows the implementation to be completely replaced without breaking any consumers of the code. For example, complex numbers can be stored on one of two forms: as coordinates on the complex plane (a+bi), or in polar form (φ and |z|). Keeping the internal storage format an implementation detail allows you to change back and forth while still exposing the number on both forms, thus letting the user of the class pick whichever is more convenient for the operation they are currently performing. In other situations, you may have a set of related fields, such as field x must have certain properties if field y falls inside a given range. A simplistic example would be where x must be in the range y through y+z, for numerical values and some arbitrary value z. By exposing accessors and mutators, you can enforce this relationship between the two values; if you expose the instance variables directly, the invariant falls apart immediately, since you cannot guarantee that someone won't set one but not the other, or set them so that the invariant no longer holds. Of course, considering reflection, it's still possible to access members you aren't supposed to, but if someone is reflecting your class to access private members, they had better realize that what they are doing may very well break things. If they are using the public interface, they might think everything is fine, and then they end up with nasty bugs because they unknowingly did not fully adhere to the implementation details of your particular implementation. A: They don't have to be private - but they should be. A field is an implementation detail - so you should keep it private. If you want to allow users to fetch or set its value, you use properties to do so (get and set methods) - this lets you do it safely (e.g. validating input) and also allows you to change the implementation details (e.g. to delegate some of the values to other objects etc) without losing backward compatibility. A: In traditional Object-Oriented design, a class will encapsulate both data (variables) and behavior (methods). Having private data will give you flexibility as to how the behavior is implemented, so for example, an object could store a list of values and have a getAverage() method that computes and returns the mean of these values. Later on, you could optimize and cache the computed average in the class, but the contract (i.e., the methods) would not need to change. It has become more popular the past few years (for better or worse) to use anemic data models, where a class is nothing but a bunch of fields and corresponding getters and setters. I would argue that in this design you would be better off with public fields, since the getters and setters provide no real encapsulation, but just fool you into thinking you are doing real OO. UPDATE: The example given in the link in the question is a perfect example of this degenerate encapsulation. I realize the author is trying to provide a simple example, but in doing so, fails to convey any real benefit of encapsulation (at least not in the example code). A: * *Because if you change the structure of the class (removing fields etc.); it will cause bugs. But if you have a getX() method you can calculate the needed value there (if field was removed). *You have the problem then that the class does not know if something is changed and can't guarantee integrity. A: Well keeping fields private has many advantages as suggested above. Next best level is to keep them package private using java default access level. Default level avoid cluttering in your own code and prevents clients of your code from setting invalid values. A: For user of class We, who are using ide like eclipse, netbins..... saw that it suggest us for public method, so if creator of class provide getter and setter for private instance variable you do not have to memorize the name of variable. just write set press ctrl+space you are getting all of setter method created by creator of that class and choose your desired method to set your variable value. For creator of class Sometimes you need to specify some logic to set variable value. "suppose you have an integer variable which should store 0
{ "language": "en", "url": "https://stackoverflow.com/questions/7622730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: C#: How to detect tampering of authenticode signed file I'm trying to write a C# program that verifies the digital signature of exe's. The exe's are signed with an authenticode certificate, and I want to detect tampering. I've been able to create a SignedCms instance as described here: Get timestamp from Authenticode Signed files in .NET I assumed SignedCms.CheckSignature would do the trick, but this method never throws an exception... Even not when I modify some bits of the exe... A: I'm assuming you've scoured the .NET Framework docs and didn't find what you needed. The answer to this StackOverflow question has a link that describes how to use the native Windows CryptQueryObject function to verify a signature. So all that's left is to check out PInvoke.NET to see how to bring that function into .NET. A: Could you just shell to signtool.exe /verify, and check the result? I recently wrote a simple app which signs executables using the same method, and it works great. Signtool on MSDN
{ "language": "en", "url": "https://stackoverflow.com/questions/7622732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get results from my Rails 3 controller with javascript and passed in parameters? I'm trying to get some results from my controller based one some javascript variables but I haven't the foggiest idea on how to do this. So far I have: $.ajax({ url: '/shops?state=' + state + '&city=' + city , type: 'get', dataType: 'html', complete: function(request){ $("#shop_results").html("<%= escape_javascript(render :partial => 'shop_results') %>"); } }); Which according to my rails console IS hitting my controller and sending in the parameters but my controller: def shops @maps = Map.where("state LIKE ?", "#{params[:state]}") respond_to do |format| format.html format.js end end my view: <div id="map_canvas" style="width: 980px; height: 400px"></div> <div id="shop_results"> <%= render :partial =>"shop_results"%> </div> and the shop_results partial has the code displaying the array: <ol class="shop_list" style="background:blue;"> <% @maps.each do |m| %> <li><% link_to m.shop_name ,"#" %></li> <% end %> </ol> Butttt nothing is showing up in my view where the partial is called A: Not exactly sure what you mean by "it's not returning anything in the console", but if you're doing a "like" query, wouldn't you want some % signs in there? Are you attempting to do state name completion?
{ "language": "en", "url": "https://stackoverflow.com/questions/7622738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using SSH in python I need to connect with other server via SSH using Python, execute few comands and assign result of each command to differrent variables. What is the simplest way to do it? I've tried SSHController, but I think, I've screwed up something with prompt, and the script is waiting for it endlessly. I'll be so grateful for any examples. A: There are a number of ways to use SSH from within Python. The general approaches are: * *Call the local ssh binary using subprocess.Popen() or similar (suitable only for gathering the results in batch) *Call and control the local ssh binary using pexpect or a similar pty (psuedo-TTY) process control mechanism (for spawning and interacting with a process in a terminal session in an automated manner) *Use a Python module/library, like Paramiko or Twisted conch, which implements SSH protocols (either directly in native Python, or by providing bindings to some underlying shared library ... .so or DLL). SSHController is in the second of these broad categories. My own humble utility, classh is in the first category. Your question suggests that you might be best served by exploring Paramiko because it sounds like you want to set local variable state based on the results from remote process execution. I'm guessing that you don't want any chance of conflating any sort of local terminal output or error messages with the remote command's results. In other words it sounds like you want to use SSH as an API rather than ssh as a command utility. This is an essential distinction. The ssh command tries to be as transparent as the UNIX (and analogous MS Windows, etc) environments allow. ssh opens a connection to the remote system and creates a number of channels over which remote job execution communicates. So the local ssh stdout will be from the remote commands' stdout and the local ssh stderr will be a mixture of the remote's stderr and any of the ssh command's own error messages (and other output, such as the debugging information you'd see from adding the -v, --verbose options to your ssh invocation). Similarly the ssh command's exit status will, normally, reflect the exit status from the remote shell. However it may also be the local ssh process' own exit code from a local error --- which, in my experience, seems to always be value 255. I know of no way that you could distinguish between a remote command's exit value of 255 vs. an "abend" (abnormal process end) from the local process --- and I suspect that there is not any portable, standard way to do so). My point here is that using the ssh command from within your code will, necessarily, preclude you from separating the output from local processes (the ssh binary itself, and perhaps, depending on how you're executing it, a local shell for that) and those which emanated from the remote process (and perhaps the shell in which the intended remote process is running). ssh is not an API. On the other hand if you use something like Paramiko then you establish a session over the SSH protocol and you can use, and re-use that to execute commands, transfer files, perform some other filesystem functions, and create tunnels. In that case you create an SSHClient instance and call its .exec_command() method for each command you which to execute on the remote host. This is conceptually similar to making a local function call ... it will raise an exception if the command could not be executed for any reason ... and any results you get from its stdout or stderr cannot be conflated with possible output from any intermediary processes (such as the ssh binary ... which isn't being executed at all in this case). That's why I'm recommending this approach. It sounds like you want to execute several separate commands on each remote target in a way that obviates the possible complications arising from running them all in a single call to the ssh utility and without the complications and performance overhead of making multiple calls to ssh. It sounds like your code will be much simpler and more robust if you can establish a session and use that as an API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python: adding calculated list elements I have a list of lists list_1 = [['good', 2, 2], ['bad', 2, 2], ['be', 1, 1], ['brown', 1, 3]] I would like to add new element to the inner list by summing the two numbers. So my list should look like list_1 = [['good', 2, 2, 4], ['bad', 2, 2, 4], ['be', 1, 1, 2], ['brown', 1, 2, 3]] How do I add insert new element into list by adding a column? Thanks for your help! A: for lst in list_1: lst.append(lst[1]+lst[2]) A: * *Iterate over your list of lists. *For each list in your list of lists, *Compute your new element, and append it to the list. A: list_1 = [['good', 2, 2], ['bad', 2, 2], ['be', 1, 1], ['brown', 1, 3]] print(list_1) for i in range(len(list_1)): list_1[i]+=[list_1[i][1]+list_1[i][2]] print(list_1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7622754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone and iPad, take screenshot with video playing My app need to take some screenshot when a video is being played on the screen. The video is played by AVPlayer and AVPlayerLayer. The problem when I try to use old methods, such as: UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow]; CGRect rect = [keyWindow bounds]; if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale); else UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); [keyWindow.layer renderInContext:context]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; It returns an image of the screen and a black area (which the video should be there). I can take a screenshot successfully with UIGetScreenImage() but it is a private API so I am not sure if I can use it or not A: From what I have read, many published apps have been using UIGetScreenImage(). It seems like Apple is quite lenient with its usage. Perhaps you could take a chance... A: Although a lot of time has passed - I would like to note this is now possible on iOS 7 using the snapshot command on a UIView: https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/occ/instm/UIView/snapshotViewAfterScreenUpdates:
{ "language": "en", "url": "https://stackoverflow.com/questions/7622759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How access an uiview subview partially outside of his parent uiview? I have the following UIVIew architecture (x,y,width,height) : - MainWindow (0,0,768,1024) - MainView (0,0,768,80) - containerview (500,40,120,80) - subview (500,40,120,80) -some buttons My problem is that the bottom of the subview lay outside of the bound of MainView. Buttons at the bottom of subview are not responsive. The one at the top are responsive, because their position is also inside on Mainview. So when i try to click the buttons at the bottom of subview i actually click on MainWindow! Position of bottoms buttons of subview are not inside of MainView Is there a way to make all my subview available even if half of it is outside of MainView bound? I know that i can create the subview directly under MainWindow instead, but i don't want to redo my code. Update Here how is design my views : A = MainWindow, B = MainView, C = container view, D = subview, X = where i want to click +----------------------------+ |A | |+-------------------------+ | ||B | | || +----------+ | | |+------------|C&D |-+ | | |X | | | +----------+ | +----------------------------+ THank you A: You need to implement hitTest:(CGPoint)point withEvent:(UIEvent *)event in your MainView. See the documentation Points that lie outside the receiver’s bounds are never reported as hits, even if they actually lie within one of the receiver’s subviews. Subviews may extend visually beyond the bounds of their parent if the parent view’s clipsToBounds property is set to NO. However, hit testing always ignores points outside of the parent view’s bounds. Addressing a comment: You should subclass UIView. Then set the class of MainView in the nib to your UIView subclass. Some hittesting is discussed here, but I wasn't able to find clear explanation of how it works. Try this StackOverflow question I haven't tested it, but the following code might do what you need: - (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent *)event { for(UIView *subview in self.subviews) { UIView *view = [subview hitTest:[self convertPoint:point toView:subview] withEvent:event]; if(view) return view; } return [super hitTest:point withEvent:event]; } A: I'm not 100% sure I understand what you are trying to do, but if the subview is visible but not within the MainView then the only way to get actions from subview to MainView is to receive them in the subview and pass them onto MainView. If that isn't an answer I need more information on what you are trying to accomplish. A: I just solved this myself. Like you, my 'B' view launched my 'C' view and portions of 'C' outside of 'B' were unavailable. My solution was slightly different because in my case 'C' was totally outside of, but bound to, 'B' (and was opened by 'B'). In my case, I simply attached 'C' to 'A' and made use of @property callbacks to communicate changes in 'C' with 'B' (via 'A'). In your case, another solution would be to simply extend the frame of 'B' to encompass 'C' - you can extend it back once 'C' is no longer visible. Make the background of 'B' to be clear.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using Linq to XML for XPath Style Document Searching Let's say I've got a web service response which looks like this: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <PMWSGetReportResponse xmlns="http://localhost/PCMilerWS/"> <PMWSGetReportResult> <ReportResponse> <Version>25.02</Version> <Report> <RptType>m</RptType> <TripID>011535</TripID> <StopNum>1</StopNum> <MilesReport> <StpLineType> <SRStop> <Region>NA</Region> <Address1 /> <City>Mill Valley</City> <State>CA</State> <Zip>94941</Zip> <Juris>Marin</Juris> <Lat>37894200</Lat> <Long>-122493488</Long> </SRStop> <LMiles>0.0</LMiles> <TMiles>0.0</TMiles> <LCostMile>0.00</LCostMile> <TCostMile>0.00</TCostMile> <LHours>0:00</LHours> <THours>0:00</THours> <LTolls>0.00</LTolls> <TTolls>0.00</TTolls> <LEstghg>0.0</LEstghg> <TEstghg>0.0</TEstghg> </StpLineType> <StpLineType> <SRStop> <Region>NA</Region> <Address1 /> <City>San Francisco</City> <State>CA</State> <Zip>94109</Zip> <Juris>San Francisco</Juris> <Lat>37790599</Lat> <Long>-122418809</Long> <StopWarning>False</StopWarning> </SRStop> <LMiles>13.2</LMiles> <TMiles>13.2</TMiles> <LCostMile>34.33</LCostMile> <TCostMile>34.33</TCostMile> <LHours>0:17</LHours> <THours>0:17</THours> <LTolls>12.50</LTolls> <TTolls>12.50</TTolls> <LEstghg>48.7</LEstghg> <TEstghg>48.7</TEstghg> </StpLineType> </MilesReport> </Report> </ReportResponse> </PMWSGetReportResult> </PMWSGetReportResponse> </soap:Body> </soap:Envelope> I've been trying to use Linq to XML to retrieve, say, the list of all StpLineType nodes. I've tried doing so with something like: XDocument xdoc = XDocument.Load(new StringReader(soapResponse)); var results = xdoc.Descendants("StpLineType"); But nothing is returned. I can see that the document is loaded into xdoc, but I can't seem to correctly query it. FWIW, I've also tried: XDocument xdoc = XDocument.Load(new StringReader(soapResponse)); XNamespace ns = "soap"; var results = xdoc.Descendants(ns + "StpLineType"); Just in case the namespace was causing the problem - no luck. What am I missing? A: Try XDocument xdoc = XDocument.Load(new StringReader(soapResponse)); XNamespace ns = "http://localhost/PCMilerWS/"; var results = xdoc.Descendants(ns + "StpLineType"); A: You should register the "soap" namespace using the XmlNamespaceManager. Check out this post: XDocument containing namespaces A: You're ignoring the two XML namespaces on this document! * *The root level and the <body> tag are in the soap namespace *the rest of the document is in the "default" namespace (without prefix) defined on the <PMWSGetReportResponse> element If you take that into account - things begin to work just fine! XDocument xdoc = XDocument.Load(new StringReader(soapResponse)); XNamespace soap = "http://schemas.xmlsoap.org/soap/envelope/"; XNamespace ns = "http://localhost/PCMilerWS/"; var results = xdoc.Root.Element(soap + "Body").Descendants(ns + "StpLineType"); But the main question really is: why on earth are you manually parsing a SOAP response?? .....
{ "language": "en", "url": "https://stackoverflow.com/questions/7622775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get a unique filename in perl I want to create in a directory many small files with unique names from many processes. Theoretically filenames may be the same, so how do I account for that? What module I should use for this purpose? Files should be persist. A: The package to use would be File::Temp. A: Append a timestamp to each file, up to the millisecond: #!/usr/local/bin/perl use Time::HiRes qw(gettimeofday); my $timestamp = int (gettimeofday * 1000); print STDOUT "timestamp = $timestamp\n"; exit; Output: timestamp = 1227593060768 A: Without any modules you could use something like this: time() . "_" . rand() A: $$ contains the process id of the running perl program. Therefore it can be used in file names to make them unique at least between instances of the running process. A: You probably want to use File::Temp for that. ($fh, $filename) = tempfile($template, DIR => $your_dir, UNLINK => 0);
{ "language": "en", "url": "https://stackoverflow.com/questions/7622778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Recommended way to store strings for a multi-language PHP application Normally I associate strings to keywords that describe them, and then store them in a database table with a structure of id int, id varchar(16), language char(2), string varchar. Then I make a PHP wrapper function to fetch each string depending on the visitor’s current language. I have been told (and read somewhere I think) to use PHP’s built in methods to handle internationalization. But I have not found any really “convincent” information about why it should be more appropriate than my database way to do it. What is the most appropriate method to handle internationalized websites strings and why? is there one that I should always prefer for its better performance? If there is one with a better performance then I will switch to use it. A: It depends on what your objectives are. If you need your translations to be updated on-line by website users, then your database approach is ok. However, if translations are to be provided by professional translators, then it's better to decouple the translation from the web site. Using something like gettext is a better idea in this case - you will be able to send out .po files for translation, then integrate it back into your web site. Think about the whole process, managing translators, managing changes, etc. A: There are a number of ways to skin a cat. I think you've been given this advice because PHP uses the client settings to get the default language (although, you're probably using a similar method). Either way, multiple strings have to be stored. If you prefer the db save those strings, then that works. If you're not seeing any performance issues, then go with it. No need to change what you're comfortable with. A: Gettext seems to normally depend on each proccess’ locale settings, and they depend on system installed locales too. For Web Applications consider using your own Database implementation along with some caching methods already pointed out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Change rootViewController of UIWindow animated Is there a way to change the rootViewController of an UIWindow with a transition? A: Your rootViewController is just a subview of your UIWindow. You can add other subviews and and do things like transitionFromView:toView:....
{ "language": "en", "url": "https://stackoverflow.com/questions/7622787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Refresh data Android application I made an android application that brings information using a web service, then when the application starts I put the data in a sqlite and I manage everything from my database. After the application starts the data fills a tablelayout. Now I want to REFRESH that content every 20 seconds (Because information from webservice could changed). How can I do this? I used the onResume method, but I don't want to refresh content every time you went back to the tablelayout. So what I want to do is to execute the oncreate method (which connect with a webservice, fills my tablelayout and display it) every 20 seconds. I read about timer or handler but I'm not sure how can I do this. Now i have a problem! i get data from web service and insert data in database in my doInBackground.. thats ok. Now, i create all textviews, the tablerows, etc in the onPostExecute method, but i have 2 problems. First, UsuariosSQLiteHelper usdbh = new UsuariosSQLiteHelper(this, "DBIncidentes", null, 1); I have a context problem there, in the doInBackground method and in onPostExecute method, i have the same problem with all the "this" , like TableRow rowTitulo = new TableRow(this); i know this is a context error, i know basically how context works, but i dont know how to resolve this context problem. i thought that initializing a context in the async constructor may help and i replace in the onpost.. please help! A: First off you do not want to be reading data from a web service OR writing it to a SQLite database in your onCreate method. You need to spawn a new thread for doing this so that it does not cause your application to freeze up. You could create a Thread or use an AsyncTask for this. If you use an AsyncTask, then you can override its onPostExecute method. This will be executed on the main UI thread, so you can refresh your TableLayout in this method. Once you've got this code working properly, then you just need to schedule it. The easiest way to do this is using a Timer. Here is some skeleton code to help you get started: class MyTask extends AsyncTask<Void,Void, MyDataStructure>{ @Override protected MyDataStructure doInBackground(Void... params) { MyDataStructure data = new MyDataStructure(); // get data from web service // insert data in database return data; } @Override protected void onPostExecute(MyDataStructure data) { TableLayout table = (TableLayout) findViewById(R.id.out); // refresh UI } } Timer timer = new Timer(); TimerTask task = new TimerTask(){ @Override public void run() { new MyTask().execute(); } }; long whenToStart = 20*1000L; // 20 seconds long howOften = 20*1000L; // 20 seconds timer.scheduleAtFixedRate(task, whenToStart, howOften); A: Maybe you could start a new thread that runs an infinite loop that fetches the data every 20 seconds: private Handler mHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Thread t = new Thread(new Runnable() { @Override public void run() { while (true) { fetchData(); try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t.start(); } private void fetchData() { // Get the data from the service mHandler.post(new Runnable() { @Override public void run() { // This will run on the ui thread // Update UI with the data here } }); } If you need the to refresh the data even while your activity is stopped, you should look into services: http://developer.android.com/guide/topics/fundamentals/services.html A: A timer task and a thread should work. Here is an example: Timer refreshTask = new Timer(); Thread refreshThread = new Thread(new Runnable() { public void run() { //pull data } }); refreshTask.scheduleAtFixedRate(new TimerTask(){ public void run() { onTimerTick_TimerThread(); } }, 0, 30000L); public void onTimerTick_TimerThread() { refreshThread.start(); } Please see this link as it has a better example of how to handle threading.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Binding Two Database Tables to the Same Datagrid I would like to know how I would be able to use two different tables from more Sql Compact database in the same wpf datagrid. I have two tables currently, Accounts and AccountType. There is a foreign key in Accounts to link it to the AccountType in which it is the ID number of the type. I also have a field in Accounts to link it to a parent account (essentially a foreign key to another account's id). Below is the wpf I have to bind the datagrid to the Accounts table. <Window.Resources> <my:MyAccountantDBDataSet x:Key="myAccountantDBDataSet" /> <CollectionViewSource x:Key="accountsViewSource" Source="{Binding Path=Accounts, Source={StaticResource myAccountantDBDataSet}}" /> <CollectionViewSource x:Key="accountTypeViewSource" Source="{Binding Path=AccountType, Source={StaticResource myAccountantDBDataSet}}" /> </Window.Resources> <DataGrid Background="DimGray" Name="GridAccounts" CanUserAddRows="True" CanUserDeleteRows="True" ItemsSource="{Binding Source={StaticResource accountsViewSource}}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Name" Binding="{Binding Path=AccountName}"/> <DataGridTextColumn Header="Description" Binding="{Binding Path=AccountDesc}" /> <DataGridTextColumn Header="Number" Binding="{Binding Path=AccountNumber}"/> <DataGridTextColumn Header="Type" /> <DataGridTextColumn Header="Parent Account" /> </DataGrid.Columns> </DataGrid> What I would like to do, is bind the Type column to the AccountType table and show the Type Name, not the Type id. Also, same idea for the Parent Account, I don't want to show the id number, but rather the Account Name if it has a parent account. How can I do this to these two columns? A: Can you create a view joining the two tables in the database and then query the view from C#? This way all the processing is done on the database and could be more efficient than from your application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to run multiple instances of DelayedJob in Rails? I don't mean multiple processes, I mean separate instances. I think. I may be going about this the wrong way. Right now dj handles 2 things in my application: Reports and image processing/upload. The problem is, People can create a WHOLE bunch of report jobs whenever they want, and there are no processes left over to do the images until after all those reports are run. How can I set up DelayedJob so that I can always have at least one proc dedicated to a particular function? This is collectiveidea's fork of DelayedJob, running on Rails 2.3.8. A: You can set a priority for delayed jobs which may address your problem. Set the reporting jobs to be a lower priority than the image processing and they'll be done only when there's no images to be processed. Using handle_asynchronously with a priority is covered in the readme but the syntax is basically: handle_asynchronously :my_method, :priority => 5 By default everything is priority zero which is the highest priority. A: DelayedJob 3.0.0pre supports named queues so you can have pools of workers for jobs coming through different queues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generics runtime check of 'instanceof' I have an object called Node<Value>. Objects NodeInternal<Value> and NodeLeaf<Value> inherit from Node<Value>. I am trying to test what is the type of the object using instanceof as follows: if (node instanceof NodeInternal). I did not add <Value> because upon runtime, the type is dropped. Without <Value> on NodeInternal however, I get the following warning: NodeInternal is a raw type. References to generic type NodeInternal<Value> should be parameterized. What should I do in this case? A: Use an unbounded wildcard: if (node instanceof NodeInternal<?>) node = ((NodeInternal<Value>) node).SE(); A: http://www.java2s.com/Code/Java/Language-Basics/Usetheinstanceofoperatorwithagenericclasshierarchy.htm Use <?>. You can also play games: Java: instanceof Generic
{ "language": "en", "url": "https://stackoverflow.com/questions/7622802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Tree menu using Mongoid I'm having some problems creating a tree menu using Rails 3.1 and Mongoid. I have a site model that embeds_many pages. Pages can have a parent page using a field called parent. I want to list all existing pages in an unordered list and sub pages should appear in a list under the parent, obviously. I'm fairly new to both Rails and NoSQL but hey, we all are in the beginning. Anyone have a simple solution for this? A: mongoid supports recursive embedding / tree structures. see here http://mongoid.org/docs/relations/embedded/1-n.html, scroll down to "RECURSIVE EMBEDDING / CYCLIC RELATIONS" works fine, even if the root node is itself embedded in another document.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to draw filled polygon using c++? I'm new to C++. I am using Visual studio Professional 2010. I learned to draw lines, but I need to draw filled polygon this time. The way that I drew lines is below: private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) { Graphics ^g = e->Graphics; //require for drawing g->DrawArc(Pens::Black, i-the_size/2, j-the_size/2, the_size, the_size, 0, 90 ); g->DrawArc(Pens::Black, i+the_size/2, j+the_size/2, the_size, the_size, 180, 90 );} How can I draw filled polygons using techniques similar to what I have learned so far? A: Call Graphics.FillPolygon(). You will need a brush rather than a pen and you must put your points into a point array Point[]. The sample code from MSDN is like this: // Create solid brush. SolidBrush^ blueBrush = gcnew SolidBrush( Color::Blue ); // Create points that define polygon. Point point1 = Point(50,50); Point point2 = Point(100,25); Point point3 = Point(200,5); Point point4 = Point(250,50); Point point5 = Point(300,100); Point point6 = Point(350,200); Point point7 = Point(250,250); array<Point>^ curvePoints = {point1,point2,point3,point4,point5,point6,point7}; // Draw polygon to screen. e->Graphics->FillPolygon( blueBrush, curvePoints );
{ "language": "en", "url": "https://stackoverflow.com/questions/7622809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I convert a DateTime object to a string with just the date using C#? Seemingly simple. I need to convert a DateTime object to a string without the time stamp. This gives me the date and time. And I can't figure out how to just get the date. startDate = Convert.ToString(beginningDate); This outputs: 10/1/2011 12:00:00 AM I need it to be: 10/1/2011 as a string Any help is appreciated. A: Check out .ToShortDateString() string startDate = beginningDate.ToShortDateString(); Also check out the .ToString method on DateTime that takes a format string. For example: string startDate = beginningDate.ToString("d"); Example: http://ideone.com/tpyZy A: use string startdate = beginningDate.ToShortDateString (); For MSDN reference see http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx A: you can do something like this; DateTime dt = beginningDate; StringBuilder sbDate = Convert.toString(dt.year);//and further for others month and days
{ "language": "en", "url": "https://stackoverflow.com/questions/7622818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make background fade out/in Is there any way I can use CSS3 to fade in and out a solid white background of a <div>? the content should remain visible so just the background should fade. Any ideas using css3 transitions/transforms? thank you for your help. A: Sure, you can use the transition property directly on the background-color: div { background-color: white; /* transition the background-color over 1s with a linear animation */ transition: background-color 1s linear; } /* the :hover that causes the background-color to change */ div:hover { background-color: transparent; } Here's an example of a red background fading out on :hover. A: You may find this useful for examples of image and background color fades: - http://nettuts.s3.amazonaws.com/581_cssTransitions/demos.html However using CSS 3 to do the transition will limit the effect to browsers that don't support it. A: You could have two divs in one container div. The first div contains the white background, the second one gets the content. Then, use a CSS3 transform to animate the opacity of the first div to zero.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: deleted migration file keeps coming back Rails 3 I have 2 versions of the same migration (bad habit, I know). I deleted old version many times, but after restarting my project (or do something with it, like rake db:test:prepare), the file shows up in my migrate folder. When I run rake db:migrate, it will complain about multiple migrations with the same name. How can I delete a migration file completely? Is there a registry that I need to remove to prevent it from coming back? A: Are you updating from a repo? I don't see how the original file could be restored otherwise. You can also delete the entry from the schema_migration table, but that just tracks if it's been run or not (IIRC). A: git add only adds new and changed files, it doesn't remove deleted ones. To delete: git rm db/migrate/<filename> or if you have already deleted it from the filesystem: git add -u
{ "language": "en", "url": "https://stackoverflow.com/questions/7622827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tracking HTML5 Web App installs on iOS devices We recently launched an HTML5 Web App (using JQuery Mobile), which has a slide down box encouraging users to bookmark the Web App on their home screens. Users can do this from Safari by clicking Bookmark and then "Add to Home Screen". Any thoughts on how we might be able to track the number of "installs". I don't believe we can add any tracking to the native iOS bookmarking behavior from within the HTML5 Web app. Thanks A: I'm not sure you can get an event whenever the user installs the web app on their homescreen. However, you can know if the user is in 'full screen' / 'web app' mode by checking the window.navigator.standalone property in Javascript. So you might be able to do a call to your statistics provider and provide them the standalone property as well. A: You can at least detect whether the app is launched from the homescreen or via browser via the window.navigator.standalone flag. You could use it in combination with cookies or localstorage to ensure you count unique installs in your backend. A: You can also try to store the result of window.navigator.standalone into Google Analytics
{ "language": "en", "url": "https://stackoverflow.com/questions/7622838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I improve my Trie implementation in terms of initialization? I'm trying to read in from a huge list of words and store them in a way that allows me to make quick retrievals later on. I first thought of using a trie and I'll admit my implementation is naive, it's basically nested hash tables with each key being a different letter. Right now it takes forever to insert a word into the trie (running this program takes 20+ seconds), and I was wondering if anyone had any ideas as to what I could do to improve my insertion? This isn't for homework. import string import time class Trie: def __init__(self): self.root = TrieNode() def insert_word(self, word): current_node = self.root for letter in word: trie_node = current_node.get_node(letter) current_node = trie_node class TrieNode: def __init__(self): self.data = {} def get_node(self, letter): if letter in self.data: return self.data[letter] else: new_trie_node = TrieNode() self.data[letter] = new_trie_node return new_trie_node def main(): start_time = time.time() trie = Trie() with open('/usr/share/dict/words', 'r') as dictionary: word_list = dictionary.read() word_list = word_list.split("\n") for word in word_list: trie.insert_word(word.lower()) print time.time() - start_time, "seconds" if __name__ == "__main__": main() A: It is utterly pointless working on speeding up your trie initialisation before you have considered whether your search facility is working or not. In the code that @unutbu referred to, why do you imagine it is mucking about with {'end':False} and pt['end']=True ? Here is some test data for you: words_to_insert = ['foo', 'foobar'] queries_expecting_true = words_to_insert queries_expecting_false = "fo foe foob food foobare".split() And here's another thought: You give no indication that you want anything more than the ability to determine whether a query word is present or not. If that is correct, you should consider benchmarking your DIY trie against a built-in set. Criteria: load speed (consider doing this from a pickle), query speed, and memory usage. If you do want more retrieved than a bool, then substitute dict for set and re-read this answer. If you do want to search for words in an input string, then you could consider the code referenced by @unutbu, with bugs fixed and some speedups in the find function (evaluate len(input) only once, use xrange instead of range (Python 2.x)) and the unnecessary TERMINAL: False entries removed: TERMINAL = None # Marks the end of a word def build(words, trie=None): # bugs fixed if trie is None: trie = {} for word in words: if not word: continue # bug fixed pt = trie # bug fixed for ch in word: pt = pt.setdefault(ch, {}) pt[TERMINAL] = True return trie def find(input, trie): len_input = len(input) results = [] for i in xrange(len_input): pt = trie for j in xrange(i, len_input + 1): if TERMINAL in pt: results.append(input[i:j]) if j >= len_input or input[j] not in pt: break pt = pt[input[j]] return results or you could look at Danny Yoo's fast implementation of the Aho-Corasick algorithm. A: There is an alternate implementation of Trie here. Compare Trie.insert_word to build: def build(words,trie={'end':False}): ''' build builds a trie in O(M*L) time, where M = len(words) L = max(map(len,words)) ''' for word in words: pt=trie for letter in word: pt=pt.setdefault(letter, {'end':False}) pt['end']=True return trie With Trie, for each letter in word, insert_word calls current_node.get_node(letter). This method has an if and else block, and must instantiate a new TrieNode whenever the else block is reached, and a new key-value pair is then inserted into the self.data dict. With build, the trie itself is just a dict. For each letter in word, there is simply one call to pt.setdefault(...). dict methods are implemented in C and are faster than implementing similar code in Python. timeit shows about a 2x speed difference (in favor of build): def alt_main(): with open('/usr/share/dict/words', 'r') as dictionary: word_list = dictionary.read() word_list = word_list.split("\n") return build(word_list) % python -mtimeit -s'import test' 'test.main()' 10 loops, best of 3: 1.16 sec per loop % python -mtimeit -s'import test' 'test.alt_main()' 10 loops, best of 3: 571 msec per loop
{ "language": "en", "url": "https://stackoverflow.com/questions/7622843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: dev.domain.com using subversion head code? Hello subversion experts, I'm attempting to split up my website between production and development through SVN. All the code for the website is stored in a folder called Application. My goal is to setup an SVN server with all the Application (Php) code in trunk. With this, my development server, dev.mydomain.com, would link directly to the latest trunk (head) code. Is this possible? I sort-of have the system working by checking svn code out to a folder which I then link the development server to. However, this approach is not ideal in that I nee to manually checkout the latest code to the development server each time anybody commits changes. I wish this folder could be updated automatically... If anybody has any ideas, I would be very grateful. Thanks, Mark A: You could implement a post-commit hook on the SVN server that would trigger an svn update on the development server, so that its working copy is always up to date. Or you could use a simple cron job that would do a svn update every x minutes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Suppress Non-Matching Lines in Grep Running service --status-all | grep "firestarter" in Ubuntu shows the entire output of service --status-all with the text "firestarter" highlighted in red. How do you get grep to only show the line that contains the matched text, and hide everything else? A: Maybe service --status-all writes to stderr, not stdout? Then you can use service --status-all 2>&1 | grep firestarter A: You must have some weird env variables set. Try this: service --status-all | `which grep` firestarter Or: service --status-all | /bin/grep firestarter And show the output of env and alias if possible so we can see whats wrong with your grep command. For me, I have: [ 13:55 jon@host ~ ]$ echo $GREP_OPTIONS --color=always You probably have something set there, and/or in GREP_COLOR that is causing this. A: if you don't want to use an alias, but the original command, you could try "\cmd". e.g. service --status-all | \grep "firestarter"
{ "language": "en", "url": "https://stackoverflow.com/questions/7622845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: php forgot password page I got this code from a website and I have been altering it to fit my needs. The problem that I am facing is that the password reset page is not firing a new password off by php mail but instead it is refreshing the page and the user is stuck on a php include file and not the site. I know some php but this seems to be beyond me. After 12+hrs of trying different things I am asking for help :) I hope its an easy fix. Thanks in advance for your help and code snippets. <?php include 'dbc.php'; /******************* ACTIVATION BY FORM**************************/ if ($_POST['doReset']=='Reset') { $err = array(); $msg = array(); foreach($_POST as $key => $value) { $data[$key] = filter($value); } if(!isEmail($data['user_email'])) { $err[] = "ERROR - Please enter a valid email"; header("Location: index.html?p=unknownuser"); } $user_email = $data['user_email']; //check if activ code and user is valid as precaution $rs_check = mysql_query("select id from users where user_email='$user_email'") or die (mysql_error()); $num = mysql_num_rows($rs_check); // Match row found with more than 1 results - the user is authenticated. if ( $num <= 0 ) { $err[] = "Error - Sorry no such account exists or registered."; header("Location: index.html?p=unknownuser"); //exit(); } if(empty($err)) { $new_pwd = GenPwd(); $pwd_reset = PwdHash($new_pwd); //$sha1_new = sha1($new); //set update sha1 of new password + salt $rs_activ = mysql_query("update users set pwd='$pwd_reset' WHERE user_email='$user_email'") or die(mysql_error()); $host = $_SERVER['HTTP_HOST']; $host_upper = strtoupper($host); //send email $message = "Here are your new password details ...\n User Email: $user_email \n Passwd: $new_pwd \n Thank You Administrator $host_upper ______________________________________________________ THIS IS AN AUTOMATED RESPONSE. ***DO NOT RESPOND TO THIS EMAIL**** "; mail($user_email, "Reset Password", $message, "From: \"Client Password Reset\" <[email protected]>\r\n" . "X-Mailer: PHP/" . phpversion()); header("Location: index.html?p=newpassword"); exit(); } } /* mail($user_email, "Reset Password", $message, "From: \"Client Registration\" <[email protected]>\r\n" . "X-Mailer: PHP/" . phpversion()); $msg[] = "Your account password has been reset and a new password has been sent to your email address."; //header("Location: index.html?p=newpassword"); //$msg = urlencode(); //header("Location: forgot.php?msg=$msg"); //exit(); } } */ ?> <script language="JavaScript" type="text/javascript" src="jquery/jquery-1.6.4.min.js"></script> <script language="JavaScript" type="text/javascript" src="jquery/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#actForm").validate(); }); </script> <?php /******************** ERROR MESSAGES************************************************* This code is to show error messages **************************************************************************/ if(!empty($err)) { echo "<div class=\"msg\">"; foreach ($err as $e) { echo "* $e <br>"; } echo "</div>"; } if(!empty($msg)) { echo "<div class=\"msg\">" . $msg[0] . "</div>"; } /******************************* END ********************************/ ?><div id="clientLogin">You are about to request a reset of your client account password | <a href="?p=login" class="clientLogin">Login</a><br> <form action="forgot.php" method="post" name="actForm" id="actForm" style="margin-top:5px;"> Your Email <input name="user_email" type="text" class="required email" id="txtboxn" size="25"><input name="doReset" type="submit" id="doLogin3" value="Submit" class="button"></form></div> A: You have: mail($usr_email, "Reset Password", $message...); When it looks like you should have mail($user_email, "Reset Password", $message...); Notice you used $usr_email instead of $user_email. That is why no email is being sent. Then it looks like the user is redirected to index.html?p=newpassword so depending on what that page is it may appear to just be reloading the same page. UPDATE: Also, you have the element doReset with a value of Submit and in your PHP code you are checking to see that $_POST['doReset'] == Reset instead of Submit. <input name="doReset" type="submit" id="doLogin3" value="Submit" class="button"> Change if ($_POST['doReset']=='Reset') to if ($_POST['doReset']=='Submit')
{ "language": "en", "url": "https://stackoverflow.com/questions/7622854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IoC Containers, WCF & ServiceHostFactories I have been reading about IoC lately, and I think it would definitely come in handy in the WCF web-service I am developing. However, it seems that Ninject, StructureMap and Spring.Net (I only did check these three) require the custom Factory attribute to be added to the *.svc file: <%@ ServiceHost Language="C#" Debug="true" Service="SomeService" CodeBehind="SomeService.svc.cs" Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory" %> The problem is that, due to the architecture of the system where the service will be deployed, I am already using a custom factory which is a must-have (a requirement) for this project. Can I somehow overcome this situation? A: Autofac also uses a custom factory, and I suspect they all will since this gives the IoC container a chance to be involved in the service creation process. Most (all?) of these are open source, so you might want to browse their source code and see if it would be possible to wrap the IoC custom factory in yours, or modify the source to integrate them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Picking the nearest 3 dates out of a list I am working on a TV-guide app, and am trying to get the nearest 3 dates from an NSArray with NSDictionary's. So far so good, but I have been trying to figure out how I can do this the best way using as little memory as possible and with as little code (hence decreasing the likelihood of bugs or crashes). The array is already sorted. I have a dictionary with all the channels shows for one day. The dictionary withholds an NSDate (called date). Lets say a channel has 8 shows and the time is now 11:45. show #3 started at 11:00 and ends at 12:00, show #4 starts at 12:00 and ends at 13:00, show #5 at 13:00 to 14:00 ect. How could I fetch show #3 (which started in the past!), #4 and #5 the fastest (memory wise) and easiest from my array of dictionaries? Currently I am doing a for loop fetching each dictionary, and then comparing the dictionaries date with the current date. And thats where I am stuck. Or maybe I just have a brain-fag. My current code (after a while of testing different things): - (NSArray*)getCommingProgramsFromDict:(NSArray*)programs amountOfShows:(int)shows { int fetched = 0; NSMutableArray *resultArray = [[NSMutableArray alloc] init]; NSDate *latestDate = [NSDate date]; for (NSDictionary *program in programs) { NSDate *startDate = [program objectForKey:@"date"]; NSLog(@"Program: %@", program); switch ([latestDate compare:startDate]) { case NSOrderedAscending: NSLog(@"latestDate is older, meaning the show starts in the future from latestDate"); // do something break; case NSOrderedSame: NSLog(@"latestDate is the same as startDate"); // do something break; case NSOrderedDescending: NSLog(@"latestDate is more recent, meaning show starts in the past"); // do something break; } // Now what? } return resultArray; } I am writing it for iOS 5, using ARC. A: The question asks for the "fastest (memory wise)". Are you looking for the fastest or the most memory/footprint conscious? With algorithms there is often a space vs. time tradeoff so as you make it faster, you typically do it by adding indexes and other lookup data structures which increase the memory footprint. For this problem the straight forward implementation would be to iterate through each channel and each item comparing each against the top 3 held in memory. But that could be slow. With additional storage, you could have an additional array which indexes into time slots (one per 15 minutes granularity good enough?) and then daisy chain shows off of those time slots. Given the current time, you could index straight into the current times slot and then look up the next set of shows. The array would have pointers to the same objects that the dictionaries are pointing to. That's an additional data structure to optimize one specific pattern of access but it does it at a cost - more memory. That would increase your foot print but would be very fast since it's just an array index offset. Finally, you could store all your shows in a sqlite database or CoreData and solve your problem with one query. Let the sql engine do the hard work. that wold also keep your memory foot print reasonable. Hope that sparks some ideas. EDIT: A crude example showing how you can construct a look table - an array with slots for every 15 minutes. It's instant to jump to the current time slot since it's just an array offset. Then you walk the absolute number of walks - the next three and you're out. So, it's an array offset with 3 iterations. Most of the code is building date - the lookup table, finding the time slot and the loop is trivial. NSInteger slotFromTime(NSDate *date) { NSLog(@"date: %@", date); NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date]; NSInteger hour = [dateComponents hour]; NSInteger minute = [dateComponents minute]; NSInteger slot = (hour * 60 + minute)/15; NSLog(@"slot: %d", (int)slot); return slot; } int main (int argc, const char * argv[]) { // An array of arrays - the outer array is an index of 15 min time slots. NSArray *slots[96]; NSDate *currentTime = [NSDate date]; NSInteger currentSlot = slotFromTime(currentTime); // populate with shows into the next few slots for demo purpose NSInteger index = currentSlot; NSArray *shows1 = [NSArray arrayWithObjects:@"Seinfeld", @"Tonight Show", nil]; slots[++index] = shows1; NSArray *shows2 = [NSArray arrayWithObjects:@"Friends", @"Jurassic Park", nil]; slots[++index] = shows2; // find next three -jump directly to the current slot and only iterate till we find three. // we don't have to iterate over the full data set of shows NSMutableArray *nextShow = [[NSMutableArray alloc] init]; for (NSInteger currIndex = currentSlot; currIndex < 96; currIndex++) { NSArray *shows = slots[currIndex]; if (shows) { for (NSString *show in shows) { NSLog(@"found show: %@", show); [nextShow addObject:show]; if ([nextShow count] == 3) break; } } if ([nextShow count] == 3) break; } return 0; } This outputs: 2011-10-01 17:48:10.526 Craplet[946:707] date: 2011-10-01 21:48:10 +0000 2011-10-01 17:48:10.527 Craplet[946:707] slot: 71 2011-10-01 17:48:14.335 Craplet[946:707] found show: Seinfeld 2011-10-01 17:48:14.336 Craplet[946:707] found show: Tonight Show 2011-10-01 17:48:21.335 Craplet[946:707] found show: Friends A: I'm not sure I understood your model structure, you have an NSArray of shows, each show being a NSDictionary holding the NSDate of the show along with other info, right? One idea then is to sort this NSArray of show according to the distance between the start time of the show and now. NSArray* shows = ... // your arraw of NSDictionaries representing each show NSArray* sortedShows = [shows sortedArrayUsingComparator:^(id show1, id show2) { NSTimeInterval ti1 = fabs([[show1 objectForKey:@"startDate"] timeIntervalSinceNow]); NSTimeInterval ti2 = fabs([[show2 objectForKey:@"startDate"] timeIntervalSinceNow]); return (NSComparisonResult)(ti1-ti2); }]; Then of course it is easy at that point to only take the 3 first shows of the sortedShows array. If I've misunderstood your model structure, please edit your question to specify it, but I'm sure you can adapt my code to fit your model then A: After your EDIT and explanation, here is another answer, hopefully fitting your question better. The idea is to find the index of the show that is next (startDate after now). Once you have it, it will be easy to get the show at the previous index (on air) and the 2 shows after it. NSUInteger indexOfNextShow = [arrayOfShows indexOfObjectPassingTest:^BOOL(id program, NSUInteger idx, BOOL *stop) { NSDate* startDate = [program objectForKey:@"date"]; return ([startDate timeIntervalSinceNow] > 0); // startDate after now, so we are after the on-air show }]; At that stage, indexOfNextShow contains the index of the show in your NSArray that will air after the current show. Thus what you want according to your question is objects at index indexOfNextShow-1 (show on air), indexOfNextShow (next show) and indexOfNextShow+1 (show after the next). // in practice you should check the range validity before doing this NSIndexSet* indexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(indexOfNextShow-1,3)]; NSArray* onAirShowAnd2Next = [arrayOfShows objectsAtIndexes:indexes]; Obviously in practice you should add some verifications (like indexOfNextShow being >0 before trying to access object at index indexOfNextShow-1 and indexOfNextShow+1 not being past the total number of shows in your array). The advantage of this is that since your array of shows is sorted by startDate already, indexOfObjectPassingTest: returns the first object passing the test, and stop iterating as soon as it has found the right object. So this is both concise, easy-to-read code and relatively efficient. .
{ "language": "en", "url": "https://stackoverflow.com/questions/7622858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to replace a image url in all occurrences of it in html i have a blogger blog. there is one image which i put in each of my blog's post( of my signature). earlier it was hosted on an image hosting site but now i want it to put it on my own site since the old hosting site may delete it any time. how can i replace all occurrences of the image previous url with the new url without changing it manually in each post? it is almost impossible to do it manually because i already have made more than a hundred posts. like is there any code which i can insert in the template which will replace the previous url with the new one whenever a page is opened? A: With jQuery: - $("a").each(function() { var existingURI = $(this).attr('href'); $(this).attr('href', './path_to_new_location/' + existingURI); }); If you're not sure how to use jQuery comment here and i'll give you a hand. Js Fiddle here: http://jsfiddle.net/jTnpk/ A: Are you able to copy all of your blog's HTML contents, because if you were able to then you could simply paste them into any good text editing software like Notepad++ from there you could go to "Replace..." under search and after typing in the old link in one and the new link in the other hit "Replace All" and from there you could just copy all the code and paste it back, if you have that option, if not you could add a script to the page which goes a little something like this: <script> for(i=0;i<document.links.length;i++) { if(document.links[i].href == /*Insert old link here*/) document.links[i].href = /*Insert new link here*/ ; } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7622861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java properties With properties in java how could I check if the value of the property is equal to something example if the property quitonload is equal to true then the program will exit on start A: Do you mean something like: if (System.getProperty("quitonload", "false").equals("true")) { System.exit(1); } Note the quotation marks; system properties are always strings. A: Or if you're using a Properties file you can do this: Properties p = new Properties() p.load(new FileInputStream(args[0])) if (p.getProperty("quitonload").equals("true")) { System.out.println("quitonload is true"); System.exit(1); } System.out.println("quitonload is false"); Check the documentation on the Properties file if you have any doubts on the file format. A: Properties are key/value pairs, each represented by a String if (myPropertiesObj.getProperty("quitonload").equalsIgnoreCase("true")) { ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Continuations usage in play framework example needed Can you give me some links with good examples how to use continuations in play framework?(beside source of play framework, their 'samples-and-tests' and on-site doc, already were there) Any documentation and theory in "for dummies" format are also appreciated. A: Continuations works mainly by using the await() method that is made available through your Controller. The await method can accept two different types of parameter (there are actually 6 overloads of the method, but they are simple variations on the 2 themes). The first is calling await with a timeout. This can be in milliseconds, or can be specified using a String literal expressing the time, e.g. 1s for 1 second etc. The second is calling await with a Future object, and most commonly using Play's implementation of the java Future called Promise (in the libs.F). A Promise returns when the promise is fulfilled, in that the event that is invoked as part of the Promise is completed. However, a Promise can be more than a single event, it can be multiple events. There are even options to say waitAny, so that that it only waits for one of many events to return. So, both approaches basically result in an event happening at some point in the future. The first is predetermined, the second depends on how long it takes for the Promise to be fulfilled. Play continuations is a way to make the coding of this event structure easier. You can enter some code that says // do some logic await(timeout or promise); // continue the execution Behind the scenes, the HTTP thread is released, so that Play can process more concurrent requests more efficiently. And when the timeout or promise is fulfilled, the method continues to execute, without you having to code any specific handling for the thread of execution starting up again. Taking the code from the Play site for continuations, it says public static void loopWithoutBlocking() { for(int i=0; i<=10; i++) { Logger.info(i); await("1s"); } renderText("Loop finished"); } This actually ends the thread of execution 10 times, and start a new thread after a 1 second wait. This whole thing is completely transparent from a programmers perspective, and allows you to build applications intuitively without worrying about creating non-blocking applications, as this is all magically handled by Play!
{ "language": "en", "url": "https://stackoverflow.com/questions/7622868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: GWT: Check if URL is dead I'm trying to check if a url (in String form) returns 404 error. However, I can't seem to use java.net.URL, and I read somewhere that java.net is not supported in GWT? If so, how do I check if URL is dead or not in GWT? Much appreciated. A: You are right. In client side GWT you cannot use java.net.URL. Take a look at Google's JRE Emulation Reference if you are unsure what parts of the Java standard library can be uses with GWT. Theoretically it would be possible to check a URL with an AJAX request (see RequestBuilder). But due to the same origin policy it is likely that the browser prevents such an attempt. So I think you should implement the check on your applications server side (according to the link provided by Roflcoptr above in the comments) and call that routine with GWT-RPC.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: java from for loop to recursion in finding combination how can i change this for loop to recursive in the event that if groupSize=3, n=6 will print 123 124 125 126 134 135 136 145 146 156 234 235 236 245 246 345 346 356 456 public static void printCombinations(int groupSize, int n){ if (groupSize <=n && groupSize>0 && n>0){ for (int i=1; i<=n; i++){ for (int j=1; j<=i-1; j++){ for (int k=1; k<=j-1; k++){ int first = k; int second = j; int third = i; if (i!=j && i!=k && j!=k){ System.out.println(first +" " + second +" "+ third); } } } } } } A: Probably going to be rough around the edges; I'm just learning Java. class comboMaker { public static void main(String args[]){ String[] test1 = startCombo(3,6); prnt(test1); } private static String[] startCombo(int len,int digits){ return combos(len,digits,"",0); } private static String[] combos(int len,int digits,String cur,int lastdig){ if (len>digits){ return null; } if (cur.length()==len){ return new String[]{cur}; } String tmp = cur; String[] rtn = {}; for(int i = lastdig+1;i<=digits;i++){ tmp=cur+Integer.toString(i); rtn=concat(rtn,combos(len,digits,tmp,i)); } return rtn; } private static String[] concat(String[] A, String[] B) { String[] C= new String[A.length+B.length]; System.arraycopy(A, 0, C, 0, A.length); System.arraycopy(B, 0, C, A.length, B.length); return C; } private static void prnt(String[] str){ if(str==null){ System.out.println("Invalid string array"); return; } for(int i =0;i<str.length;i++ ){ System.out.println(str[i]); } } } I included a method to concatenate arrays that I found here: How can I concatenate two arrays in Java? Also a method to print your string array generated with the combo maker. A: Create a method that will produce the suffix to a particular value with x digits and return a list of all possible suffixes. Might be something like: List<String> generateSuffixes(int prefix, int suffixSize, int maxDigitValue); The method would iterate from prefix + 1 to maxDigitValue. It would then call itself with the iterate value and suffixSize - 1. It would append the iterate to each suffix generated to create the list to return.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Whenever I use ajax to get data from my textarea and insert it into mysql, line breaks are not inserted I am using ajax to insert a form using GET. When that form is submitted, it goes into a mysql database. I know that the error is occurring when this data is being submitted into mysql and not when I am retrieving it. My problem is that all line breaks, and when you press the "enter" key are not being submitted into the database. All of the text just goes in as a straight line without breaks or anything of the sort. I would appreciate any help as to figuring out how to get these breaks to actually be inserted into mysql because this is a big problem for my site. Any help is very much appreciated. Here is the code for the ajax that I am using $echovar400= " <script language='javascript' type='text/javascript'> function ajaxFunction(){ var ajaxRequest; try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try{ ajaxRequest = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e){ // Something went wrong alert('Your browser broke!'); return false; } } } ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('pagecomments'); ajaxDisplay.innerHTML = ajaxRequest.responseText; } } var age = document.getElementById('age').value; var wpm = document.getElementById('wpm').value; var queryString = '?age=' + age + '&wpm=' + wpm; ajaxRequest.open('GET', 'ajaxprofilechat.php' + queryString, true); ajaxRequest.send(null); } </script> <form name='myForm' method='GET' > <textarea rows='4' name='message' class='comment' maxlength='250' id='age' wrap='hard'> </textarea><br><h40> <input type='hidden' id='wpm' value='$profilename'/> <input type='button' onclick='ajaxFunction()' value='Comment' /> </form> "; } ?> I realize that is not the start of the php, but the rest is unimportant. here is the code for ajaxprofilechat $age = strip_tags($_GET['age']); $wpm = $_GET['wpm']; // Escape User Input to help prevent SQL Injection $wpm = mysql_real_escape_string($wpm); $chatname6 = ($_SESSION['username']); $message6 = $_GET['site_message']; $month6 = date("F"); $dayofmonth6 = date("d"); $year6 = date("Y"); $date10 = "$month6 $dayofmonth6 $year6"; $hours6 = date("g"); $min6 = date("i"); $sec6 = date("s"); $amorpm6 = date("A"); $time6 = "$hours6:$min6 $amorpm6"; if (strlen($age)>4) { mysql_connect("","","") or die($error); mysql_select_db("") or die($error); mysql_query("INSERT INTO guestbook VALUES ('','$wpm','$chatname6','$age','$date10','$time6')"); echo "&nbsp;<h80><b>Comment Posted</b></h80<p><p>"; } else { echo "&nbsp;<h80><b>Your comment must be greater than four characters</b></h80><p>"; } ?> Any help would be great. Thanks! if you need to see my site to look at the error, here is a link to my profile page http://www.pearlsquirrel.com/profile.php?u=eggo Guys I have literally tried everything that you have told me, and in every possible way. However, i am still encountering the same problem. Should I try to use the POST method of ajax instead of GET? Do you have any other suggestions? And thank you for the help so far. A: Try $message6 = nl2br($_GET['site_message']);, then you don't have to worry about the \n or \r\n in your MySQL record since it will be stored as HTML <br /> and will display as intended during output. If you need to put it back in a textfield for edit, you'd simply use br2nl(). function br2nl($str) { return preg_replace('#<br\s*?/?>#i', "\n", $str); } A: try to wrap the POST data from the textarea with the nl2br() function nl2br
{ "language": "en", "url": "https://stackoverflow.com/questions/7622885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Generating a random 32 bit hexadecimal value in C What would be the best way to generate a random 32-bit hexadecimal value in C? In my current implementation I am generating each bit separately but the output is not completely random ... many values are repeated several times. Is it better to generate the entire random number instead of generating each bit separately? The random number should make use of the entire 32 bit address space (0x00000000 to 0xffffffff) file = fopen(tracefile,"wb"); // create file for(numberofAddress = 0; numberofAddress<10000; numberofAddress++){ //create 10000 address if(numberofAddress!=0) fprintf(file,"\n"); //start a new line, but not on the first one fprintf(file, "0 "); int space; for(space = 0; space<8; space++){ //remove any 0 from the left hexa_address = rand() % 16; if(hexa_address != 0){ fprintf(file,"%x", hexa_address); space++; break; } else if(hexa_address == 0 && space == 7){ //in condition of 00000000 fprintf(file,"%x", "0"); space++; } } for(space; space<8; space++){ //continue generating the remaining address hexa_address = rand() % 16; fprintf(file,"%x", hexa_address); } } A: x = rand() & 0xff; x |= (rand() & 0xff) << 8; x |= (rand() & 0xff) << 16; x |= (rand() & 0xff) << 24; return x; rand() doesn't return a full random 32-bit integer. Last time I checked it returned between 0 and 2^15. (I think it's implementation dependent.) So you'll have to call it multiple times and mask it. A: Do this way.It creates a bigger number than the earlier logic .If you are interested the MSB then the below logic is good .: /** x = rand() ^ rand()<<1; **/ #include <algorithm> #include <string.h> #include <ctype.h> #include <stdint.h> #include <string> #include <stdio.h> int main () { int i, n; n = 50; uint x,y ; //4294967295 :UNIT_MAX /* Intializes random number generator */ srand((unsigned) time(0)); for( i = 0 ; i < n ; i++ ) { /**WAY 1 **/ x = rand() ^ rand()<<1; printf("x:%u\t",x); printf("Difference1:(4294967295 - %u) = %u\n",x,(4294967295 - x)); /**WAY 2 **/ y = rand() & 0xff; y |= (rand() & 0xff) << 8; y |= (rand() & 0xff) << 16; y |= (rand() & 0xff) << 24; printf("y:%u\t",y); printf("Difference2:(4294967295 - %u) = %u\n",y,(4294967295 - y)); printf("Difference between two is = %u\n",(x) - (y)); } printf("End\n"); return(0); } A: You can just create any random number that's at least 32 bit wide and format that as hex. Examples: #include <stdint.h> #include <stdlib.h> #include <stdio.h> uint32_t n; n = mrand48(); // #1 n = rand(); // #2 FILE * f = fopen("/dev/urandom", "rb"); fread(&n, sizeof(uint32_t), 1, f); // #3 // ... etc. etc. E.g. Windows Crypto API char hex[9]; sprintf(hex, "%08X", n); Now hex is a string containing eight random hexadecimal digits. Don't forget to seed the various pseudo random number generators (using srand48() and srand(), respectively, for #1 and #2). Since you'll essentially have to seed the PRNGs from random source with at least one 32-bit integer, you might as well tap the random source directly (unless you're using time() or something "non-random" like that).
{ "language": "en", "url": "https://stackoverflow.com/questions/7622887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Eclipse Memory Analyzer: How to import analyze result from remote MAT by ParseHeapDump.sh? I have a large heap dump file in the remote server. And I run MAT's ParseHeapDump.sh file remotely. How can I import those analyzed files (dump.*.index) to my local MAT? I don't want to download the huge heap dump file. A: It seems like dump.*.index is just index file and I will whatever need to download the entire heap dump file A: If you want just the analysis results, you need to copy just the zip file containing those results. For example, if you used the MAT to generate "Leak suspects" report, the results would be stored as HTMLs in a zip file whose name ends with "_Leak_Suspects.zip". This file is much smaller than the heap dump. You could copy this file to you local machine and analyze the report. Here is an article that explain this - https://javaforu.blogspot.com/2013/11/analyzing-large-java-heap-dumps-when.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7622891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP FPDF - "call to a member function Stuff() on a non-object" So basically what I have been doing is convert one xml file to a well-formed pdf with wamp. The codes below are simple illustration of my idea.I learnt from the process of parsing xml to html and I suppose that the thing is all about telling xml parser the ways you would like to display on the screen.So then I did it like below: <?php require('fpdf.php'); class PDF extends FPDF { //...I skipped couple of functions like Footer() //Display stuff from string in pdf manner function Stuff($data) { $this->SetFont('Arial','',12); $this->Cell(0,4,"$data",0,1,'L',true); $this->Ln(1); } } //Parse xml start tags function start($parser,$element_name,$element_data) { ...... } //Parse xml end tags function stop($parser,$element_name) { ...... } //Parse xml contents between start tags and end tags function data($parser,$data) { $pdf->Stuff($data); } //create pdf page $pdf = new PDF(); $pdf->AliasNbPages(); $pdf->AddPage(); $pdf->SetFont('Times','',12); //Parse xml file to pdf $parser=xml_parser_create(); xml_set_element_handler($parser,"start","stop"); xml_set_character_data_handler($parser,"char"); $fp=fopen("test.xml","r"); while($data=fread($fp,4096)) { xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error:$s at line $d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); } xml_parser_free($parser); ?> Unfortunately I received this warning as I described in the title.However,I tested my xml parser functions with my start,stop and data functions individually,they all worked fine.Then I tried to convert xml to html,everything is still good.It is primarily converting to pdf that I encounter this situation when working on my idea. Could anyone give me some hints about this problem? A: In your data function, you reference $pdf->Stuff() but there is no variable $pdf so that is why you see the error. Because $pdf is not an object because it doesn't exist. Did you mean $parser->Stuff($data)? or if that function is inside of your class, then maybe it should be $this->Stuff($data) You can have the handlers in your class, you just need to specify them a bit differently. You can do xml_set_object ( $parser, $this ); xml_set_element_handler ( $parser, 'start', 'stop' ); xml_set_character_data_handler ( $parser, 'char' );
{ "language": "en", "url": "https://stackoverflow.com/questions/7622892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: User-defined Controls and Their Properties I am working on a user-defined button, this has two custom properties like this: public enum FirstType { egg, leg } // first property: public FirstType FirstProperty { get; set; } and I have a base class and 5 derived classes of this base class, and the second property will refer to one of these 5, //second property public BaseClass SecondProperty { get; set; } Now my question is: how can I have a drop down list of these 5 classes for the second property in properties window like the first one? Is it possible? A: For that property you need to create your own custom TypeConverter and override GetStandardValues This is your property: [TypeConverter(typeof(MyTypeConverter)] public BaseClass SecondProperty { get; set; } This is your type converter: public class MyTypeConverter : TypeConverter { ... public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } /// <summary> /// select only from list /// </summary> public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(/* list of derived classes */); } } A: OK,I used enum to solve my problem, first a property of this enum type, then called those classes in set statement of the property. Thanks to all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 3D world in Java using lwjgl? So I have very little experience using lwjgl and was wonrdering where I could find tutorials for making 3d worlds using it... I need to have stuff like a floor, roof, walls, and the ability to move in this area. Please help. A: An excellent modern tutorial on using OpenGL3. EDIT: New link. EDIT: Java specific tutorials (but OpenGL2) A: LWJGL's own Wiki has pretty good series of tutorials right on the front page. Note that creating actual graphics assets, both models and textures is a whole different thing than "just" progamming the game around a game engine. A: Great YouTube series on modern lwjgl 3D Engine: http://www.youtube.com/thebennybox A: You might want to take a look at jMonkeyEngine - It's built on top of LWJGL but contains a lot more higher level "game engine" features that could be helpful in constructing a 3D world. LWJGL is much more low level - so it's great if you just want direct, fast access to OpenGL functionality, but you will have to pretty much build your game engine yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Getting user profile with google oauth2 I'm trying to get user profile information upon logging in with google-oauth2. User successfully logs in and i can get the access_token and can refresh the token when needed. Though i could not manage to get any information about the user despite reading the docs and trying for hours. From "Retrieving profiles" section of developers guide : https://www.google.com/m8/feeds/profiles/domain/domainName/full should be enough. i've tried with "gmail.com", "google.com", "gmail", "google", "orkut", "orkut.com" , myregisteredappsdomainname (and .com) as domainName. i've also tried it with https://www.google.com/m8/feeds/profiles/domain/domainName/full?access_token=access_token_for_user all i managed to get was 401 error, where it says "That’s an error.". Regarding 401 error, I've refreshed the token and tried again with new token, but kept getting 401s. How can i get profile information and image address for user upon logging in? A: The scope you're looking for is: https://www.googleapis.com/oauth2/v1/userinfo This has been already answered here A: I was getting similar errors requesting profiles even after correctly defining the scope and getting access tokens etc.. The trick for me was to include the API version on my requests. See here for more info http://code.google.com/googleapps/domain/profiles/developers_guide.html#Versioning A: Maybe little late yet could this be helpful to someone. Below is the working code I wrote to get gplus user profile In HTML below markup will display goolge signIn button <span id="signinButton"> <span class="g-signin" data-callback="signinCallback" data-clientid="YOUR GPLUS CLIENT ID" data-cookiepolicy="single_host_origin" data-scope="email"> </span> </span> Below is the java script var access_token; /** * Called when the Google+ client library reports authorization status. */ function signinCallback(authResult) { access_token = authResult.access_token; gapi.client.load('plus', 'v1', function () { gapi.client.plus.people.get({ userId: 'me' }).execute(printProfile); }); } /** * Response callback for when the API client receives a response. * * @param resp The API response object with the user email and profile information. */ function printProfile(resp) { if (resp.code != 403) { console.log('name:' + access_token.givenname); console.log('last name:' + access_token.lastname); console.log('email:' + access_token.emails[0]); console.log('gender:' + access_token.gender); console.log('profile image url:' + access_token.image.url); } } Please make sure that you load google api javascript asynchronously within the body tag as below <script type="text/javascript"> (function () { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/platform.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> To handle logout refer to the answer I provide in below link, you will need to store access_token in backend so that during logout call this to be used, in my case I have stored in session and getting through ajax call gapi.auth.signOut(); not working I'm lost A: Hey why don't you look at the code given at: http://www.codeproject.com/KB/aspnet/OAuth4Client.aspx It definitely helps you. The project is actually an oauth playground to send correct oauth header to correct endpoints.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Recover a .CS class file after crash I was working on a class in visual studio 2010 when suddenly my computer crashes. after I restart the computer. I start Visual studio and I find that class to be completely empty. it contained more than 1000 lines of codes before the class. is there anyway i can recover that file? Help please because I don't have another copy of it (Stupid of me) A: Something which worked for me was back-up. BTW I was trying to recover a VS2013 file on a Windows 8 machine. Try to check in below location in your system. C:\Users\username\My Documents\Visual Studio \Backup Files\ProjectFolder I found an original file with original-date.filename.cs name and a recovered-date.filename.cs files. The original was the one needed. Deleted the one in project, added the original file and renamed it to file.cs. Tried building and debugging and it gave the expected results. A: Also just want to add one more thing... In my case i had an aspx page with its respective .cs and designer.cs The .cs file got corrupted and I did build on project, with the designer.cs the project got build successfully and the dll got replaced. And when i tried to recover using reflector everything was in a state no return. :( So don't build the project if you see any file got corrupted. A: in visual studio 2019 I find the file in a files with TMP extension FileName.cs~xxxxxxxx.TMP A: If you cannot find the source code file, try using Reflector to decompile the most recently built dll you have containing that class. It won't give you your complete source, but at least will give you something to start with. Note: Reflector is no longer free; if that matters, try dotPeek from JetBrains instead. Also, look into using a source code control system. This will let you 'commit' versions of your code to a repository, so you'll have a copy in case something like this happens in the future. Subversion, Git, and Mercurial are popular ones; In my opinion, Subversion would be the easiest to start out with, especially with TortoiseSVN (OS integration) and AnkhSVN (Visual Studio integration). If you don't want to worry about setting up a repository/server, look into a hosted solution, like Beanstalk, which offers Subversion and Git and lets you try it out with a free, limited account. Good luck - I hope you are able to recover your source! A: This happened to me a few times as well when Visual Studio was crashed or System was shutdown unexpectedly.You can recover these corrupted file using Recuva. It dose not recover the file every time but in most of the cases it's work perfectly. Below are the settings which you need to configure before recovery. * *Start Recuva. Enter Advanced mode if the Wizard launches. *Click Options. *In the Options dialog box, click the Actions tab. *Click Scan for non-deleted files, and then click OK. *Run the Recuva scan as normal. Non-deleted files are indicated with a green double-circle status icon. Hopefully, you will find your corrupted file in recovered files as it recover multiple versions for that file. A: Very useful question. I got issue of file crash on sudden shutdown of my PC. recovered file using "Recuva"(download link: https://filehippo.com/download_recuva/) software. Scan for non-deleted files was helpful. I got help from: https://www.samnoble.co.uk/2014/11/30/visual-studio-crashes-and-a-corrupted-cs-file/ A: Well, that happen recently for me and I did get my file back this way. 1. Find the project DLLs in the bin folder. Example MySolution.dll 2. Download and Install .Net Reflector from https://www.red-gate.com/products/dotnet-development/reflector/trial/thank-you 3. Open the .Net Reflector app and click the open folder icon then move to your bin directory and select MySolution.dll file 4. Then traverse and expand through your namespaces and classes to look into your codes. 5. Have fun!
{ "language": "en", "url": "https://stackoverflow.com/questions/7622901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: PHP SQL only returning 1 response instead of multiple Here's the PHP and I'll explain as I go $query = "SELECT id, attendees FROM events WHERE creator = '63' AND attendees LIKE '%74%'"; $result = mysqli_query($dbc,$query); $uid_events = mysqli_fetch_array($result,MYSQLI_ASSOC); echo $_GET['callback'] . '("' . stripslashes(json_encode($uid_events)) . '");'; It's a jquery JSONP request and I'm trying to retrieve 2 records. When I test this exact same query directly in my database I get these 2 records: 34acb43ccc4c34b911ba8b7d850a846b63 - 63,1,74 09fa87b2ed809d6741c43dd669c83e1a63 - 63,74 But the PHP echoes out: ({"id":"34acb43ccc4c34b911ba8b7d850a846b63","attendees":"63,1,74"}"); Any help would be appreciated. A: try this: while ($uid_events = mysqli_fetch_array($result,MYSQLI_ASSOC)) { echo $_GET['callback'] . '("' . stripslashes(json_encode($uid_events)) . '");'; } A: The function mysqli_fetch_array fetches only one row (or returns FALSE if there are no more rows). If you want to read all rows you should run this statement in a loop, until it returns FALSE. A: mysqli_featch_array() returns a single row, then advances the cursor to the next row. To get all rows, you need to call it in a loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DROP FUNCTION without knowing the number/type of parameters? I keep all my functions in a text file with 'CREATE OR REPLACE FUNCTION somefunction'. So if I add or change some function I just feed the file to psql. Now if I add or remove parameters to an existing function, it creates an overload with the same name and to delete the original I need type in all the parameter types in the exact order which is kind of tedious. Is there some kind of wildcard I can use to DROP all functions with a given name so I can just add DROP FUNCTION lines to the top of my file? A: Basic query This query creates all necessary DDL statements: SELECT 'DROP FUNCTION ' || oid::regprocedure FROM pg_proc WHERE proname = 'my_function_name' -- name without schema-qualification AND pg_function_is_visible(oid); -- restrict to current search_path Output: DROP FUNCTION my_function_name(string text, form text, maxlen integer); DROP FUNCTION my_function_name(string text, form text); DROP FUNCTION my_function_name(string text); Execute the commands after checking plausibility. Pass the function name case-sensitive and with no added double-quotes to match against pg_proc.proname. The cast to the object identifier type regprocedure (oid::regprocedure), and then to text implicitly, produces function names with argument types, automatically double-quoted and schema-qualified according to the current search_path where needed. No SQL injection possible. pg_function_is_visible(oid) restricts the selection to functions in the current search_path ("visible"). You may or may not want this. If you have multiple functions of the same name in multiple schemas, or overloaded functions with various function arguments, all of those will be listed separately. You may want to restrict to specific schema(s) or specific function parameter(s). Related: * *When / how are default value expression functions bound with regard to search_path? Function You can build a plpgsql function around this to execute the statements immediately with EXECUTE. For Postgres 9.1 or later: Careful! It drops your functions! CREATE OR REPLACE FUNCTION f_delfunc(_name text, OUT functions_dropped int) LANGUAGE plpgsql AS $func$ -- drop all functions with given _name in the current search_path, regardless of function parameters DECLARE _sql text; BEGIN SELECT count(*)::int , 'DROP FUNCTION ' || string_agg(oid::regprocedure::text, '; DROP FUNCTION ') FROM pg_catalog.pg_proc WHERE proname = _name AND pg_function_is_visible(oid) -- restrict to current search_path INTO functions_dropped, _sql; -- count only returned if subsequent DROPs succeed IF functions_dropped > 0 THEN -- only if function(s) found EXECUTE _sql; END IF; END $func$; Call: SELECT f_delfunc('my_function_name'); The function returns the number of functions found and dropped if no exceptions are raised. 0 if none were found. Further reading: * *How does the search_path influence identifier resolution and the "current schema" *Truncating all tables in a Postgres database *PostgreSQL parameterized Order By / Limit in table function For Postgres versions older than 9.1 or older variants of the function using regproc and pg_get_function_identity_arguments(oid) check the edit history of this answer. A: Improving original answer in order to take schema into account, ie. schema.my_function_name, select format('DROP FUNCTION %s(%s);', p.oid::regproc, pg_get_function_identity_arguments(p.oid)) FROM pg_catalog.pg_proc p LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE p.oid::regproc::text = 'schema.my_function_name'; A: You would need to write a function that took the function name, and looked up each overload with its parameter types from information_schema, then built and executed a DROP for each one. EDIT: This turned out to be a lot harder than I thought. It looks like information_schema doesn't keep the necessary parameter information in its routines catalog. So you need to use PostgreSQL's supplementary tables pg_proc and pg_type: CREATE OR REPLACE FUNCTION udf_dropfunction(functionname text) RETURNS text AS $BODY$ DECLARE funcrow RECORD; numfunctions smallint := 0; numparameters int; i int; paramtext text; BEGIN FOR funcrow IN SELECT proargtypes FROM pg_proc WHERE proname = functionname LOOP --for some reason array_upper is off by one for the oidvector type, hence the +1 numparameters = array_upper(funcrow.proargtypes, 1) + 1; i = 0; paramtext = ''; LOOP IF i < numparameters THEN IF i > 0 THEN paramtext = paramtext || ', '; END IF; paramtext = paramtext || (SELECT typname FROM pg_type WHERE oid = funcrow.proargtypes[i]); i = i + 1; ELSE EXIT; END IF; END LOOP; EXECUTE 'DROP FUNCTION ' || functionname || '(' || paramtext || ');'; numfunctions = numfunctions + 1; END LOOP; RETURN 'Dropped ' || numfunctions || ' functions'; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100; I successfully tested this on an overloaded function. It was thrown together pretty fast, but works fine as a utility function. I would recommend testing more before using it in practice, in case I overlooked something. A: Slightly enhanced version of Erwin's answer. Additionally supports following * *'like' instead of exact function name match *can run in 'dry-mode' and 'trace' the SQL for removing of the functions Code for copy/paste: /** * Removes all functions matching given function name mask * * @param p_name_mask Mask in SQL 'like' syntax * @param p_opts Combination of comma|space separated options: * trace - output SQL to be executed as 'NOTICE' * dryrun - do not execute generated SQL * @returns Generated SQL 'drop functions' string */ CREATE OR REPLACE FUNCTION mypg_drop_functions(IN p_name_mask text, IN p_opts text = '') RETURNS text LANGUAGE plpgsql AS $$ DECLARE v_trace boolean; v_dryrun boolean; v_opts text[]; v_sql text; BEGIN if p_opts is null then v_trace = false; v_dryrun = false; else v_opts = regexp_split_to_array(p_opts, E'(\\s*,\\s*)|(\\s+)'); v_trace = ('trace' = any(v_opts)); v_dryrun = ('dry' = any(v_opts)) or ('dryrun' = any(v_opts)); end if; select string_agg(format('DROP FUNCTION %s(%s);', oid::regproc, pg_get_function_identity_arguments(oid)), E'\n') from pg_proc where proname like p_name_mask into v_sql; if v_sql is not null then if v_trace then raise notice E'\n%', v_sql; end if; if not v_dryrun then execute v_sql; end if; end if; return v_sql; END $$; select mypg_drop_functions('fn_dosomething_%', 'trace dryrun'); A: Here is the query I built on top of @Сухой27 solution that generates sql statements for dropping all the stored functions in a schema: WITH f AS (SELECT specific_schema || '.' || ROUTINE_NAME AS func_name FROM information_schema.routines WHERE routine_type='FUNCTION' AND specific_schema='a3i') SELECT format('DROP FUNCTION %s(%s);', p.oid::regproc, pg_get_function_identity_arguments(p.oid)) FROM pg_catalog.pg_proc p LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE p.oid::regproc::text IN (SELECT func_name FROM f); A: As of Postgres 10 you can drop functions by name only, as long as the names are unique to their schema. Just place the following declaration at the top of your function file: drop function if exists my_func; Documentation here. A: pgsql generates an error if there exists more than one procedure with the same name but different arguments when the procedure is deleted according to its name. Thus if you want to delete a single procedure without affecting others then simply use the following query. SELECT 'DROP FUNCTION ' || oid::regprocedure FROM pg_proc WHERE oid = {$proc_oid}
{ "language": "en", "url": "https://stackoverflow.com/questions/7622908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "58" }
Q: Difference between OnlyOnRanToCompletion and NotOnFaulted? These two values are from the TaskContinuationOptions enumeration. I'm a bit unsure of which one to use. Another pair I'm confused between is NotOnRanToCompletion and OnlyOnFaulted. The wording is a bit confusing to me and each value from each pair seem to function equally. Am I missing something here? A: OnlyOnFaulted means that the continuation will run if the antecedent task throws an exception that is not handled by the task itself, unless the task was canceled. NotOnRanToCompletion means that the continuation will not run if the task ran to completion, that is to say it will run if the task threw an exception, or if it was canceled. So to summarize, if you want your continuation to run if the task is canceled or threw an exception, use NotOnRanToCompletion. If you want it to run only if it threw an exception but not if it is canceled, use OnlyOnFaulted. A: Yes: if something is canceled, it's neither faulted nor ran-to-completion; so it would be processed by NotOnRanToCompletion but not by OnlyOnFaulted. So: NotOnRanToCompletion | NotOnFaulted == OnlyOnCancelled NotOnCanceled | NotOnFaulted == OnlyOnRanToCompletion NotOnRanToCompletion | NotOnCanceld == OnlyOnFaulted
{ "language": "en", "url": "https://stackoverflow.com/questions/7622909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Fastest method to filter and get a chunk of a list of strings I have a huge list of tag strings that should be filtered by a given tag_filter. The returned joined string should contain 20 max tags \n separated. The code, right now, looks like this: tags = Tag.get_tags() #This returns the list of tags strings return '\n'.join([tag for tag in tags if tag.startswith(tag_filter)][:20]) How can I improve it avoiding to scan all the tags list after 20 tags are matched? I'm using Python 2.5. A: Use a genex and itertools.islice(). '\n'.join(itertools.islice((tag for tag in tags if tag.startswith(tag_filter)), 20)) A: See the itertools recipies: def take(n, iterable): "Return first n items of the iterable as a list" return list(islice(iterable, n)) so in your case return '\n'.join(take(20, (tag for tag in tags if tag.startswith(tag_filter)))) Edit: Really, the list call is unnecessary in this case because of join so just using islice as in Ignacio's answer is adequate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hide Facebook App Page From Search Possible Duplicate: Hide facebook app from search Okay, I know that this question was asked here: http://facebook.stackoverflow.com/questions/6904530/hide-facebook-app-from-search And the answer was that it's not 'currently' possible. HOWEVER, Facebook changes things every damn day (and that post is from August 1st), so 'currently' has absolutely no meaning to me in this case. So... having said that... is it possible to hide an App page from appearing in Facebook Search? The reasoning behind this is that it's meant to be just a Page Tab, and when a user clicks on the App Page, it's just a blank wall (why would anyone be posting to the app's wall? I don't know). I am aware that Facebook changed it so you no longer have to submit an app to search for it to appear -- it's automatic. BUT WHY WOULD THEY DO THAT?! I can't put it in Sandbox Mode, because then no one will be able to use a Page Tab. So, it seems that all of my options are exhausted. Anyone have any suggestions? Any help would be greatly appreciated. Note: What is even more frustrating is that said Page Tab is NOT EVEN set up to be an 'App' on Facebook (what used to be 'Canvas', I believe?)... it's JUST a Page Tab in the App Settings Page. A: As an option you can define a custom tab on your app which simply redirects away and set this tab as default landing tab for your app page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: getLoaderManager in ListActivity I wish to implement a Loader for in a ListActivity but the activity do not recognize getLoaderManager. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dbHelper = new DBHelper(this,DBNAME,FindPackageName(), TABLE_NAME); sql = dbHelper.getReadableDataBase(); //Log.d("Gaurav","Database Open"); String[] from = new String[]{"word","_id","MyList"}; int[] to = new int[]{R.id.listrow }; simpleCursorLoader = new SimpleCursorLoader(this, TABLE_NAME, from, null, null, null, null, null, null, sql); //query result will be whole database //cursor = sql.query(TABLE_NAME, from, null, null, null, null, null); //startManagingCursor(cursor); //this method is deprecated //Log.d(TAG,"Cursor Set"); completerOrMyListAdapter = new CompleteOrMyListAdapter(this, R.layout.completeormylist_adapter, cursor, from, to, dbHelper); setListAdapter(completerOrMyListAdapter); // Prepare the loader. Either re-connect with an existing one, // or start a new one. LoaderManager lm = getLoaderManager(); //if (lm.getLoader(0) != null) { // lm.initLoader(0, null, this); //} //getLoaderManager().initLoader(0, null, this); } A: If your app will only run on API Level 11 or higher, set your build target appropriately, and the method will be available. However, if you are using the Android Compatibility Library to have support for loaders before API Level 11, you cannot use ListActivity. You have to inherit from FragmentActivity. Either use a ListFragment, or just a plain ListView that you manage yourself. A: i think you probably use below instead getSupportLoaderManager().initLoader(0, null, this); if you use the support v4 package
{ "language": "en", "url": "https://stackoverflow.com/questions/7622913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Is it good practice to index a list of objects with a hashmap? I need to find objects by an attribute. One option is to iterate over an array of objects and check for each object that the attribute matches. The other option is to put the objects in a hashmap, with the attribute as key. Then one can simply retrieve the object by the attribute. Is the second option good practice, despite the fact that you duplicate the attribute data? Note: the attribute is assumed to be unique A: YES! From what you have given, it would generally always be better to use a Map. Finding a value in a Map (where the key has a good hash function) is O(1). Finding an element in an array or list is O(n). A: If the attribute is unique, and there's a lot of objects to search over, or you need to search over them a lot, sure--create an index. That's often the tradeoff--memory over speed. OTOH, if there aren't a lot of objects, or you don't do it a lot, it may not matter either way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: OpenGL - Fast Textured Quads? I am trying to display as many textured quads as possible at random positions in the 3D space. In my experience so far, I cannot display even a couple of thousands of them without dropping the fps significantly under 30 (my camera movement script becomes laggy). Right now I am following an ancient tutorial. After initializing OpenGL: glEnable(GL_TEXTURE_2D); glShadeModel(GL_SMOOTH); glClearColor(0, 0, 0, 0); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); I set the viewpoint and perspective: glViewport(0,0,width,height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); Then I load some textures: glGenTextures(TEXTURE_COUNT, &texture[0]); for (int i...){ glBindTexture(GL_TEXTURE_2D, texture[i]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D,3,TextureImage[0]->w,TextureImage[0]->h,GL_RGB,GL_UNSIGNED_BYTE,TextureImage[0]->pixels); } And finally I draw my GL_QUADS using: glBindTexture(GL_TEXTURE_2D, q); glTranslatef(fDistanceX,fDistanceZ,-fDistanceY); glBegin(GL_QUADS); glNormal3f(a,b,c); glTexCoord2f(d, e); glVertex3f(x1, y1, z1); glTexCoord2f(f, g); glVertex3f(x2, y2, z2); glTexCoord2f(h, k); glVertex3f(x3, y3, z3); glTexCoord2f(m, n); glVertex3f(x4, y4, z4); glEnd(); glTranslatef(-fDistanceX,-fDistanceZ,fDistanceY); I find all that code very self explaining. Unfortunately that way to do things is deprecated, as far as I know. I read some vague things about PBO and vertexArrays on the internet, but i did not find any tutorial on how to use them. I don't even know if these objects are suited to realize what I am trying to do here (a billion quads on the screen without a lag). Perhaps anyone here could give me a definitive suggestion, of what I should use to achieve the result? And if you happen to have one more minute of spare time, could you give me a short summary of how these functions are used (just as i did with the deprecated ones above)? A: Perhaps anyone here could give me a definitive suggestion, of what I should use to achieve the result? What is "the result"? You have not explained very well what exactly it is that you're trying to accomplish. All you've said is that you're trying to draw a lot of textured quads. What are you trying to do with those textured quads? For example, you seem to be creating the same texture, with the same width and height, given the same pixel data. But you store these in different texture objects. OpenGL does not know that they contain the same data. Therefore, you spend a lot of time swapping textures needlessly when you render quads. If you're just randomly drawing them to test performance, then the question is meaningless. Such tests are pointless, because they are entirely artificial. They test only this artificial scenario where you're changing textures every time you render a quad. Without knowing what you are trying to ultimately render, the only thing I can do is give general performance advice. In order (ie: do the first before you do the later ones): * *Stop changing textures for every quad. You can package multiple images together in the same texture, then render all of the quads that use that texture at once, with only one glBindTexture call. The texture coordinates of the quad specifies which image within the texture that it uses. *Stop using glTranslate to position each individual quad. You can use it to position groups of quads, but you should do the math yourself to compute the quad's vertex positions. Once those glTranslate calls are gone, you can put multiple quads within the space of a single glBegin/glEnd pair. *Assuming that your quads are static (fixed position in model space), consider using a buffer object to store and render with your quad data. I read some vague things about PBO and vertexArrays on the internet, but i did not find any tutorial on how to use them. Did you try the OpenGL Wiki, which has a pretty good list of tutorials (as well as general information on OpenGL)? In the interest of full disclosure, I did write one of them. A: I heard, in modern games milliards of polygons are rendered in real time Actually its in the millions. I presume you're German: "Milliarde" translates into "Billion" in English. Right now I am following an ancient tutorial. This is your main problem. Contemporary OpenGL applications don't use ancient rendering methods. You're using the immediate mode, which means that you're going through several function calls to just submit a single vertex. This is highly inefficient. Modern applications, like games, can reach that high triangle counts because they don't waste their CPU time on calling as many functions, they don't waste CPU→GPU bandwidth with the data stream. To reach that high counts of triangles being rendered in realtime you must place all the geometry data in the "fast memory", i.e. in the RAM on the graphics card. The technique OpenGL offers for this is called "Vertex Buffer Objects". Using a VBO you can draw large batches of geometry using a single drawing call (glDrawArrays, glDrawElements and their relatives). After getting the geometry out of the way, you must be nice to the GPU. GPUs don't like it, if you switch textures or shaders often. Switching a texture invalidates the contents of the cache(s), switching a shader means stalling the GPU pipeline, but worse it means invalidating the execution path prediction statistics (the GPU takes statistics which execution paths of a shader are the most probable to be executed and which memory access patterns it exhibits, this used to iteratively optimize the shader execution).
{ "language": "en", "url": "https://stackoverflow.com/questions/7622923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is there a more concise jQuery syntax to disable a submit button on form submit? I have the following code to disable a submit button when the form is submitted: $('#myform').submit(function(){ $('input[type=submit]', this).attr('disabled', 'disabled'); }); Is there a more concise syntax for this? A: jQuery disable plugin. $('input').disable(); //disables $('input').enable(); //enables $('input').toggleDisabled(); //toggles $('input').toggleEnabled(); //toggles $('input').toggleDisabled(true); //disables $('input').toggleEnabled(true); //enables Or, if you don't want a plugin, you can use this: jQuery.fn.disable = function() { $( this ).prop( "disabled", true ); }; $('input[type=submit]', this).disable(); A: Well, I'd give it an ID, first of all, otherwise you'll disable every submit button, which may or may not be what you intend. Other than that, that's about it unless you want to use the disable plugin. A: $('#myform').submit(function(){ $('input[type=submit]', this).prop('disabled', true); }); It can't get more concise than this. It is clean enough. I changed $.attr() with $.prop(), because this is what you should use to set and get values, which change the state of an element, but not the attribute itself. From the docs: The .prop() method should be used to set disabled and checked instead of the .attr() method. A: One cleaner version can be this: $(this).find(':submit').attr('disabled', true); also $(this).find(':submit').prop('disabled', true);
{ "language": "en", "url": "https://stackoverflow.com/questions/7622924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't install module with python-pip properly I would like to install a module but pip is not installing it in the right directory which I assume should be /usr/local/lib/python2.7/site-packages/. After all, I just installed Python 2.7.2 today. Originally I had 2.6.5 and had installed modules successfully there. So I think something is wrong with my Python path. How to have all my module installations go to the proper python2.7 directory? s3z@s3z-laptop:~$ pip install requests Requirement already satisfied: requests in /usr/local/lib/python2.6/dist-packages/requests-0.6.1-py2.6.egg Installing collected packages: requests Successfully installed requests s3z@s3z-laptop:~$ python Python 2.7.2 (default, Oct 1 2011, 14:26:08) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import requests Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named requests >>> ^Z [3]+ Stopped python Also here is what my Python directories look like now http://pastie.org/2623543 A: After you installed Python 2.7, did you install the Python 2.7 version of easy_install and PIP? The existing installations are configured to use Python 2.6 by default which may be causing your issue. A: You are probably using pip linked to python2.6, instead of 2.7. If you have installed pip properly with python2.7, you can do: pip-2.7 install requests If not, try installing this way: curl -O http://python-distribute.org/distribute_setup.py [sudo] python2.7 distribute_setup.py curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py [sudo] python2.7 get-pip.py
{ "language": "en", "url": "https://stackoverflow.com/questions/7622930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: WM_QUERYENDSESSION is not working in IE8 activeX control I have a ActiveX control written in Delphi 6 which handles WM_QUERYENDSESSION message to pop up a message box to let users to save changes before shutting down windows. It works fine in IE6 / IE7 , but in IE8 the ActiveX control cannot receive WM_QUERYENDSESSION , how to solve this? thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7622937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 1 click open more than 1 link html I made a page which I put all links next to each other. Every link opens different website. I have to click one by one to them in order to open them and there are 20 links so it takes while everytime. Is there anybody knows how can I make it so when I click only 1 link it opens all of them ? A: You can do this with JavaScript, but popup blockers and what not are going to get in the way. You're looking for window.open(). If it were me, I'd just build an all-in-one installer with NSIS, or at least zip the installers into one ZIP file to distribute.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight, open xml from outside application package I have to open and read an xml file in my Silverlight application. I can't put this file in resources (my teacher's will). I tried to use this code: XmlReader reader = XmlReader.Create("products.xml"); but got an error: Cannot find file 'products.xml' in the application xap package. This xml file is currently located in Debug folder next to .xap What should I do to make it work? XML file(just in case): <products> <product> <name>nameA</name> <desc>descA</desc> <image>imgA</image> </product> <product> <name>nameB</name> <desc>descB</desc> <image>imgb</image> </product> <product> <name>nameC</name> <desc>descC</desc> <image>imgC</image> </product> </products> Error caught in returnResult(args.Result); of Anthony's code: System.Reflection.TargetInvocationException: An exception occurred during the operation, making the result invalid. Check InnerException for exception details. ---> System.Net.WebException: An exception occurred during a WebClient request. ---> System.NotSupportedException: The URI prefix is not recognized. in System.Net.WebRequest.Create(Uri requestUri) in System.Net.WebClient.GetWebRequest(Uri address) in System.Net.WebClient.OpenReadAsync(Uri address, Object userToken) --- The end of stack trace of inner exceptions (my translation) --- in System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary() in System.Net.OpenReadCompletedEventArgs.get_Result() in ProjektAI.MainPage.<>c__DisplayClass1.<GetStreamFromUri>b__0(Object s, OpenReadCompletedEventArgs args) A: You will need the help of WebClient to download the xml file from the web server first. Here is a utility method to help. public static void GetStreamFromUri(Uri uri, Action<Stream> returnResult) { WebClient client = new WebClient(); client.OpenReadCompleted += (s, args) => { returnResult(args.Result); }; client.OpenReadAsync(uri); } Your code would then use:- GetStreamFromUri(new Uri("products.xml", UriKind.Relative), stream => { using (stream) { XmlReader reader = XmlReader.Create(stream); // Rest of reader processing code called here. } }); // Note really really well: **Code here will run before XmlReader processing** Likely the code you've written so far works synchronously. Silverlight allows resources found in the XAP to be loaded and processed synchronously. However network operations are always asynchronous. Its my guess that "(my teacher's will)" is in fact that you learn this important asynchronous aspect of Silverlight coding and what effect it has on the way you need to code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove user account from administrators group on remote machine using C# and AccountManagment namespace I have the code: public bool RemoveUserFromAdministratorsGroup(UserPrincipal oUserPrincipal, string computer) { try { PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine, computer, null, ContextOptions.Negotiate, _sServiceUser, _sServicePassword); GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, "Administrators"); oGroupPrincipal.Members.Remove(oUserPrincipal); oGroupPrincipal.Save(); return true; } catch { return false; } } It is worked without any excaption. But when i run my app again i see this user in my listview. So, the user wasn't removed. A: I have solved the issue without AccountManagment namespace. public bool RemoveUserFromAdminGroup(string computerName, string user) { try { var de = new DirectoryEntry("WinNT://" + computerName); var objGroup = de.Children.Find(Settings.AdministratorsGroup, "group"); foreach (object member in (IEnumerable)objGroup.Invoke("Members")) { using (var memberEntry = new DirectoryEntry(member)) if (memberEntry.Name == user) objGroup.Invoke("Remove", new[] {memberEntry.Path}); } objGroup.CommitChanges(); objGroup.Dispose(); return true; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return false; } } A: The below solution is for deleting the user with the help of Directory Service ... using System.DirectoryServices private DeleteUserFromActiveDirectory(DataRow in_Gebruiker) { DirectoryEntry AD = new DirectoryEntry(strPathActiveDirectory , strUsername, strPassword) DirectoryEntry NewUser = AD.Children.Find("CN=TheUserName", "User"); AD.Children.Remove(NewUser); AD.CommitChanges(); AD.Close(); } A: I don't know what is exactly your problem but coding this way : try { PrincipalContext context = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "passwd"); /* Retreive a user principal */ UserPrincipal user = UserPrincipal.FindByIdentity(context, "user1"); /* Retreive a group principal */ GroupPrincipal adminGroup = GroupPrincipal.FindByIdentity(context, @"dom\Administrateurs"); foreach (Principal p in adminGroup.Members) { Console.WriteLine(p.Name); } adminGroup.Members.Remove(user); adminGroup.Save(); } catch (Exception e) { Console.WriteLine(e.Message); } Give me the following exception : Information about the domain could not be retrieved (1355) Digging a bit arround that show me that I was running my code on a computer that was not on the target domain. When I run the same code from the server itself it works. It seems that the machine running this code must at least contact the DNS of the target domain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: InputStream not receiving EOF I am attempting to send an image from my android device to my computer via a socket. The problem is the input stream on my computer reads in every single byte but the last set of them. I have tried trimming the byte array down and sending it, I've manually written out -1 to the outputstream multiple times but the inputstream never reads -1. It just hangs waiting for data. I've also tried not closing the stream or sockets to see if it was some sort of timing issue, but that didn't work as well. Client side (Android Phone) //This has to be an objectoutput stream because I write objects to it first InputStream is = An image's input stream android ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream()); objectOutputStream.writeObject(object); objectOutputStream.flush(); byte[] b = new byte[socket.getSendBufferSize()]; int read = 0; while ((read = is.read(b)) != -1) { objectOutputStream.write(b, 0, read); objectOutputStream.flush(); b = new byte[socket.getSendBufferSize()]; } //Tried manually writing -1 and flushing here objectOutputStream.close(); is.close(); socket.close(); Server Side (Computer) This bit of code takes place after the object input stream reads in the objects sent. It only starts to read when the file starts to send File loc = Location of where the file is stored on the computer loc.createNewFile(); FileOutputStream os = new FileOutputStream(loc); Socket gSocket = The socket ObjectInputStream gInputStream = Object Input stream created from the sockets input stream already used to read in the previous objects byte[] b = new byte[gSocket.getReceiveBufferSize()]; int read = 0; while ((read = gInputStream.read(b)) != -1) { os.write(b, 0, read); os.flush(); b = new byte[gSocket.getReceiveBufferSize()]; } os.close(); This code never reads in -1 even if I write -1 directly and flush the stream. The outcome is java.net.SocketException: Connection reset when the stream or socket from the android device is closed. The picture is almost completely sent but the very last pixels of the picture are gray. I also even tried using the out/input stream directly from the socket instead of using the already created objectinputstream/objectoutputstream and it still doesn't work. A: Since you're already using ObjectInputStream and ObjectOutputStream, you can use their respective readObject and writeObject methods to read/write entire objects at a time. Maybe you could send/receive the entire byte array as an object? On your android: 1) byte[] imageBytes = ...; // contains the Image 2) objectOutputStream.writeObject(imageBytes); On your computer: 1) byte[] imageBytes = (byte[])readObject(); 2) get image from imageBytes Of course, you'll have to use readObject from within a thread since it'll block. A: Firstly, I think you misunderstood the meaning of EOF (-1). It doesn't mean the server wrote a -1, it means the server closed the stream. I think your main problem though is that both the server and the client are reading in a loop, and neither get to the point where they close the stream. They are deadlocked - both are waiting for the other one to close first. Your client: Your server: If you know that you have no more data to write then just close the stream. A: You are writing byte[] arrays as objects, bur reading bytes. You should be reading Objects and casting them to byte[]. EOS will cause an EOFException to be thrown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: defining sub-domain based on a function in routes.py of Web2Py I have this page: http://mysite.org/myapp/pages/blog?name=user9 and I need to have this: user9.mysite.org What should i write in my routes.py? A: Ok, so i think misinterpreted this a little. You need user9.mysite.org to be served from the web2py app. One way, if you have your site hosted at mysite.org, is to pass all requests (regardless of subdomain) to the web2py application (you'll need an A record like *.mysite.org with your DNS provider: http://kb.mediatemple.net/questions/791/DNS+Explained#/A_Record ) Then, you can use routes Something like: routes_in = ( ('http://(?P<user>.*).mysite.org/(?P<any>.*)', '/app/pages/blog/\g<any>?name=\g<user>'), ) The <any> will save any args you may need. This should map a request from user9.mysite.org to mysite.org/app/pages/blog/<args>?name=user9 You might have to play with it a little to get it working. The key is to make sure that a request to any subdomain of mysite.org be given directly to the app. Meaning if you go to www.mysite.org, mysite.org, somerandomfakesubdomain.mysite.org, you'll always get to the same place as mysite.org. You'll probably want to put some logic in your blog function to ensure that the subdomain string (e.g. user9) represents a valid user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error JSF 2.1.at org.apache.myfaces.view.facelets.compiler.TagLibraryConfig$LibraryHandler.endElement I have a error when run my myfaces(JSF 2.1), richfaces 4, 2.3.0.BUILD-SNAPSHOT, in Jboss 7.0.2 "Arc": 11:50:33,556 SEVERE [org.apache.myfaces.view.facelets.compiler.TagLibraryConfig] (http--127.0.0.1-8080-1) Error Loading Library: vfs:/opt/jboss-as-7.0.2.Final/standalone/deployments/projvehimerc.war/WEB-INF/lib/jsf-facelets-1.1.15.B1.jar/META-INF/jsf-html.taglib.xml: java.io.IOException: Error parsing [vfs:/opt/jboss-as-7.0.2.Final/standalone/deployments/projvehimerc.war/WEB-INF/lib/jsf-facelets-1.1.15.B1.jar/META-INF/jsf-html.taglib.xml]: at org.apache.myfaces.view.facelets.compiler.TagLibraryConfig.create(TagLibraryConfig.java:637) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.compiler.TagLibraryConfig.loadImplicit(TagLibraryConfig.java:668) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.compiler.Compiler.initialize(Compiler.java:97) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.compiler.Compiler.compileViewMetadata(Compiler.java:129) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.impl.DefaultFaceletFactory._createViewMetadataFacelet(DefaultFaceletFactory.java:355) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.impl.DefaultFaceletFactory.access$100(DefaultFaceletFactory.java:53) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.impl.DefaultFaceletFactory$2.newInstance(DefaultFaceletFactory.java:120) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.impl.DefaultFaceletFactory$2.newInstance(DefaultFaceletFactory.java:117) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.impl.FaceletCacheImpl.getViewMetadataFacelet(FaceletCacheImpl.java:112) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.impl.FaceletCacheImpl.getViewMetadataFacelet(FaceletCacheImpl.java:50) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.impl.DefaultFaceletFactory.getViewMetadataFacelet(DefaultFaceletFactory.java:430) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.impl.DefaultFaceletFactory.getViewMetadataFacelet(DefaultFaceletFactory.java:420) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage._getViewMetadataFacelet(FaceletViewDeclarationLanguage.java:2115) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.access$000(FaceletViewDeclarationLanguage.java:129) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage$FaceletViewMetadata.createMetadataView(FaceletViewDeclarationLanguage.java:2225) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.lifecycle.RestoreViewExecutor.execute(RestoreViewExecutor.java:162) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:171) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [myfaces-impl-2.1.1.jar:] at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189) [myfaces-api-2.1.1.jar:] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:90) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) [spring-web-3.0.5.RELEASE.jar:] at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) [spring-web-3.0.5.RELEASE.jar:] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:139) [jboss-as-web-7.0.2.Final.jar:7.0.2.Final] at org.jboss.as.web.NamingValve.invoke(NamingValve.java:57) [jboss-as-web-7.0.2.Final.jar:7.0.2.Final] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:154) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:667) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:952) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at java.lang.Thread.run(Thread.java:662) [:1.6.0_25] Caused by: org.xml.sax.SAXException: Error Handling [vfs:/opt/jboss-as-7.0.2.Final/standalone/deployments/projvehimerc.war/WEB-INF/lib/jsf-facelets-1.1.15.B1.jar/META-INF/jsf-html.taglib.xml@25,74] <library-class> at org.apache.myfaces.view.facelets.compiler.TagLibraryConfig$LibraryHandler.endElement(TagLibraryConfig.java:454) [myfaces-impl-2.1.1.jar:] at org.apache.xerces.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:596) at org.apache.xerces.impl.dtd.XMLNSDTDValidator.endNamespaceScope(XMLNSDTDValidator.java:221) at org.apache.xerces.impl.dtd.XMLDTDValidator.handleEndElement(XMLDTDValidator.java:2049) at org.apache.xerces.impl.dtd.XMLDTDValidator.endElement(XMLDTDValidator.java:923) at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanEndElement(XMLNSDocumentScannerImpl.java:673) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(XMLDocumentFragmentScannerImpl.java:1645) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:324) at org.apache.xerces.parsers.XML11Configuration.parse(XML11Configuration.java:845) at org.apache.xerces.parsers.XML11Configuration.parse(XML11Configuration.java:768) at org.apache.xerces.parsers.XMLParser.parse(XMLParser.java:108) at org.apache.xerces.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1196) at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:555) at org.apache.xerces.jaxp.SAXParserImpl.parse(SAXParserImpl.java:289) at javax.xml.parsers.SAXParser.parse(SAXParser.java:198) [:1.6.0_25] at org.apache.myfaces.view.facelets.compiler.TagLibraryConfig.create(TagLibraryConfig.java:632) [myfaces-impl-2.1.1.jar:] ... 61 more 11:50:33,802 INFO [org.apache.myfaces.util.ExternalSpecifications] (http--127.0.0.1-8080-1) MyFaces Unified EL support enabled 11:50:33,974 INFO [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/projvehimerc]] (http--127.0.0.1-8080-1) No state saving method defined, assuming default server state saving 11:50:34,859 INFO [org.apache.myfaces.config.annotation.TomcatAnnotationLifecycleProvider] (http--127.0.0.1-8080-2) Creating instance of org.richfaces.skin.SkinBean This is my web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!-- Log4j configurated in spring!!!, before any code directly calling log4j (calling through commons logging doesn't count)? Jing Xue --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j-webapp.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>1000</param-value> </context-param> <context-param> <param-name>webAppRootKey</param-name> <param-value>myWebapp-instance-root</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <display-name>richfaces-application</display-name> <!-- Listener para crear el Spring Container compartido por todos los Servlets y Filters (WebApplication Context)--> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:META-INF/spring/spring-master.xml WEB-INF/spring/spring-security.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- For JSF --> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <!-- Jboss not use it bundle integrated JSF --> <context-param> <param-name>org.jboss.jbossfaces.WAR_BUNDLES_JSF_IMPL</param-name> <param-value>true</param-value> </context-param> <!-- Facelets, tell JSF to use Facelets --> <context-param> <param-name>org.ajax4jsf.VIEW_HANDLERS</param-name> <param-value>com.sun.facelets.FaceletViewHandler</param-value> </context-param> <!-- Spring JavaServiceFaces framework ApacheMyfaces --> <listener> <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class> </listener> <!-- Spring Security, for all --> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- RichFaces Framework --> <!-- RichFaces 4, no more Filter!!! <filter> <filter-name>richfaces</filter-name> <filter-class>org.ajax4jsf.Filter</filter-class> </filter> <filter-mapping> <filter-name>richfaces</filter-name> <servlet-name>faces</servlet-name> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> </filter-mapping> <filter-mapping> <filter-name>richfaces</filter-name> <servlet-name>transportes</servlet-name> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> </filter-mapping> --> <context-param> <param-name>org.richfaces.SKIN</param-name> <param-value>blueSky</param-value> </context-param> <!-- For control of skins --> <context-param> <param-name>org.richfaces.CONTROL_SKINNING_CLASSES</param-name> <param-value>enable</param-value> </context-param> <!-- Servlets for JSF--> <servlet> <servlet-name>faces</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>faces</servlet-name> <url-pattern>*.xhtml</url-pattern> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <!-- Servlet for Dispatcher of flows --> <servlet> <servlet-name>transportes</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/spring/transportes-servlet.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>transportes</servlet-name> <url-pattern>/flows/*</url-pattern> </servlet-mapping> <!-- Servlet register for SpringFaces, SpringJavaScript --> <servlet> <servlet-name>resources</servlet-name> <servlet-class>org.springframework.js.resource.ResourceServlet</servlet-class> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>resources</servlet-name> <url-pattern>/resources/*</url-pattern> </servlet-mapping> <!-- Page That control SpringWeb --> <!-- <error-page> <error-code>404</error-code> <location>/WEB-INF/jsp/error.jsp</location> </error-page> --> <welcome-file-list> <welcome-file>/WEB-INF/flows/inscripcion/login.xhtml</welcome-file> </welcome-file-list> </web-app> Why is this error? thnks. A: Not sure about the cause (perhaps corrupt JAR?), but you definitely shouldn't have the old Facelets 1.x jsf-facelets.jar in a JSF 2.x project. The JSF 2.x libraries already bundles Facelets 2.x. So removing the offending JAR should at least fix this problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use Android OS VirtualBox as device in Eclipse I found this tutorial on how to run Android OS here: http://www.javacodegeeks.com/2010/06/install-android-os-on-pc-with.html Has anyone tried to use the set-up as a replacement for the emulator? If so, how did you do it? A: I haven't used the guide you link to, but instead downloaded an eeepc image from the Android x86 Project. The steps I followed are: * *Install Android to a virtual PC - I used a 64bit virtual machine, enabled all the hardware virtualisation, and used the PCnet-FAST III virtual network adapter in bridged mode - see image 1 *Disable host mouse pointer integration - this will allow Android to display it's own mouse pointer so you know where you're clicking. *You need to work out what IP address the VM has, so that you can connect with adb connect <YOUR_VIRTUALBOX_IP>. I do this by logging into my router and identifying the IP of the device that shares the port with my laptop, since that's the Android VM using bridged networking. See image 2. You are supposed to be able to use VBoxManage commands to identify the IP of the guest, but I've never gotten those working, so the router method is the only one I have that works. Performance is pretty good - much quicker than running hte ARM emulator, though of course, you can only run Android versions that have been compiled for x86. A: You are supposed to be able to use VBoxManage commands to identify the IP of the guest, but I've never gotten those working, so the router method is the only one I have that works. Hit Alt + F1. when the root@android prompt comes up, type netcfg and press enter. That will show you the IP address. Hit Alt + F7 to get back to the GUI.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ASP.NET MVC 3 - How to Reuse Solution? What's the best way to structure the base functionality of an ASP.NET MVC 3 solution so it can be reused in subsequent solutions? For example, I'm going to develop a basic skeleton MVC app with user registration using email verification, enhanced users/right/roles, blogging with comments, and a forum. I understand maintaining the business logic in class libraries but how about the controllers and views? Do I basically have to just copy and paste my base solution to create each of my new solutions? A: * *Creating a Custom ASP.NET MVC Project Template *templify
{ "language": "en", "url": "https://stackoverflow.com/questions/7622974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mechanize - Simpliest way to check if page have been updated? What is the simpiest solution with Mechanize to see if a page have been updated? I was thinking about create a table named pages. That would have: pagename - varchar page - text pageupdated - boolean How should I create the screen scraper and save the data in the database? And how to create an method to compare the html in the table with the scraped data. To check if the page have been updated. A: Answer updated and tested. Here's an example using a Page model (and using retryable-rb): rails generate scaffold Page name:string remote_url:string page:text digest:text page_updated:boolean ####### app/models/page.rb require 'digest' require 'retryable' class Page < ActiveRecord::Base include Retryable # Scrape page before validation before_validation :scrape_content, :if => :remote_url? # Will cause save to fail if page could not be retrieved validates_presence_of :page, :if => :remote_url?, :message => "URL provided is invalid or inaccessible." # Update digest if/when all validations have passed before_save :set_digest # ... def update_page! self.scrape_content self.set_digest self.save! end def page_updated? self.page_updated end protected def scrape_content ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X) ' + 'AppleWebKit/535.1 (KHTML, like Gecko) ' + 'Chrome/14.0.835.186 Safari/535.1' # Using retryable, create scraper and get page scraper = Mechanize.new{ |i| i.user_agent = ua } scraped_page = retryable(:times => 3, :sleep => false) do scraper.get(URI.encode(self.remote_url)) end self.page_updated = false self.page = scraped_page.content self.name ||= scraped_page.title self.digest ||= Digest.hexencode(self.page) end def set_digest # Create new digest of page content new_digest = Digest.hexencode(self.page) # If digest has changed, update digest and set flag if (new_digest != self.digest) && !self.digest.nil? self.digest = new_digest self.page_updated = true else self.page_updated = false end true end end I'm fairly sure this is an unrelated matter, but I seem to be encountering an LoadError when trying to require 'mechanize' in rails console and my test application. Not sure what's causing this, but I'll update my answer when I'm able to successfully test this solution. Make sure you remember to add this to your application's Gemfile: gem 'mechanize', '2.0.1' gem 'retryable-rb', '1.1.0' Usage Example: p = Page.new(:remote_url => 'http://rubyonrails.org/') p.save! p.page_updated? # => false, since page hasn't been updated since creation p.remote_url = 'http://www.google.com/' # for the sake of example p.update_page! p.page_updated? # => true
{ "language": "en", "url": "https://stackoverflow.com/questions/7622977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Updating Oracle Table using Stored Procedure from C# Odd bug I am using a stored procedure to Insert a new user or update their existing information if the user already exists in the Database. I am grabbing 3 of the Parameters (User name, first name, and last name) from Active Directory and using 4 textboxes to grab the rest (PI Code, phone, email, address). <asp:TextBox ID="TXT_PI_CODE" runat="server" style="position: absolute; left:120px; top:100px;"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator_PI_CODE" runat="server" ErrorMessage="" ControlToValidate="TXT_PI_CODE"></asp:RequiredFieldValidator> <br /> <asp:TextBox ID="TXT_EMAIL" runat="server" style="position: absolute; left:120px; top:140px;"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator_EMAIL" runat="server" ErrorMessage="" ControlToValidate="TXT_EMAIL"></asp:RequiredFieldValidator> <asp:RegularExpressionValidator ID="RegularExpressionValidator_EMAIL" runat="server" ErrorMessage="Invalid Email Format." ControlToValidate="TXT_EMAIL" style="position: absolute; top:140px; left:300px;" ValidationExpression="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"></asp:RegularExpressionValidator> <br /> <asp:TextBox ID="TXT_PHONE" runat="server" style="position: absolute; left:120px; top:180px;"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator_PHONE" runat="server" ErrorMessage="" ControlToValidate="TXT_PHONE"></asp:RequiredFieldValidator> <br /> <asp:TextBox ID="TXT_ADDRESS" runat="server" style="position: absolute; left:120px; top:220px;" Width="200"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator_ADDRESS" runat="server" ErrorMessage="" ControlToValidate="TXT_ADDRESS"></asp:RequiredFieldValidator> <br /> <asp:Label ID="LBL_REQUIRED" runat="server" Text="*Required Fields" CssClass="labels" style="position: absolute; top:260px;" ForeColor="#FF9900"></asp:Label> <asp:Button ID="BTN_SUBMIT" runat="server" Text="Submit" style="position: absolute; top:300px; left:120px;" Width="100" Height="40" OnClick="BTN_SUBMIT_Click"/> My Stored Procedure is as follows: create or replace PROCEDURE SP_ADD_USER ( p_USER_NAME IN T_USER.USER_NAME%TYPE, p_FIRST_NAME IN T_USER.FIRST_NAME%TYPE, p_LAST_NAME IN T_USER.LAST_NAME%TYPE, p_PI_CODE IN T_USER.PI_CODE%TYPE, p_EMAIL IN T_USER.EMAIL%TYPE, p_PHONE IN T_USER.PHONE%TYPE, p_ADDRESS IN T_USER.ADDRESS%TYPE ) AS BEGIN INSERT INTO T_USER (USER_ID, USER_NAME, FIRST_NAME, LAST_NAME, PI_CODE, EMAIL, PHONE, ADDRESS) VALUES (S_USER.NEXTVAL, p_USER_NAME, p_FIRST_NAME, p_LAST_NAME, p_PI_CODE, p_EMAIL, p_PHONE, p_ADDRESS); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN UPDATE T_USER SET PI_CODE = p_PI_CODE, EMAIL = p_EMAIL, PHONE = p_PHONE, ADDRESS = p_ADDRESS WHERE LOWER(USER_NAME) = p_USER_NAME; COMMIT; END; And finally my C# looks like this: protected void BTN_SUBMIT_Click(object sender, EventArgs e) { //Retrieve Username, firstname, and last name from AD. string STR_USER_ID = ADQuery.ExtractUserName(User.Identity.Name.ToString()); string STR_FIRST_NAME = ADQuery.GetADValue(STR_USER_ID, "givenName"); string STR_LAST_NAME = ADQuery.GetADValue(STR_USER_ID, "SN"); string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; using(OracleConnection connection = new OracleConnection(connectionString)) { connection.Open(); OracleCommand ora_cmd = new OracleCommand("SP_ADD_USER", connection); ora_cmd.BindByName = true; ora_cmd.CommandType = CommandType.StoredProcedure; ora_cmd.Parameters.Add("p_USER_NAME", OracleDbType.Varchar2, STR_USER_ID.ToLower(), ParameterDirection.Input); ora_cmd.Parameters.Add("p_FIRST_NAME", OracleDbType.Varchar2, STR_FIRST_NAME, ParameterDirection.Input); ora_cmd.Parameters.Add("p_LAST_NAME", OracleDbType.Varchar2, STR_LAST_NAME, ParameterDirection.Input); ora_cmd.Parameters.Add("p_PI_CODE", OracleDbType.Varchar2, TXT_PI_CODE.Text, ParameterDirection.Input); ora_cmd.Parameters.Add("p_EMAIL", OracleDbType.Varchar2, TXT_EMAIL.Text, ParameterDirection.Input); ora_cmd.Parameters.Add("p_PHONE", OracleDbType.Varchar2, TXT_PHONE.Text, ParameterDirection.Input); ora_cmd.Parameters.Add("p_ADDRESS", OracleDbType.Varchar2, TXT_ADDRESS.Text, ParameterDirection.Input); ora_cmd.ExecuteNonQuery(); } Response.Redirect("Default.aspx"); } The insert portion works fine as a new user, however when attempting to update the information in the same text boxes nothing has updated on the database after the postback. However the oddity is that if I change my C# to ora_cmd.Parameters.Add("p_PI_CODE", OracleDbType.Varchar2, TXT_EMAIL.Text, ParameterDirection.Input); ora_cmd.Parameters.Add("p_EMAIL", OracleDbType.Varchar2, TXT_EMAIL.Text, ParameterDirection.Input); where both of those parameters are populated from the same textbox it will update the PI_CODE field on the database with what was originally in the email address textbox, but the email address will remain unchanged on the database. I don't know if there is some bug I am missing or my syntax is off? I've made sure my parameter orders are correct, or what I believe is correct. Anyone seen this before? A: Figured out how to fix the textboxes ignoring the changes. Placing the textbox populate code inside of an if(!IsPostback) allowed the program to use the newly updated values in the textbox instead of the old ones. Hope this helps someone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to left align peoperly my logo I have a page and its header navihation is properly inherit therefore its coming to the center. But the Logo which is not coming to proper left, its going to left side of the page. HTML <title>VRBO</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="main_layout"> <div id="header_menu"> <center> <a href="#"><img src="images/nav_header.png" width="900" height="43" /></a> </center> </div> <div id="header_logo"> <img src="images/logo.png" class="logoImage" width="96" height="96" /> </div> </div> </body> </html> CSS html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } a {text-decoration:none;} body { } h1,h2,h3,h4,h5 { font-family:Verdana, Geneva, sans-serif; font-weight:normal; line-height:100%; margin-top: 0; } #main_layout { background-image: url(images/vrbo_bg.jpg); background-repeat: no-repeat; background-position: center top; height: auto; min-height: 100%; min-width: 900px; left: 0px; top: 0px; position: fixed; width: 100%; } #header_menu { overflow:hidden; width: 100%; } #header_menu img { float:inherit; margin:0px; } #header_logo { overflow: hidden; width: 100%; float:inherit; margin:0px; } #header_logo img.logoImage { float: left; margin-left: 10px; } Also could you please let me know what I did wrong ? Thanks!!! A: Put the logo in the header_menu div and you should be fine; if that's where you want it (over the header image). Check out this jsfiddle where I have set logo to float:left and menu to float:right within the header div, which acts as a container for the elements. In the example, margin: 0px auto makes the header centered on the page (so you don't need the center tags) as long as the width and height are given. If you want to adjust the position of the logo or menu within the header div, simply add margin properties. A: I don't know if it's related to your problem because you didn't post any HTML - but you are missing a } in your #header_menu definition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make content automatically go into multiple pages On a site such as http://failblog.org/, there are a bunch of photos with content around them. Whenever failblog uploads a new photo, it pushes the bottom photo of the first page onto the second page, and the bottom of the second onto the third, etc. How can I do this? I want to have a section of HTML (such as the contents of a <div>) automatically wrap onto multiple pages, and everything not inside the section will repeat. (As on failblog.org). Thank you. A: Ok, you have 2 options. Server-Side Only You need something called pagination to occur- when there is too much content to display on one page, server-side code can create virtual "pages" for each page of content to display. This can't be solved with HTML, Javascript, or CSS, this depends on the server-side language (such as PHP, Ruby, Python, etc) that you are working with. AJAX If you want to flip through content, though on the same page, then you might consider looking at a jQuery plugin that can do that for you. Here's a list of plugins that look like they might suit your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: flash / as2 loadmovie issue I'm using the loadMovie(url,target); command to load an external swf file into a movieclip container. The problem is that the external swf is sort of dynamic, when a user clicks on any links inside the swf it does a little loading screen to load more content. So when I load that movie into my swf and click on links it does nothing. Does anyone know a workaround for this? extswf.loadMovie("http://mydomain.com/ext_swf.swf");
{ "language": "en", "url": "https://stackoverflow.com/questions/7622981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert data from other table and update on duplicate key I have this query where I want to insert into table exp_channel_data data from the table homes but it inserts 7 and 8 entries and then returns the error: [Err] 1062 - Duplicate entry '8' for key 'PRIMARY' This is my query (I reduced the fields to be readable): INSERT INTO exp_channel_data (entry_id,site_id,channel_id,field_id_1) SELECT 7,1,1,summary FROM homes ON DUPLICATE KEY UPDATE entry_id = entry_id+1 A: If you want to copy all your homes table data into the new one: INSERT INTO exp_channel_data (entry_id, site_id, channel_id, field_id_1) SELECT homes_id + (COALESCE(maxExp,0) + 1 - minHomes) , site_id, channel_id, summary FROM homes AS h CROSS JOIN ( SELECT MAX(entry_id) AS maxExp FROM exp_channel_data ) AS mh CROSS JOIN ( SELECT MIN(homes_id) AS minHomes FROM exp_channel_data ) AS me
{ "language": "en", "url": "https://stackoverflow.com/questions/7622984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Equivalent to C#'s Delegates/Events: Changing Event Invoked Code Dynamically I have a simple Screen class in C# that has a bunch of events (with corresponding delegates) like the FadeOutEvent. I want to port my library to Java, and I find that the mechanism for events/delegates is really cludgey. Specifically, I cannot easily write code like: if (someVar == someVal) { this.FadeOutComplete += () => { this.ShowScreen(new SomeScreen()); }; } else { this.FadeOutComplete += () => { this.ShowScreen(new SomeOtherScreen()); }; } For all you Java-only guys, essentially, what I'm whinging about is the inability to reassign the event-handling method in the current class to something else dynamically, without creating new classes; it seems that if I use interfaces, the current class must implement the interface, and I can't change the code called later. In C#, it's common that you have code that: * *In a constructor / early on, assign some event handler code to an event *Later during execution, remove that code completely *Often, change that original handler to different handler code Strategy pattern can solve this (and does), albeit that I need extra classes and interfaces to do it; in C#, it's just a delcarative event/delegate and I'm done. Is there a way to do this without inner/anonymous classes? Edit: I just saw this SO question, which might help. A: Most of the time, it's done the other way round: this.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (someVar == someVal) { showSomeScreen(); } else { showSomeOtherScreen(); } } }); But you could do something similar to your C# code by delegating to two other objects: private Runnable delegate; // ... this.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { delegate.run(); } }); // ... if (someVar == someVal) { this.delegate = new Runnable() { @Override public void run() { showSomeScreen(); } }; } else { this.delegate = new Runnable() { @Override public void run() { showSomeOtherScreen(); } }; } Delegates were proposed by Microsoft for Java a long long time ago, and were refused by Sun. I don't remember if anonymous inner classes already existed at that time or if they were chosen as the alternative. A: With lambdas in JDK 1.8 / Java 8: private Runnable delegate; public void delegateTest() { // ... this.addActionListener(e -> delegate.run()); // ... if (someVar == someVal) { this.delegate = () -> showSomeScreen(); } else { // or like this: this.delegate = this::showSomeOtherScreen; } } private void showSomeOtherScreen() { } private void showSomeScreen() { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to check if it has class in jQuery? How can I check if a the #load div has a class also? if (cap > 20) { $(".p" + (cap-9)).slideto({ slide_duration : 'slow' }); } A: you could try just adding a class to the button once it's been clicked: $("#loadmore").click(function() { cap += 10; $(this).addClass("loadmore-clicked"); $(".p" + (cap-10)).addClass("loading"); setTimeout(function() { $(".p" + (cap-10)).removeClass('loading'); }, 7000); loadfeed(); }); And then just see if you have that class on the button below: function loadfeed(){ if ($("#loadmore").hasClass("loadmore-clicked")){ //loadmore was clicked }else{ //loadmore hasn't been clicked } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: error with devise in ruby on rails So, I have never used devise before and am trying to implement it in my program via http://railscasts.com/episodes/209-introducing-devise. I installed it and everything word for word as this guy did and then when I try and go to http://localhost:3000/users/sign_up, I get this error: Routing Error No route matches [GET] "/users/sign_up" here is what I get when I do rake route: new_user_session GET /users/sign_in(.:format) {:action=>"new", :controller=>"devise/sessions"} user_session POST /users/sign_in(.:format) {:action=>"create", :controller=>"devise/sessions"} destroy_user_session GET /users/sign_out(.:format) {:action=>"destroy", :controller=>"devise/sessions"} password POST /users/password(.:format) {:action=>"create", :controller=>"devise/passwords"} new_password GET /users/password/new(.:format) {:action=>"new", :controller=>"devise/passwords"} edit_password GET /users/password/edit(.:format) {:action=>"edit", :controller=>"devise/passwords"} PUT /users/password(.:format) {:action=>"update", :controller=>"devise/passwords"} POST /users/registration(.:format) {:action=>"create", :controller=>"devise/registrations"} new GET /users/registration/sign_up(.:format) {:action=>"new", :controller=>"devise/registrations"} edit GET /users/registration/edit(.:format) {:action=>"edit", :controller=>"devise/registrations"} PUT /users/registration(.:format) {:action=>"update", :controller=>"devise/registrations"} DELETE /users/registration(.:format) {:action=>"destroy", :controller=>"devise/registrations"} vote_post POST /posts/:id/vote(.:format) {:action=>"vote", :controller=>"posts"} posts GET /posts(.:format) {:action=>"index", :controller=>"posts"} POST /posts(.:format) {:action=>"create", :controller=>"posts"} new_post GET /posts/new(.:format) {:action=>"new", :controller=>"posts"} edit_post GET /posts/:id/edit(.:format) {:action=>"edit", :controller=>"posts"} post GET /posts/:id(.:format) {:action=>"show", :controller=>"posts"} PUT /posts/:id(.:format) {:action=>"update", :controller=>"posts"} DELETE /posts/:id(.:format) {:action=>"destroy", :controller=>"posts"} root / {:controller=>"users", :action=>"index"} If you watch the video the guy is just able to go to that web address and it just works. I noticed that there is a [GET] /users/registration/sign_up(.:format) but no [GET] /users/sign_up like the guy in the video has. Is there something I am missing? p.s. this is the error I get when I try to go to one of the routes listed above (user/sign_in): NoMethodError in Devise/registrations#new Showing /Users/davidfleischhauer/.rvm/gems/ruby-1.9.2-p290/gems/devise- 1.1.rc0/app/views/devise/registrations/new.html.erb where line #3 raised: undefined method `user_registration_path' for #<#<Class:0x007f85eafec758>:0x007f85eaf77ed0> A: You have to use new_user_registration_path in order to create a link to the sign up page. You have to use new_user_session_path in order to create a link to sign_in. A: Bear in mind the video is a year+ old :) If you look at the current devise source where the routes are generated you'll see that it apparently no longer creates a "sign_up" route--looks like the registration paths are the current method. It also looks like you're using a release candidate version, which always makes me a little nervous, since that's a release candidate and not necessarily 100% stable--which might explain why the default template is using a path variable that doesn't exist. A: I am trying to figure out why you are using Devise version 1.1rc0 and not the latest gem available which is 1.4.7? I have several applications all running this latest version in which the sign_up path works just fine. I would recommend updating to the latest version of the gem and try again. Outside of that, I can only think of problems that could be caused by something in your routes.rb file or if you are trying to override the Devise Registrations Controller. A: add to routes.rb this is: devise_for :users do get'users/sign_out'=>'devise/sessions#destroy' end it's for sign_out for sign_up go to config/initializers/secret_token.rb and copy line: config.secret_token ='...' and paste it in config/aplication.rb
{ "language": "en", "url": "https://stackoverflow.com/questions/7623000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Could you post examples on how to use PHPUnit with NetBeans? I'm new to PHPUnit and I want to use it with Netbeans. I'm already aware that there is documentation for PHPUnit on it's own but there isn't much documentation on how to use it with Netbeans. It would be great to see some working examples first. I learn better that way. So from the Netbeans site they give this example and then you would Right Click File->Create PHPUnit Tests to automatically generate PHPUnit classes: class Calculator{ /** * @assert (0,0) == 0 * @assert (0,1) == 1 * @assert (1,0) == 1 * @assert (1,1) == 2 * @assert (1,2) == 4 */ public function add($a, $b){ return $a + $b; } } However, im reading another PHP book and in it they do it this way class Session { public function __construct($one, $two){} public function login(){} public function isLoggedIn() {return null;} } require_once("PHPUnit/Autoload.php"); class TestSession extends PHPUnit_Framework_TestCase { private $_session; function setUp() { $dsn = array( 'phptype' => "pgsql", 'hostspec' => "localhost", 'database' => "widgetworld", 'username' => "wuser", 'password' => "foobar" ); $this->_session = new Session($dsn, true); } function testValidLogin() { $this->_session->login("ed", "12345"); $this->assertEquals(true, $this->_session->isLoggedIn()); } function testInvalidLogin() { $this->_session->login("ed", "54321"); // fail $this->assertEquals(false, $this->_session->isLoggedIn()); } } $suite = new PHPUnit_Framework_TestSuite; $suite->addTest(new TestSession("testValidLogin")); $suite->addTest(new TestSession("testInvalidLogin")); $testRunner = new PHPUnit_TextUI_TestRunner(); $testRunner->run( $suite ); Could you help me understand how to do PHPUnit tests in Netbeans by converting the above example? Thanks I don't know but would doing something like this in Netbeans be correct?: class Session { public function __construct($one, $two) {} public function login() { /** * @assert ("ed", "12345")->isLoggedIn() == true */ /** * @assert ("ed", "54321")->isLoggedIn() == false */ } public function isLoggedIn() {return null;} } A: I have never use @assert in NetBeans, but it looks like they simply inform the test case generator how to write the tests. In the end, NetBeans creates a test case for the class which will look similar to TestSession above (though it would be called SessionTest). If you use @assert to define your test data, keep in mind that you'll need to regenerate the test every time you change them, and this will overwrite any changes you made to the test case after doing so. I would recommend writing the test cases by hand as you can't use @assert as you write it to test the session. It is designed to write tests like "Given parameters X, Y, and Z, the return value should be R." You can't use it to test side effects of your methods. A: To do PHPUnit testing in Netbeans, do the following things. * *Go to "File" > "Project properties" from the main men *Then select click on "PHPUnit" tab on vertical menu on the left of the dialog window *Choose the option how you will run PHPUnit such as using bootstrap file or XML or custom suites *Then, go to "Run" > "Test Project" from the main menu *Then, you will prompted for selecting where are the test files *Then, you will also prompted for where is your PHPUnit shell script or bat file(on Windows) on your computer if you haven't configured it for Netbeans Once you setup properly like above, every time you need to run test cases, going to "Run" > "Test Project" from the menu
{ "language": "en", "url": "https://stackoverflow.com/questions/7623001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Process JSON using jQuery I have the following JSON-encoded data being returned and need to process it with jQuery. How can I access different depots and vehicle data inside this list using jQuery.getJSON()'s callback function? $.getJSON('url', function(data) { // ...? }); The JSON-encoded data: // top-level result is a list of dictionaries [ // return dictionary for each depot { depot: { _id: 'D3', intersection: { first: 'Bay', second: 'King' }, address: { number: '100', street: 'King street West', city: 'Toronto', province: 'ON', postal_code: 'M5X 1B8' }, }, // return dictionary for each car in that depot vehicle: [{ _id: 'V4', _depot_id: 'D3', model: 'Ford F150', price: '80', km_per_litre: '15', cargo_cu_m: 'YES', category: 'Truck', image: 'www.coolcarz.com' }, { _id: 'V24', _depot_id: 'D3', model: 'Toyota Camry Hybrid', price: '90', km_per_litre: '25', cargo_cu_m: 'YES', category: 'Hybrid car', image: 'www.coolcarz.com' } ] }, { depot: { _id: 'D9', intersection: { first: 'Bay', second: 'Front' }, address: { number: '161', street: 'Bay', city: 'Toronto', province: 'ON', postal_code: 'M5J 2S1' }, }, // return dictionary for each car in that depot vehicle: [{ _id: 'V11', _depot_id: 'D9', model: 'Ford Crown Victoria', price: '45', km_per_litre: '13', cargo_cu_m: 'YES', category: 'Standard car', image: 'www.coolcarz.com' }, ] }, ] A: $.getJSON('url', function(data) { alert(data.length); // 2 alert(data[0].depot.intersection.second); // "King" alert(data[0].vehicle[1].category); // "Hybrid car" alert(data[1].depot.address.city); // "Toronto" });
{ "language": "en", "url": "https://stackoverflow.com/questions/7623006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Avoid container div Say you have a website and have a fancy pink header which stretches all across your screen horizontal. Inside the header there some text which needs to be centered and have a 960px fixed width area. --------------------------- | x | hello | x | | | | y | hi | y | --------------------------- x = pink background row y = yellow background row Does someone has an up to date css (no js) solution to dismiss the need of a container div just often for padding? html: <header> <div> hello </div> </header> <footer> <div> hi </div> </footer> css: header { background: pink; } header > div { width: 960px; margin:0 auto; } Does someone has a solution, maybe something with pseudo before and after? So you can just write beautiful html: <header>hello</header> <footer>hi</footer> and fix it all in css. This is a basic example, the point is; I am often bound to use a div just for layout things, mostly padding. Of course I can set seperate background to do the trick, but I am talking about keeping this all together, since, the probably has the same issue and another background. And same with the main content, and so on. Wish there was something like: header{ background: pink; padding: 100%-960px; } That would 'do the trick' and scales after resizing the viewport. A: Typically I would just use multiple container divs, with a container class... Like hellow and hi would both be in a div with "wrapper class", and x and y would both be 100% width wrapper-of-wrapper divs. But since your goal is to avoid wrapper divs... then I won't go into detail about how you can accomplish this with 4 wrapper divs :) I think you should look into these links: * *http://sass-lang.com/ *http://twitter.github.com/bootstrap/#less
{ "language": "en", "url": "https://stackoverflow.com/questions/7623009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to resize a buffer so it only takes a small part of the screen? In Emacs how can I resize a buffer so it only takes a small part of the screen ? Is there any way ? I would like to have the src taking 70% of the screen and a file manager in the other 30% A: Set width of current window on current frame to ~ 70%: (window-resize nil (- (truncate (* 0.7 (frame-width))) (window-width)) t) The other windows are shrunk automatically. If you want to adjust more than one it gets more difficult. As command: (defun window-resize-to-70-percent () (interactive) (window-resize nil (- (truncate (* 0.7 (frame-width))) (window-width)) t)) A: Use separate window-manager frames for individual buffers (by default). Automatically shrink-fit the frames to fit the buffer content. See One-On-One Emacs, in particular, libraries fit-frame.el and autofit-frame.el.
{ "language": "en", "url": "https://stackoverflow.com/questions/7623013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom post type and comments in wordpress Is it possible in wordpress to display comments and comment form on custom post type, and how to do that? Thanks in advance. A: It is very important that you put this attributes "comments" in this line : 'supports' => array( 'title', 'editor', 'comments', 'excerpt', 'custom-fields', 'thumbnail', 'revisions', 'author', 'page-attributes' ), in your functions.php file // register post type MySpecialPost add_action( 'init', 'register_cpt_MySpecialPost' ); function register_cpt_MySpecialPost() { $labels = array( 'name' => _x( 'MySpecialPost', 'MySpecialPost' ), 'singular_name' => _x( 'MySpecialPost', 'MySpecialPost' ), 'add_new' => _x( 'Ajouter', 'MySpecialPost' ), 'add_new_item' => _x( 'Ajouter une MySpecialPost', 'MySpecialPost' ), 'edit_item' => _x( 'Modifier', 'MySpecialPost' ), 'new_item' => _x( 'Nouvelle MySpecialPost', 'MySpecialPost' ), 'view_item' => _x( 'Voir la MySpecialPost', 'MySpecialPost' ), 'search_items' => _x( 'Recherche', 'MySpecialPost' ), 'not_found' => _x( 'Aucune MySpecialPost trouvé', 'MySpecialPost' ), 'not_found_in_trash' => _x( 'Aucune MySpecialPost trouv&eacute;', 'MySpecialPost' ), 'parent_item_colon' => _x( 'Parent Service:', 'MySpecialPost' ), 'menu_name' => _x( 'MySpecialPost', 'MySpecialPost' ), ); $args = array( 'labels' => $labels, 'hierarchical' => false, 'supports' => array( 'title', 'editor', 'comments', 'excerpt', 'custom-fields', 'thumbnail', 'revisions', 'author', 'page-attributes' ), 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 21, 'show_in_nav_menus' => true, 'publicly_queryable' => true, 'exclude_from_search' => false, 'has_archive' => true, 'query_var' => true, 'can_export' => true, 'rewrite' => true, 'capability_type' => 'page' ); register_post_type( 'MySpecialPost', $args ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7623015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Resharper 6.0 (current version) support Microsoft Visual Studio 11 Developer Preview or can it be made to? I've read articles that explain how to enable Visual Studio 2010 managed extensions to get them working with Microsoft Visual Studio 11 Developer Preview Running VS2010 Gallery Extensions In VS11, Meet Git Source Control Provider However I haven't been able to apply the same logic to Resharper. Although it's a managed extension now, it doesn't appear to be packaged in a VSIX file, so I can't follow all the steps in the above mentioned article. A: Resharper 6.0 does not support VS11. The nightly builds of Resharper 6.1 though are now available, and do support VS11. * *To download Resharper for VS 11: http://confluence.jetbrains.net/display/ReSharper/ReSharper+6.1+Nightly+Builds *To learn more about Resharper 6.1: http://blogs.jetbrains.com/dotnet/2011/11/resharper-61-eap-opens-much-more-than-a-bugfix-release/ *For details on how the experience with VS11 in general is like, compared to VS2010: http://gurustop.net/blog/2011/11/10/notes-on-using-visual-studio-11-as-primary-ide-on-windows-7/ Update: For notes on installing Resharper on VS 11, and small gotachas and solution, check this post as well: http://gurustop.net/blog/2011/11/11/resharper-6-0-resharper-6-1-vs11-visual-studio-11-support-keyboard-shortcuts/ Update 2: Since VS11 has been fully released as VS 2012, Resharper has released final version 6.1 (free for 6.0 owners), and 7.x for it already and they're working just nice. Wrote this update as the answer still gets up-votes (thank you). A: No (For R#6.0) Whilst I can't find an official looking page on JetBrain's resharper web site, I did find a reply from a JetBrain's engineer The upcoming ReSharper 6.1 will have initial experimental support for Visual Studio vNext. http://devnet.jetbrains.net/message/5320971#5320971 Yes (For R#6.1) Resharper 6.1 has now got experimental support for Visual Studio 11, albeit via a separate download to the normal 6.1 installer: http://www.jetbrains.com/resharper/download/index.html#related Blog post explaining the current level of support in VS11: http://blogs.jetbrains.com/dotnet/2011/12/christmas-is-here-resharper-61-dotcover-12-and-dottrace-452-released/
{ "language": "en", "url": "https://stackoverflow.com/questions/7623023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Fire action at specific date and time iPhone in my Core Data model, I have an entity which has got a date attribute. For example, I'll set this date to 10/07/2011 4:00pm and I want to fire an action when current date will pass the saved date by one minute. A local notification will be fired but I also want to fire another method to change another entity attribute's value. Is it possible to do something like this? I've also thought to NSTimer but I've never used them... And a last question: will this action fire always even is app isn't in background or foreground? Thank you so much! Matteo A: You can't fire an action while running in background mode other than through local notifications. To check if the date condition has been met while running in foreground, NSTimer is the way to go. A: Try to check Local notifications
{ "language": "en", "url": "https://stackoverflow.com/questions/7623029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transformed content created using jQuery mobile and Transform plugin not mobile-styled My stylesheet: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/states"> <select id="states"> <xsl:for-each select="state"> <xsl:element name="option"> <xsl:attribute name="value"> <xsl:value-of select="@abbreviation"/> </xsl:attribute> <xsl:value-of select="@name"/> </xsl:element> </xsl:for-each> </select> </xsl:template> </xsl:stylesheet> An fragment from the xml document: <?xml version="1.0" encoding="utf-8" ?> <states> <state name="Alabama" abbreviation="AL" /> <state name="Alaska" abbreviation="AK" /> </states> The html: <!DOCTYPE html> <html> <head> <title>Template</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css" /> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.3.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"></script> <script type="text/javascript" src="js/jquery.transform.js"></script> <script type="text/javascript"> $().ready(function () { $("#container").transform({ xml: "xml/states/states.xml", xsl: "xsl/states.xsl" }); }); </script> </head> <body> <div id="searchPage" data-role="page" data-theme="c" > <div data-role="content"> <div id="container"></div> </div> </div> </body> </html> In this example the xsl transformation occurs, the select list renders, but without the mobile styling. I understand that styling has already been applied by the jQuery Mobile framework, and that the transformation happened too late in the event chain. I've seen the recommendations to refresh the control or parent container using a variety of techniques (.page(), .selectmenu('refresh')), but none of these work. Any help here would be appreciated. Rendering dynamically-created content is a must for this library to be considered ready for prime time. Note that the Transform plugin is at: http://plugins.jquery.com/project/Transform A: I fixed it. I pulled the select control itself out of the xsl and placed it in the html body: <select id="states"></select> The transformation then is responsible for rendering just the option tags: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/states"> <option data-placeholder="true">Select your state</option> <xsl:for-each select="state"> <xsl:element name="option"> <xsl:attribute name="value"> <xsl:value-of select="@abbreviation"/> </xsl:attribute> <xsl:value-of select="@name"/> </xsl:element> </xsl:for-each> </xsl:template> </xsl:stylesheet> Finally, a refresh on the contol after the transformation added the appropriate mobile styling: $('#searchPage').live('pageinit', function (event) { // Get the states select options. var options = $.transform({ async: false, xml: "xml/states/states.xml", xsl: "xsl/states.xsl" }); $("#states").html(options).selectmenu('refresh', true); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7623030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I display DB contents after selecting a dropdown list option using PHP, AJAX and MySQL? I am new to AJAX and want to create something with two dropdown boxes. When a user selects the first one, the second dropdown populates with the corresponding fields. After selecting an option from the second dropdown I want a table to display all information from the database that corresponds to the selection. I have found an example online, but am having trouble modifying it. I am only able to display one field. This is the code: ajax_select //function used to remove the next lists already displayed when it chooses other options function removeLists(colid) { var z = 0; // removes data in elements with the id stored in the "ar_cols" variable // starting with the element with the id value passed in colid for(var i=1; i<ar_cols.length; i++) { if(ar_cols[i]==null) continue; if(ar_cols[i]==colid) z = 1; if(z==1) document.getElementById(preid+ar_cols[i]).innerHTML = ''; } } // create the XMLHttpRequest object, according browser function get_XmlHttp() { // create the variable that will contain the instance of the XMLHttpRequest object (initially with null value) var xmlHttp = null; if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } // for Forefox, IE7+, Opera, Safari else if(window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } // IE5 or 6 return xmlHttp; } // sends data to a php file, via POST, and displays the received answer function ajaxReq(col, wval) { removeLists(col); // removes the already next selects displayed // if the value of wval is not '- - -' and '' (the first option) if(wval!='- - -' && wval!='') { var request = get_XmlHttp(); // call the function with the XMLHttpRequest instance var php_file = 'select_list.php'; // path and name of the php file // create pairs index=value with data that must be sent to server var data_send = 'col='+col+'&wval='+wval; request.open("POST", php_file, true); // set the request document.getElementById(preid+col).innerHTML = 'Loadding...'; // display a loading notification // adds a header to tell the PHP script to recognize the data as is sent via POST request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); request.send(data_send); // calls the send() method with data_send // Check request status // If the response is received completely, will be added into the tag with id value of "col" request.onreadystatechange = function() { if (request.readyState==4) { document.getElementById(preid+col).innerHTML = request.responseText; } } } } selected_list.php <?php // Multiple select lists - www.coursesweb.net/ajax/ if(!isset($_SESSION)) session_start(); // Here add your own data for connecting to MySQL database $server = 'localhost'; $user = 'root'; $pass = '***'; $dbase = '**'; // Here add the name of the table and columns that will be used for select lists, in their order // Add null for 'links' if you don`t want to display their data too $table = 'cpu_table'; $ar_cols = array('endor', 'ype', 'name'); $preid = 'slo_'; // a prefix used for element's ID, in which Ajax will add <select> $col = $ar_cols[0]; // the variable used for the column that wil be selected $re_html = ''; // will store the returned html code // if there is data sent via POST, with index 'col' and 'wval' if(isset($_POST['col']) && isset($_POST['wval'])) { // set the $col that will be selected and the value for WHERE (delete tags and external spaces in $_POST) $col = trim(strip_tags($_POST['col'])); $wval = "'".trim(strip_tags($_POST['wval']))."'"; } $key = array_search($col, $ar_cols); // get the key associated with the value of $col in $ar_cols $wcol = $key===0 ? $col : $ar_cols[$key-1]; // gets the column for the WHERE clause $_SESSION['ar_cols'][$wcol] = isset($wval) ? $wval : $wcol; // store in SESSION the column and its value for WHERE // gets the next element in $ar_cols (needed in the onchange() function in <select> tag) $last_key = count($ar_cols)-1; $next_col = $key<$last_key ? $ar_cols[$key+1] : ''; $conn = new mysqli($server, $user, $pass, $dbase); // connect to the MySQL database if (mysqli_connect_errno()) { exit('Connect failed: '. mysqli_connect_error()); } // check connection // sets an array with data of the WHERE condition (column=value) for SELECT query for($i=1; $i<=$key; $i++) { $ar_where[] = '`'.$ar_cols[$i-1].'`='.$_SESSION['ar_cols'][$ar_cols[$i-1]]; } // define a string with the WHERE condition, and then the SELECT query $where = isset($ar_where) ? ' WHERE '. implode($ar_where, ' AND ') : ''; $sql = "SELECT DISTINCT `$col` FROM `$table`".$where; $result = $conn->query($sql); // perform the query and store the result // if the $result contains at least one row if ($result->num_rows > 0) { // sets the "onchange" event, which is added in <select> tag $onchg = $next_col!==null ? " onchange=\"ajaxReq('$next_col', this.value);\"" : ''; // sets the select tag list (and the first <option>), if it's not the last column if($col!=$ar_cols[$last_key]) $re_html = $col. ': <select name="'. $col. '"'. $onchg. '><option>- - -</option>'; while($row = $result->fetch_assoc()) { // if its the last column, reurns its data, else, adds data in OPTION tags if($col==$ar_cols[$last_key]) $re_html .= '<br/>'. $row[$col]; else $re_html .= '<option value="'. $row[$col]. '">'. $row[$col]. '</option>'; } if($col!=$ar_cols[$last_key]) $re_html .= '</select> '; // ends the Select list } else { $re_html = '0 results'; } $conn->close(); // if the selected column, $col, is the first column in $ar_cols if($col==$ar_cols[0]) { // adds html code with SPAN (or DIV for last item) where Ajax will add the select dropdown lists // with ID in each SPAN, according to the columns added in $ar_cols for($i=1; $i<count($ar_cols); $i++) { if($ar_cols[$i]===null) continue; if($i==$last_key) $re_html .= '<div id="'. $preid.$ar_cols[$i]. '"> </div>'; else $re_html .= '<span id="'. $preid.$ar_cols[$i]. '"> </span>'; } // adds the columns in JS (used in removeLists() to remove the next displayed lists when makes other selects) $re_html .= '<script type="text/javascript">var ar_cols = '.json_encode($ar_cols).'; var preid = "'. $preid. '";</script>'; } else echo $re_html; ?> Is there an easier way to achieve this? Thank You A: This is what I use to get database content in a dropdownlist. <?php mysql_connect('localhost','username','password'); mysql_select_db('databasename'); $query = mysql_query("SELECT columname FROM tablename"); echo '<select name="name">'; while ($row = mysql_fetch_array($query)) { echo '<option value="'.$row['columname'].'">'.$row['columname'].'</option>'; } echo '</select>'; ?> (I know mysql_ is not the way anymore but this worked for me) hopefully this works for you aswell
{ "language": "en", "url": "https://stackoverflow.com/questions/7623031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fuzzy c-means tcp dump clustering in matlab Hi I have some data thats represented like this: 0,tcp,http,SF,239,486,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,8,8,0.00,0.00,0.00,0.00,1.00,0.00,0.00,19,19,1.00,0.00,0.05,0.00,0.00,0.00,0.00,0.00,normal. Its from the kdd cup 1999 which was based on the darpa set. the text file I have has rows and rows of data like this, in matlab there is the generic clustering tool you can use by typing findcluster but it only accepts .dat files. Im also not very sure if it will accept the format like this. Im also not sure why there is so many trailing zeros in the dump files. Can anyone help how I can utilise the text document and run it thru a fcm clustering method in matlab? Code help is really needed. A: FINDCLUSTER is simply a GUI interface for two clustering algorithms: FCM and SUBCLUST You first need to read the data from file, look into the TEXTSCAN function for that. Then you need to deal with non-numeric attributes; either remove them or convert them somehow. As far as I can tell, the two algorithms mentioned only support numeric data. Visit the original website of the KDD cup dataset to find out the description of each attribute.
{ "language": "en", "url": "https://stackoverflow.com/questions/7623036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Paypal IPN Inventory Control I have been developing an online retail shop. It is written in php and uses paypal and IPN to handle payments. I have written my own shopping cart. When the user wants to checkout they click on the checkout button which has the standard cart upload function wrapped around the button and the user is taken to paypal to complete payment. Paypal then sends me an IPN to notify me of the payment. My question is, at what point should I store the order and when should the stock levels be reduced? The standard process flow is that I have right now is as follows: * *User adds item to cart. * *If item is now sold out or the quantity added is more than available, the cart is updated to reflect this. *However, stock added to the cart does not reduce stock levels. *User clicks checkout. * *The cart is loaded into an order record in the db AND the stock levels are reduced. *User is taken to paypal to complete payment. *(a) User completes payment. (b) User does not complete payment by either returning to website or going somewhere else / closing browser. *(Optional) User clicks return to website. * *User sees a 'thank you, order complete' complete page. *Nothing is processed relating to the order table since paypal will send IPN anyway. *Paypal sends IPN * *Update order with the transaction status As you may see, there are some issues with this process. If the customer leaves the paypal page without completing payment I will have a 'dangling' order and since stock levels are also reduced this stock will not be available to other customers! A solution to this is to manually 'clean' the database every so often. Alternatives? * *option I) Do not store the order in the database until a 'completed transaction' IPN is received, then use the cart info stored in the session to create an order and reduce stock levels. However, sessions can expire and paypal payments might take days depending on payment. *option II) Store the order as is now but do not reduce stock levels until completed transaction IPN is received. This still has the issue of dangling orders but at least no stock will have to be re added again when cleaning up, I'll just have to remove the orders. Another problem with this though is that if multiple people order at similar times and thus collectively their orders contain quantities that exceed stock. This could be quite chaotic when the system receives completed IPNS and then reduces stock levels to negative quantities! I have looked everywhere on the internet for some sort of help, but it is not mentioned anywhere! Everyone just skips to how IPN should be handled. I just don't understand how other people could not have had this problem?! Please help! A: You're dealing with the same problem that airline reservation systems have for ages. Use the same solution ie 1.Upon user clicking checkout (while being redirected to Paypal) reduce inventory count place a timestamp in the database along with a state that this order is temporary 2a. Once you receive an IPN ie know the billing has been successful change state of the order to permanent 2b. Have a cron job that runs every few minutes to track temporary orders. If temporary orders are from a time greater than what you allow eg 20 mins then: remove the temporary order from database undo the change in inventory count A: As both a merchant and a developer, I prefer to adjust inventory stock with the IPN, even if that IPN is pending (eg. an eCheck). The chance of 2 customers going through checkout at the same time with your last remaining stock is typically low. If you do have high enough volume and low stock levels (why would you?) then you may want to do something in the cart to place locks on the items for the duration of the session timeout. Make sure your order processing code returns the inventory to stock if the order is canceled or returned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7623037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What's the use of pointer-casting a dereferenced pointer? This question is about code explanation, not code debugging. The code I'm using works. I'm using a public code and I was curious to look at one of their "grow array" template, which looks like this: template <typename TYPE> TYPE *grow(TYPE *&array, int n, const char *name) { if (array == NULL) return create(array,n,name); bigint nbytes = ((bigint) sizeof(TYPE)) * n; array = (TYPE *) srealloc(array,nbytes,name); return array; } and the function srealloc looks like this: void *Memory::srealloc(void *ptr, bigint nbytes, const char *name) { if (nbytes == 0) { destroy(ptr); return NULL; } ptr = realloc(ptr,nbytes); if (ptr == NULL) { error(); } return ptr; } Please disregard the create function for now. My main question is why do they pointer-cast and dereference array in the template? What's the advantage of that? What if they just didn't have *& at all? Thanks! A: *& is not a "pointer-dereference". It's a reference to a pointer. It's needed so the grow function can change the pointer, rather than just what the pointer points to. The alternative would have been a pointer to a pointer, like in the following code. template <typename TYPE> TYPE *grow(TYPE **array, int n, const char *name) { if ((*array) == NULL) return create((*array),n,name); bigint nbytes = ((bigint) sizeof(TYPE)) * n; (*array) = (TYPE *) srealloc((*array),nbytes,name); return *array; } A: The & token has many meanings, two of which you have confused here. You are not alone! As an operator, it means "address of", which you seem to be comfortable with (this comes from C). But as a type qualifier, it means "reference to", which is quite different. First meaning: int x ; int* p = &x ; // p = address of x (as in C) Second meaning: void f (int& x) { // x is a reference to an int -- its address is passed to f x++ ; } ... int y = 99 ; f (y) ; // After this call, y is equal to 100 In this example, the code is equivalent to void f (int* x) { (*x)++ ; } ... int y = 99 ; f (&y) ; // After this call, y is equal to 100 This code doesn't look as clean, but it's easier to understand for C programmers. So...the function declaration void f (int*& p) ; (as in your example) means that f can change the value of the int* parameter passed by the calling function. Your sample code looks a bit screwy to me, because why does it need to return the new value of array if it can change the parameter directly? But that is a question of style, and I have learnt not to discuss such matters here :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7623045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: geocoding rails I am trying to geocode multiple addresses in a model using either geokit or geocoder and I can't get either on of the gems to work as I want them to. Here is the code that I am applying to my model for both use cases and the errors I get for each option. The Geocoder gist: https://gist.github.com/112cc28b7d52402079ad The Geokit gist https://gist.github.com/adef30cb458c1177df2b I am using devise, and rails 3.1 if that helps, and I am fairly certain that I am close to the correct code in the geocoder option, but don't know what I am doing wrong. A: I defined my own custom geocoding method similar to this: def custom_geocode var = Geocoder.coordinates(self.address1) var2 = Geocoder.coordinates(self.address2) self.latitude1 = var.first self.longitude1 = var.last self.latitude2 = var2.first self.longitude2 = var2.last end Geocoder.coordinates returns an array of the latitude and longitude from the resulting address, and you save the resulting latitudes and longitudes. A: dont know geocoder, but i entered your shipping_address on this demo site for geocoder and it seems the response is an array. Your error message says that you're calling the latitude method on an array and ruby is angry about it. try using this instead : start_result[0].latitude
{ "language": "en", "url": "https://stackoverflow.com/questions/7623046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: A Star Search Pen Plotter moving from two unconnected nodes I'm having trouble with a programming assignment, its a penplotter, there have been quite a few questions about it already here. Here's a summary: The paper sheet is understood to be laid out on a grid with both the x-axis and y-axis running from 0 up to infinity (notionally). All drawings are fully contained in this quadrant and can be assumed to fit on the page. Lines can always be assumed not to be contained in other lines. The pen always starts at the origin (0, 0) but can finish anywhere. Lines are specified by the (x, y) coordinates (in integers) of their end points on the grid. The pen can either draw a line between any two points or move (without drawing anything) in a straight line between any two points. As should be obvious, a line can be drawn in either direction. Since we want to minimize the total time to draw a figure, assume the pen moves at constant speed so that an optimal drawing is one that minimizes the total distance moved by the pen whilst not drawing. All input will be in a file with a sequence of lines of the following form: Line between x1 y2 and x2 y2 I'm using this for my input: Line between 0 0 and 2 2 Line between 4 1 and 4 4 Line between 4 4 and 4 7 Line between 2 6 and 4 4 Line between 4 4 and 6 2 Line between 6 6 and 4 4 Line between 2 2 and 4 4 and the edges are being stored into the arraylist. I'm not sure why its returning an NullPointerException I'm almost done, except the following for loop is returning an exception and I'm not sure why. It aims to get the list of all connected edges in the graph The exception says: Exception in thread "main" java.lang.NullPointerException at Nodes.getConnectedEdges(Nodes.java:55) which is the for loop line "for (Edges a : lines" public ArrayList<Edges> getConnectedEdges(ArrayList<Edges> lines) { ArrayList<Edges> returnData = new ArrayList<Edges>(); for (Edges a : lines) { if(a.getFromNode() == this ){ // if this node is the from node of that edge returnData.add(a); } // if this node is the to node of that edge if(a.getToNode() == this){ returnData.add(a); } } return returnData; } The on flowing problem would be how to get from say the origin (0,0) to an unconnected point say (2,2)? Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/7623050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }