text
stringlengths
8
267k
meta
dict
Q: What Time Is This Returning Deep in the sauce here. I haven't worked with time to much so I'm a little confused here. I know there is FILETIME and SYSTEMTIME. What I am trying to get at this point (because it might change) are file that are less than a 20 seconds old. This returning the files and their size and something in seconds, What I'd like to know is where it is filtering by time if it is, and how can I adjust it to suit my needs. Thank you. using namespace std; typedef vector<WIN32_FIND_DATA> tFoundFilesVector; std::wstring LastWriteTime; int getFileList(wstring filespec, tFoundFilesVector &foundFiles) { WIN32_FIND_DATA findData; HANDLE h; int validResult=true; int numFoundFiles = 0; h = FindFirstFile(filespec.c_str(), &findData); if (h == INVALID_HANDLE_VALUE) return 0; while (validResult) { numFoundFiles++; foundFiles.push_back(findData); validResult = FindNextFile(h, &findData); } return numFoundFiles; } void showFileAge(tFoundFilesVector &fileList) { unsigned _int64 fileTime, curTime, age; tFoundFilesVector::iterator iter; FILETIME ftNow; //__int64 nFileSize; //LARGE_INTEGER li; //li.LowPart = ftNow.dwLowDateTime; //li.HighPart = ftNow.dwHighDateTime; CoFileTimeNow(&ftNow); curTime = ((_int64) ftNow.dwHighDateTime << 32) + ftNow.dwLowDateTime; for (iter=fileList.begin(); iter<fileList.end(); iter++) { fileTime = ((_int64)iter->ftLastWriteTime.dwHighDateTime << 32) + iter->ftLastWriteTime.dwLowDateTime; age = curTime - fileTime; cout << "FILE: '" << iter->cFileName << "', AGE: " << (_int64)age/10000000UL << " seconds" << endl; } } int main() { string fileSpec = "*.*"; tFoundFilesVector foundFiles; tFoundFilesVector::iterator iter; int foundCount = 0; getFileList(L"c:\\Mapper\\*.txt", foundFiles); getFileList(L"c:\\Mapper\\*.jpg", foundFiles); foundCount = foundFiles.size(); if (foundCount) { cout << "Found "<<foundCount<<" matching files.\n"; showFileAge(foundFiles); } system("pause"); return 0; } A: I don't know what you've done to try to debug this but your code doesn't work at all. The reason is you're passing getFileList() a wstring but then passing that to the ANSI version of FindFirstFile(). Unless you #define UNICODE or use the appropriate compiler option, all system calls will expect char *, not UNICODE. The easiest fix is to simply change the declaration of getFileList() to this: int getFileList(const char * filespec, tFoundFilesVector &foundFiles) Change the call to FindFirstFile() to this: h = FindFirstFile((LPCSTR)filespec, &findData); And then change the calls to it to this: getFileList("c:\\Mapper\\*.txt", foundFiles); getFileList("c:\\Mapper\\*.jpg", foundFiles); Your other option is to switch all char strings to wide chars, but either way you need to be consistent throughout. Once you do that the program works as expected. As for your final question, your program is not filtering by time at all. A: Not quite an answer, but you might want to read about file system tunneling. It may prevent you from what you're trying to do in some situations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find anagram frequency in a string? Given a string value of arbitrary length, you're supposed to determine the frequency of words which are anagrams of each other. public static Map<String, Integer> generateAnagramFrequency(String str) { ... } For example: if the string is "find art in a rat for cart and dna trac" your output should be a map: find -> 1 art -> 2 in -> 1 a -> 1 cart -> 2 and -> 2 The keys should be the first occurrence of the word, and the number is the number of anagrams of that word, including itself. The solution i came up with so for is to sort all the words and compare each character from both strings till the end of either strings. It would be O(logn). I am looking for some other efficient method which doesn't change the 2 strings being compared. Thanks. A: I've written a JavaScript implementation of creation a n-gram (word analysis), at Extract keyphrases from text (1-4 word ngrams). This function can easily be altered to analyse the frequency of anagrams:Replace s = text[i]; by s = text[i].sort(), so that the order of characters doesn't matter any more. A: Create a "signature" for each word by sorting its letters alphabetically. Sort the words by their signatures. Run through the sorted list in order; if the signature is the same as the previous signature, you have an anagram.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Proper way to remove ads I have an app that displays an ad, and I have given the user the option to remove ads for $0.99 The in-app purchase system works great, but what is the proper protocol for removing an ad from an app? Right now I'm displaying my ad like so: ADBannerView *adView; adView = [[ADBannerView alloc] initWithFrame:CGRectMake(0, 0, 480, 32)]; adView.requiredContentSizeIdentifiers = [NSSet setWithObjects: ADBannerContentSizeIdentifier320x50, ADBannerContentSizeIdentifier480x32, nil]; adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier480x32; adView.delegate = self; [self addSubview:adView]; //adView.backgroundColor = [UIColor whiteColor]; CGAffineTransform transformAV = CGAffineTransformMakeRotation(((-90*3.14159265358979323846264338327950288)/(180))); //rotate to fit landscape display adView.transform = transformAV; adView.center = CGPointMake(303, 240); //translate to be at bottom of screen. Also, since it's a landscape-only ad should I remove this part of the code from the requiredContentSizeIdentifiers? I'm new to iAd: ADBannerContentSizeIdentifier320x50 A: When the user purchases this no ad feature you should create an NSDefaults bool set to YES to indicate this. than just query this NSDefault before adding the ad subview. if it is set to YeS than the subview should not be added . You can also use the bool to determine whether to setup the ad code entirely.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET return response before async task completes I have a webapp, and users make requests to change large amounts of data. Maybe persisting 1000 or more objects. I validate these requests up front, and then begin persisting the data. It really doesn't take LONG to persist individually, but multiple by a few thousand and it does. I'm using an OR/M framework and don't want to move away from it... and it is not really the bottleneck. I could build persist a smaller object graph - simply a 'plan' on how to persist the rest of it and then persist it some other way, but I'd really prefer an easier solution. Ideally, I'd validate, then start an async task that would persist all of the data. The user would get confirmation after it is validated and they can go along on their merry little way. Is this possible in .NET? Any suggestions? Thanks A: You can validate the input first, set some sort of status label indicating that everything went fine, and then launch the persistence part in a new Thread. I mean something like this: protected void Button1_Click(object sender, EventArgs e) { new Thread(() => { //logic to save the data goes here. }).Start(); Label1.Text = " Input validated. Thanks!"; } The user can safely close the browser and the operation will finish. EDIT Broken Glass' comment is correct in the sense that this approach does not scale well. There's a better way to perform this type of async operations. It's detailed here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Searching the output of a program through Terminal Suppose my C++ program has outputted a lot of stuff to the terminal, say a 10000x3 matrix. Is there any Unix command-line utility for me to inspect the lines which contain a desired number/string? In other words if the output looks like 1.23 4.56 7.89 1.54 9.86 7.78 6.78 1.23 9.86 4.56 6.77 8.98 9.86 3.45 7.54 Some unix command should search this output for 9.86 and print only the lines containing this number . A: Try using mycppprogram | grep '9.86' A: grep is your friend : man grep
{ "language": "en", "url": "https://stackoverflow.com/questions/7629127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FireFox not rendering font correctly Can someone tell me why FireFox is not rendering the Lucida Sans Unicode font type? It's a default websafe font according to w3schools. Chrome and IE both render it fine. html, body { height: 100%; font-size: 100%; min-width: 950px; color: #000; font: normal 12px "Lucida Sans Unicode" Geneva, Tahoma; } A: You probably want a comma after the Lucida part: html, body { height: 100%; font-size: 100%; min-width: 950px; color: #000; font: normal 12px "Lucida Sans Unicode", Geneva, Tahoma; } http://jsfiddle.net/GVCy2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7629131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access of undefined property myItem I am new in as3 and flex and there is probably a dump question. The following code raises an error Access of undefined property myItem. But why? All variables are accessable and defined. Do i register this variable somewhere else? I can not just define a new variable? <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"> <fx:Script> <![CDATA[ var myList:Array = new Array(); var myItem:int = 12; myList.push(myItem); trace(myList); ]]> </fx:Script> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> A: it has to be in a function in order for you to reference your declared variables. You can put myList.push(myItem); and trace(myList); in a function and call that function on creationComplete or preInitialize if you want to run it right away. Or if you absolutely want to initialize myList with the value 12, just declare it like var myList:Array = [12]; and get rid of myItem altogether.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Store check box value as bit in DB Hi i have a checkbox and in code behind i insert the value from checkbox into the DB. This is what i did: ClassRegInfo order1 = new ClassRegInfo { classID = classID.Text, ObtainedPermission = Convert.ToByte(obtainedPermission.Checked)} Obtained Permission in DB is of type bit. So when I do the above step, i get an error: Cannot implicitly convert type byte to bool So, can u let me know how to store the value as a bit in DB? A: Dont convert it to byte. Bit equals Bool ClassRegInfo order1 = new ClassRegInfo { classID = classID.Text, ObtainedPermission = obtainedPermission.Checked } A: For SQL to accept a boolean, I got this to work Convert.ToInt32(checkbox.Checked)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Printing all the directories using c++ This program is printing the directories at the root level Directory_1 Directory_2 but I want to be able to print the directories within them too Directory_1 Directory_1_2 Directory_1_3 Directory_2 Directory 2_1 Directory_2_1_1 Directory_4 I am trying to do it recursively but I am finding it hard to pass the Directory_1 as a root so it gets evaluated.. What am i missing? Here is my output .. . Directory_1 Directory_2 Failed to open directory: No such file or directory Code #include <dirent.h> #include <errno.h> #include <stdio.h> #include <sys/stat.h> char *arg_temp; int printDepthFirst(char *arg_tmp); int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s directory_name\n", argv[0]); return 1; } arg_temp = argv[1]; printDepthFirst(arg_temp); } int printDepthFirst(char *arg_tmp) { struct dirent *direntp; DIR *dirp; if ((dirp = opendir(arg_tmp)) == NULL) { perror ("Failed to open directory"); return 1; } while ((direntp = readdir(dirp)) != NULL) { printf("%s\n", direntp->d_name); arg_tmp = direntp->d_name; } printDepthFirst(arg_tmp); while ((closedir(dirp) == -1) && (errno == EINTR)) ; return 0; } Now, I know some people get irritated when asking questions that they think I am expecting them to code this, you dont need to, if you can tell me theoretically what i need to do.. I will research it although if its a small programmatically fix and you can post that I would really appreaciate it.. but if not.. I would also love to hear about what needs to be done in words.. Thank you A: Well this should help: #define _XOPEN_SOURCE 500 #include <ftw.h> #include <stdio.h> static int display_info(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) { switch(tflag) { case FTW_D: case FTW_DP: puts(fpath); break; } return 0; /* To tell nftw() to continue */ } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s directory_name\n", argv[0]); return 1; } int flags = FTW_DEPTH | FTW_MOUNT | FTW_PHYS; if (nftw(argv[1], display_info, 20, flags) == -1) { perror("nftw"); return 255; } return 0; } A: Have a look at what fields struct dirent contains. A: The string dirent::d_name is a name of a directory, not it's full path. So, if your directory "C:\Alpha" contains directory "C:\Alpha\Beta", d_name would only contatin "Beta", not "C:\Alpha\Beta". You will have to assemble the full path yourself - appending slash/backslash to your arg_tmp and then appending new directory name, like this: while ((direntp = readdir (dirp)) != NULL) { char *dirname = direntp->d_name; // Only work with directories and avoid recursion on "." and "..": if (direntp->d_type != DT_DIR || !strcmp (dirname, ".") || !strcmp (dirname, "..")) continue; // Assemble full directory path: char current [strlen (arg_tmp) + 2 + strlen (dirname)]; strcpy (current, arg_tmp); strcat (current, "\\"); // Replace "\\" with "/" on *nix systems strcat (current, dirname); // Show it and continue: printf ("%s\n", current); printDepthFirst (current); } Also, you should call recursively inside the loop, not outside. A: Inside your while loop inside printDepthFirst you might need something like: if(direntp->d_type == DT_DIR) printDepthFirst(directp->d_name); You might perhaps have to worry about .. directories too. Alternatively, I've found boost::filesystem to work quite well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: allocate user-space memory from kernel I'm trying to call sys_readlink(const char __user *path, char __user *buf, int bufsiz) directly, but get EFAULT error code. This error appears because buf points to memory from kernel-space. So, is there possible way to allocate user-space memory from kernel ? kmalloc(size, GFP_USER) is similar to kmalloc(size, GFP_KERNEL) and returns pointer to kernel memory. A: You can temporarily disable memory address validity checking by using set_fs mm_segment_t old_fs; old_fs = get_fs(); set_fs(KERNEL_DS); /* Your syscall here */ set_fs(old_fs);
{ "language": "en", "url": "https://stackoverflow.com/questions/7629141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How can I dynamically add text onto an image with HTML/Javascript/CSS? I want to add text onto an image giving the text a transparent black background. Essentially, I want to achieve the effect described in the following link: http://www.google.com/url?sa=t&source=web&cd=4&ved=0CD8QFjAD&url=http%3A%2F%2Fcss-tricks.com%2F3118-text-blocks-over-image%2F&rct=j&q=text%20on%20image&ei=IsmITsK4DYWc0AWj-4H9Dw&usg=AFQjCNHD2pL0MiEQObwT53pWzFq2gJoH6g&cad=rja The problem is that I am dynamically generating these images and randomly placing them on the screen. Therefore, I cannot absolutely position the text (at least, not without knowing the height of the text in total). Is there another way to do this? Thanks! A: you can position text absolutely. once images are loaded, even if randomly, jQuery's position() method will provide you will all the information you need. obviously, you would like to to encapsulate images in containers e.g. or use and set image using div's background image. then you have all the freedom to put whatever text/effects you want in the container. A: I am dynamically generating these images and randomly placing them on the screen. Without seeing some of the code you have so far, it’s a bit difficult to help. If you’re dynamically generating the images, couldn’t you also dynamically generate the text along with it? I.e. instead of generating: <img style="position: absolute; top: RANDOMVALUE; left: RANDOMVALUE;"> Could you generate: <div class="image-with-text-over-it" style="position: absolute; top: RANDOMVALUE; left: RANDOMVALUE;"> <img> <p>Text to be overlaid on image</p> </div> And then in your stylesheet, write some CSS that positions the text in every instance of this over the image in that instance: .image-with-text-over-it p { position: absolute; bottom: 2em; left: 0; color: #fff; background: rba(0, 0, 0, 0.8); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7629142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python CGI queue I'm working on a fairly simple CGI with Python. I'm about to put it into Django, etc. The overall setup is pretty standard server side (i.e. computation is done on the server): * * User uploads data files and clicks "Run" button * Server forks jobs in parallel behind the scenes, using lots of RAM and processor power. ~5-10 minutes later (average use case), the program terminates, having created a file of its output and some .png figure files. * Server displays web page with figures and some summary text I don't think there are going to be hundreds or thousands of people using this at once; however, because the computation going on takes a fair amount of RAM and processor power (each instance forks the most CPU-intensive task using Python's Pool). I wondered if you know whether it would be worth the trouble to use a queueing system. I came across a Python module called beanstalkc, but on the page it said it was an "in-memory" queueing system. What does "in-memory" mean in this context? I worry about memory, not just CPU time, and so I want to ensure that only one job runs (or is held in RAM, whether it receives CPU time or not) at a time. Also, I was trying to decide whether * *the result page (served by the CGI) should tell you it's position in the queue (until it runs and then displays the actual results page) OR *the user should submit their email address to the CGI, which will email them the link to the results page when it is complete. What do you think is the appropriate design methodology for a light traffic CGI for a problem of this sort? Advice is much appreciated. A: Definitely use celery. You can run an amqp server or I think you can sue the database as a queue for the messages. It allows you to run tasks in the background and it can use multiple worker machines to do the processing if you want. It can also do cron jobs that are database based if you use django-celery It's as simple as this to run a task in the background: @task def add(x, y): return x + y In a project I have it's distributing the work over 4 machines and it works great.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Actionmailer not recognised rails 3 app I am trying to send mail using actionmailer on a Rails 3.0.1 application. Here is my setup config/initializers/setup_mail.rb ActionMailer::Base.delivery_method = :smtp ActionMailer::Base.smtp_settings = { :address => "smtp.gmail.com", :port => 587, :domain => "saidyes.co.uk", :user_name => "username", :password => "password", :authentication => "plain", :enable_starttls_auto => true } ActionMailer::Base.default_url_options[:host] = "localhost:3000" ActionMailer::Base.register_interceptor(DevelopmentMailInterceptor) if Rails.env.development? config/environments/development.rb config.action_mailer.raise_delivery_errors = true config.action_mailer.delivery_method = :smtp config.action_mailer.perform_deliveries = true app/mailers/user_mailer.rb class UserMailer < ActionMailer::Base default :from => "[email protected]" def self.registration_confirmation(user) @user = user attachments["rails.png"] = File.read("#{Rails.root}/public/images/rails.png") mail(:to => "#{user.email}", :subject => "Welcome") end end app/models/user.rb require "#{Rails.root}/app/mailers/user_mailer" after_create :send_welcome_email private def send_welcome_email UserMailer.registration_confirmation(self).deliver end The first error i got was an uninitialized constant UserMailer in my Users model class. I fixed it by adding the require at the top of the User model definition. Now I get undefined local variable or method `attachments' for UserMailer:Class I must have configured actionmailer incorrectly or my rails app is not configured correctly to use mailer. Anyway any advice or help would be appreciated. Cheers A: I think the simple problem you've encountered is that the mail methods should be defined on instances of your mailer class. Namely it should be class UserMailer < ActionMailer::Base def registration_confirmation(user) @user = user attachments["rails.png"] = File.read("#{Rails.root}/public/images/rails.png") mail(:to => "#{user.email}", :subject => "Welcome") end end Note there is no self Take a look at the helpful Rails Guide on the subject As in your example you'll still call the method on the class UserMailer.registration_confirmation(user).deliver The class method does some magic to instantiate an instance, and ensure the correct template is rendered.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I change label text to contrast with toolbar background color in UISplitView? When using Apple's UISplitViewController, the master view has a black toolbar when in portrait mode and gray when in landscape. I have created a label inside a UIView on the toolbar, as described here: Adding a UILabel to a UIToolbar, but by default the text is black which means it is only visible in landscape mode. How should I code my view controller so it can change the text color so it is always visible, and ideally to match the way Apple apps like Mail work (white in portrait and dark gray in landscape) ? ...later... Following the direction in Alan Moore's answer, I decided to use code like this: UIInterfaceOrientation o = [UIApplication sharedApplication].statusBarOrientation; if (UIDeviceOrientationIsPortrait(o)) label.textColor = [UIColor whiteColor]; else label.textColor = [UIColor darkTextColor]; This is called from my viewDidLoad and didRotateFromInterfaceOrientation methods. Seems to me that didRotate is better than shouldRotate for this case. Also note I am querying the statusBar, because in my view self.interfaceOrientation always returns 1. This is also noted here: Determine UIInterfaceOrientation on iPad. Not 100% sure that darkText is the right color for landscape. A: I would add code to the - (BOOL)shouldAutorotateToInterfaceOrientation:(...) { } which would do a setTextColor on your label depending on whether it's rotating to portrait or landscape mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get the Height and Width of a jQuery UI Datepicker I'm using the jQuery UI Datepicker widget. When the user changes the month or year on the widget my code makes an ajax request to the server to get the highlighted dates for that month/year. In order to give the user an indication that the webpage is waiting for the server I'm trying to grey out the datepicker and display a loading image. I can already do all of this, except, I'm having problems getting the height and width of the greyed out section to match the height and width of the datepicker widget. Because the datepicker's height can change based on the number of weeks in a month each time I called the overlay I was trying to use jQuery to get the height of the widget and then display the overlay. However, the height never seems to match the actual height of the datepicker. Here are the two ways I've tried setting the height. $('#loading').height($('.ui-datepicker-calendar').height() + $('.ui-datepicker-header').height()) and $('#loading').height($('.ui-datepicker-inline.ui-datepicker.ui-widget.ui-widget-content.ui-helper-clearfix.ui-corner-all').height()) Neither of which work. Does anyone know a way I can programmatically get the height and width of a jQuery UI Datepicker widget? A: This is a long shot as I can't tell exactly what you mean by the height never seems to match the actual height, other than it's not covering the whole datepicker. A solution to this may be outerWidth() and outerHeight(). These functions get the width of the element including border, padding and (optionally) margins: $('#loading').height($('.ui-datepicker-calendar').outerHeight(false) + $('.ui-datepicker-header').outerHeight(false)) $('#loading').height($('.ui-datepicker-inline.ui-datepicker.ui-widget.ui-widget-content.ui-helper-clearfix.ui-corner-all').outerHeight(false)) outerHeight(false) means "get the height plus padding and border, but leave out the margin". Set it to true if you want to include the margin too. A: height() works fine, the problem was that someone else had edited the file and added padding without my knowledge. So when I set the height it always had a bunch of extra pixels added, making my overlay too large for the datepicker widget. In addition it is sufficient to select .ui-datepicker-inline. So my final jQuery code is: $('#loading').height($('.ui-datepicker-inline').height());
{ "language": "en", "url": "https://stackoverflow.com/questions/7629152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cache gauss points for numerical integration in c++ This is a question on what people think the best way to lay out my class structure for my problem. I am doing some numerical analysis and require certain "elements" to be integrated. So I have created a class called "BoundaryElement" like so class BoundaryElement { /* private members */ public: integrate(Point& pt); }; The key function is 'integrate' which I need to evaluate for a whole variety of different points. What happens is that, depending on the point, I need to use a different number of integration points and weights, which are basically vectors of numbers. To find these, I have a class like so: class GaussPtsWts { int numPts; double* gaussPts; double* gaussWts; public: GaussPtsWts(const int n); GaussPtsWts(const GaussPtsWts& rhs); ~GaussPtsWts(); GaussPtsWts& operator=(const GaussPtsWts& rhs); inline double gwt(const unsigned int i) { return gaussWts[i]; } inline double gpt(const unsigned int i) { return gaussPts[i]; } inline int numberGPs() { return numGPs; } }; Using this, I could theoretically create a GaussPtsWts instance for every call to the integrate function. But I know that I maybe using the same number of gauss points many times , and so I would like to cache this data. I'm not very confident on how this might be done - potentially a std::map which is a static member of the BoundaryElement class? If people could shed any light on this I would be very grateful. Thanks! A: I had a similar issue once and used a map (as you suggested). What I would do is change the GaussPtsWts to contain the map: typedef std::map<int, std::vector<std::pair<double, double>>> map_type; Here I've taken your two arrays of the points and weights and put them into a single vector of pairs - which should apply if I remember my quadrature correctly. Feel free to make a small structure of the point and weight to make it more readable. Then I'd create a single instance of the GaussPtsWts and store a reference to it in each BoundaryElement. Or perhaps a shared_ptr depending on how you like it. You'd also need to record how many points you are using. When you ask for a weight, you might have something like this: double gwt(const unsigned int numGPs, const unsigned int i) { map_type::const_iterator found = themap.find(numGPs); if(found == themap.end()) calculatePoints(numGPs); return themap[numGPs][i].first; } Alternatively you could mess around with templates with an integer parameter: template <int N> class GaussPtsWts...
{ "language": "en", "url": "https://stackoverflow.com/questions/7629155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Query to find customers who registered and purchased on the 2nd day to within 7th day of their registration I would like to get all the customers who registered and purchased on the 2nd day to within 7th day of their registration given a startdate and enddate. Below is the schema : Users --CustId --PostedDate Order --OrderId --CustId --PostedDate How do i write a query to pull same day registered and purchased orders on the 2nd day to within 7th day of their registration within a specific date period? A: I'm very slightly modifying Richard Simoes's code from your other question: SELECT DISTINCT Users.CustId FROM Users JOIN Order ON Users.CustId = Order.CustId WHERE DATEDIFF(dd, Users.PostedDate, Order.PostedDate) BETWEEN 1 AND 6 AND Users.PostedDate BETWEEN @start_date AND @end_date
{ "language": "en", "url": "https://stackoverflow.com/questions/7629160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Enumerate all network interfaces with IPs on FreeBSD My application needs to list all network interafaces on a machine and their IPs, IPv4 and IPv6. I can get all interfaces with IPv4 IPs using ioctl(SIOCGIFCONF), but I need the IPv6 IPs, too. On Linux, those can get gotten from /proc/net/if_inet6, but where would I get them on FreeBSD ? A: getifaddrs(3) provides portable way to get network addresses and interface names.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google map and divs interaction similar to Groupon.com/now Can someone help me understand how to get the tight interaction between the map, list views and div marker elements on the "Groupon Now" UI. You can check it out here: www.groupon.com/now How can I get the list items to highlight when I hover over/click an item on the map? I've tried to do it with built in google map markers, but I would like to know how groupon uses additional divs to achieve this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to insert created object into a div I created an iframe using jQuery that I want to insert into an existing div element. However, when I use innerHTML to insert it, it shows up as: "[object HTMLIFrameElement]" What could be the reason for this? Here is the example: http://jsfiddle.net/MarkKramer/PYX5s/2/ A: You want to use the appendChild method rather than innerHTML. Change the last line in the JSFiddle from iframediv.innerHTML = iframe; to iframediv.appendChild(iframe); Edit to actually answer your question: Your variable iframe is a reference to a DOM element. It's object representation is an <iframe> element while its textual representation is simply [object HTMLIFrameElement]. By using innerHTML you are attempting to insert its textual representation into the DOM. This is just how the method works. You may come across JS code where elements are added to the DOM via innerHTML, but it's always with text, e.g. element.innerHTML = '<div>some text</div>'; In this case the browser will correctly add a <div> node as a child of element. For your <iframe> element to be inserted into the DOM using the variable iframe, you must use the appendChild method which will add the IFrame object as a child node to iframediv. A: var new_iframe = $("<iframe></iframe>"); new_iframe.appendTo($("#div_to_insert_into")); A: $('#iframecontainer').append(iframe); instead of var iframediv = document.getElementById('iframecontainer'); iframediv.innerHTML = iframe; should fix the problem A: The idea behind (most) of the posted solutions is that you can work with your iframe and it's container as jQuery objects instead of regular dom elements. A jQuery object is a reference to a div or an iframe that has access to all of jQuery's awesome methods... like .append() and .click(). Generally speaking, jQuery's real purpose is to turn lines of code like var iframediv = document.getElementById('iframecontainer'); ...into ... var iframediv = $("#iframecontainer"); ...which you can then use to do with whatever you please, like iframediv.appendTo("#anotherDiv"); Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating a collage from a collection of images in Ruby I have a collection of images that have been laid out in a rectangle to look like a collage. How can I take those images and create a single image out of them in Ruby? For example I have three images that I want placed in the image as follows: Image 1: (0,0) - (300,400) Image 2: (350, 0) - (500, 200) Image 3: (350, 220) - (500, 400) A: You can try something like this with RMagick: require 'RMagick' bg = Image.read('bg.png') # may be a background image... image1 = Image.read('image1.png') image2 = Image.read('image2.png') image3 = Image.read('image3.png') bg.composite!(image1, 0, 0, OverCompositeOp) bg.composite!(image2, 350, 0, OverCompositeOp) bg.composite!(image3, 350, 220, OverCompositeOp) bg.write('collage.png') A: you probably want to use an image library like RMagick ... http://www.imagemagick.org/RMagick/doc/
{ "language": "en", "url": "https://stackoverflow.com/questions/7629167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AtomicInteger not reading value from main memory for non-volatile mutable refrence Below is a non-thread-safe implementation of popular Husband Wife bank account problem. (One thread first checks the account, and before the same thread performs withdraw, another thread performs withdraw operation, thus breaking the code). If we look at the logs of the program after execution of Demo.java file. It is clear that, "Wife Thread" is not reading value of AtomicInteger amount from main memory. Also, I tried the same example with plain "volatile int". But again, I am facing the same problem :- "Wife-Thread is not reading value of amount integer from main memory." Kindly explain this behaviour to help me understand the concept. Please find the code below :- AtomicBankAccount.java package pack; import java.util.concurrent.atomic.AtomicInteger; public class AtomicBankAccount { private AtomicInteger amount ; public AtomicBankAccount(int amt) { this.amount = new AtomicInteger(amt) ; } // returns // -1 for insufficient funds // remaining balance without subtracting from actual amount for sufficient funds public int check(int amtToWithdraw){ if(amtToWithdraw <= amount.get()){ System.out.println(Thread.currentThread().getName() + " checks amount : " + amount.get() + ". Remaining ammount after withdrawl should be : " + (amount.get() - amtToWithdraw)); return (amount.get() - amtToWithdraw) ; }else{ return -1 ; } } // returns // remaining balance after subtracting from actual amount public int withdraw(int amtToWithdraw){ amount.getAndAdd(-amtToWithdraw) ; System.out.println(Thread.currentThread().getName() + " withdraws " + amtToWithdraw + ". Remaining : " + amount.get() + " [latest updated value of account in main memory]"); return amount.get() ; } public int getAmount(){ return amount.get() ; } } AtomicWithdrawThread.java package pack; public class AtomicWithdrawThread extends Thread{ private AtomicBankAccount account ; public AtomicWithdrawThread(AtomicBankAccount acnt, String name) { super(name) ; this.account = acnt ; } @Override public void run() { int withDrawAmt = 2 ; int remaining = 0 ; while(true){ if( (remaining = account.check(withDrawAmt)) != -1 ){ int temp = account.withdraw(withDrawAmt) ; if(temp != remaining){ System.out.println("[Race condition] " + Thread.currentThread().getName()); System.exit(1) ; } }else{ System.out.println("Empty Account...."); System.exit(1) ; } } } } Demo.java package pack; public class Demo { public static void main(String[] args) { AtomicBankAccount bankAccount = new AtomicBankAccount(1000) ; AtomicWithdrawThread husbandThread = new AtomicWithdrawThread(bankAccount, "husband") ; AtomicWithdrawThread wifeThread = new AtomicWithdrawThread(bankAccount, "wife") ; husbandThread.start() ; wifeThread.start() ; } } Best Regards, rits A: That code looks fishy: amount.getAndAdd(-amtToWithdraw) ; return amount.get() ; If the other thread creeps between that... funny things can happen. Use and test that code instead (also in the System.out please): int amt = amount.getAndAdd(.amtToWithdraw); return amt - amtToWithdraw; And here also: if(amtToWithdraw <= amount.get()){ return (amount.get() - amtToWithdraw) ; use again the pattern int amt = amount.get(); if(amtToWithdraw <= amt){ return (amt - amtToWithdraw) ; But that code is NOT fixable: if( (remaining = account.check(withDrawAmt)) != -1 ){ int temp = account.withdraw(withDrawAmt) ; Between those accesses to the AtomicInteger the other thread can creep in and wreck havok. You must adapt the code to be thread safe. A usual pattern/idiom is like this: // In AtomicBankAccount public int withdraw(int amtToWithdraw){ for(;;){ int oldAmt = amount.get(); int newAmt = oldAmt - amtToWithdraw; if( newAmt < 0 ) return -1; if( amount.compareAndSet(oldAmt, newAmt) ){ System.out.println(Thread.currentThread().getName() + " withdraws " + amtToWithdraw + ". Remaining : " + newAmt + " [latest updated value of account in main memory]"); return newAmt; } } } // in AtomicWithdrawThread: public void run() { int withDrawAmt = 2 ; while(true){ if( account.withdraw(withDrawAmt) >= 0 ){ // OK } else{ System.out.println("Empty Account...."); System.exit(1) ; } } } Note that checkWithdraw is no more. That`s good because that way no one else can get get between the check and the actual withdrawal. A: Note: These first few paragraphs describe the deliberate lack of thread safety in the question, and don't actually answer the point the questioner was asking about.. The check method and the withdraw method, while individually are atomic, don't combine into a single atomic operation. Say Husband checks the accounts, finds there is enough remaining, and then gets suspended. Wife checks the accounts, then withdraws the remaining money. Husband is then allowed to continue, and tries to withdraw the money, but finds wife has already gone off with it all. Edit: Describes the reason for the questioner's issue You aren't calling System.out in a thread-safe way. There is a race condition between calculating the message that you are going to display and actually getting it to appear on the console - so the wife's message is probably calculated before the husband's withdrawal, but displayed after it. You need to add synchronized keywords around those System.out lines (or something equivalent) if you want to eliminate this effect. Just imagine your code actually looks like this: String message = Thread.currentThread().getName() + " checks amount : " + amount.get() + ". Remaining ammount after withdrawl should be : " + (amount.get() - amtToWithdraw); System.out.println(message); Does this help show where the race condition is?
{ "language": "en", "url": "https://stackoverflow.com/questions/7629172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: passing information from ASP.NET ashx to aspx I am using Jquery ajax to Upload files to my database to produce a progress bar.. The problem is, I have no way of passing the uploaded filename to my backend code. I can easily enough pass the filename that was sent via the user using Hiddenfields and jquery, however my ASHX Handler may have renamed it if that file exists. I tried to create a Session["variable"] in the ASHX file with the passed context, however it was null.. Here is my Javascript : $(function () { $("#<%=supplierInfo.FUclientID %>").makeAsyncUploader({ upload_url: '<%=ResolveUrl("~/Controls/UploadHandler.ashx")%>', // Important! This isn't a directory, it's a HANDLER such as an ASP.NET MVC action method, or a PHP file, or a Classic ASP file, or an ASP.NET .ASHX handler. The handler should save the file to disk (or database). flash_url: '../../Scripts/swfupload.swf', button_image_url: '../../Scripts/blankButton.png', disableDuringUpload: 'INPUT[type="submit"]', upload_success_handler: function () { var hiddenfield = document.getElementById('<% =hdnTest.ClientID %>'); hiddenfield.value = "test"; $("span[id$=_completedMessage]", container).html("Uploaded <b>{0}</b> ({1} KB)" .replace("{0}", file.name) .replace("{1}", Math.round(file.size / 1024)) ); } }); }); The ASHX Handler: <%@ WebHandler Language="C#" Class="UploadHandler" %> using System; using System.Web; using System.IO; public class UploadHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { string strFileName = Path.GetFileName(context.Request.Files[0].FileName); string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower(); int i = 0; while (File.Exists(context.Server.MapPath("~/images/Upload/SupplierImg") + "/" + strFileName)) { strFileName = Path.GetFileNameWithoutExtension(strFileName) + i.ToString() + strExtension; } string strLocation = context.Server.MapPath("~/images/Upload/SupplierImg") + "/" + strFileName; context.Request.Files[0].SaveAs(strLocation); context.Response.ContentType = "text/plain"; context.Response.Write("OK"); } public bool IsReusable { get { return false; } } } A: Why not return strFileName instead of "OK", then you have the file name? context.Response.Write(strFileName ); A: If you want to use Session in your handler you need to implement the IRequiresSessionState interface. A: Make sure you are explicitly declaring the content type in your jQuery AJAX call. $.ajax({ type: "POST", url: "UploadHandler.ashx", data: "{ 'fileName' : 'myFileName' }", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { // This may be data.d depending on what version of .NET you are running // See this link for more info on .d - http://haacked.com/archive/2009/06/25/json-hijacking.aspx $("span[id$=_completedMessage]", container).html("Uploaded <b>{0}</b> ({1} KB") .replace("{0}", data.fileName) .replace("{1}", Math.round(data.fileSize / 1024)) ); } }); And you may want to pre-serialize your data on the server: public void ProcessRequest (HttpContext context) { string strFileName = Path.GetFileName(context.Request.Files[0].FileName); ... context.Response.ContentType = "text/plain"; context.Response.Write(JsonConvert.SerializeObject(new { fileName = strFileName, fileSize = iFileSize })); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7629176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Including a PHAR file in a PHP Script (PHP5.3 / Debian) I'm trying to include a PHAR file (PHP Archive) in my PHP script, it works fine on WAMP, but not on my debian server ! My server has PHP5.3 (including PHAR extension natively !), but my script stops when including the PHAR (in fact Silex) My code (file_exists() works fine): <?php require_once __DIR__.'/../vendor/silex.phar'; I saw that PHAR is enabled thanks to phpinfo(). However, I tried many things to correct this problem: * *I had AddType application/x-httpd-php .phar in my httpd.conf *Also, I tried to fixe a bug: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=639268 *I saw this: http://www.shaunfreeman.co.uk/article/A-Phar-problem, but not resolving my prob... Nothing works... have a solution ? A: when you use PHP with the Suhosin patch, you may need to enable the use of phars in the suhosin.ini. You can add the line to the suhosin.ini suhosin.executor.include.whitelist = phar If you don't do so the script will fail silently This is common on debian and ubuntu A: Solutions to the most common problems with getting PHAR to work are documented in the pitfalls section of the Silex documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring.NET WebServiceExporter and MVC3 I'm trying to get a simple Spring.NET webservice working with MVC3 but although there are no errors, and I can see from the logs that Spring is deploying it, I can't htt the correct URL for my web service at all. I think I've followed the example (that comes with Spring.NET) correctly. Mine differs in that I'm not doing any AOP weaving on my service. As far as I can tell, it should work.... but doesn't. Here's my service class (very basic) public interface IHelloService { string SayHello(); } public class HelloService : IHelloService { public String SayHello() { return "Hello"; } } And here's my config <!-- Web services --> <object id="HelloService" type="Munch.Service.Web.HelloService, Munch.Service"/> <!-- Exports contact service (weaved or not) as a web service. --> <object id="HelloWebService" type="Spring.Web.Services.WebServiceExporter, Spring.Web"> <property name="TargetName" value="HelloService"/> <property name="Namespace" value="http://Munch.Service.Web/HelloService"/> <property name="Description" value="Hello Web Services"/> <property name="TypeAttributes"> <list> <object type="System.Web.Script.Services.ScriptServiceAttribute, System.Web.Extensions"/> </list> </property> </object> I would expect to be able to access my web service at something like http://localhost:8080/Munch/HelloWebService.asmx but no joy with any of the variations I have tried. Is there a way to find out what web services have been deployed (some debug page perhaps)? The example that comes with Spring does actually work(!) so I know it's possible to get a working Spring WS on my machine, I just can't see where I've gone wrong. A: I was able to use to publish your HelloService in the spring.net Spring.Mvc3QuickStart that ships with spring.net 1.3.2. These were the things I had to do to get it to work: * *Add the service configuration to the spring.net mvc context *Add all asmx resources to routes.IgnoreRoute *Add the Spring.Web.Services.WebServiceHandlerFactory from Spring.Web, as bbaia had commented on your question I suspect you've forgotten to add all asmx resources to routes.IgnoreRoute. Step-by-step Start with the Spring.Mvc3QuickStart example application that ships with Spring.Net 1.3.2. Reference the project that contains the HelloService class from your question. Add a file ~/Config/services.xml to the project, containing your service configuration: <object id="HelloService" type="Munch.Service.Web.HelloService, Munch.Service"/> <object id="HelloWebService" type="Spring.Web.Services.WebServiceExporter, Spring.Web"> <property name="TargetName" value="HelloService"/> <property name="Namespace" value="http://Munch.Service.Web/HelloService"/> <property name="Description" value="Hello Web Services"/> <property name="TypeAttributes"> <list> <object type="System.Web.Script.Services.ScriptServiceAttribute, System.Web.Extensions"/> </list> </property> </object> In Global.asax, add routes.IgnoreRoute("{resource}.asmx/{*pathInfo}"); to RegisterRoutes. This will tell the asp.net mvc handler to leave requests to asmx resources alone. In web.config, add the following http handler: <system.web> <!-- ... --> <httpHandlers> <add verb="*" path="*.asmx" type="Spring.Web.Services.WebServiceHandlerFactory, Spring.Web" /> </httpHandlers> <!-- ... --> In web.config, add your service configuration to the spring context: <spring> <context> <resource uri="file://~/Config/controllers.xml" /> <resource uri="file://~/Config/services.xml" /> </context> </spring> When you run the application from Visual Studio, you should be able to view the service at http://localhost:12345/HelloWebService.asmx (replace 12345 with you dev port). Notes I'm unfamiliar with asp.net-mvc, so there might be better ways to configure it than I've suggested.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to prevent my site form being parsed? Are there any tips or tricks to prevent my site (let's say it's pure HTML and CSS) from being parsed? How can I protect my site from things like f.ex? Maybe messing around with the DOM would help? Any ideas? A: You can't "prevent your site form from being parsed". If your HTML page was not parsable, the visitor could not read it with their browser. You could obfuscate your page using Javascript and generate the HTML using it, but that's easily circumvented. If your goal is "protecting" your HTML source, keep the page on your notebook / tablet / smartphone and show it to others without making the page available on the Internet. In that way, users cannot see your HTML source nor parse it. Still, any form of HTML source protection is questionable. Another way to hide your HTML is by taking a picture of your page, but that has some disadvantages like increase of file size and inability for screen readers to read your page. DOM stands for Document Object Model and is in short an easy way to access your HTML elements. It's no magic and cannot help you from preventing the form being parsed. Again, if the browser cannot parse it, the user won't see it either. A: I see this question is old, but just in case, Yes you actually can prevent (not a rock solid answer) your site from being parsed if you check for the browser headers, before you display anything. In PHP for example (I tested it myself) $arraySet = array(); $arraySet =apache_request_headers(); if($arraySet['User-Agent']){ // place your code or html here if you dont want it to be accessed via fopen, fread etc. } if accessed directly, I can see/read the website content, but If via file_get_contents(), nothing shows up in the response. Of course, this way, you would most probably prevent web crawlers among other ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7629192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you lay out your custom binary file format? Every application has its own custom binary file format (e.g. .mpq, .wad). On top of that, its commonly zipped. So, my question is, how do you artfully/skillfully layout the binary contents of your file. Do you have a "table of contents" like structure at the beginning? Is it better to dump everything in one file? So say you have an array of Shapes, and in each Shape is deformed vertex data (so the vertex data has changed from the file it was originally loaded from, so it should be saved anew). class Shape { vector<Vertex> verts ; } ; class Sphere : public Shape { } ; // ...more geometric shapes (Tet, Cube) are defined.. class Model : public Shape { } ; // general model "Shape" loaded from file vector<Shape*> shapes ; // save me! contents are mix of Model, Sphere, Tet.. // each with variable number of verts A: My favorite article on the topic of file formats is at http://www.fadden.com/techmisc/file-formats.htm. Beyond that, it probably comes down to what kind of data you are storing, and how that data will be used (will it be transmitted across a network, primarily? How important is seek access? Etc...). Start with that article; it may help crystallize your thoughts if you already have a format that needs designing. A: In short - if your only need serialization, which means that you'll read and write from and to a stream, than you can use no-brainer here and emit your scructs member by member, or use any serialization library there is, from CArchive to .... whatever you see fancy. If not, and you will have a need to directly access your data inside the file, then... you'll use your requirements and they will, with some skill, tell you what will be layout of the file you are having. And yeah, to broad topic to dwell here. For example, I have a need for a database of thumbnails for my software. Each thumbnail has a timestamp, and I know that they will be of a different size. Requirements are: * *sequential write (thumbs will be appended to the end of the database) *thumbs will be appended in ascending order *direct read (given time, get thumbnail in o(1) ) *no later modification to the database *thumbnails will be in 15 seconds interval Yes, requirements ARE simple here, but they stand for themselves. I created two files, one with indexes and other with pictures. Storing: append data file with image, append index file with index of the image in the data file. Reading: find the index in the file using simple indexing ( index is (timestamp-timestamp_start)/15 ). Use that index to fetch image data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Mobile: Embedding Images for Speed Would embedding images in mobile Air applications speed up the process of drawing the UI that uses images? How does one properly embed the images? Thanks! A: The advantage of embedding an images is that it is included in the SWF file, and can be accessed faster than it can if the application has to load it from a remote location at run time. but it also have disadvantage that is your SWF file is larger than if you load the asset at run time. The embed process is very simple, just follow to follow steps: * *copy your image files where the "src" folder is of your application. the Flex 4 will get these files from there. Of course you may define sub folders to do not mess up. *In your class define like the example bellow [Embed (source="728x90a.jpg" )] public static const imgData1:Class; The 728x90a.jpg is the file name of the image (I didn't use sub folders here) The imgData1 is the object where contains the data of the embedded image! *Somewhere in your code, load the data into a visual component, like the example bellow img1.source=imgData1; The img1 is an Image component. package { public class TestProjectAssets { [Embed(source="fonts/MySuperDuperFont.otf", fontFamily="SuperDuperFont", mimeType="application/x-font", embedAsCFF="true")] private const SuperDuperFont:Class; [Embed(source="assets/mainMenu.png")] public static const mainMenuImg:Class; } } If you need to handle a large number of resources you can follow these 3 steps: Place them in an uncompressed zip archive Embed the zip file as binary data: [Embed(source = 'resources.zip', mimeType = 'application/octet-stream')] Access the resources using [FZip][1] If you choose a different method that involves loading external files be aware that some flash game websites require the games they host to be contained within a single swf file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why must we assign a clone to a new variable? I am currently learning to use the Propel ORM, and I want to reuse a critera for two slightly different queries: $criteria = ArticleQuery::create() ->filterByIsPublished(true) ->orderByPublishFrom(Criteria::DESC) ->joinWith('Article.Author') ->keepQuery(); $this->news = $criteria ->filterByType('news') ->find(); $this->articles = $critera ->filterByType('article') ->find(); However, this won't work as expected, because now the query for articles will try to find entries where the type is both 'news' and 'article', which of course is impossible. So we need to get a clone of this object, and what seemed intuitive to me was to simply add the clone keyword inside paranthesis: $this->news = (clone $criteria) ->filterByType('news') ->find(); Parse error: syntax error, unexpected T_OBJECT_OPERATOR Instead we have to assign it to a variable before we can use it: $clonedCritera = clone $criteria; $this->news = $clonedCriteria ->filterByType('news') ->find(); You have the same behaviour with the newoperator. I see the propel developers have circumvented this limitation by replacing: new ArticleQuery()->doOperations() with ArticleQuery::create()->doOperations(). Why did the PHP language designers choose to do it this way? If you could use the result of these expressions directly, it would make the code more fluent and, in some cases, easier to read. A: Why must we assign a clone to a new variable? Unfortunately, the answer is that the developers haven't gotten around to supporting direct dereferencing on objects returned via clone yet. In PHP 4, you couldn't "dereference" any objects returned by method. You had to assign it to a dummy variable first. In the next version of PHP, array dereferencing is to be supported. So, it's clear that the dev team incrementally adds such features on their timetable. The best I can tell you is to request this functionality from the dev team.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What is preventing tables from being correctly formatted with CSS when table is built by PHP functions? I have a table that is built dynamically on my web app. The number of the rows and contents within rows is determined by a series of PHP functions. Once this is determined, they call another set of PHP functions that create the individual table rows and contain classes to define how they should look. Despite having working tables everywhere else on my app, I can't figure out why I can't get standard and formatting to work for this table. The output is ordered into a table but I can't change font size, min-width, background color or anything. If someone could point out my problem, that would be greatly appreciated! Here is the PHP function that determines structure: // Determines the core number of buckets and the appropriate general structure for tree function drawFullTree ($hyp, $b_count, $sb_count, $b, $sb) { // loop through *all* buckets // if any bucket has no-sub buckets, put three (blanks) in it for($i = 0; $i < $b_count; $i++){ if(!isset($sb[$i])){ $sb[$i][0] = '(blank)'; $sb[$i][1] = '(blank)'; $sb[$i][2] = '(blank)'; } } echo '<table class="answer">'; if($b_count > 0){ if(isset($sb[0])){ drawBuc_Sub($b[0], $sb[0]); } else{ echo 'sub-bucket blank'; } } if($b_count == 0){ echo 'What! No buckets - lets turn up the effort here!'; } else if($b_count == 1){ echo "One bucket! Ok, it's a start... keep 'em coming"; } else if($b_count == 2){ drawTop_Hyp_Buc_Sub($hyp, $b[1], $sb[1]); } else if($b_count == 3){ drawHyp_Buc_Sub($hyp, $b[1], $sb[1]); drawBuc_Sub($b[2], $sb[2]); } else if($b_count == 4){ drawBuc_Sub($b[1],$sb[1]); writeHyp($hyp); drawBuc_Sub($b[2],$sb[2]); drawBuc_Sub($b[3],$sb[3]); } else if($b_count == 5){ drawBuc_Sub($b[1],$sb[1]); drawHyp_Buc_Sub($hyp, $b[2],$sb[2]); drawBuc_Sub($b[3],$sb[3]); drawBuc_Sub($b[4],$sb[4]); } else if($b_count == 6){ drawBuc_Sub($b[1],$sb[1]); drawBuc_Sub($b[2],$sb[2]); writeHyp($hyp); drawBuc_Sub($b[3],$sb[3]); drawBuc_Sub($b[4],$sb[4]); drawBuc_Sub($b[5],$sb[5]); } echo '</table>'; } Here is an example of a PHP function where I can't get formatting applied correctly: function writeHyp_Buc_Sub ($hyp, $buc, $sub) { echo '<tr>'; echo '<td class="x">' . $hyp . '</td>'; echo '<td class="x">' . $buc . '</td>'; echo '<td class="x">' . $sub . '</td>'; echo '</tr>'; } And here is the CSS I have: table{ border-collapse: collapse; } td { font-size:.80em; color: #333333; padding: 6px 4px; text-align:left; /*border-bottom: 1px dotted #cccccc;*/ } table.answer{ background-color:green; border:3px black; } td.x { width:230px; font-size:1.1em; border:2px solid black; /*#DCDCDC; */ } the jquery that calls the php functions and inserts it into page: $('#process_structure').live('click', function () { var postData = $('#inputs_structure').serializeArray(); postData.push({name: 'count', value: count}); $('#testing').fadeOut('slow'); $.ajax ({ type: "POST", url: "structure_process.php", data: $.param(postData), success: function(text){ $('#testing').fadeIn('500', function(){ $('#testing').html(text); }) } }); $(this).parent().html('<form action="structure.php"><button class="begin_mod_button">Do another!</button></form>'); clearInterval(interval); return false; }); A: is your css in the head of the html document? if not that might be the problem... if you're using IE<=7 (maybe newer versions too) I'm pretty sure this is the solution. IE only renders css on pageload... inline css is not applied on new things inserted in the dom if the css is not in the head section. since the php are functions I guess they output correct html (you are probably using them elsewhere). so the only thing that can be wrong (considered the statement above) is your html/css "binding".
{ "language": "en", "url": "https://stackoverflow.com/questions/7629198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a cumulative sum column in MySQL Sample table ID: (num is a key so there wouldn't be any duplicates) num 1 5 6 8 2 3 Desired output: (Should be sorted and have a cumulative sum column) num cumulative 1 1 2 3 3 6 5 11 6 17 8 25 This is one solution I got: select a.num, sum(b.num) from ID a, ID b where b.num <= a.num group by a.num order by a.num; A: You can use a temporary variable to calculate the cumulative sum: SELECT a.num, (@s := @s + a.num) AS cumulative FROM ID a, (SELECT @s := 0) dm ORDER BY a.num; A: I think I figured out the solution. Select num as n, (select sum(num) from ID where num <= n) from ID order by n; A: Since MySQL 8, cumulative sums are ideally calculated using window functions. In your case, run: SELECT num, SUM(num) OVER (ORDER BY num) cumulative FROM id A: as these answer i already tested in my project and actually i want to know which one is faster so i also posted this here which one is faster declare @tmp table(ind int identity(1,1),col1 int) insert into @tmp select 2 union select 4 union select 7 union select 5 union select 8 union select 10 SELECT t1.col1,sum( t2.col1) FROM @tmp AS t1 LEFT JOIN @tmp t2 ON t1.ind>=t2.ind group by t1.ind,t1.col1 select t1.col1,(select sum(col1) from @tmp as t2 where t2.ind<=t1.ind) from @tmp as t1
{ "language": "en", "url": "https://stackoverflow.com/questions/7629200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is -z in if [ -z "${FILE_LIST}" ] Came across this, what is -z in the shell script if [ -z "${FILE_LIST}" ]? A: [ is the same as test. And man test gives: -z STRING the length of STRING is zero Note: On some platforms, [ is a symlink or hardlink to test A: From help test: -z STRING True if string is empty. A: -z tests for a zero-length string. A: I think if you're using bash, then it would return true if the length of the string is zero (so in your case, there are no files in the list).
{ "language": "en", "url": "https://stackoverflow.com/questions/7629201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Display UIImage Instead of TableView if Empty I have a NSFetchResultsController that loads up my tableview. When the app is first downloaded, there will be no data to show in the tableview so I want to have a static image with instructions on it. I have the following code and I call this method in viewWillAppear but it doesn't function right. Any ideas? - (void)checkIfEmpty { if ([self.fetchedResultsController fetchedObjects] > 0) { self.defaultImage.hidden = NO; self.logTableView.hidden = YES; } else { self.defaultImage.hidden = YES; self.logTableView.hidden = NO; } } A: Try putting the same code in viewDidAppear . Try using alpha = 0 instead of hidden. Try putting the same code in one of your tableview delegate methods. Since you don't explain exactly what occurs I'm just throwing stuff out there. A: [self.fetchedResultsController fetchedObjects] > 0 will always be true because even an empty array is an object (and not nil). You need to use self.fetchedResultsController.fetchedObjects.count > 0 instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: substrings and garbage in java 1.6 Using a profiler, I seem to be seeing the following with Apple's 1.6 Java: I start with a moderately long Java string. I split it into tokens using String.split("\\W+"). The code then holds references to some of the split up pieces. It seems, if I believe my eyes in yourkit, that Java has helpfully not copied these strings, so that I'm in fact holding references to the lengthy originals. In my case this leads to a rather large waste of space. Does this seem plausible? It's easy enough to add a loop making copies of these guys. A: String.split() does not copy the parts of the String [the new objects...], instead it uses the String's fields: offset and count. By "changing" them, when later you access the String object, it is done by adding the offset to the original reference. This is indeed done to prevent copying the whole String, and save space [well, at least usually...]. So basically yes. All of your new objects, will have the same char[] reference, which leads to the original char[], in the original String.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: The name "comportnumber" does not exist in the current contex I decided to save all settings in SQL. In case I want to read for ex. comport from SQL DB and than I got an error: "c# the name "comportnumber" does not exist in the current contex" What should I change to solve it ? SqlCeConnection conn = new SqlCeConnection("Data Source = \\Program Files\\myprogram\\db.sdf; Password ='mypassword'"); conn.Open(); SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [COMPORT]", conn); SqlCeDataReader rdr = cmd.ExecuteReader(); cmd.Connection = conn; cmd.ExecuteNonQuery(); while (rdr.Read()) { string comportnumber = rdr.GetString(0); } serialPort1.PortName = comportnumber; conn.Close(); serialPort1.Close(); if (!serialPort1.IsOpen) serialPort1.Open(); A: The issue with your question is that your comportnumber variable's scope was limited to the relatively small bracketed section in the while loop. Just move the declaration up. But you have other issues as well - note how I restructured the code. string comportnumber = ""; using (SqlCeConnection conn = new SqlCeConnection("Data Source = \\Program Files\\myprogram\\db.sdf; Password ='mypassword'")) using (SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [COMPORT]", conn)) { conn.Open(); using (SqlCeDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { comportnumber = rdr.GetString(0); } } } serialPort1.PortName = comportnumber; serialPort1.Close(); if (!serialPort1.IsOpen) serialPort1.Open(); A: As you have it, comportnumber only exists in the scope of the while loop. Try changing it to: string comportnumber = string.Empty; while (rdr.Read()) { comportnumber = rdr.GetString(0); } serialPort1.PortName = comportnumber;
{ "language": "en", "url": "https://stackoverflow.com/questions/7629213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Update server-processed DataTables source with additional parameters I'm trying to pass additional parameters (list of selected checkboxes) to a server-processed DataTables-table #my_table when a Submit input button has been clicked: Which probably means I must set the my_table.sAjaxSource to the backend script plus a compiled list of checkboxes and then call my_table.fnDraw()? I've prepared a very simple test case - test.php: <?php error_log('QUERY_STRING: ' . $_SERVER['QUERY_STRING']); ?> and index.html: <html> <head> <style type="text/css" title="currentStyle"> @import "/css/demo_table_jui.css"; @import "http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/redmond/jquery-ui.css"; </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>; <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>; <script type="text/javascript" src="/js/jquery.dataTables.min.js"></script> <script type="text/javascript"> $(function() { my_table = $('#my_table').dataTable( { bJQueryUI: true, bServerSide: true, bProcessing: true, sAjaxSource: '/test.php' } ); }); var my_table; function redrawTable() { var str = ''; var boxes = new Array(); //loop through all checkboxes $(':checkbox').each(function() { if ($(this).is(':checked')) { boxes.push($(this).attr('name') + '=' + $(this).val()); } }); str = '/test.php?' + boxes.join('&'); // TODO: set my_table.sAjaxSource to str my_table.fnDraw(); } </script> </head> <body> <p>Select fruit:</p> <p><label><input type="checkbox" name="fruits" value="apple">apple</label></p> <p><label><input type="checkbox" name="fruits" value="banana">banana</label></p> <p><label><input type="checkbox" name="fruits" value="pear">pear</label></p> <p>Select candy:</p> <p><label><input type="checkbox" name="candy" value="toffee">toffee</label></p> <p><label><input type="checkbox" name="candy" value="fudge">fudge</label></p> <p><input type="button" onclick="redrawTable();" value="Submit"></p> <table class="display" id="my_table"> <thead> <tr> <th>Column_1</th> <th>Column_2</th> <th>Column_3</th> </tr> </thead> <tbody> </tbody> </table> </body> </html> Please advise me, how to achieve this (passing custom params to DataTables AJAX source script). UPDATE: this code seems to work well for me, thanks Nicola <html> <head> <style type="text/css" title="currentStyle"> @import "/css/demo_table_jui.css"; @import "http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/redmond/jquery-ui.css"; </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script> <script type="text/javascript" src="/js/jquery.dataTables.min.js"></script> <script type="text/javascript"> var my_table; $(function() { my_table = $('#my_table').dataTable( { bJQueryUI: true, bServerSide: true, bProcessing: true, sAjaxSource: '/test.php', fnServerParams: function ( aoData ) { $(':checkbox').each(function() { if ($(this).is(':checked')) { aoData.push( { name: $(this).attr('name'), value: $(this).val() } ); } }); } }); }); </script> </head> <body> <p>Select fruit:</p> <p><label><input type="checkbox" name="fruits" value="apple">apple</label></p> <p><label><input type="checkbox" name="fruits" value="banana">banana</label></p> <p><label><input type="checkbox" name="fruits" value="pear">pear</label></p> <p>Select candy:</p> <p><label><input type="checkbox" name="candy" value="toffee">toffee</label></p> <p><label><input type="checkbox" name="candy" value="fudge">fudge</label></p> <p><input type="button" onclick="my_table.fnDraw();" value="Submit"></p> <table class="display" id="my_table"> <thead> <tr> <th>Column_1</th> <th>Column_2</th> <th>Column_3</th> </tr> </thead> <tbody> </tbody> </table> </body> </html> And in the error_log I see: QUERY_STRING: sEcho=2& iColumns=3& sColumns=& iDisplayStart=0& iDisplayLength=10& mDataProp_0=0& mDataProp_1=1& mDataProp_2=2& sSearch=& bRegex=false& sSearch_0=& bRegex_0=false& bSearchable_0=true& sSearch_1=& bRegex_1=false& bSearchable_1=true& sSearch_2=& bRegex_2=false& bSearchable_2=true& iSortingCols=1& iSortCol_0=0& sSortDir_0=asc& bSortable_0=true& bSortable_1=true& bSortable_2=true& fruits=apple& fruits=banana& candy=toffee& candy=fudge& _=1317666289823 A: As you can see from this example you should use fnServerParams: "fnServerParams": function ( aoData ) { aoData.push( { "name": "more_data", "value": "my_value" } ); } where aoData is an array of objects to send to the server
{ "language": "en", "url": "https://stackoverflow.com/questions/7629218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Checkbox Checked Enables Textbox I have created a form that enables a text box when a certain checkbox is checked, however the text I enter in the form is not stored in my Classipress/wordpress install. What do I need to do to fix this code so it stores what the user enters in the text box? <li> <div class="labelwrapper"> <label>Certifications: </label> </div> <ol class="checkboxes"> <li> <input type="checkbox" name="cp_certifications_list" id="cp_certifications_1" value="TEFL" class="checkboxlist " onclick="addRemoveCheckboxValues(this, 'cp_certifications_value')">&nbsp;&nbsp;&nbsp;TEFL </li> <!-- #checkbox --> <li> <input type="checkbox" name="cp_certifications_list" id="cp_certifications_2" value=" TESOL" class="checkboxlist " onclick="addRemoveCheckboxValues(this, 'cp_certifications_value')">&nbsp;&nbsp;&nbsp;TESOL </li> <!-- #checkbox --> <li> <input type="checkbox" name="cp_certifications_list" id="cp_certifications_3" value=" CELTA" class="checkboxlist " onclick="addRemoveCheckboxValues(this, 'cp_certifications_value')">&nbsp;&nbsp;&nbsp;CELTA </li> <!-- #checkbox --> <li> <input type="checkbox" name="cp_certifications_list" id="cp_certifications_4" value=" ESL Degree" class="checkboxlist " onclick="addRemoveCheckboxValues(this, 'cp_certifications_value')">&nbsp;&nbsp;&nbsp;ESL Degree </li> <!-- #checkbox --> <li> <input type="checkbox" name="cp_certifications_list" id="cp_certifications_5" value=" Teaching Certificate" class="checkboxlist " onclick="addRemoveCheckboxValues(this, 'cp_certifications_value')">&nbsp;&nbsp;&nbsp;Teaching Certificate </li> <!-- #checkbox --> <li> <input type="checkbox" name="cp_certifications_list" id="cp_certifications_6" value=" English Degree" class="checkboxlist " onclick="addRemoveCheckboxValues(this, 'cp_certifications_value')">&nbsp;&nbsp;&nbsp;English Degree </li> <!-- #checkbox --> <li> <input type="checkbox" name="cp_certifications_list" id="cp_certifications_7" value=" Other" class="checkboxlist " onclick="document.getElementById('cp_certifications_8').disabled=(this.checked)?0:1">&nbsp;&nbsp;&nbsp;Other </li> <!-- #checkbox --> <li> <input name="cp_certifications_list" id="cp_certifications_8" type="text" minlength="2" value="" class="text " disabled /></li> <input type="hidden" name="cp_certifications" id="cp_certifications_value" value="" style="display:none;" /> </ol> <!-- #checkbox-wrap --> <div class="clr"></div> </li> A: I don't think this is the appropriate forum for this question. I think you may have more success over at http://wordpress.stackexchange.com . I don't know how the Classipress Wordpress theme works, but you may want to ask on their forums or ask their developers what people typically do. Otherwise I think there are two options left to you. One is to createa Wordpress plugin. Wordpress plugins have a means for saving information to the Wordpress database. http://codex.wordpress.org/Writing_a_Plugin#Saving_Plugin_Data_to_the_Database The other option is to setup your own database. You'll need to submit your form to a server that can postprocess the data and write it to a database. Sounds like you may be in over your head. You may want to try and enlist a programmer friend for help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple OpenCL CPU Devices on a single host? Will a host ever have more than one CPU-type device? Multi-core CPUs will come up as a single device, but what about dual-socket motherboards? Will there be two separate devices in OpenCL for each processor? I'm trying to plan ahead with an application I'm working on. A: Besed on my experience, on dual-socket motherboards you still have one CPU device. The OS usually hides from user whether cores are located on same physical CPU or on different ones, even on NUMA machines (of course you can get detailed info, but it's not all that straightforward). And I think this behaviour is quite logical, at least on SMP machines, since there is not much difference how cores are located physically (in case of GPU, accessing other device memory is quite troublesome; on CPUs pinning all your threads to same physical CPU rarely worth worrying), so there are barely any disadvantages in melting two physical CPUs into one OpenCL device, and it has advantage of simplifying its usage. However I've not seen this mentioned in OpenCL specification, so it's all implementation-specific, and is not guaranteed to always hold true. A: It is possible that in a multiple CPU environment on even on a multicore CPU there are more than one device. Take IBM's cell for an example, the 9 core CPU is seen by the OpenCL driver as 2 different devices. One is the PPU's device and the other represents the SPUs and has a CL_DEVICE_TYPE_ACCELERATOR profile). http://oscarbg.blogspot.com/2009/11/about-imd-open.html A: A compute cluster (multiple physical machines with separate memory) could possibly be abstracted as multiple OpenCL devices on a single "master" node, though I don't know if any implementations actually do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using std::vector with boost::bind While trying to get comfortable with boost, stumbled into problem with using boost::function along with std::vector. I'm trying to do a simple thing: have a list of functions with similair signatures and then use all that functions with std::for_each on sample data. Here is the code: typedef boost::function<int (const char*)> text_processor; typedef std::vector<text_processor> text_processors; text_processors processors; processors.push_back(std::atoi); processors.push_back(std::strlen); const char data[] = "123"; std::for_each(processors.begin(), processors.end(), std::cout << boost::bind(&text_processors::value_type::operator(), _1, data) << "\n" ); So, with for_each I'm trying to write to standard output the result of applying every function to sample data. But it won't compile like this (some long message about missing operator << for bind result). If I remove stream operators then I'll have compilable, but useless code. The trick is that I want to do function applying and text output in single for_each. What am I missing? Thought it should be easy with lambdas or smth like that, but can't figure out the correct solution. A: The problem with your code is that you are trying to create a functor in place in a way that is not allowed (you cannot just throw code at the third argument of for_each, you need to pass a functor). Without lambda support in the compiler you can use std::transform rather than std::for_each (not tested... but this should work): std::transform( processors.begin(), processors.end(), std::ostream_iterator<int>( std::cout, "\n" ), bind( &text_processors::value_type::operator(), _1, data ) ); If your compiler supports lambdas you can do with it: const char data[] = "123"; std::for_each(processors.begin(), processors.end(), [&data]( text_processors const & ) { std::cout << boost::bind(&text_processors::value_type::operator(), _1, data) << "\n" } ); But then you can avoid the bind altogether: std::for_each( processors.begin(), processors.end(), [&data]( text_processors::value_type & op ) { std::cout << op( data ) << "\n"; } );
{ "language": "en", "url": "https://stackoverflow.com/questions/7629230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: gcc sizeof(struct) giving unexpected value I am writing a program to unpack PE files. I have a struct, Pe_SymbolHeader. It looks like this: typedef struct _Pe_SymbolHeader { char Name[8]; // 8 uint32_t Value; // 12 uint16_t SectionNumber; // 14 uint16_t Type; // 16 uint8_t StorageClass; // 17 uint8_t NumberOfAuxSymbols; // 18 } Pe_SymbolHeader; gcc is telling me the size of this struct is 20 bytes. printf("sizeof Pe_SymbolHeader %d\n", sizeof(Pe_SymbolHeader)); I decided to place a Pe_SymbolHeader on the stack and take a look at where everything was located in memory Pe_SymbolHeader test printf("%p\n", &(test.Name)); printf("%p\n", &(test.Value)); printf("%p\n", &(test.SectionNumber)); printf("%p\n", &(test.Type)); printf("%p\n", &(test.StorageClass)); printf("%p\n", &(test.NumberOfAuxSymbols)); This gave me the following, which seems ok: 0x7fffffffe150 0x7fffffffe158 0x7fffffffe15c 0x7fffffffe15e 0x7fffffffe160 0x7fffffffe161 So if gcc is using 18 bytes to store my struct, why is sizeof telling me the struct will take 20 bytes? Edit: Ok, it seems what gcc is doing to try and help me is what is killing me, and several answers are correct. I can only vote for one, but thank you those who answered. A: The uint32_t part of the structure needs to be aligned on a multiple of 4 bytes, so the size of the structure has to be a multiple of 4 bytes to ensure that an array of the structure will not cause trouble (misaligned access trouble - which can lead to SIGBUS errors on some machines and to (very) inefficient access on (most) other machines). Therefore, the compiler mandates 2 padding bytes at the end of the structure; these have no name, so you cannot legitimately access them. A: Because of padding for alignment There is padding at the end of the struct. The reason has to do with what happens in an array or possibly some other context where something follows your struct. That something might be another instance of this struct. The struct contains a 32-bit object so it will have an alignment requirement of 32 bits. The compiler very much wants the next item to start on a natural word boundary for the architecture it is compiling for, so that any field in the next object can be read with a single operation instead of two operations plus some fiddling to combine two different "words". A: So if gcc is using 18 bytes to store my struct, why is sizeof telling me the struct will take 20 bytes? Put 2 structs like this on the stack and print the same thing for both of them, this will enlighten you. A: uint32_t Value; this is adding 6 bytes as opposed to expected 4. I tend to agree with Jonathan Leffler about the underlying reasons.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Library for converting PPTX presentations to HTML I'm looking for a .NET-library which allows me to convert PPTX-presentations (MS PowerPoint) to HTML. It should support animations and keep fidelity of original presentations. Which ones would you recommend? My goal is to stream pptx-presentations to several participants as html. It's kind of conferencing app like MS Lync in PP sharing mode. p.s. I'm aware of Aspose. It can export ppt to SVG but not pptx. A: This is a late answer and it still doesnt answer all because of the lacking animation support but Aspose does support PPTX to HTML and SVG. http://www.aspose.com/docs/display/slidesnet/Converting+PPTX+to+HTML PresentationEx pres = new PresentationEx(docStream); string css = "html,body{padding:0;margin:0;}"; css += ".slide{border:1px solid #ddd;}"; SlideImageFormat slideImageFormat = SlideImageFormat.Svg(new SVGOptions()); HtmlFormatter htmlFormatter = HtmlFormatter.CreateDocumentFormatter(css, false); HtmlOptions opts = new HtmlOptions { SlideImageFormat = slideImageFormat, HtmlFormatter = htmlFormatter }; pres.Save(Response.OutputStream, SaveFormat.Html, opts); Additionally, you could add JavaScript to load animations afterwards based on id or some custom engine. A: I believe the author has already found a solution, but perhaps my answer will be useful for anyone else with a similar issue. One can use iSpring Platform (http://www.ispringsolutions.com/ispring-platform) to deal with this task. This is a COM SDK that allows programs using .NET to convert PowerPoint presentations into HTML5 and Flash. It also supports all the animations, effects, and all the ppt capabilities. All the published presentations can be managed by Javascript, so it’s possible to use them in online conferencing apps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: "Shuffling" a Lucene Hits result set I have the following program: public class Hit { readonly Hits _hits; readonly int _index; public Hit(Hits hits, int index) { this._hits = hits; this._index = index; } public int id { get { return _hits.Id(_index); } } public float score { get { return _hits.Score(_index); } } public string this[string key] { get { return _hits.Doc(_index).Get(key); } } } class HitList : IList<Hit> { protected Hits hits; public HitList(Hits hits) { this.hits = hits; } #region IList Members public int Add(object value) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(object value) { throw new NotImplementedException(); } public int IndexOf(object value) { throw new NotImplementedException(); } public void Insert(int index, object value) { throw new NotImplementedException(); } public bool IsFixedSize { get { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public void Remove(object value) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } public object this[int index] { get { return new Hit(hits, index); } set { throw new NotImplementedException(); } } #endregion #region ICollection Members public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public int Count { get { return hits.Length(); } } public bool IsSynchronized { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } #endregion #region IEnumerable Members public System.Collections.IEnumerator GetEnumerator() { throw new NotImplementedException(); } #endregion #region IList<Hit> Members public int IndexOf(Hit item) { throw new NotImplementedException(); } public void Insert(int index, Hit item) { throw new NotImplementedException(); } Hit IList<Hit>.this[int index] { get { return new Hit(hits, index); } set { throw new NotImplementedException(); } } #endregion #region ICollection<Hit> Members public void Add(Hit item) { throw new NotImplementedException(); } public bool Contains(Hit item) { throw new NotImplementedException(); } public void CopyTo(Hit[] array, int arrayIndex) { throw new NotImplementedException(); } public bool Remove(Hit item) { throw new NotImplementedException(); } #endregion #region IEnumerable<Hit> Members IEnumerator<Hit> IEnumerable<Hit>.GetEnumerator() { throw new NotImplementedException(); } #endregion } private const string IndexFileLocation = @"C:\Users\Public\Index"; private IList<Hit> _hits; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Lucene.Net.Store.Directory dir = Lucene.Net.Store.FSDirectory.GetDirectory(IndexFileLocation, true); Lucene.Net.Analysis.Analyzer analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer(); var indexWriter = new Lucene.Net.Index.IndexWriter(dir, analyzer, true); for (var i = 0; i < 10; i++) { var doc = new Lucene.Net.Documents.Document(); var fldContent = new Lucene.Net.Documents.Field("content", "test " + i, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.TOKENIZED, Lucene.Net.Documents.Field.TermVector.YES); doc.Add(fldContent); indexWriter.AddDocument(doc); } indexWriter.Optimize(); indexWriter.Close(); var searcher = new Lucene.Net.Search.IndexSearcher(dir); var searchTerm = new Lucene.Net.Index.Term("content", "test"); Lucene.Net.Search.Query query = new Lucene.Net.Search.TermQuery(searchTerm); Lucene.Net.Search.Hits hits = searcher.Search(query); for (var i = 0; i < hits.Length(); i++) { Document doc = hits.Doc(i); string contentValue = doc.Get("content"); Debug.WriteLine(contentValue); } HitList h = new HitList(hits); h.Shuffle(); for (var i = 0; i < h.Count; i++) { var z = (Hit)h[i]; string contentValue = z.id.ToString(); Debug.WriteLine(contentValue); } } } public static class SiteItemExtensions { public static void Shuffle<T>(this IList<T> list) { var rng = new Random(); int n = list.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } } What I am trying to do is "shuffle" the results I get back from the Hits collection. When I run this program, as is, it bombs when I get to the h.Shuffle(); line. I understand why its bombing. Its bombing because its executing my Shuffle extension method, when in turn, is trying to do a set operation on an array value and I do not have a set implementation on the public object this[int index] line. My problem is, I can't implement a set because the Lucene id and score properties are read only, which, again, makes sense why Apache made them read only. My question is, how can I "shuffle" or randomize the Hits that I'm getting back? Any help would be appreciated. A: There might be some performance problems with the approach in question for shuffling search results. First, If I recall correctly, Hits class does a local document caching and repeats the search for every 100 documents. So, enumarating all search results would require "HitCount/100" searches. Second, loading a document is one of the most costly parts of the Lucene.Net. Just to be able to shuffle, loading all search results may not be a good choise. I would prefer a "random scoring" approach as below: public class RandomScoreQuery : Lucene.Net.Search.Function.CustomScoreQuery { Random r = new Random((int)(DateTime.Now.Ticks & 0x7fffffff)); public RandomScoreQuery(Query q): base(q) { } public override float CustomScore(int doc, float subQueryScore, float valSrcScore) { return r.Next(10000) / 1000.0f; //rand scores between 0-10 } } Query q1 = new TermQuery(new Term("content", "test")); Query q2 = new RandomScoreQuery(q1); TopDocs td = src.Search(q2, 100); A: You need to copy your hits to an appropiate data structure and do your sorting there; the underlying problem is that the Hits type is not intended for modification. For the shuffling, I believe this should do the trick: var shuffledHits = hits.Cast<Hit>().OrderBy(h => rng.Next());
{ "language": "en", "url": "https://stackoverflow.com/questions/7629235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIGraphicsBeginImageContext cutting off image this is my code I'm using to convert a UIView to UIImage and then emailing it out. When I go to send the new image its cutting off the sides but not the bottom. I do have a scroll view in place because the image is larger than the screen. UIGraphicsBeginImageContext(viewSubs.bounds.size); [viewSubs.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); A: Is this on a retina screen device so that the scale factor is 2.0? Try to use UIGraphicsBeginImageContextWithOptions(viewSubs.bounds.size, YES, 0.0f); instead to automatically set the scale factor to that of the main screen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compile errors when including GameLayer.h in Cocos2D project with Box2D so i have the following code in a file called mainMenu: [[CCDirector sharedDirector] runWithScene:[GameLayer scene]]; and I have #import "GameLayer.h". GameLayer has cocos2d, box2d, GLES-Render included in the .h header file. so whenever I include GameLayer in the mainMenu file (.m) and try to build the app, it fails returning around 360 errors all about b2d (b2settings, b2math etc). anyone has any idea what I am doing wrong?? NOTE the mainMenu code works perfectly fine without including the GameLayer, and so does GameLayer without mainMenu! A: Change Main Menu's extension to .mm. This makes it an Objective-C++ file, which is needed, because box2d is in C++.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fullscreen video background html5 I've read through every post there is about html5 fullscreen video here at stackoverflow. And the best example that keeps on coming up is http://www.html5-fullscreen-video.com .. And it's a beautiful solution.. But it's missing the full description on how to implement it.. Look at the bottom of this page.. http://www.html5-fullscreen-video.com/html5_fullscreen/tutorial/fullscreen_solutions/18 Does anyone have the solution? Big thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7629246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Group data by frequency I am trying create a trending system that displays which keywords are trending by checking the occurrence of their usage. I have able to get the count of occurences of the keywords into an array like this $keyword_occurences = array("pheed"=>5, "php"=>7, "love" => 700); How do I display this in descending order of occurrence? A: Give sort() a go. You can specify SORT_NUMERIC to sort an array numerically. There are other array sorting functions here. On second thoughts, asort() might be better, considering it maintains indexes. I haven't used them with an associative array like yours, so I don't know how both functions will behave, but one should work. A: Try using functions asort and/or arsort to sort an associative array by values.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Organize model and collection in backbone I have a JSON response with the following structure: { id: 1, status: 0, created_at: "Y:m:d H:m:s", updated_at "Y:m:d H:m:s)", order_items: [items] } Could I make a collection with it? The ID, status etc. are just metadata. Or should I create new ItemsCollection for the items array? Also will I get notified when an item changed? A: Yes, you're on the right track. You simply have to define three things: * *A Model for your order object *A Model for the order_item object *A Collection for order_items Remember that every Model is responsible for its own validation, so you need to write a validate function for it. Then, every time you parse your JSON, in your item's parse method, you need to convert the order_items to a backbone Collection using something like: parse: function(response) { if (!_.isNull(response) && !_.isNull(response.orderitems)) { response.orderitems = new OrderItems(response.orderitems); } return response; } Once you've done this, everything should work as-intended! A: you can do all of that, but you have to do it yourself or with a plugin. chances are, the code you end up writing will be similar to what's available in the Backbone.Relational plugin: http://github.com/PaulUithol/Backbone-relational i recommend using that plugin instead of rolling the code yourself A: As described in Backbone (http://backbonejs.org/#FAQ-nested) you should use the following way... Edit: You do not need any plugins. Futhermore I do not recommend this, as with Backbone you can be sure you have a rock-solid framework, but they do not check how rock-solid is any plugin they propagate on their website. I had many projects where I had to think about nesting. In the end, the here shown way was the most secure and the most conventional. Strucutre var Order = Backbone.Model.extend({ initialize : function(data) { this.orderItems = new OrderItems(null, {order:this}); if (!!data.order_items) { this.orderItems.reset(data.order_items, {parse:true}); //we dont want nesting in "attributes" this.unset("order_items"); } }, // this is used, when a change from server happens. So when // the model already exists, and the stuff in initialize // wouldnt be called anymore. parse : function(data) { if (!!data.order_items) { this.orderItems.reset(data.order_items); delete data.order_items; } return data; } }); var Orders = Backbone.Collection.extend({ model : Order }); var OrderItem = Backbone.Model.extend({ }); var OrderItems = Backbone.Collection.extend({ model : OrderItem, initialize : function(data, options) { if (options && options.order) { this.order = options.order; } } }; Binding myOrder.orderItems.on("..."); myOrder.on("..."); Access access your Order from within the OrderItems. var someOrderItem = myOrders.get(1).orderItems.first(); someOrderItem.collection.order === myOrders.get(1) // will result in "true" Lazy loading sometimes we dont want to load everything in one request. Most of the time I prefer to load the base collection, and only when a view does load one model, and the model has subcollections, I retrieve them later. For this I have a fetchOnce method. var OrderItems = Backbone.Model.extend({ initialize : function() { if (options && options.order) { this.order = options.order; } this.fetchOnce = _.once(this.fetch, this); //this will always return you an jquery xhr deferred. }, url : function() { if (this.order) { // url() would return you something like "/order/1234" return this.order.url() + "/items" } } ); Then somewhere else, you would initialize and fetch your complete orders. var orders = new Orders(); orders.fetch(); if you then do some edit view and want all order items to be present too, you would do following. var view = new Backbone.View({ order : orders.get(1) }); view.order.orderItems.fetchOnce().done(function() { view.render(); }); as fetchOnce returns a new deferred if not existant, or an existing (because of _.once) you can always bind to it, if it was called already previously, you will be notified in the done too... A: You could also define it dynamically: var Order = Backbone.Model.extend({ initialize: function () { this.getItems = _.memoize(this.getItems); // not necessary, but improves performance }, getItems: function () { var that = this; var col = new Backbone.Collection(this.get('order_items')); col.on('change', function() { that.set({order_items: this.toJSON()}); }); return col; } }) Any change to the returned collection would automatically update the parent model. Note: the parent model can only listen for changes to 'order_items' not it's children.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Problematic If-statement, unused variable error i am new to programming and i need your help... i have a label named "typeLabel" that has a default label text se to "NiMH". This text changes to NiCad through a pickerView. I want through an if-statement to change a multiplier value however "unused variable floatTime" halts the program. The code is: -(IBAction)calculate:(id)sender { if ([typeLabel.text isEqualToString:@"NiCad"]) { float floatTime=([mAhLabel.text floatValue]/chargerSlider.value)*1.4; } else { float floatTime=([mAhLabel.text floatValue]/chargerSlider.value)*1.5; } int intHourhs=(floatTime); float floatHours=(intHourhs); float floatMinutes=(floatTime-floatHours)*60; NSString *stringTotal = [NSString stringWithFormat: @"%1.1i Hours and %.0f Minutes", intHourhs, floatMinutes]; chargeLabel.text=stringTotal; } A: You need to move the declaration above the if statement: float floatTime; if ([typeLabel.text isEqualToString:@"NiMH"]) { floatTime=([mAhLabel.text floatValue]/chargerSlider.value)*1.5; } else { floatTime=([mAhLabel.text floatValue]/chargerSlider.value)*1.4; } When you declare a local variable inside a scope it is not visible outside that scope. A: float floatTime is defined inside the if statements braces and they define it's scope. Move it out: float floatTime; if ([typeLabel.text isEqualToString:@"NiMH"]) { floatTime=([mAhLabel.text floatValue]/chargerSlider.value)*1.5; } else { floatTime=([mAhLabel.text floatValue]/chargerSlider.value)*1.4; } Curly braces define scope, things defined inside them are not available outside. A: You should declare float time in the main block of code, outside the if/else, that's why you are getting an error. Try this: -(IBAction)calculate:(id)sender { float floatTime; if ([typeLabel.text isEqualToString:@"NiMH"]) { floatTime=([mAhLabel.text floatValue]/chargerSlider.value)*1.5; } else { floatTime=([mAhLabel.text floatValue]/chargerSlider.value)*1.4; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7629252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Gaps when rendering function after rotating it I'm rendering a sine function which renders fine with angle 0, but has gaps when rotating it. See pictures: 45º: 0º: The values are generated with PHP. Each square picks up its status from the matrix generated with PHP. for ($i = 4; $i < 125; $i++) { $angle = deg2rad(0); $x1 = $i; $y1 = round(8*sin($i/8),0)+50; $x = round($x1*cos($angle) - $y1*sin($angle),0); $y = round($x1*sin($angle) + $y1*cos($angle),0); if (($x > 1 and $x < 120) and ($y > 1 and $y < 120)){ $this->mapArray[$x][$y]->set_value(1); // square rendered. } } I thought it had something to do with the round, but I use no rounding and also have the same results. Any tips? A: you are rendering points and you want it to be curve. you are approximating curve with 121 points and there are ofcourse holes because it's length is bigger than 121 pixels. what you need to do is to draw lines from last point to the next. it will still be approximation, but you won't have gaps. A: This is only an idea, that would need a further elaboration. Suppose that the curve is drawn from left to right and from top to bottom. We could remember the last pixel (x0, y0) that was set. When drawing the pixel (x, y), there is no gap before (x, y) if (x0, y0) is one of the pixels (x-1, y), (x, y-1), (x-1, y-1). If it is not the case, then there is a gap between (x0, y0) and (x, y). This gap can be filled by interpolation. If only one pixel is missing, then it can be set by a case analysis. If the distance between the pixels (x0, y0) and (x, y) is larger, then an interpolating line could be drawn between them using the Bresenham's algorithm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fontsize of Contextmenu I spend now some time in trying to change the textsize of the contextmenu. I searched the sdk's themes.xml and styles.xml and tried a lot but didn't succeed in actually resizing the text. Anyone knows how to do it? Cheers! Nob A: Short answer: No Long answer: Why don't you create your custom dialog that looks like the ContextMenu? It's so easy to create a custom dialog in this way. For an example to this, http://developer.android.com/guide/topics/ui/dialogs.html go look at "Add a list" section.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Transpose 1 Dimensional Array So I have a ONE dimensional array with N values, where N is a perfect square. I visualize this one dimensional array as a two dimensional array (although it is not). For example, an array with values int Array = { 0,1,2,3,4,5,6,7,8 } That is int *Array = new int [9]; for ( int i = 0 ; i < 9 ; i ++ ) Array[i] = i; // For example This is printed as 0 1 2 3 4 5 6 7 8 So, I want to interchange the position in the one dimensional array such that I get the transpose of it,... For example... 0 3 6 1 4 7 2 5 8 This is basically the same one dimensional array , but the values are swapped such that the array is now int Array = {0,3,6,1,4,7,2,5,8} If I were to scale it to an array of dimension 1024*1024, how will the logic be ? A: The transpose operation performs swap(v[y][x],v[x][y]) for the upper or lower triangle excluding the diagonal of the matrix, (let's say upper). In a C one-dimensional vector vc, v[y][x] corresponds to vc[y*n+x]. So you want to do vc[y*n+x] = vc[x*n+y] The elements you want to swap are the ones for which x > y. You end up doing: for(int y = 0; y < n; ++y) for(int x = y+1; x < n; ++x) swap(vc[x*n + y], vc[y*n + x]); You could have figured this yourself... A: With n = sqrt(N), you could just try something simple like: for(int i = 0; i < n; ++i) for(int j = i+1; j < n; ++j) std::swap(Array[n*i + j], Array[n*j + i]); A: #include <iostream> #include <cmath> using namespace std; int xyToIndex(const int x, const int y, const int size){ return x + y * size; } int main(){ int a[] = { 0,1,2,3,4,5,6,7,8 }; const int size = sqrt(sizeof(a)/sizeof(int)); //print only for(int x = 0;x < size; ++x){ for(int y = 0; y < size; ++y) cout << a[xyToIndex(x,y,size)] << " ";; cout << endl; } //make array int b[size*size]; int index = 0; for(int x = 0;x < size; ++x) for(int y = 0; y < size; ++y) b[index++] = a[xyToIndex(x,y,size)]; for(int i = 0; i< size * size ; ++i){ cout << b[i] << " "; } } A: You can either swap the values in the matrix or swap the interpretation in the later functions. For example, instead of printing a(i, j) you can print a(j,I) and print the trans pose. That being said, what exaclty are you trying to do? If you look at LAPACK and BLAS, their routines take flags that control the algorithms to interpret them normally or as transposed. A: without using swap function. len is the length of the array. int i,j; N = sqrt(len); int temp[len]; for(i=0;i<N;i++) { for(j=0;j<N;j++) { temp[j+(i*N)] = a[(j*N)+i]; } } A: static unsigned other(unsigned dim0, unsigned dim1, unsigned index) { #if 0 unsigned x0,x1; x0 = index % dim0 ; x1 = index / dim0 ; return x0 * dim1 + x1; #else unsigned mod,val; mod = dim0 * dim1 -1; val = (index==mod) ? mod: (dim1*index) % mod; return val; #endif } The above function returns the "other" index of index (the one in the transposed matrix := with x and y swapped). dim0 and dim1 are the "horizontal" and "vertical" size of the matrix. The #ifdeffed-out part is the naive implementation. In your case, you could initialise (or analyse) the 1-dimensional array with: for (i=0; i < 9; i++) arr[i] = other(3, 3, i);
{ "language": "en", "url": "https://stackoverflow.com/questions/7629259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Multicasting in Java I've got a lot of questions regarding this e.g.. Hence enumerating them: * *Why do they use datagram sockets? Is there another alternative to them? *I'm trying to send objects over the datagram sockets in this example. It takes a long time for the server to receive the object from the client's side. Is there any alternative to that as well? Note - I'm trying to integrate both programs to make a network discovery program wherein the client replies with it's details in the form of an object. A: For your first question, you need datagrams (UDP) because tcp is a connection oriented protocol. i.e., each connection is for communication between one server and one client. You can have multiple clients connected to a server, but they'd all be individual unicast communication. Regarding your second question, I don't think a delay you observe is due to your code. Post more details about your topology, etc. to help solve that issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What passes through serialization? A dumb question, but still: In C#, when I pass an object from one machine to another - what is available at the destination side? Only public members? Properties? Methods? What else? A: Depends on the serialization method. The BinaryFormatter takes everything (that is ISerializable), the XmlSerialzer only public properties and fields with a setter (by default). A: The important thing to realize is that the type definition of the object being deserialized must be available at the destination. Serialization only generates data. Either all or partial. The deserialization process constructs an object according to the type definition at the receiving end populates it according to deserialization data. It would be worth your while to experiment with deserializing a type that is not defined or has a different definition at receiving end.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does std::string allocate memory in GCC with -fwhole-program? Update: The following problem appears to depend on the -fwhole-program option. I've been playing around a bit with memory allocation, and I encountered a small mystery: In GCC (4.6), how does std::string allocate its memory [edit]when I compile with -fwhole-program[/]? Have this following test program: #include <new> #include <string> #include <iostream> #include <cstdlib> void * operator new(std::size_t n) throw(std::bad_alloc) { void * const p = std::malloc(n); if (p == NULL) throw std::bad_alloc(); std::cerr << "new() requests " << n << " bytes, allocated at " << p << ".\n"; return p; } void operator delete(void * p) noexcept { std::cerr << "delete() at " << p << ".\n"; std::free(p); } int main() { std::string s = "Hello world."; } When I use any other dynamic container (which uses std::allocator<T>), the allocator uses ::operator new, and so I see the debug messages happily. However, with std::string, I see nothing at all. I'm sure that dynamic allocation happens, though, as I can confirm with valgrind (13 plus string length bytes are allocated). I went through several source files and the standard, and I'm pretty sure that the template is std::basic_string<T, std::char_traits<T>, std::allocator<T>>, so I'm at a loss why I don't see the messages from my replaced allocation functions. Can anyone shed any light on this conundrum? What do I do to track string allocations? Also, could anyone run this through some other compiler and see if it produces any output? (For example: if I add std::map<int, int> m { { 0, 1 } };, I have output new() requests 24 bytes, allocated at 0x8d53028 etc.) A: Looking at the output of g++ ... -S with / without -fwhole-program it appears that the whole custom new/delete operators aren't emitted at all when using fwhole-program. I'm starting to suspect we're looking at a bug here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Why do I get "ambiguous type variable" error here? import Data.Monoid times :: Monoid a => Int -> a -> a times i = mconcat . replicate i main = print $ times 5 5 This code gives the following error: Ambiguous type variable `a0' in the constraints: (Monoid a0) arising from a use of `times' at :7:11-15 (Show a0) arising from a use of `print' at :7:3-7 (Num a0) arising from the literal `5' at :7:19 Probable fix: add a type signature that fixes these type variable(s) In the second argument of `($)', namely `times 5 5' In the expression: print $ times 5 5 In an equation for `main': main = print $ times 5 5 Why does it give this error? How is Num even involved here? A: The problem is that there are two monoids defined for numbers. One with addition, and one with multiplication. These are implemented as instances for the newtypes Sum and Product, and you have to specify which one you want, as there are no monoid instances for plain numeric types. *Main> times 5 (Sum 5) Sum {getSum = 25} *Main> times 5 (Product 5) Product {getProduct = 3125} Num is mentioned because 5 is a polymorphic value: *Main> :t 5 5 :: Num a => a This would normally cause ambiguous type errors all over the place, if not for type defaulting, which causes the compiler to go through a set of default types (normally Integer and Double), and choose the first one that fits. Since neither Integer nor Double has a Monoid instance, type defaulting fails, and you get the ambiguous type error. It's also possible that you meant to use the list monoid, as it's not clear from the question what result you were expecting. *Main> times 5 [5] [5,5,5,5,5]
{ "language": "en", "url": "https://stackoverflow.com/questions/7629275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to generate fixed cells row in django? I am making Django app, where in page is a table with fixed number of cells (4 rows x 3 columns = 12 cells). It is ok, when there are 12 records on page - it fits nicely. But when there are less records on page, I have to fill rest of the table with some predefined values (image and link to registration page). I was searching for solution, but didn't find any. Does anybody have any ideas, how to do this? A: Convert the QuerySet to a list, pad it out with 12 dummy objects, then slice the list in the template to 12 items. A: In the dictionary of items you pass into the template from the view, include a variable for range(12-len(your_records)). Then, in the template, use the for tag to loop over that variable, to add in the appropriate number of cells.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any successful Windows Azure based website and web services? I am evaluating Windows Azure and Google App Engine. Personally I prefer Windows Azure as I have been a C# developer for years. However, I do understand Azure will be too expensive for a start up company. Could anyone let me know any successful Azure based website or web services? Any opinion about Azure VS GAE is welcome. Thanks A: Google can give you the answer to who is using Azure and how they are using it. Whatever answer is given today will not neccessarily be accurate when this post is read so it's a bit of a time lock. Boeing is using Azure. Microsoft is using Azure. Azure is even using Azure. I disagree that Azure is anymore expensive than any other PaaS offering. And I find Azure as a PaaS offering to be "bizarrely" less expensive than IaaS offering from the likes of Rackspace etc. I say "bizarrely" because we get the hardware and the platform for less than what Rackspace charge us for just the hardware. I find it's very reasonably priced so long as you read the not so fine print.... i.e. watch out for part hour charging and know that deployed = paying whether the service is turned on or not. I've found GAE to be similar in cost. Which metric are you particularly interested in? I also dont agree that it's too expensive for a startup. I can get a 2 small instance with a 1 Gb database and CDN use for about $130NZD a month. That's peanuts when you look at the amount of grunt sitting in behind that... specially when you consider you can run multiple domains off a single hosted service. Azure vs GAE is IHMO really just a developmental/deployment difference in the stack. I'm an MS developer and I can ride my skillset into Azure very easily. There's so much info and so many introductory videos available on it's use. Check out the latest build conference videos and a series called Cloud Cover on channel 9). You can get up and running on Azure in a basic developer test sense in half a day to a day. It's a really very well thought out offering IMHO. So there you go, a very general answer to a very general question. ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Annoying javascript timezone adjustment issue I have set up a JSON endpoint that returns the current time from server. For example: { "myservertime": "2011-10-02T23:00+02:00" } So this is the CET summer time right now. Now, I also have a jQuery code that parses that very well. $.sysTime = function(success) { $.ajax({ url: '/jsontimepath/', dataType: 'json', async: false, success: function(json){ sysDateTime = new Date(Date.parse(json.myservertime)); console.log('The system time now is: ' + sysDateTime) } }); return sysDateTime; }; The problem is that when I check the console, it still shows wrong time... It is still affected by the timezone of my computer... For example, for a user in Hong Kong, the time quoted above would result: Mon Oct 03 2011 05:00:00 GMT+0800 (HKT) I do give it a valid ISO8601 time string and it just adjusts it. The actual time that is returned is correct (in that timezone)... But why does it adjust it like that??? I want it to return CET time not the local time... A: Everything is fine, try this: new Date(Date.parse("2011-10-02T23:00+02:00")).getUTCHours() //21 The date is parsed correctly (taking the timezone into account as expected). However when you simply print Date.toString() it shows the date in current browser timezone (one of the sins of Java Date object shamelessly copied to JavaScript...) If you stick to getUTC*() family of methods you will get correct values (like in example above). The ordinary get*() methods are always affected by browser timezone (and not the timezone from the date you parsed, which is lost), hence often useless. Another example: the 2011-10-03 02:00+03:00 is actually 23:00 on 2nd of October. But when you parse it (my current browser time zone is +0200 (CEST)): new Date(Date.parse("2011-10-03T02:00+03:00")) //Oct 03 01:00:00 GMT+0200 However current day of month in UTC is: new Date(Date.parse("2011-10-03T02:00+03:00")).getUTCDate() //2 (2nd of Oct)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Securely store Oauth token(s) in file I'm developing a small webapp in python that'll interact with a users dropbox account. What is the best way to store the Oauth tokens for that account in a flat file? Is hashing the tokens secure enough? Or should I encrypt them? If encrypting them is the way to go, how would you suggest storing the key, since 2 way encryption would be necessary to decrypt the tokens for sending to Dropbox? I could load up sqlite and store the tokens in there, but I'm wondering if there's a good way to do it using flat files. Same issue is run into with Sqlite, since its also a file. Of course, the file permissions would only be set to the least permissible privilege to be accessed by the webapp. A: Hashing won't work, since, as skjaidev mentions, it's one way. If you have a reasonable fear that your file or database will get stolen(*), encryption is the way to go. But indeed as you mention, your app will need the decryption key, so the question is where to store it. Obviously storing it in the same spot as the data, doesn't enhance security. Please consider the following: * *When your data is in a database, it's (most likely) less secure than in a flat file. This is because there are database injection techniques that may allow you to read the database, but not files. In this case putting your decryption key somewhere on the file system (in your code) makes sense: the data from the database alone is in that case useless. *Even when your data is in a flat file, putting the decryption key somewhere in a file, can decrease risk. Many systems get "hacked" when the hacker gets access to a system that wasn't even supposed to contain that data, that contained old backups of the data, or in some other way doesn't (necessarily) contain your code with the decryption key. *Best is to have your decryption key not on the filesystem at all, but just in the computer memory. A good hacker with root access or physical access may still get to it, but I would argue that in 99% of the cases that hackers get access to the file systems, they won't be able to read the memory as well (in the cases they steal backups, steal the physical machine (turning it off in the process), get user-level access, etc). This is basically the keychain-approach. Problem is, how to get the decryption key into the memory, and there is only one solution that I know of: type it in (or some other password that decrypts the decryption key) every time the application starts. Whether this is acceptable depends on how often your application will restart. *There is one other method. If you only need access to dropbox when your users are actually logged in to your app, you can consider encrypting the token with some unique user property (or instance the password that the user uses to log in to your site, or some random string you set in a cookie on the first visit). In this case you can also consider storing the whole access token encrypted in a cookie (and not on your server at all). Whatever method you choose, it will never really protect, as you mention yourself. If your app can get to decrypted tokens (which it can, else your app would not need to store them in the first place), some hacker with unlimited privileged can as well. The nice thing about access tokens is, though, that probably they can be easily revoked, so if they get stolen it's probably not the end of the world; and a hacker knows they can be easily revoked so they will hardly be interesting as a target. (*) Note: it's always reasonable to assume that stuff will get stolen eventually one way or another. I can imagine though that if you set up a small site for 20 friends on your home PC, you care less about your passwords being stolen, than when you're building the next instagram. It's always a tradeoff between security and amount of work. As mentioned, having your tokens in a flat file in stead of a database (if handled correctly) should make it less likely that they get stolen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: hide file extensions with mod_rewrite How can you hide all file extentions like .php to counter SEO /page => /page.php RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L] This doesn't work... edit RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !\.php$ [NC] RewriteRule ^(.*)([^/]*)$ /$1$2.php [QSA,L] A: You've written some strange faults in your code! * *%{REQUEST_FILENAME} already contains the file-extension, so you are asking for a file wich ends with .php.php, and with the -f-flag, you are checking if such a file exists. Also, there actually is no need to check if the requested file exists for what you want to do. *Your RewriteRule would rewrite any dot-php-file to the same URL plus an additional .php. So index.php would become index.php.php *What for is the exclamation mark at the very beginning of your RewriteRule? Fixing these errors, you get something like: RewriteRule (.*)\.php$ $1/ You can use $1, $2, $... in the right part of your expresison to access the n-th match between brackets () on the left. For more information about mod_rewrite, see here. Maybe it helps to look there from time to time. ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: How do I test CSS over many form factors? I only have a single monitor with a 1920x1080 resolution. Is there some tool that helps me see the outcome of my CSS changes instantly over multiple resolutions? I'm only starting to learn CSS, but constantly resizing my browser into all directions after every tiny modification of my CSS file seems cumbersome. A: The Web developer toolbar has a built-in option to resize your window. Alternatively, you can also create bookmarklets to resize the window using the resizeTo function. A: Here's a good topic about your question, with your monitor, you should be able to test it with this solution http://www.cssgirl.com/resources/2006/05/27/browser-size-check/ A: If you set your dimensions using px pixels - you shouldn't need to concern yourself with resolution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to count lines in a c++ project? Possible Duplicate: How do you count the lines of code in a Visual Studio solution? I am looking for software or means to count lines of code in a VC6.0: c++ project: 1500 files: cpp, h, My hunch is there are 2 to 5 million lines of code in this project. I need a means to verify this per file. thx A: If your code is on a Unix machine with access to the find and wc commands (or you have an installation of Cygwin on your Windows machine), you can use the following shell command: find . -name \*.cpp -or -name \*.hpp -exec cat {} \; | wc -l Adjust the wildcards to pick the files that you'd like to scan (the above example picks anything with the .cpp or .hpp extension). There are may be other ways using Visual Studio to do this. If you absolutely must use a Visual Studio-based solution, look at this Stackoverflow question: How do you count the lines of code in a Visual Studio solution?
{ "language": "en", "url": "https://stackoverflow.com/questions/7629294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: .htaccess regex issue RewriteEngine on RewriteRule ^([a-zA-Z0-9]{1,3})\/([0-9])\.html$ thread.php?board=$1&thread=$2 Here is my .htaccess file. Let me explain you how it should work: website.com/vg/1337.html => website.com/thread.php?board=vg&thread=1337 in the other words: website.com/x/y.html => website.com/thread.php?board=x&thread=y x - 1-3 symbols, A-z, 0-9; y - unlimited amount of symbols, 0-9; It does look pretty simple, but... website.com/vg/1337.html just leads me to 404. What am I doing wrong? A: Your regular expression only matches URLs that contain a single digit, for example "5.html". To fix it change [0-9] to [0-9]+. The plus means "one or more of the previous token". A: [0-9]* or [0-9]+ missing enumerator after [0-9]. if you don't put anything, it would work for one char only A: y is not "unlimited" in your example above, just allow one single digit. Add a star * after it (or a + for "1 or more").
{ "language": "en", "url": "https://stackoverflow.com/questions/7629298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AsyncTask context SQLite I'm making an application that get data from webservice, insert it into a database and show the data into a tablelayout. So what I want to do is that in a X lapse of time, REFRESH the table with the content of webservice. I can do that with the onResume method, but it isn't what I want. I was reading about asynctask, so the task of using webservice and inserting data into sqlite could be in a second thread. In the method doInBackground I start the webservice and insert information into a sqlite, and in the onPostExecute I put the information dynamically into a table. My problem is that, when I initialize the database to read it, I put: UsuariosSQLiteHelper usdbh = new UsuariosSQLiteHelper(this, "DBIncidentes", null, 1); and in THIS, there is a context problem. This happened too in the part of refreshing data into the table (in onPostExecute), because all the time I put THIS like creating a textview, there is a context problem. I basically know about context, I read that I have to create a constructor of the asynctask class and initialize a context, and I can change THIS for the context of the constructor. I'm a bit lost in this part, anyone can help me? A: In this case this refers to your ASyncTask and not your Activity. You need to use ActivityName.this instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mySQL - If statement giving syntax error So I have the following query: IF ( ( SELECT RevisionNumber FROM SchemaVersion ) > 1 ) THEN BEGIN CREATE TABLE Test ( ID INT ); CREATE TABLE Test2 ( ID INT ); END; END IF Basically I want to decide based on a value in my table (SchemaVersion - always has 1 row) whether or not I need to make certain changes. However, when I use this query I get the following error message: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF ( ( SELECT RevisionNumber FROM SchemaVersion ) > 1 ) THEN BEGIN CREATE T' at line 1 Any idea why this is erroring / how to fix? I was just reading another post and apparently BEGIN / END are only allowed within stored procs. Is there any way to get around this (without putting it in a stored proc). Thanks A: Using IF with brackets calls the IF function, which is different from IF statement Note There is also an IF() function, which differs from the IF statement described here. See Section 11.4, “Control Flow Functions”. A: The IF statement is part of what's called Compound-statement Syntax, and it is only available inside stored code, like a trigger, function, or stored procedure. http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-compound-statements.html A: I think you would need to run that within a stored procedure. See http://dev.mysql.com/doc/refman/5.0/en/stored-routines.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7629306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Extracting Frequency Data from Sorted List of Phrases After plumbing the documentation/past questions on list operations, I've come up blank - many of the cases involve numbers, whereas I'm working with large quantities of text. I have a sorted list of common three-word phrases (trigrams) that appear in a large body of textual information, generated through Mathematica's Partition[], Tally[], and Sort[] commands. An example of the sort of data that I'm operating on (I have hundreds of these files): {{{wa, wa, wa}, 66}, {{i, love, you}, 62}, {{la, la, la}, 50}, {{meaning, of, life}, 42}, {on, come, on}, 40}, {{come, on, come}, 40}, {{yeah, yeah, yeah}, 38}, {{no, no, no}, 36}, {{we, re, gonna}, 36}, {{you, love, me}, 35}, {{in, love, with}, 32}, {{the, way, you}, 30}, {{i, want, to}, 30}, {{back, to, me}, 29}, <<38211>>, {{of, an, xke}, 1}} I'm hoping to search this file so that if the input is "meaning, of, life" it will return "42." I feel like I must be overlooking something obvious but after tinkering around I've hit a brick wall here. Mathematica is number heavy in its documentation, which is.. well, unsurprising. A: Assuming that you can load your data into Mathematica in the form you outlined, one very simple thing to do is to create a hash-table, where your trigrams will be the (compound) keys. Here is your sample (the part of it that you gave): trigrams = {{{"wa", "wa", "wa"}, 66}, {{"i", "love", "you"}, 62}, {{"la", "la", "la"}, 50}, {{"meaning", "of", "life"}, 42}, {{"on", "come", "on"}, 40}, {{"come", "on", "come"}, 40}, {{"yeah", "yeah", "yeah"}, 38}, {{"no", "no", "no"}, 36}, {{"we", "re", "gonna"}, 36}, {{"you", "love", "me"}, 35}, {{"in", "love", "with"}, 32}, {{"the", "way", "you"}, 30}, {{"i", "want", "to"}, 30}, {{"back", "to", "me"}, 29}, {{"of", "an", "xke"}, 1}}; Here is one possible way to create a hash-table: Clear[trigramHash]; (trigramHash[Sequence @@ #1] = #2) & @@@ trigrams; Now, we use it like In[16]:= trigramHash["meaning","of","life"] Out[16]= 42 This approach will be beneficial if you perform many searches, of course. EDIT If you have many files and want to search them efficiently in Mathematica, one thing you could do is to use the above hashing mechanism to convert all your files to .mx binary Mathematica files. These files are optimized for fast loading, and serve as a persistence mechanism for definitions you want to store. Here is how it may work: In[20]:= DumpSave["C:\\Temp\\trigrams.mx",trigramHash] Out[20]= {trigramHash} In[21]:= Quit[] In[1]:= Get["C:\\Temp\\trigrams.mx"] In[2]:= trigramHash["meaning","of","life"] Out[2]= 42 You use DumpSave to create an .mx file. So, the suggested procedure is to load your data into Mathematica, file by file, create hashes (you could use SubValues to index a particular hash-table with an index of your file), and then save those definitions into .mx files. In this way, you get fast load and fast search, and you have a freedom to decide which part of your data to keep loaded into Mathematica at any given time (pretty much without a performance hit, normally associated with file loading). A: This is probably not as fast as the solution that Leonid gave, but you could just turn your list of pairs into a list of rules. In[1]:= trigrams = {{{"wa", "wa", "wa"}, 66}, {{"i", "love", "you"}, 62}, {{"la", "la", "la"}, 50}, {{"meaning", "of", "life"}, 42}, {{"on", "come", "on"}, 40}, {{"come", "on", "come"}, 40}, {{"yeah", "yeah", "yeah"}, 38}, {{"no", "no", "no"}, 36}, {{"we", "re", "gonna"}, 36}, {{"you", "love", "me"}, 35}, {{"in", "love", "with"}, 32}, {{"the", "way", "you"}, 30}, {{"i", "want", "to"}, 30}, {{"back", "to", "me"}, 29}, {{"of", "an", "xke"}, 1}}; In[2]:= trigramRules = Rule @@@ trigrams; Which (if you want) you can wrap up in a function that has a similar behaviour to Leonid's In[3]:= trigram[seq__String] := {seq} /. trigramRules In[4]:= trigram["meaning", "of", "life"] Out[4]= 42 Since you have a very large list of pairs, then the application of the generated rules can be sped up by using Dispatch. That is, do everything else the same as above, except define trigramRules using trigramRules = Dispatch[Rule @@@ trigrams] A: This is one way to get the individual words in your string into a list. In[262]:= str = "meaning, of, life"; ReadList[ StringToStream[str], Word, WordSeparators -> {",", " "}] Out[262]= {"meaning", "of", "life"} You could use this in a Cases or other form of look-up to get the 42 result (very suspicious, that figure...) --- edit--- By "look-up" I have in mind the sort of mechanism shown by Leonid Shifrin. I was uncertain as to whether the difficulty being encountered was that, or simply converting from strings to lists of triads. I (only) show a way to manage the latter. --- end edit --- --- edit 2 --- A comment shows ways to avoid ReadList. Let me state for the record that I'm ecstatic I managed to find that approach. Below is the code I had put into my original response, then replaced when I realized there was a more concise code. str = "meaning, of, life"; commaposns = StringPosition[str, ", "]; substrposns = Partition[ Join[{1}, Riffle[commaposns[[All, 1]] - 1, commaposns[[All, 2]] + 1], {-1}], 2]; substrs = Map[StringTake[str, #] &, substrposns] Out[259]= {"meaning", "of", "life"} Bottom line (almost literally): I can find convoluted approaches as well as anyone else, and better than most. --- end edit --- Daniel Lichtblau A: Quite an old question.. but now we have Association lookup = Association[Rule @@@ trigrams]; lookup[{"come", "on", "come"}] 40 or even lookup = Association[ Rule[StringJoin@Riffle[#1, " "], #2] & @@@ trigrams] lookup["meaning of life"] 42
{ "language": "en", "url": "https://stackoverflow.com/questions/7629311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: PHPUnit + Selenium : error I recently tried to install PHPUnit and Selenium, but I'm running into some errors: Fatal error: Call to undefined method PHPUnit_Framework_ExpectationFailedException::getCustomMessage() in /phpunit/phpunit-selenium/PHPUnit/Extensions/SeleniumTestCase.php on line 1041 Did I forget something in my install ? I'm using the last version available on Git. A: You should update your version of PHPUnit_Selenium. PHPUnit doesn't include Selenium extension since version 3.6 and you have to install/upgrade it manually. pear upgrade phpunit/PHPUnit_Selenium or pear install phpunit/PHPUnit_Selenium A: Sounds like you need to reinstall - use PEAR
{ "language": "en", "url": "https://stackoverflow.com/questions/7629312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Should I use Workflow or fsYacc? I have a very simple DSL I need to parse on a .Net platform. Not being very experienced with parsers, I have been looking at examples using F# (fsLex, fsYacc, FParsec). I am not that familiar with F#, but do have some experience with Workflow and LINQ. Given the simplicity of the DSL, I can get away with using LINQ to implement the lexer. Workflow (I would be using V4) is appealing to implement the grammar, since I am more familiar with it, it's easier to explain to others given its graphic nature, and it is supported by Microsoft and will continue to evolve, presumably.If my DSL becomes more sophisticated, however, I can image the WF implementation becoming a nested hell of activities and a LINQ based lexer going the same way. At that point learning F# and using one of the F# tools would make more sense. I am wondering if others have compared WF and F# parsing tools to implement a simple DSL interpreter and what the conclusions might be. A: It's hard to give an answer without knowing a little more about what the DSL is supposed to do and how complex it may get in the future. If your DSL is about workflow then WF would seem like a very logical choice to store your parsed results in. If your language is not too complex then LINQ or a handrolled little parser could very well do. It's good to keep it simple and use tooling that your colleagues know. When your language becomes more complicated however this approach tends to come apart pretty quickly. But on the upside, you can just switch your parser then. Don't solve problems you may never have. Personally I really like FParsec for parsing. It requires some knowledge about F# but when you've got your head around it it is so insanely powerful for turning text into AST, and it's very lean in that there are no 'magical steps' that turns your EBNF into gibberish code, you can see how it works and tune it. When you don't have time to dive into F# and FParsec there's also Irony which is like FParsec but then for C#. This is what I can say from what you've told us, if you have any concrete issues let us know. Rgds GJ
{ "language": "en", "url": "https://stackoverflow.com/questions/7629321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Displaying a specific field in a django form I have the following field in a django form: position = forms.ModelChoiceField(Position.objects.order_by('-ordering'), empty_label='Select Position',) In my Position model, I am using the unicode field to display the field called "position". However, in this particular form, I want the output to be a different field in the model called "position-select". How would I do this without altering the default output of the unicode field? Thank you. A: This is what worked: class PositionSelect(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.select_display class Position(forms.Form): position = PositionSelect(Position.objects.order_by('-ordering'), empty_label='Select Position',) A: Try "subclassing ModelChoiceField and override label_from_instance", per the example at https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield. You could specify a reference to the __unicode__ function of your other field within that overridden class. A: In one line inside the init method of your Form : self.fields['position'].label_from_instance = lambda obj: f"{obj.position_select}"
{ "language": "en", "url": "https://stackoverflow.com/questions/7629323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: position relative in firefox Possible Duplicate: Does Firefox support position: relative on table elements? Here is an example: full-width menu as a table and ul-s as dropdown menus. http://cssdesk.com/dW7WS Works fine in ie and opera, but in firefox dropdown uls streched on whole screen! Any help? A: position: relative does not work on table cells (<td> or display: table-cell). From the spec: http://www.w3.org/TR/CSS21/visuren.html#propdef-position The effect of 'position:relative' on table-row-group, table-header-group, table-footer-group, table-row, table-column-group, table-column, table-cell, and table-caption elements is undefined. So, Firefox is doing nothing wrong, although I do wish it would copy other browsers and make this work. To make this work, you need to add a wrapper div inside each td (and adjust your CSS selectors): <table id="mainmenu"> <tr> <td> <div style="position: relative;"> <a href="#">..</a> <ul> .. </ul> </div> </td> .. </tr> </table> A: Like @Jared Farrish said using tables for layout is bad practice and the problem here. #mainmenu ul li { width: 100%; } Is causing the li elements to display 100% of the screen. I would suggest you wrap the menu in a container div, there is absolutely no need for a table here you should put the menu in an unordered list something like: - <ul> <li class="parent_node"> Menu Header 1 <ul class="sub_node"> <li> Sub item 1</li> </ul> </li> <li class="parent_node"> Menu Header 2 <ul class="sub_node"> <li> Sub item 1</li> </ul> </li> </ul>
{ "language": "en", "url": "https://stackoverflow.com/questions/7629326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ObjectContext is leaking memory for detached entities I already checked this using a memory profiler and there are no real entities which stay in memory but hash-sets, dictionaries and EntityKey objects -- but I found no way how to disconnect these references. So simple question: How do I stop the context (or its ObjectStateManager) from growing infinitely in size? [And yes, I know that long living contexts should be avoided, but in this case it's one complex analysis run which needs several hierarchical data being loaded (and the sample below is just a minimal problem demonstration) so finally it is a "short" living one-operation context.] Steps to repro: * *create a new console application *create a EF model for a Northwind database (either use some real SQL Server or copy Northwind.sdf from Compact Samples folder) *use code below: Code [Updated, doesn't need real DB connection anymore]: class Program { static void Main() { const double MiB = 1024 * 1024; using ( var context = new NorthwindEntities() ) { var last = GC.GetTotalMemory(true) / MiB; Console.WriteLine("before run: {0:n3} MiB", last); var id = 0; while ( true ) { Run(context, ref id); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); var current = GC.GetTotalMemory(true) / MiB; Console.WriteLine("after run: {0:n3} MiB (+{1:n3} MiB)", current, current - last); last = current; if ( Console.KeyAvailable ) break; Console.WriteLine(new string('-', 100)); } } } static void Run(NorthwindEntities context, ref int id) { for ( int i = 0; i < 100000; i++ ) { var category = new Category { Category_ID = ++id }; category.EntityKey = new EntityKey("NorthwindEntities.Categories", "Category_ID", id); var product = new Product { Product_ID = id, Category_ID = id }; product.EntityKey = new EntityKey("NorthwindEntities.Products", "Product_ID", id); product.Category = category; context.Attach(product); context.Detach(product); context.Detach(category); } var ctr = 0; Console.WriteLine("Enumerating living/attached objects:"); const EntityState AllStates = EntityState.Added | EntityState.Deleted | EntityState.Modified | EntityState.Unchanged; foreach ( var entry in context.ObjectStateManager.GetObjectStateEntries(AllStates) ) Console.WriteLine(" #{0} [{1}] {2}", ++ctr, entry.EntityKey, entry.Entity); if ( ctr == 0 ) Console.WriteLine(" NOTHING (as expected)"); } } A: Since I'm only detaching entities directly after having called SaveChanges(), I'm now counting the number of detached entities and when the counter reaches 10,000 I detach all still living (and needed) objects from the context and create a new context to which I attach all detached objects. Downside: The IsLoaded property of EntityReferences and EntityCollections is now always false (but I don't rely on this). A: My understanding is that detach is meant to remove the context from the entity, not the entity from the context. Don't trust the context to remove references to entities(or their internals). I agree this leakage is a problem, but a lot of people(myself included) have tried and failed to prevent EF contexts from growing indefinitely(as long as queries are being run). As a proposed solution, perhaps instead of relying on the database as a "working space" for your calculations, it might be possible to recreate database structure in your own in-memory representation, work on that, and then translate back into db. You could use temporary files if you have a lot of data. This should have the effect of shortening lifespan of contexts. Alternatively, maybe consider using something else other than EF(at least for the processing intensive parts), since it may not be suited to your situation. Perhaps something lower level, like a DataReader would be more suitable for your situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: CSS background: want a diff. background for my other pages I'm using CSS background: url(stuffhere.jpeg) for my background, but when you click on other videos, "projects" not pages, the background won't change. I've tried <body id="home"> and <body id="projects">, and tried making two backgrounds for #home and #projects but the projects won't work.. Then I used <div id="projects">, but the problem is that since it's not a page, div won't change the entire background. Please check this out and let me know... www.montagemd.com, and then click on one of the videos. I want the grey background to fill the whole thing... or to over-ride what I have in #home A: You can make the gray background fill the entire viewport by doing the following: * *Giv the div a width of 100% and min-height of 100% (min-height will let it grow if its content is taller than the window). *Make sure the div's parent is the <body> with a 100% height defined on it as well. Percentage heights only work if the element's parent has a height defined as well. It'll look something like this in the code: <body> <div id="gray-box"></div> </body> And then the CSS would be: html, body { /* Defines a height on #gray-box's parents (required for % height to work) */ height: 100%; /* Eliminate any extra spacing around #gray-box */ margin: 0; padding: 0; } #gray-box { width: 100%; min-height: 100%; /* Let #gray-box grow with its content */ background: #ddd; } Here's a demo of it in action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to disable button over class of parent element? I have the following HTML: <label class="fileinput-button"> <span>add file...</span> <input type="file" name="file" disabled> </label> I want to disable the input element (button) using the label's class name (without the button's ID). $('label.fileinput-button') ... button ... disable. How can I do this? A: $('label.fileinput-button input').prop('disabled', true); Note: .prop() is available since version 1.6 A: Use the attr method to assign the disabled property to your named input. $('label.fileinput-button input[name=file]').attr("disabled", "disabled");
{ "language": "en", "url": "https://stackoverflow.com/questions/7629341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trouble with reading Serial Port using VB.net 2008 let me first tell you about the problem I have been facing. I have microcontroller interfaced with serial port of my computer. In my microcontroller I have 2000 sample data and my primary target is to read those data. Now I can read those data in hyper terminal, but when it comes to my application it doesnt show anything. Now I am very new to VB.net so there must be something missing. Private Sub sp1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles sp1.DataReceived sp1.Open() MsgBox(sp1.ReadExisting()) End Sub this simple code block should show me the data.But it doesnt. data format coming Microcontroller is in this following formate : nitialization successful !,1023 Starting sampling process... 1023,1023 1023,1023 0,2 1023,1023 1023,1023 1023,1023 212,686 1023,1023 1023,1023 1,5 1023,1023 1023,1023 1023,1023,659 213,689 1023,1023 1023,1023 now, I dont understand why it doesnt read anything :( please help me out. Thank you NB: SP1 has a baudrate of 19200,Databits 8 and no parity,COM1 port. I aisnt sure whether I will be needing a buffer or not A: You will need to check whether or not you need to turn on flow control. Most often, the serial port will be using RTS hardware flow control. Setting RtsEnable = True will allow data to flow to your application. As was mentioned in another comment, you should not attempt to open the serial port object within the data received event handler. The serial port object should already be open when the data received event is fired. That is probably the reason you aren't getting data when you perform the ReadExisting method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Netbeans 7 Swing not working I had a gui (swing) project developed using netbeans 7 and JDK 6. Then I've installed JDK 7 and project still worked fine. But then I've reinstalled netbeans and now when I open my project it says that "swing-app-framewok" library is missing. Also I'm unable to create new swing application - there is no such item in menu. Can I make my project work again? P.S. I'm using Ubuntu 10.04 if it's important. A: Vicente Plata was right, I just needed to enable Swing plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ActiveRecord 'no method found' exception on simple one-to-many relationship This is a very basic task, but I can't for the life of me find the cause of the issue. I am doing a basic to-do lists attached to user accounts. I am using Sorcery to help with the user authentication & creation, which seemingly works fine. The Problem Is This: When I try to call `@user.list' in any way, I get the following exception (this is copied out of the rails console): @user = User.where(:email => "[email protected]") => [#<User id: 1, email: "[email protected]", crypted_password: "$2a$10$tiLFyiuLGSB.UXElEdaTGerSv6/TZoLL4nVFdCNsv1AW...", salt: "e6275124385b0ea157875bba281c7ae9e3a9858e", created_at: "2011-10-02 05:59:02", updated_at: "2011-10-02 05:59:02", remember_me_token: nil, remember_me_token_expires_at: nil>] @user.lists NoMethodError: undefined method `lists' for #<ActiveRecord::Relation:0x007f8b6ca89748> from /Users/<myaccount>/.rvm/gems/[email protected]/gems/activerecord- 3.1.0/lib/active_record/relation.rb:459:in `method_missing' from (irb):4 from /Users/<myaccount>/.rvm/gems/[email protected]/gems/railties-3.1.0/lib/rails/commands/console.rb:45:in `start' from /Users/<myaccount>/.rvm/gems/[email protected]/gems/railties-3.1.0/lib/rails/commands/console.rb:8:in `start' from /Users/<myaccount>/.rvm/gems/[email protected]/gems/railties-3.1.0/lib/rails/commands.rb:40:in `<top (required)>' from script/rails:6:in `require' from script/rails:6:in `<main>' My Code/DB Setup The setup is simple - I have a User model and a List model. a List :belongs_to :user, and a User has_many :lists. I have added user_id to the lists table with the following migration: class AddUserIdForeignKeyToLists < ActiveRecord::Migration def change add_column :lists, :user_id, :integer end end I have confirmed that the field user_id does exist in my table (MySQL). My User model is: class User < ActiveRecord::Base has_many :lists authenticates_with_sorcery! attr_accessible :email, :password, :password_confirmation validates_confirmation_of :password validates_presence_of :password, :on => :create validates_presence_of :email validates_uniqueness_of :email end ... and my List model looks like this: class List < ActiveRecord::Base belongs_to :user end The table design view from MySQL is as follows: users: lists: This sounds to me like there might be a relationship issue, but I can't seem to put this together. Does anyone have any insight? I've never run into any trouble at all like this running Rails 3.0.X on a linux machine, but this is my first foray into Rails 3.1 on OSX, so I'm not sure if maybe I overlooked an underlying change? Thanks for any guidance A: User.where(...) returns a collection of User objects, not a User object. You need to get a User object. @user = User.where(...).first or, better @user = User.find_by_email("[email protected]")
{ "language": "en", "url": "https://stackoverflow.com/questions/7629348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Use DNN Profile/User objects from ASP.NET web application Is there any way to leverage the DNN components for creating users and setting their profile properties from within a standard ASP.NET application? I am able to access this base ASP.NET Membership database without issue, but without being able to use DNN.Entities.Users.* I cannot truly create users and set/get their profile properties. A: I've never done it, but I am sure it can be done, and it's probably not that hard. Essentially you want a membership provider that runs outside of DNN. You might even get away with simply calling methods on the existing membership provider. I would start by reviewing the source of the ASPNetMembership provider. http://dotnetnuke.codeplex.com/SourceControl/list/changesets The provider is at \Library\Providers\MembershipProviders\AspNetMembershipProvider. A: I would assume that you could setup your web.config with the appropriate connection strings and include the DotNetNuke dll in your bin directory and have a shot ;) Might need to include some other dependent DLL's and work through a couple error messages. But in theory I think you could eventually get there going with this route.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sending commands to the client with Javascript For a site I'm planning, I need the server to be able to send commands to a logged-in user's browser. Simplic example: When a call center rep gets a call, I want to automatically pull up the lead who is calling in. I've got the rest of the technology sorted out and I need to get a sketch together of how the actual communication to the browser will work. From my research so far, this is often done with desktop software or plugins, but that feels pretty old school at this point. I know it can be done with javascript, either by writing something that constantly polls the server for commands (this could work, but it feels a little wasteful and brute force-y) or by some other technique that gives the server a way to call out to the client. Something like whatever mechanism stackoverflow uses to tell you new answers have arrived on the current question would probably do the trick. So is there a known best practice? What worked for you? A: WebSockets and long polling may be a good answer for you, as the other answers suggest. But also be sure to investigate the sw needed to support either on the backend (the non-browser, big iron part of your system.) If an always open file descriptor is needed per browser, that can add up. -- there are ways to add support for more file descriptors, but decide if that's the road you want to take. From a total system viewpoint, it may (or may not) be easier to set up a polling system. There's nothing wrong with polling the server, especially a specialized low overhead, "I've got nothing for you now"-type server. Remember that you want your solution to be robust. It should smoothly handle client disconnects, reboots, intermittent network failure, etc. Remember to test all of the above.... A: I believe that this is what the new web sockets html 5 standard is attempting to create, opening a connection between server and client to allow two way communication. But before that standard takes hold I'm not aware of any way other than polling at the moment. A: The server can not usually call the client. In order to do that, there must be a server software installed on the client side that would listen and respond. In case of a web browser there is no such thing. So the only thing you can do is to poll the server and check if you have something new. EDIT: I made a little test to see how stackoverflow works with this. My conclusion is periodic polling with the following system. When you want to add an answer, a post request is sent to the server, maybe to start a counter. After that at some intervals, requests are sent to /posts/ID/editor-heartbeat/edit sending the draft (what you managed to type until then) and the respons is a josn containing the success status of your request and the number of messages that where posted until then. If that number is different than 0 than the bar is shown to alert you. A: Websockets are what you want. A: The traditional way to do this has been with periodic XHRequests from the client, asking "do you have a new message for me?" There are fancier ways, which involve not closing a TCP connection and/or iframes; if you are interested you can google for how GMail does it. Websockets are a fairly new technology which is only implemented on the absolutely latest browsers, though I might risk it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rich Text Editor in Django Admin with image upload I'm looking for a good Rich Text Editor for the Django Admin Panel. I need an integrated with Django server which uploads the images. I also need a functionality of different configurations for two instances of RichText placed at one admin page. I've already tried four editors: TinyMce, CKEditor, NiceEdit, and Dojo, but each of them had some problems with the functionality. A: In my experience the best thing you could do is to use a markup language like Markdown in your administrative interface and not a RTE, coupled with a javascript editor like Markitup!, django-markitup and django-adminfiles you get pretty good functionality. A: I Think CKEditor Solve Your Problem. You Can Upload Image Too. If You Don't Know How Can Use It In Admin Panel, Comment On This Post Then I Can Help You :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Getting the source code . I am trying to get data from a web site.I looked online but haven't find any valuable information. when I do GetResponseStream() the code bellow is what I am getting from the reader. But when I go through browser I can see the source code with no problems. How should I go to bypass this page and access to the real page? this is the code I have so far. string baseUrl = @"url"; System.Net.HttpWebRequest httpwr = v (HttpWebRequest)WebRequest.Create(baseUrl); httpwr.AllowAutoRedirect=true; httpwr.Method = "GET"; httpwr.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; v:1.9.2.8) Gecko/20100722 Firefox/3.6.8"; httpwr.ContentType = "text/html"; httpwr.CookieContainer = cookies; and this is the string I am getting from the stream. <html><head><meta http-equiv="Pragma" content="no-cache"/> <meta http-equiv="Expires" content="-1"/> <meta http-equiv="CacheControl" content="no-cache"/> <script type="text/javascript">function test(){var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D"; var c = 1935516302 var slt = "f6kot5S9" var s1 = 'a' var s2 = 'e' var n = 4 var start = s1.charCodeAt(0); var end = s2.charCodeAt(0); var arr = new Array(n); var m = Math.pow(((end - start) + 1),n); for (var i=0; i<n; i++) arr[i] = s1; for (var i=0; i<m-1; i++){ for(var j=n-1; j>=0;--j) { var t = arr[j].charCodeAt(0); t++; arr[j] = String.fromCharCode(t); if (arr[j].charCodeAt(0)<=end) { break;} else { arr[j] = s1 ;}} var chlg = arr.join(""); var str = chlg + slt; var crc = 0; var crc = crc ^ (-1); for( var k = 0, iTop = str.length; k < iTop; k++ ){ crc = (crc >> 8) ^ ("0x" + table.substr(((crc ^ str.charCodeAt(k) ) & 0x000000FF) * 9, 8));} crc = crc ^ (-1); crc = Math.abs(crc); if (crc == parseInt(c)){break;}} document.cookie = "TS600f4f_75=" + "5829ff68b11a1b8f29078a2d7368c4ce:" + chlg + ":" + slt + ":" + crc + ";Max-Age=3600;path=/"; document.forms[0].submit();}</script></head><body onload="test()"> <form method="POST" action=""/><input type="hidden" name="TS600f4f_id" value="3"/><input type="hidden" name="TS600f4f_md" value="1"/><input type="hidden" name="TS600f4f_rf" value="0"/><input type="hidden" name="TS600f4f_ct" value="text/html"/><input type="hidden" name="TS600f4f_pd" value="0"/></form></body></html> A: The source you're getting back appears to be some form of intermediate page; a form that is automatically submitted by the browser, so what you see in the browser is not this page, but the page that follows it. You need to parse this source and generate an appropriate HTTP POST in order to get the next page. However, it looks pretty obvious that the author has gone to some lengths to prevent you doing what you're trying to. Ask yourself if you really should and don't forget to consider relevant laws around misuse of computers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Prompt user during unit test in Perl I'm writing a module which has unit tests that require a certain external server program to be running, and, if it is, the hostname and port need to be known. I would like to prompt for this information when running the test suite, and skip those tests if the user declines to provide it. What's the best way to handle this? Thanks A: Are you looking for ExtUtils::MakeMaker::prompt? Other Handy Functions prompt my $value = prompt($message); my $value = prompt($message, $default); The prompt() function provides an easy way to request user input used to write a makefile. It displays the $message as a prompt for input. If a $default is provided it will be used as a default. The function returns the $value selected by the user. If prompt() detects that it is not running interactively and there is nothing on STDIN or if the PERL_MM_USE_DEFAULT environment variable is set to true, the $default will be used without prompting. This prevents automated processes from blocking on user input. If no $default is provided an empty string will be used instead. A: I'll take a different tack on this. Why exactly do you need the user as a middleman for this - especially for automated tests? A significantly better approach (from my own experience) is to do one of the following: * *Make the server (hostname/port) somehow discoverable by the test. It can be either a genuine discoverability, or having the server register itself, or, heck, some config service. Considering that the server's clients in real world would need to be able to connect to the server, such a discovery logic (again, worst case scenario being some config file) should already exist. *For a really advanced case, allow the test harness the ability to start the test instance of a server on a test port if one is not running. Mind you, if your server for some reason can not be instrumented to allow either of the approaches above, then socket puppet's answer is the best approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to set SelectListItem in SelectList/@Html.DropDownList? How do I set the value of a SelectList/@Html.DropDownList given the following code? --Controller: public ActionResult Edit(int id) { Order o = db.Orders.Find(id); ViewBag.OrderStatusTId = new SelectList(db.OrderStatusTIds, "OrderStatusTId", "Name", o.OrderStatusTId); // I thought the last item would send in the selected item to the view?!?!? return View(o); } --View: @Html.DropDownList("OrderStatusTId", (IEnumerable<SelectListItem>)ViewBag.OrderStatusTId, String.Empty) A: Use viewdata instead of viewbag and change your helper to: @Html.DropDownList("OrderStatusTId",null, String.Empty)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to draw route on Google map inside a webview? I am displaying a map inside a webview not a mapview , how to draw a rout on the map where the points(lats,lngs) are coming from another activity ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7629366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: when minimizing browser, has a white space when scrolling over I have a problem with my page when I minimize a browser, say horizontally, and theres overflow. When I scroll over to the hidden section from minimizing, my whole page section is blank. Does anyone know why this happen? I have set my div's to a certain height (i.e. 900px, and not a percentage)? A: From your comment, that could well be your problem; your fixed width. Try replacing width with max-width. max-width will behave much the same as width while the containing element is that wide or wider, but will allow the div to contract when it gets smaller than the width you set. There's a simple example here. Stretch and resize the bottom right panel to see it in action. If this doesn't work, we'll need to see a page link or a demo on JSFiddle. A: Here's a solution for you: CSS .wrapper { display: block; width: 100%; padding: 10px 0; /* add some top + bottom padding */ background-color: #252525; } .aligner { display: block; width: 960px; /* site width */ margin: 0 auto; } .container { display: inline-block; } HTML <div class="wrapper"> <div class="aligner"> <div class="container"> // stuff </div><!-- /container --> </div><!-- /aligner --> </div><!-- /wrapper --> It's not the prettiest, but it allows you to throw 100% width background-colors on any section, and works in < IE8. You can do whatever you need to within div.container (float, position, etc) and it will expand the .wrapper element (thus expanding your background color vertically). You will not experience white space on the right hand side because the background color is applied to the wrapper, which has a 100% width. Each div.wrapper should be treated as a "section" - 'header', 'feature', 'content', 'footer', etc...
{ "language": "en", "url": "https://stackoverflow.com/questions/7629380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Timer, or Handler for capturing data at regular intervals in Android mobile apps? I am writing an Android app that uses the accelerometer to record captured data at regular time intervals and store them into SQLite. Is is better to use Timer (and TimerTask), or Handler for this task? A: I would use a Handler in a TimerTask. Then I would use this task with a Timer. A: I would personally use a Handler. How are you recording the data? A: Handler is right way not timertask....You can directly use it for view invalidation not timer task
{ "language": "en", "url": "https://stackoverflow.com/questions/7629381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: sql select query for one row in one table and multiple row from another table I have tables like post,tag and post_tag .. Each post have some tags.. I want to get data like post 1 with tagA, tagB, tagC post 2 with tagB, tagD . .. post N with tagZ how is the right sql statement? post: id(int), title(varchar), text(varchar) tag: id(int), title(varchar) post_tag: id(int), post_id(int), tag_id(int) -> post_id foreign key on post table and tag_id foreign key on tag table. for example i want fetch all posts with tags title. 1 "post1" "somepost bla bla" "tag1 title " "tag2 title" . .. A: Try using group_concat to list all tags for a given post in a single field. See http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html A: you can first create a view of tags grouped by post then you can use query to get your desired result. More specific answer could be given if you actually post the details of your tables and their attributes
{ "language": "en", "url": "https://stackoverflow.com/questions/7629382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: xmlparser parse returns no always, how to fix? NSURL *url = [[NSURL alloc] initWithString:@"..."]; NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url]; //Initialize the delegate. XMLParser *parser = [[XMLParser alloc] initXMLParser]; //Set delegate [xmlParser setDelegate:parser]; //Start parsing the XML file. BOOL success = [xmlParser parse]; if(success) NSLog(@"No Errors"); else NSLog(@"Error Error Error!!!"); [xmlparser parse] returns no . Why is that happening? output: Error Error Error!!! A: If you implement the parseErrorOccurred: method in your delegate XMLParser class, it will give you the exact reason for the errors. Something like: - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { NSLog(@"NSXMLParser ERROR: %@ - %@", , [parseError localizedDescription], [parseError localizedFailureReason]); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7629388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is there any ready land-address regex matcher in c#? I have a list of strings. Does someone knows if there is a website that has some ready to use regex matches\validators in c# to popular land-address formats? like: <word_street>_<1-3digits>, <alphabetic_word_City>,<country> st <alphabetic_word_Street> and so on.. A: Take a look here http://regexlib.com I have found some usable regular expressions there , not sure about your request because i didn't understood exactly what you mean by and on the other hand if you are need the country i don't think that regular expression is your solution (Hard to maintain)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to update image after row is updated in jqgrid Code from How to show image in jqgrid in edit mode is used to show images in jqgrid. If row is updated (edit action is controller is called), row image is changed in server: image url remains same but new image is returned from server after row save. jqgrid still shows old image: it does not request new image from server. Pressing grid refresh button also does not request new image. Pressing browser refresh button retrieves new image but this is very inconvenient. How to show new image after row is updated in jqgrid ? Update I added outputcache attribute as Oleg recommends. Using fiddler I verifed that image response header from image call GET http://localhost:50076/erp/Grid/GetImage?_entity=Artpilt&size=54&id=734 HTTP/1.1 Accept: image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5 Referer: http://localhost:50076/erp/Grid?_entity=Artpilt Accept-Language: et-EE User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) Accept-Encoding: gzip, deflate Host: localhost:50076 If-Modified-Since: Mon, 03 Oct 2011 11:25:29 GMT If-None-Match: "ArtPilt734" Connection: Keep-Alive Cookie: .MyAuth=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx is: HTTP/1.1 200 OK Server: ASP.NET Development Server/10.0.0.0 Date: Mon, 03 Oct 2011 11:17:46 GMT X-AspNet-Version: 2.0.50727 X-AspNetMvc-Version: 2.0 Cache-Control: public, max-age=0, s-maxage=0 Expires: Mon, 03 Oct 2011 11:17:46 GMT Last-Modified: Mon, 03 Oct 2011 11:17:46 GMT ETag: "ArtPilt734" Content-Type: image/jpeg Content-Length: 1444 Connection: Close If data in edit form is changed and saved, old image still remains. fiddler shows that tmage is not retrieved from server. If edit form is closed, old image is shown in grid. Pressing jqgrid refresh button in jqgrid toolbar causes old image still to be displayed. Fiddler shows that new image request is not is not read from server. Only pressing F5 in browser retrieves new image. How to refresh image immediately if row data is changed in edit form ? Update2 I think Oleg means HttpCacheability.NoCache , not HttpCacheability.Private as he wrote in comment. I changed MVC2 controller to [OutputCache(Duration = 0, VaryByParam = "")] public FileContentResult GetImage(string _entity, int id, int? size) { HttpContext.Response.Cache.SetExpires(DateTime.Now.AddDays(-1)); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetMaxAge(new TimeSpan(0)); ... retrieving image and fileextension form database skipped ... HttpContext.Response.Cache.SetETag("\"ArtPilt" + id.ToString() + "\""); return File(image, "image/" + imagetype ); } respose header is HTTP/1.1 200 OK Server: ASP.NET Development Server/10.0.0.0 Date: Mon, 03 Oct 2011 13:10:35 GMT X-AspNet-Version: 2.0.50727 X-AspNetMvc-Version: 2.0 Cache-Control: no-cache Pragma: no-cache Expires: -1 Content-Type: image/jpeg Content-Length: 1457 Connection: Close but problem persists. Fiddler shows that current row image is not retrieved. A: It sounds like caching problem. You should set Cache-Control: max-age=0 in HTTP header of the GetImage action. You can consider to set ETag additionally. See this answer for more information. In ASP.NET MVC program you can use OutputCache attribute [OutputCache (Duration = 0, VaryByParam = "")] or Response.Cache.SetCacheability (HttpCacheability.Public); Response.Cache.SetMaxAge (new TimeSpan (0)); or something like Response.AddHeader ("Cache-Control", "max-age=0"); UPDATED: I used HttpContext.Current.Response.Cache.SetMaxAge (new TimeSpan (0)); in one demo project which generate Chat used in the <img src=...>. The HTTP header will be HTTP/1.1 200 OK Server: ASP.NET Development Server/10.0.0.0 Date: Mon, 03 Oct 2011 11:59:40 GMT X-AspNet-Version: 4.0.30319 X-AspNetMvc-Version: 2.0 Cache-Control: private, max-age=0 Content-Type: image/png Content-Length: 55420 Connection: Close and the corresponding action which generate and provide image will be called every time. The Expires header from the HTTP response which you posted looks suspected for me. I don't have it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET MVC2 Browser caching with HTTP304 Status Code In the company I work for, we have a web application developed with ASP.NET MVC2 and hosted on IIS7. In a specific action, we return a JsonResult object holding an array. This array is updated daily; so any request coming in the same day will end up with the same response. public ActionResult SomeAction(int id) { // Some calculations return Json(resultArray, JsonRequestBehavior.AllowGet); } Since the operation is costly, we wanted to improve performance with browser caching and so. I added a cache header, so we are telling user browser to cache the result till the next update of the database. Besides that, I want to add a "Last-Modified" header, so browser will ask for if the source is modified after the specified date. What is the way to accomplish that? I want to check if DB is modified after the date browser asked (Last-Modified header) and if not modified, I want to return 304 just IIS automatically does for static files (images, css and js files etc) A: Add a truthful Last-Modified header. If your data is updated daily, you should know when, right? Then, in the beginning of the action method, add a check for the incoming If-Modified-Since by parsing that datetime string in the HTTP request and checking against the actual last-modified time of your data. If the data hasn't been modified, just return 304 manually. If it has, do what the action method normally does. You could also (or instead) return an ETag with your content, the value of which must then change whenever the content changes. Then wrap the whole thing up as an ASP.NET MVC Action Filter for reusability. Then post about it on your blog. :) To protect against misbehaving clients and clients who don't cache anything (perhaps your data is loaded by an application and not a desktop browser), you could store the result of the action method in the ASP.NET output cache anyway, to avoid the costly operation. You'd probably have to VaryByCustom to implement absolute expiration though. 
{ "language": "en", "url": "https://stackoverflow.com/questions/7629398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: pyserial/python and real time data acquisition I have an infrared camera/tracker with which I am communicating via the serial port. I'm using the pyserial module to do this at the moment. The camera updates the position of a tracked object at the rate of 60 Hz. In order to get the position of the tracked object I execute one pyserial.write() and then listen for an incoming reply with pyserial.read(serialObj.inWaiting()). Once the reply/position has been received the while loop is reentered and so on. My question has to do with the reliability and speed of this approach. I need the position to be gotten by the computer at the rate of at least 60Hz (and the position will then be sent via UDP to a real-time OS). Is this something that Pyserial/Python are capable of or should I look into alternative C-based approaches? Thanks, Luke A: This is more a matter of latency than speed. Python always performs memory allocation and release, but if the data is reused, the same memory will be reused by the C library. So the OS (C library / UDP/IP stack) will have more impact than Python itself. I really think you should use a serial port on your RTOS machine and use C code and pre-allocated buffers. A: I would suspect that Python will keep up with the data just fine. My advice would be to try it, and if Python appears to lag, then try PyPy instead — an implementation of Python that compiles most of your inner loops down to machine code for speed close so that of C. http://pypy.org/ A: Python should keep up fine, but the best thing to do is make sure you monitor how many reads per second you are getting. Count how many times the read completed each second, and if this number is too low, write to a performance log or similar. You should also consider decoupling the I/O part from the rest of your python program (if there is one) as pyserial read calls are blocking.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: deleting tables on MySQL from jdbc Problem when deleting tables from jdbc I have a. jar that deletes records from multiple tables through a previously prepared statement i did it this way: -- SQL delete from tabla_a using tabla_a join tabla_c join tabla_b join tabla_d where tabla_a.tabla_c_id = tabla_c.id and tabla_c.tabla_b_id = tabla_b.id and tabla_b.tabla_d_id = tabla_d.id and tabla_d.field = 2; note: where (?) is an integer // Java conn = DriverManager.getConnection(dsn, user, pass); stmt = conn.createStatement(); int rows = stmt.executeUpdate(query); does not work does not erase any record, I tested the SQL directly to MySQL and working properly. A: Try using a PreparedStatement instead, and set the parameters. Something along these lines: conn = DriverManager.getConnection(dsn, user, pass); stmt = conn.prepareStatement(query); stmt.setInt(1, 2); int rows = stmt.executeUpdate();
{ "language": "en", "url": "https://stackoverflow.com/questions/7629409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove unreachable rules from a grammar in OCaml I'm new to Ocaml and for a homework assignment I have to write a function filter_reachable that takes a grammar and returns a reduced grammar with the unreachable rules removed. The only modules I'm allowed to use are Pervasives and List modules and no other modules. The idea I have is to first make a list of all reachable nonterminals. Then a rule is reachable if it's nonterminal part is in the list of all reachable nonterminals. All the rules that are reachable then placed into a new list and paired with the start symbol to create the reduced grammar. My solution is below. However it doesn't work and I don't understand why. Can anyone help me fix it? let rec member x s= match s with []->false | y::ys-> (x = y) || member x ys (*the type of a symbol*) type ('nonterminal, 'terminal) symbol = | N of 'nonterminal | T of 'terminal let rec get_nont sl= match sl with |[]->[] |h::t->match h with |N x-> x::get_nont t |T y-> get_nont t let rec get_rea_nont (n,r) = n::(match r with |[]->[] |h::t->match h with | a,b -> if a=n then (get_nont b)@(get_rea_nont (n,t)) else get_rea_nont(n,t) | _-> []) let rec fil (st,rl)= let x = get_rea_nont(st,rl) in (match rl with |[]-> [] |h::t-> match h with |a,b -> if (member a x) then h::fil(st,t) else fil(st,t) |_->[] |_->[] ) let rec filter(st,rl)= (st,fil(st,rl)) A: Imagine the second last recursive call to fil (st, rl). In this call rl has just one rule in it. Your code is going to try to discover whether the nonterminal of the rule is reachable by just looking at this one rule. This isn't going to work unless the nonterminal is the start symbol. Generally speaking I'd say you have to carry around quite a bit more context. I don't want to give too much away, but this is basically a classic directed graph traversal problem. Each grammar rule is a node in the graph. Edges go from a rule R to the other rules defining the nonterminals that appear in the RHS of R. This famous graph traversal algorithm generally works with a list of "visited" nodes. You need this because the graph can have cycles. Here is a grammar with cycles: A ::= B | B '+' A B :: = 'x' | 'y' | '(' A ')' A: Some remarks on your code: * *Instead of member, you could use List.mem *The pattern matching in get_nont can be combined: let rec get_nont sl = match sl with | [] -> [] | N x :: tl -> x :: get_nont tl | T _ :: tl -> get_nont tl;; *In functional programming, currying is used to define functions with more than one argument. See Scope, Currying, and Lists,section "Curried functions". *Use the power of pattern matching, e.g., demonstrated for get_rea_nont: let rec get_rea_nont_old n r = n :: (match r with | []->[] | (a, b) :: t when a = n -> (get_nont b) @ (get_rea_nont_old n t) | _ :: t -> get_rea_nont_old n t );; *Try modularize your code, e.g., for get_rea_nont: * *First filter elements being equal to n (see List.filter). *For the filtered elements, apply the function get_nont (see List.map) *Consider List.flatten to get the expected result. Thus, ... let get_rea_nont n r = let filtered = List.filter (fun (a, _) -> a = n) r in let nonterminals = List.map (fun (_, b) -> get_nont b) filtered in n :: (List.flatten nonterminals);;
{ "language": "en", "url": "https://stackoverflow.com/questions/7629412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: If URL not equal to specified URL then apply this jQuery? if the current uURL is not same as specified then apply jQuery. BUT THIS WONT WORK <script type="text/javascript"> var myurl = http://example.com/document.html; var currenturl = window.location if(myurl == currenturl) { $("<span>url's match</span>").replaceAll("body"); // check replaceWith() examples } </script> Also current URL can be a standard link http://example.com/ or as shown in example. A: You need to quote your URL: var myurl = http://site.com/document.html; // Should be var myurl = "http://site.com/document.html"; For best practice, don't omit the ; here: var currenturl = window.location //---------------------------^^^^ A: You are missing quotes on the first line: var myurl = "http://site.com/document.html"; And it should be != on the third line
{ "language": "en", "url": "https://stackoverflow.com/questions/7629413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Using ajax to load a jQuery DataTable I'm trying (and failing) to load a jQuery DataTable using the built-in ajax source argument. The datatable, however, shows the message "Loading..." where the row(s) should be appearing. Here's my datatable call : $('#my-table').dataTable( {bFilter: false, bInfo: false, bJQueryUI: true, bPaginate: false, bStateSave: false, bSort: false, aoColumns: [ {"sTitle" : "Date"}, {"sTitle" : "Our Co."}, {"sTitle" : "Their Co."}, {"sTitle" : "Note"} ], sAjaxSource: "/contact/company_name/"} ); Using Chrome, I can see that the call to /contact/company_name/ is occurring, is returning status 200, and has the following data: [[[Hello], [Goodbye], [Test1], [Test2]]] (which is my test data). I can also see that the dataTables.min.js is returning the error Uncaught TypeError: Cannot read property 'length' of undefined. I assume that my returned data is not formatted properly. Can anyone suggest the solution? A: If your ajax source returns [[[Hello], [Goodbye], [Test1], [Test2]]] This is not ok for datatables. It should be: { iTotalRecords: "54", iTotalDisplayRecords: "22", aaData: "[['Hello', 'Goodbye', 'Test1', 'Test2']]" } aaData stands for array of arrays. A: according to the website your service should return data in this format: { "aaData": [ [ "row 1 col 1 data", "row 1 col 2 data", "row 1 col 3 data", "row 1 col 4 data" ], [ "row 2 col 1 data", "row 2 col 2 data", "row 2 col 3 data", "row 2 col 4 data" ], [ "row 3 col 1 data", "row 3 col 2 data", "row 3 col 3 data", "row 3 col 4 data" ], [ "row 4 col 1 data", "row 4 col 2 data", "row 4 col 3 data", "row 4 col 4 data" ] ] } so, wrap your array in an object, name the array as aaData and try again. or you can name it any way you like, but then you need to add the sAjaxDataProp parameter in the datatables initialisation (say you name it data you would do it like this: $('#example').dataTable( { "bProcessing": true, "sAjaxSource": "/ajaxsource/callmydata", "sAjaxDataProp": "data" } );
{ "language": "en", "url": "https://stackoverflow.com/questions/7629423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: p:commandLink ajax events inside of a p:dataTable Let's say we have a simple table defined as: <p:dataTable value="#{testBean.dummyStringData}" var="data"> <p:column> <p:commandLink action="#{testBean.printData(data)}"> <h:outputLabel value="#{data}" /> </p:commandLink> </p:column> </p:dataTable> And a simple backing bean: public class TestBean { private List<String> dummyStringData = new ArrayList<String>(); //getters and setters omitted @PostConstruct public void postConstruct() { dummyStringData.add(new String("DummyData1")); dummyStringData.add(new String("DummyData2")); dummyStringData.add(new String("DummyData3")); } public void printData (String data) { System.out.println(data); } Predictably, clicking on a link within the table will print the content of the clicked row to stdout. Now, I would like for the printData method to be also called when a user hovers the mouse cursor over the p:commandLink within the table. To accomplish that I've tried nesting a p:ajax element inside the p:commandLink element: <p:commandLink action="#{testBean.printData(data)}"> <p:ajax event="mouseover" listener="#{testBean.printData(data)}" /> <h:outputLabel value="#{data}" /> </p:commandLink> This approach doesn't seem to work for p:commandLink and p:commandButton component. Hovering the mouse over the link seems to do nothing. If I were to use a component other than those two (i.e. a p:inputText and nest a p:ajax like the above) I get the expected behaviour. Now, using a p:commandLink's onmouseover and p:remoteCommand I do manage to trigger the appropriate ajax event: <p:commandLink action="#{testBean.printData(data)}" onmouseover="rc()"> <h:outputLabel value="#{data}" /> </p:commandLink> <p:remoteCommand name="rc" action="#{testBean.printData(data)}" /> However, the data variable passed as a parameter to the printData method isn't specific to the row from which the event was triggered. Instead, the last element from the collection is always used (in this case, that would be "DummyData3"). I'm using Primefaces 3.0.M3 on MyFaces 2.1.3 with Tomcat 7. Cheers! A: There's a solution on the PrimeFaces forum. Alternatively... I suspect that because the name of the generated JavaScript function will be the same for each iteration, the last one is the winner. You could do something like this to give each one a unique name: <p:dataTable value="#{testBean.dummyStringData}" var="data" rowIndexVar="rowIndex"> <p:column> <p:commandLink action="#{testBean.printData(data)}" onmouseover="rc_#{rowIndex}()"> <h:outputLabel value="#{data}" /> </p:commandLink> <p:remoteCommand name="rc_#{rowIndex}" action="#{testBean.printData(data)}" /> </p:column> </p:dataTable>
{ "language": "en", "url": "https://stackoverflow.com/questions/7629425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: deadlock occuring in mutex code I have developed a user level thread library. In the code, deadlock occurs sometimes, but i am unable to figure out why it is happening. Here is the code for mutex lock and unlock functions: int gtthread_mutex_lock(gtthread_mutex_t *mutex) { if(!mutex) //checks if mutex is null return -1; while(mutex->available==1); //spin locks if mutex is already locked by someone else __sync_val_compare_and_swap(&mutex->available,0,1); //atomic function to swap value 0 with 1 mutex->owner=node->th; return 0; } int gtthread_mutex_unlock(gtthread_mutex_t *mutex) { if(!mutex) return -1; if(mutex->available) { mutex->available=0; mutex->owner=NULL; } return 0; } A: Another thread might obtain the lock between your while test and the swap. You'd have to check the return of __sync_val_compare_and_swap and reiterate if it didn't succeed. Also your code for keeping track of the owner will not work, because in your unlock you may delete the information that some other thread has written. Better you just have one field (handled with atomic operations) which holds the info on the owner and that is 0 if there is none.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: MODx Revolution backend browser doesn`t display thumb images After I`m trying to put an image to my TV or whatsoever I see only empty gif images instead of thumb images. Well let me describe my problem with this image! Where is the problem? A: You can try to delete all the "hidden" .image.jpg images that is inside the picture folder. That way MODX will generate new thumbs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Receive data from Apply With LinkedIn I am using the Data-Url option in the Apply With LinkedIn button. I have the data-url pointing to an action in my controller. I can confirm that my action is being hit after I complete an application using the Apply with LinkedIn button, however I don't know how to receive the data. My application is built in C# and MVC3. https://developer.linkedin.com/application-response-data-structure Here is an example of the response from LinkedIn, I am receiving it as a JSON but I have no idea how to accept a JSON like that one. https://developer.linkedin.com/processing-results-code-samples Here are some examples on how to parse it but they seem to parse a post body and not a JSON so i'm a bit confused. Any help would be appreciated A: Does this help? http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx Scroll down to the part titled "JavaScript and AJAX Improvements". What we're doing is similar to if we were sending you an HTTP POST of JSON via AJAX (even if it's not coming via AJAX, but your script shouldn't care). I'm not a C# guy, but that seems to be what you're looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Conservative garbage collector I've seen garbage collectors labelled as a lot of things- generational, etc. But I've seen the Boehm GC labelled as "conservative". What exactly does that mean? A: A conservative garbage collector is one that does not know whether or not a given word is a pointer. If the word points into an allocated heap block then the garbage collector conservatively assumes that the word is a pointer and, therefore, does not recycle that heap block or anything considered to be reachable from it. The main advantage of this approach is that it can collect unreachable values without having to work in harmony with the compiler. However, there are many disadvantages: * *Values that happen to look like pointers cause memory leaks by preventing parts of the heap from being recycled. This is a much bigger problem with 32-bit address spaces because almost every int will point to a heap block if GBs of RAM have been allocated. *Determining whether or not a word points into an allocated heap block requires the heap to be searched which is slow and (objectively) unnecessary. *The GC cannot move heap blocks because it cannot update pointers because it does not know where they all are. *Code that hides pointers or uses pointers outside the heap block will crash a conservative GC. This problem arose with the Numerical Recipes code and Boehm GC, albeit because the NR C code violated the C spec. These disadvantages are severe enough that production garbage collectors try not to be conservative whenever possible. A: A garbage collector must scan all objects and invocations (execution stack) to identify all of the "live" addresses in the executing program and then "collect" objects that do not have "live" addresses. In some environments it's possible for the GC algorithm to be PRECISE and know exactly what is an object address and what is not. In other environments it must scan parts of storage (most notably the execution stack) where there are words of storage that MIGHT be an object address and make the CONSERVATIVE assumption that if it looks like a valid address, and there is an object that has that address, then the object should not be collected. There are advantages to conservative collection, most notably that the code generator (if not interpreted) is freer to allocate variables where and when it needs them and it need not keep rigorous track of which are object pointers. (The need to keep track of object pointer locations can lead to less well optimized code, in addition to making the code generator considerably more complex. Also, a conservative collector stands some reasonable chance of being used with a compiler which was never intended to support garbage collection, while a precise collector would require that the compiler be radically altered.) The major disadvantage of the conservative approach is that a full "copying" collector cannot be implemented. When copying is done the pointers to the copied objects must be updated, and if it's not clear whether a given bit value is an object pointer or just a numeric value, it cannot be safely determined whether or not it should be modified when the object is copied. There's also the disadvantage that some "dead" objects may end up not getting collected, due to random bit patterns that look like their addresses, though in practice this is not a serious concern.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }