text
stringlengths
8
267k
meta
dict
Q: displaying django form error messages instead of just the field name I have a form and I want to display the errors in a for loop. {% for error in form.errors %} <tr><td>{{ error }}</td></tr> {% endfor %} By doing this the {{ error }} only contains the field name that has an error, but not the error message. How can I display the error message? A: You can get all field errors in a form like this: {% for field in form %} {{ field.errors|striptags }} {% endfor %} Or for a specific field: {% if form.subject.errors %} <ol> {% for error in form.subject.errors %} <li><strong>{{ error|escape }}</strong></li> {% endfor %} </ol> {% endif %} More Infos here: https://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template
{ "language": "en", "url": "https://stackoverflow.com/questions/7585606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Parsing JSON for GOOGLE API Returning Images iPhone SDK Just wondering if I am doing this correctly, It seems a lot of code for something so simple... Passing the google json request with my key to this function using ASIHTTPREQUEST NSString *url4Google = [[NSString alloc] initWithFormat:@"https://www.googleapis.com/shopping/search/v1/public/products?key=(MY SECRET KEY)&country=GB&q=5035822086234"]; ASIHTTPRequest* request = [self requestWithURL:url4Google]; Code for processing... - (void)requestFinished:(ASIHTTPRequest*)request { NSLog(@"GOOGLE SHOPPER IMAGE LOADING"); NSDictionary *result = [[request responseString] objectFromJSONString]; //GOOGLE SHOPPER IMAGE RETURN.. NSArray *Image = [[[[result objectForKey:@"items"] valueForKey:@"product"] valueForKey:@"images"] valueForKey:@"link"] ; NSArray *Title = [[[result objectForKey:@"items"] valueForKey:@"product"] valueForKey:@"title"]; //NSLog(@"TITLE OF ITEM = %@", Title); int size = [Image count]; NSLog(@"there are %d product images for this barcode ", size); int titlez = [Title count]; NSLog(@"there are %d title names for this barcode ", titlez); NSArray *imagearray = [Image objectAtIndex:3]; NSString *titleofitemis = [Title objectAtIndex:2]; //Choosing a number objectAtIndex... NSMutableString * result1 = [[NSMutableString alloc] init]; for (NSObject * obj in imagearray) { [result1 appendString:[obj description]]; } NSLog(@"FULL IMAGE URL IS = %@", result1); //SET IMAGE NSURL* _url = [[NSURL alloc] initWithString:result1]; self.url = _url; [_url release]; [result1 release]; NSLog(@"url = %@", url); UIImage* image = [ImageManager loadImage:url]; if (image) { imageView.image = image; } //SET TITLE self.title = titleofitemis; NSLog(@"FULL TITLE NAME IS = %@", titleofitemis); } I am using SBJSON and also ImageManager to async load the image after it has located an image.. I have done a bit of memory management as for me that isn't too much of a problem for this example... NSLOG OUTPUT 2011-09-28 16:29:17.351 IOSBoilerplate[17906:11c03] done pressed 2011-09-28 16:29:18.031 IOSBoilerplate[17906:11c03] GOOGLE SHOPPER IMAGE LOADING 2011-09-28 16:29:18.034 IOSBoilerplate[17906:11c03] there are 25 product images for this barcode 2011-09-28 16:29:18.035 IOSBoilerplate[17906:11c03] FULL URL FOR IMAGE = http://static.gam.co/media/films/00/000/0032/32467/image/30403.jpg Is this the quickest way & has this been done right, I can do all error level detection later.. Any help would be appreciated. A: Your code looks good. Some cleanup / style suggestions: //... NSMutableString *urlString = [NSMutableString string]; // shorter, autoreleased for (NSString *s in imagearray) { // already typed [urlString append:s]; } self.url = [NSURL urlWithString:urlString]; // that's all it takes UIImage *displayImage = [ImageManager loadImage:url]; // code is very readable, too Please refrain from using instance names starting with a capital letter, such as your Image or Title. The convention is that capitalized names are used for classes, not instances. Also, more descriptive names such as imageArray or imageList makes the code much more understandable. A: You can also use Google's Objective-C API library with the Shopping API. The library handles networking and authentication, and returns results as first-class Objective-C objects. The library includes a sample application for Shopping as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JSF Streaming PDF on iOS devices I have a JSF page that uses a backing bean to stream a PDF document to the browser. This functionality works great and I haven't had any problems with it until now when testing this functionality on iOS devices. On Safari on both an iPad and iPod Touch, the PDF stream ends up just being pasted as a non-scrollable layer on the webpage when it gets the response. In the browsers on a desktop, the file prompts to save or open and opens correctly with Adobe Reader. This is an issue because only part of the first page of the PDF shows on the iOS devices and there is no way to view other parts. I've tested other PDF's on these devices from web and they do not behave the same. Either a PDF application is launched or Safari loads a scrollable preview which are the desired outcomes. Has anyone else had this? My backing bean is writing a buffered input stream of the PDF to an output stream. I have set the following response headers: response.setContentType ("application/pdf"); response.setContentLength(inputLength); response.setHeader ("Content-Disposition", "inline;filename=\"" + saveFilename + ".pdf\""); response.setHeader ("Cache-Control", "must-revalidate, post-check=0, pre-check=0, public"); I have attempted to switch content-disposition from inline to attachment, but that did not help. A: I'd imagine that those devices require Range support in the server side so that the content can be requested in separate parts. This ultimately saves eventually unnecessary network bandwidth and improves the performance feeling in the client side. If those PDFs are dynamically generated, then your best bet is to write them to a temporary location in the disk file system and redirect the request to an URL which reads them by a servlet. Having a physical file is mandatory because you'd like to use RandomAccessFile in order to be able to return partial content of the file. This class requires a physical File on disk. Here's an example which uses File#createTempFile() to create a temp file and redirects the response to a servlet with the filename as URL parameter: File tempFile = File.createTempFile(saveFilename, ".pdf"); OutputStream output = new FileOutputStream(tempFile); // Now write PDF to output. // ... // Then, redirect to some servlet URL. String tempFilename = tempFile.getName(); externalContext.redirect("/pdf/" + URLEncoder.encode(tempFilename, "UTF-8")); Then, you need to have a servlet like this one which supports range requests. You only need to modify it to change the basePath value to System.getProperty("java.io.tmpdir"). Finally map this servlet on an URL pattern of /pdf/*. Alternatively, if you have full admin control over the server, then you could also create an additional webapp context pointing to an absolute path somewhere on the server's disk file system. E.g. /var/webapp/pdf. In case of for example Tomcat, you could make this public by adding the following to /conf/server.xml: <Context docBase="/var/webapp/pdf" path="/pdf" /> This way the /var/webapp/pdf folder's content is available by http://localhost:8080/context/pdf. With a minor change in the above code example to specify the temp file location, File tempFile = File.createTempFile(saveFilename, ".pdf", "/var/webapp/pdf"); // ... you don't need a custom servlet anymore. Tomcat's DefaultServlet will then do the job of properly handling Range requests. Last but not least, consider storing the temp file in session and implementing a HttpSessionListener or HttpSessionAttributeListener which deletes the temp file when the session has expired.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Embedding chaco in GTK Embedding Chaco into Qt and Wx seems to be no problem. Does anyone have an example or an idea how to embed Chaco into GTK? A: I use python with matplotlib. To have a graphic inserted in the GUI, I need a "backend" : http://matplotlib.sourceforge.net/faq/installing_faq.html#backends Code snippet : from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as Canvas Then, instance it (the add_subplot prepares a place for one plot) : figsn = matplotlib.pyplot.figure() ax = figsn.add_subplot(1,1,1) canvas = Canvas(figsn) ... snBox.pack_start(canvas, True, True) canvas.draw() So, what I want to say is that you need a "backend" from your package where you may be able to draw into, and that GTK can recognize. It suppose your chaco lib has to be compiled with GTK support. I can not install chaco here today, so please dig that way and let me know what you find !
{ "language": "en", "url": "https://stackoverflow.com/questions/7585611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Django planmember_set issue I have a question that I hope someone can help me with. I'm using a form to have the user select a "plan". Now I want to list all the members in the plan, in the form. I have a function 'get_owners' that grabs all the members in the plan, by using this function: def get_owners(self): owners = self.planmember_set.filter(ownership_type__code__in=["primary","joint"]) return owners Only problem is that I get an output of: [<PlanMember: Doe, John (Primary)>, <PlanMember: Doe, Jane(Joint Subscriber)>, etc] Now is there a way for me to just show their names and the member type (the words in brackets)? A bit of background code. Here is my views.py: if request.POST: form = PlanMaturityYearForm(Plan.objects.all().filter(profile = p), request.POST) if form.is_valid(): selected_plan = form.cleaned_data['plans'] plan = get_object_or_404(Plan, pk=selected_plan.pk) investment_list = Investment.objects.all().filter(Q(plan = plan)).order_by('maturity_date') context['investment_list'] = investment_list context['plan'] = plan context['today'] = now context['current_yr'] = current_year context['next_yr'] = next_year context['show_report'] = True else: form = PlanMaturityYearForm(Plan.objects.all().filter(profile = p)) context['form'] = form return render_to_response('reports/planmaturities_year.html', RequestContext(request, context)) And my forms.py: class PlanMaturityYearForm(forms.Form): def __init__(self, plans, *args, **kwargs): super(PlanMaturityYearForm, self).__init__(*args, **kwargs) self.fields['plans'] = forms.ModelChoiceField( plans, required=True, widget=forms.Select(attrs={'size': 20}), error_messages={'required':'Please select the plan you wish to build the report for',} ) Edit: models.py class Plan(models.Model): old_id = models.IntegerField(null=True) closed = models.BooleanField(default=False, blank=True) closed_date = models.DateField(null=True) profile = models.ForeignKey(Profile, default=False) plan_type = models.ForeignKey(PlanType) ownership_type = models.ForeignKey(OwnershipType) status = models.PositiveSmallIntegerField(max_length=2, default=PLAN_OPEN) timestamp = models.DateTimeField(auto_now_add=True, null=True, blank=True) notes = HTMLField(blank=True, null=True) bank = models.CharField(max_length=50, blank=True, null=True) account = models.CharField(max_length=50, blank=True, null=True) transit = models.CharField(max_length=50, blank=True, null=True) objects = PlanManager() class Profile(models.Model): old_id = models.IntegerField(null=True, blank=True) label = models.CharField(max_length=255, blank=True, verbose_name='Profile label/description') location = models.ForeignKey(Location, null=True, blank=True) client = models.BooleanField(default=False, blank=True) corp = models.BooleanField(default=False, blank=True) noncorp = models.BooleanField(default=False, blank=True) timestamp = models.DateTimeField(auto_now_add=True, default=False) bak_agent_id = models.CharField(max_length=10, null=True, blank=True) agent = models.ForeignKey(Agent, related_name='profiles') check1 = models.BooleanField(default=False, blank=True) incorp_date = models.DateField(null=True, blank=True) corp_records = models.BooleanField(default=False, blank=True) articles_of_incorp = models.BooleanField(default=False, blank=True) other_corp_articles = models.CharField(max_length=50, null=True, blank=True) bin = models.CharField(max_length=50, null=True, blank=True, verbose_name='BIN') phone = models.CharField(max_length=25, null=True) registration = models.CharField(max_length=45, null=True, blank=True) num_sigs = models.IntegerField(max_length=1, null=True, blank=True, verbose_name='Number of signatures required to transaction the account') charity = models.BooleanField(default=False, blank=True) donations_solicited = models.BooleanField(default=False, blank=True) ownership_type = models.CharField(max_length=45, null=True, blank=True) ownership_other = models.CharField(max_length=45, null=True, blank=True) #work around for other business type selction business_nature = models.CharField(max_length=45, null=True, blank=True) date_incept = models.DateField(null=True, blank=True) bind_power = models.BooleanField(default=False, blank=True) reg_documents = models.BooleanField(default=False, blank=True) other_documents = models.CharField(max_length=50, null=True, blank=True) reg_number = models.CharField(max_length=45, null=True, blank=True) tax_number = models.CharField(max_length=45, null=True, blank=True) phone = models.CharField(max_length=25, null=True, blank=True) fax = models.CharField(max_length=25, null=True, blank=True) email = models.CharField(max_length=100, null=True, blank=True) A: You can use values_list: owners = self.planmember_set.filter( ownership_type__code__in=["primary","joint"] ).values_list('name', 'type') A: def get_owners(self): owners = self.planmember_set.filter(ownership_type__code__in=["primary","joint"]).values_list('name_field', 'ownership_type__code') return owners Write where and how you use get_owners if not correct.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WP7 - Detect 'Click' event on a MapPolygon I am developing an app for windows phone 7. I have an overlay on the standard Map object that contains several MapPolygon objects. What is the best and/or simplest solution for knowing if the user has tapped one of the polygons? A: Using the Silverlight Toolkit is probably the easiest way to do it. Once added to your project use the gesture listener like so: var gestureListener = GestureService.GetGestureListener(poly); gestureListener.Tap += new EventHandler<GestureEventArgs>(gestureListener_Tap); Where gestureListener_Tap is the method called.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google gauges in python (reportlab) I am currently writing a program that will automatically generate PDF files using reportlab (a python module). I would like to know if it would be possible to put google gauges in but not as an image, instead as a request sent to google which outputs the correct gauges based on inputs or whatever it may be. sorry if this question is unclear but if anyone understands what I mean, any help is very appreciated. thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7585617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Extracting -Strings from a ByteBuffer - I'm getting all confused I've been sitting with this problem for some hours now without getting it to work the way I want it to work. I'm creating a server which reads data from a telnet client. The server uses java.nio (ServerSocketChannel) and reads into a ByteBuffer. After each read() I'm calling a method which is suppose to extract all lines (seperated by "\r\n") from the ByteBuffer and leave the (if any) remaining bytes in a way so the next read() puts them in the correct position. Example: read() reads 6 bytes, the ByteBuffer now contains "Hi\r\nHo". What I want to do is to extract all completely recieved strings, in this example "Hi\r\n". I want to "Ho" to be left in the ByteBuffer, shifted so that the "H" is at position 0, so that when I call read() next time and recieve "w are you?\r\n", it will be put at the correct place in the ByteBuffer. I created a small test program but I can't seem to get it to do it correct: http://pastebin.com/eun1nV2N Try different test strings ("HI", "HI\r\n", "HI\r\nHEY\r", etc) and you'll see when it fails. (I used the eclipse debug tool to inspect variables) A: Try wrapping the ByteBuffer an InputStream and a BufferedReader, then you should be able to use readline to get the lines one by one. A: * *Flip the buffer. *Call get() until you have the \r\n, storing the get() result of course. *Compact the buffer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Strange behavior with the method getUploadedBlobs I've a problem with the methode blobstoreService.getUploadedBlobs(). I've a JSP page in wich one I set an uploader like this : <formname='form' action='<%= blobstoreService.createUploadUrl("/Edit_Engine") %>' method='POST' enctype='multipart/form-data' > <input label='...' multiple='false' name='myFile' /> //...and multiple input for text </form> and I retrieve this code with my servlet : java.util.Map<String,BlobKey> blobs = blobstoreService.getUploadedBlobs(req); BlobKey blobK = blobs.get("myFiles[]"); //I don't know why I need to add the characters 's[]' at the end... But the behavior is strange. The first time I upload an image, everything works. However, the second time, I send my form without uploading somehting (only text data), and then my java code finds a BlobKey. But this BlobKey seems to be the previous sended data, or a corrupted data. I mean that not normal, because when I deploy this version on my localhost, if the form uploads no file the method getUploadedBlobs returns an empty HashMap. However, when I deploy on google servers, if the form uploads no file, the method getUploadedBlobs seems to return a HashMap with wrong data. Could you help me? Or tell me if this behaviro is normal... Many thanks, bat A: If you're getting a valid BlobKey, then myFiles[] is most likely the name given to the file input field in the form. Is that the case? That seems like an odd name for an input field. Are you using a template library to help generate HTML from the JSP?
{ "language": "en", "url": "https://stackoverflow.com/questions/7585622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create adsense ads using only the users account id? I have a website with articles and I want to share the adsense revenue of the articles with the article writers (in percentage of 90%). Iwe created a PHP code that rotates the ads, but I have a problem. Iwe discovered that It`s not enough the account ID, i need a the ad slot number, too. It would be much better if the user should send me only his account id, because else each user would need to create the ad in it`s own adsense account and send me the whole code and than I would need to check if the ad is the size I need. Any suggestions ? Is it possible to rotate the ads only by the user id ? A: You can use the old (but well working) AdSense code. It looks like this: <script> google_ad_client="YOUR-PUB-ID"; google_ad_width=300; google_ad_height=250; google_ad_format="300x250_as"; google_ad_type="image"; google_color_border="f3f3f3"; google_color_bg="f3f3f3"; google_color_link="313135"; google_color_text="626262"; google_color_url="2c89bc"; google_ui_features="rc:0"; </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> Available google_ad_type: 'text_image', 'text', 'image', for link units: omit this param. Ad formats are: 728x90_as (Leaderboard), 468x60_as (Banner), 234x60_as (Half Banner), 125x125_as (Button), 120x600_as (Skyscraper), 160x600_as (Wide Skyscraper), 180x150_as (Small Rectangle), 120x240_as (Vertical Banner), 200x200_as (Small Square), 250x250_as (Square), 300x250_as (Rectangle), 336x280_as (Large Rectangle) Link unit formats: 120x90_0ads_al (4 links), 120x90_0ads_al_s (5 links), 160x90_0ads_al (4 links), 160x90_0ads_al_s (5 links), 180x90_0ads_al (4 links), 180x90_0ads_al_s (5 links), 200x90_0ads_al (4 links), 200x90_0ads_al_s (5 links), 468x15_0ads_al (4 links), 468x15_0ads_al_s (5 links), 728x15_0ads_al (4 links), 728x15_0ads_al_s (5 links) Just play around. The other values are self explanatory ... Width/height must match the selected ad format's width and height. That's how we do it on Pagewizz.com and Wizzley.com with some ten thousands of users.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Precedence of post and pre incrementation operators There is code: #include <iostream> class Int { public: Int() : x(0) {} Int(int x_) : x(x_) {} Int& operator=(const Int& b) { std::cout << "= from " << x << " = " << b.x << std::endl; x = b.x; } Int& operator+=(const Int& b) { std::cout << "+= from " << x << " + " << b.x << std::endl; x += b.x; return *this; } Int& operator++() { std::cout << "++ prefix " << x << std::endl; ++x; return *this; } Int operator++(int) { std::cout << "++ postfix " << x << std::endl; Int result(*this); ++x; return result; } private: int x; }; Int operator+(const Int& a, const Int& b) { std::cout << "operator+" << std::endl; Int result(a); result += b; return result; } int main() { Int a(2), b(3), c(4), d; d = ++a + b++ + ++c; return 0; } Result: ++ prefix 4 ++ postfix 3 ++ prefix 2 operator+ += from 3 + 3 operator+ += from 6 + 5 = from 0 = 11 Why postfix operator isn't executed before prefix operator (++ prefix 4) altough priority of postfix operator is higher than prefix operator? This was compiled by g++. A: The order of evaluation of the different operands is unspecified which means that the compiler is free to reorder the evaluation of the ++a, b++ and ++c subexpressions as it pleases. The precedence of the operators does not really have any impact in that example. It does have an effect if you try to write ++i++ (where i is an int) which will be grouped as ++(i++) and it will fail to compile as the subexpression i++ is an rvalue and prefix increment requires an lvalue. If the precedence was reversed, then that expression would compile (and cause Undefined Behavior) A: Postfix ++ has the highest precedence in the expression ++a + b++ + ++c, but + has the lowest precedence and is left associative. This expression can be equivalently written as (++a) + (b++) + (++c) (each ++ is part of a different subexpressions) which explains why ++a is evaluated first. Consider traversing/evaluating the corresponding parse tree and it becomes obvious what the order of evaluation: E / | \ / | E / | | \ E + ++ c / | \ / | \ E + E / \ / \ ++ a b ++
{ "language": "en", "url": "https://stackoverflow.com/questions/7585625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Calling static methods from Spring Security Expressions? I'm looking for a way to extend Spring Security Expressions to support an existing security infrastructure. I'm aware you can extend the MethodSecurityExpressionRoot as described here, but I also found reference to directly calling static methods through Spring Expression Language (Spring EL or SpEL). Unfortunately the official page on Spring Expression methods doesn't directly describe how to do this. How can I invoke a static method through Spring Expression methods? A: By using the T(fully.qualified.name).methodName() syntax: You can use the special T operator to specify an instance of java.lang.Class (the type). Static methods are invoked by using this operator as well. The StandardEvaluationContext uses a TypeLocator to find types, and the StandardTypeLocator (which can be replaced) is built with an understanding of the java.lang package. This means that T() references to types within java.lang do not need to be fully qualified, but all other type references must be. The T element returns a reference to the type instead of an instance. For example, the equivalent of Collections.singleton("Hello") is T(java.util.Collections).singleton('Hello')
{ "language": "en", "url": "https://stackoverflow.com/questions/7585627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "45" }
Q: Android: How to pass data from android native code to jquerymobile My android app is getting session id as part of login service response, for the subsequent requests i have to pass this sess id. Now I'm using jquerymobile pages as webview content. I have to call some services from jquerymobile page using ajax. Can I pass sessid from android native code to jquerymobile for this. Thanks in advance. Thanks, Venkat Papana A: (It's quite the same question I answered here.) So this answer describes how to communicate with your webview with a javascript bridge. I think that's what your looking for... A: If I understand well, you're using ajax, meaning the webview content is served by a remote site. Assuming you have access to the site javascript, simply define a callback, say sessidFromAndroid(sessid) then get it called by java : mWebview.loadUrl("javascript:sessidFromAndroid("+mSession+")");
{ "language": "en", "url": "https://stackoverflow.com/questions/7585635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the loading order for fixtures files in Symfony 1.4 In my current project, I have multiple fixtures files. I would like to assign each files with data related to my tests. ie: * *Articles has one Author *Articles has many tags Fixtures: test/fixtures/commonAuthor.yml # Contains Common authors, with no particularities Author: Author1: name: Author1 test/fixtures/commonTag.yml # Contains Common tags, with no particularities Tag: Tag1: name: Tag1 Tag2: name: Tag2 test/fixtures/test_Article.yml # Contains All the data that is used by my functionals and unit tests Tag: Tag_not_active: name: Tag not active Article: Article_1: title: Article 1 Tags: [Tag1, Tag2] Author: Author1 Article_with_tag_innactive: title: Article 2 Tags: [Tag1, Tag2, Tag_not_active] Author: Author1 I wonder if the files are loaded alphabetically, or in any other order. Thanks. A: If you're using doctrine, the dependencies between fixtures are detected automatically and they will be loaded in order to fulfill all of them. If you're using propel, the files are loaded in alphabetical order.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: pulling unique values from an array of custom objects i have an array list of custom objects. each object contains a value i need to pull out, claimNO, but is not a unique value, meaning say 5 objects may have the same claimNO. what i need to do is make an array that only has unique claimNO's. i need to display this in a picker and can't have any repeating claimNO. my object: @interface ClaimCenterClaim : NSObject { NSNumber *claimID; NSString *claimNO; NSNumber *coid; NSString *eventDates; } @property (nonatomic, retain) NSNumber *claimID; @property (nonatomic, retain) NSString *claimNO; @property (nonatomic, retain) NSNumber *coid; @property (nonatomic, retain) NSString *eventDates; @end to me, this should work: NSMutableDictionary *ClaimCenterClaimNOList = [[NSMutableDictionary alloc] init]; int count01 = [sortedClaimList count]; for (int i = 0; i < count01; i++) { claimCenterClaim = [sortedClaimList objectAtIndex:i]; if ([ClaimCenterClaimNOList objectForKey:claimCenterClaim.claimID] != claimCenterClaim.claimNO) { NSLog(@"entered the bloody loop"); [ClaimCenterClaimNOList setObject:claimCenterClaim.claimNO forKey:claimCenterClaim.claimID]; } else NSLog(@"did not add value"); } but my value for "[ClaimCenterClaimNOList objectForKey:claimCenterClaim.claimID]" is always null untill after the if statement. if i have a claimID value, can't i just check if that key value in the dictionary already exists, and if it doesn't, add it? i would like to avoid needing to iterate thru the ClaimCenterClaimNOList dictionary (creates a loop in a loop). but i know the key, can't i just see if that key already exists in the dictionary? EDIT: incorrect logic my claimID values are unique, so i was checking my dictionary if a claimID was already added to the dictionary. since claimID is unique, it never found a match. i switched the search around and is now working. here's the correct code: int count01 = [sortedClaimList count]; for (int i = 0; i < count01; i++) { claimCenterClaim = [sortedClaimList objectAtIndex:i]; NSLog(@"lets see before: claimCenterClaim.claimiD: %@ the object: %@",claimCenterClaim.claimID, [ClaimCenterClaimNOList objectForKey:claimCenterClaim.claimID]); if ([ClaimCenterClaimNOList objectForKey:claimCenterClaim.claimNO] == nil) { NSLog(@"not in the dictionary"); [ClaimCenterClaimNOList setObject:claimCenterClaim.claimID forKey:claimCenterClaim.claimNO]; } else { NSLog(@"it works, it is in the dictionary"); } } A: Couple points, for the objectForKey, check for nil to determine the absence of the key. Also, you could just drop the array of claims into an NSSet that seems to closer to the desired behavior. But I am unsure, if you want to just access one or all of the claims for any given claim number. I think design wise what you are doing will work, but generalize your claim class to include all the claims for any given claim number. Keep you dictionary and the claim number key will access all of the given claims attached to a unique claim number.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: protobuf-net's [ProtoInclude(1, "MyClass")] did not work I am using protobuf-net v2 beta r431 for C# .net 4.0 application. In my application I have a Dictionary<int, IMyClass> which i need to serialize. A class MyClass implements IMyClass interface. As per protobuf's documentations I wrote the code as under: [ProtoContract] [ProtoInclude(1, typeof(MyClass))] public interface IMyClass { int GetId(); string GetName(); } [ProtoContract] [Serializable] public class MyClass : IMyClass { [ProtoMember(1)] private int m_id = 0; [ProtoMember(2)] private string m_name = string.Empty; public MyClass(int id, string name) { m_id = id; m_name = name; } public MyClass() { } #region IMyClass Members public int GetId() { return m_id; } public string GetName() { return m_name; } #endregion } However, as per my application's design, the interface is defined at a higher level (in a different project than the classes) and it is not possible to determine the class/classes that implements this interface at compile time. Hence, it gives compile time error for [ProtoInclude(1, typeof(MyClass))]. I tried to use [ProtoInclude(int tag, string KownTypeName)] as following: [ProtoContract] [ProtoInclude(1, "MyClass")] public interface IMyClass { int GetId(); string GetName(); } But, this threw an "Object reference not set to instance of an object" exception at line Serializer.Serialize(stream, myDict); where Dictionary myDict = new Dictionary(int, IMyClass)(); Please let me know how to use ProtoInclude in this case so as to serialize interface type inside dictionary / list. A: Since it will have no idea where to get your MyClass, you should probably use the Type.AssemblyQualifiedName value for your class. Here's some example code: namespace Alpha { [ProtoContract] [ProtoInclude(1, "Bravo.Implementation, BravoAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")] //[ProtoInclude(1, "Bravo.Implementation")] // this likely only works because they're in the same file public class PublicInterface { } } namespace Bravo { public class Implementation : Alpha.PublicInterface { } public class Tests { [Test] public void X() { // no real tests; just testing that it runs without exceptions Console.WriteLine(typeof(Implementation).AssemblyQualifiedName); using (var stream = new MemoryStream()) { Serializer.Serialize(stream, new Implementation()); } } } } A: Austin is correct (I believe): using an assembly-qualified name (as a string) should resolve this. In v2, an additional option exists: you can perform the mapping at runtime instead of via attributes: RuntimeTypeModel.Default[typeof(PulicInterface)] .AddSubType(1, typeof(Implementation)); This could be be through static code if your "app" tier knows about both types, or could be done via some custom configuration / reflection process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Automatically call class method in objective c my situation: * *a dashboard controller who register the widgets inside it and automatically builds the view. *widget classes that are going to populate the dashboard, who adopt <widget> protocol(some informal methods required), and need to be registered in the dashboard class so the dashboard singleton knows who wants to be in. *the dashboard class has +(void)register:(Class<widget>)w; that simply register the classes who wants to be in in an NSArray I need each widget class to call automatically that method.in c++ i used to make a boolean static variable that i would initialize with that method. Language = objective-c A: The objective-c runtime will call two methods when a class is first loaded. +load and +initialize. I believe what you want could be done by calling [self register] from within +initialize. A: A way you could do it is with the runtime: * *Grab a list of all the classes known to the runtime. *Iterate the list, and check to see if the class conforms to your widget protocol *If it does conform to the protocol, invoke the +register: method or whatever Regarding step #2, you can't use the +conformsToProtocol: method, because one of the classes you'll iterate is the NSZombie class, which triggers an exception whenever you invoke a method on it. Thus, you'd want to use the class_conformsToProtocol() runtime function instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: youtube videos on iphone phonegap app I'm sorry to come back to this topic again, but i'm really frustrated!! I've read every resource i've found, googling around the web, but i couldn't come up with a definitive answer to my problem. Problem description I'm creating an iphone app with phonegap 1.0. In this app, one tab is dedicated to a rss feed from my youtube channel and i want my users to be able to play these videos, after clicking on a specific entry. Question: is it possible? best solution would be to play the video inside the app, but displaying a thumbnail image and redirecting the user to native youtube app is also acceptable (even though in this case i want the control back to the original app when youtube finishes to play the video). Tried solutions Searching on the web I found several solutions and people say that these solutions work for them, but none of them work for me! * *use an "object" tag, i end up with a white screen <object id="video" width="296" height="100%" data="http://www.youtube.com/v/gDjb9RVMF4c" type="application/x-shockwave-flash"> <param name="allowfullscreen" value="true" /> <param name="src" value="http://www.youtube.com/v/gDjb9RVMF4c" /> </object> *using an "embed" tag, i end up with a white screen <embed src="http://www.youtube.com/v/gDjb9RVMF4c" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="280" height="100%"></embed> *i also tried a "video" tag, but as far as i understood, this is still not possible. I'm really sorry if i missed a solution already written somewhere, but trust me ... i did my homework before askying :-) Thx!! A: Here is a nice tutorial Which Saved my Day http://eisabainyo.net/weblog/2012/01/24/embed-a-youtube-video-iframe-in-phonegap-app/ Also i m posting some codes For a quick Access. <html> <head> <title>YouTube video</title> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" /> <script src="phonegap-1.2.0.js"></script> </head> <body> <iframe width="560" height="315" src="http://www.youtube.com/embed/9HDeEbJyNK8" frameborder="0" allowfullscreen></iframe> </body> </html> Then make the following changes in Phonegap.plist MediaPlaybackRequiresUserAction: NO AllowInlineMediaPlayback: YES OpenAllWhitelistURLsInWebView: YES ExternalHosts *.youtube.com *.ytimg.com Video will play on your Simulator Also. A: Apart from using <iframe> ... </iframe> you also need to set the property OpenAllWhitelistURLsInWebView to YES in your PhoneGap.plist. This would show and play the video inside the PhoneGap application itself. It is tried and tested. A: You could try embedding the YouTube video as an iframe, I believe that is the recommended way to do it now: http://apiblog.youtube.com/2010/07/new-way-to-embed-youtube-videos.html <iframe src="http://www.youtube.com/embed/VIDEO_ID" class="youtube-player" type="text/html" width="640" height="385" frameborder="0"> </iframe> A: Here is a component I've end up using in my app. Done with a help of YouTube iFrame API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: General Android semi transparent bug I use anti aliasing to make my images more smooth. When using anti aliasing a dark border will be drawn around the images. This happens because Android uses the color black and mixes it with the yellow from the images. This is a gernal problem! When I draw a rectangle and set the alpha value to 127 the image also gets quiet dark. Instead of using black Android should use white to draw the transparency. Is there any workaround how I can handles this problem? Example sourcecode for drawing a semi transparent rectangle to a canvas. The rectangle is dark as well but it should be bright. Bitmap bmp = Bitmap.createBitmap(200, 200, Config.ARGB_8888); Canvas canvas = new Canvas(bmp); Paint rPaint = new Paint(); rPaint.setColor(Color.parseColor("#F7E836")); rPaint.setAlpha(127); rPaint.setStyle(Paint.Style.FILL); canvas.drawRect(0, 0, 100, 100, rPaint); The images are SVG graphics which are rendered with the following library: http://code.google.com/p/svg-android/ I think I found the bug. The problem is the SurfaceView. Its background is black. The same semi-transparent bug occurs when I use the code above and display it on an ImageView and the background color of the UI element behind the ImageView is black. The background color of the SurfaceView is always black. If I change this to white with setBackgroundColor, the SurfaceView gets white, but the white background will be drawn OVER all my other images drawn with OpenGL. I think these must be switched. First the background color should be drawn and than the OpenGL stuff. A: Post links to the original source images and show how your anti-aliasing them (code). When an image is anti-aliased the algorithm will insert colors between the colors which make up the edges. So with your yellow star image, if the background was white, it will attempt to add pixels around the edge which are between the yellow and white (a lighter shade of yellow). This is what 'smooths' the image. But, if the image has an indexed color space, those lighter shades of yellow probably don't exist in the images pallet and as a result, you can get almost any other color in its place, whatever color in the index lands on the index value calculated. The image in your question is an indexed png and hence has this problem. If this is the issue, then you need to convert your original source images to an non-indexed color space, or anti-alias them prior to indexing the images which doesn't work well if the images need to be scaled by your application or if you need to anti-alias against various different backgrounds. The other thing that could be happening is that your anti-aliasing against a different background than you think you are, specifically the yellow star is anti-aliased correctly if the background were black, posting your code is the easiest way to figure this out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: "simple" PHP script to display progress upload using no modules, no package, no flash I am trying to make a 'simple" php+ajax script to show progress of multiple uploaded files. I have found on this website and on other pages, packages ready to use, etc.... I want to start from scratch for several reasons, and one of them is learning. Here is how I wanted to approach it: First, I start with a ajax code in upload.php (this file contains the upload form and a to display upload progress) <script> $(document).ready(function(){ $("#uploadform").change(function(e) { e.preventDefault(); setInterval(function(){ $('div#upload_progress').load('upload_progress.php'); }, 1000); }); }); </script> upload_progress.php contains the code to get the instant file size on the server (I have not got there yet). So, as for now, the only line I have in 'upload_progress.php' is: 'VOILA'. Here is my problem: the div #upload_progress does not load during the file uploaded, so I don't see the text in upload_progress.php. I have tried to upload large files or reduce the setInterval time, but without success. Except that when I put an alert window (alert('alertme');) after the setInterval, the div#upload_progress magically get loaded. I'd really appreciate some help. A: Try html5 <progress value="1" max="100">Loading</progress> And increase value A: U can use 2 divs like JMarc says..It's a little rusty and not very religious but it does the job.U retained the width in a session variable that holds the amount of file uploaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why does LLVM complain about missing function prototypes? LLVM 2.1 has an option that enables warnings for "missing function prototypes." When enabled, the warning will complain about a file like this: double square( double d ) { return d*d; } void main() { // ... } The function "square" will trigger a warning because it is defined without having been declared (prototyped). You can eliminate the warning thus: double square( double d ); double square( double d ) { return d*d; } void main() { // ... } I've programmed in C++ for twenty years and I've never seen a warning like this. It does not seem useful to me. By default, this warning is enabled in new Mac console projects (at least) in Xcode 4.1. Evidently someone found it useful enough to first implement it and then enable it by default. Why is this a useful warning? Why does LLVM have it as an option? Why is the option enabled by default on Xcode? A: The compiler uses the prototype declaration to match types for the function definition. If you are writing the prototype in a header(interface) file and the implementation in the source file then this warning (by forcing you to provide a declaration, effectively) would prevent you from making a typo error where function definition is different than the one in declaration. Though, without such an warning, you would get the errors while linking. One might end up wondering what the actual problem is(n number of reasons for linking errors). The warning during compilation stage is much better indication of error than a linking error. A: If could be useful to make sure every function is either visible from some header, or static. I had cases where two files were linked together, even though none of them used the same header file. Take this example: int test() { return 0; } If there's no header, you can have a second file which does: extern int test(); test(); If you are writing a library, this warning could tell you that someone could be using this function even if they were not supposed to, since this function is in no header. They should have been marked as static. A: Prototype of "int test()" should be "int test(void)" then it's OK.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Spring MVC and Encryption at Rest Sorry for the newbie question, I'm trying to use the Spring MVC framework to upload files. I am trying to maintain encryption at rest, however the MultipartFile states that the uploaded file may be stored on disk during the upload(1). I do not encrypt the file until after the upload. Does this break encryption at rest? Does "at rest" include information temporarily stored on disk during the course of the program? Thanks in advance for any responses! 1: states that "The file contents are either stored in memory or temporarily on disk." A: As long as the file is being stored in a temp location where it will not persist longer than the transaction, then I would say it doesn't break the at rest paradigm. If someone is watching a temp directory for fleeting files (whether a rogue admin or an outsider who has rooted your box), then you have bigger issues to deal with. If the file persists in that temp location, then yes, the at rest paradigm is not being followed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Installing Ext JS 4 - Where to put files? Hi to all from Córdoba !. My question would be the following one... How to configure my Ext JS 4 files so as to start working ?. Coz although I manage to show a window, the close button when I put: "closable: true" doesn't appear or for instance when I put "frame:true" the window doesn't show a frame and the title bar is all white... So it is a little bit weird !. I would like to know If someone can explain me in which folders I should place all the css, js and png or jpg files in order to have a correct rendering of the widgets or maybe if someone could upload somewhere an ext js 4 project with all the files it would be ok (the entire ext js library I would prefere) !... For example: My project structure would be: * *resources * *css *sass *themes *extjs * *ext-all-debug.js *index.html <link rel="stylesheet" type="text/css" href="resources/css/ext-all.css"> <script type="text/javascript" src="extjs/ext-all-debug.js"></script> <script type="text/javascript"> Ext.BLANK_IMAGE_URL = 'resources/themes/images/default/tree/s.gif'; Ext.onReady(function() { Ext.BLANK_IMAGE_URL = 'resources/themes/images/default/tree/s.gif'; var win = Ext.create('Ext.window.Window', { renderTo: document.body, title: 'Hello', height: 200, width: 400, draggable: true, frame: true, closable: true }).show(); Ext.create('Ext.tab.Panel', { width: 400, height: 400, renderTo: document.body, items: [{ title: 'Foo' }, { title: 'Bar', tabConfig: { title: 'Custom Title', tooltip: 'A button tooltip' } }] }); }); </script>      If someone sees something incorrect, pls tell me... A: A summary of what is given at the sencha website: Your project structure should look like this: * *appname * *app * *namespace * *Class1.js *Class2.js *... *extjs *resources * *css *images *... *app.js *index.html Mainly concentrate on extjs folder. That should be a copy of the folder that you receive from the sencha website. Don't change the files inside. The minimum number of files required to run extjs are to be included in the following order: <html> <head> <title>Hello Ext</title> <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css"> <link rel="stylesheet" type="text/css" href="path/to/your/own/css/if/any"> <script type="text/javascript" src="extjs/ext-debug.js"></script> <script type="text/javascript" src="your/own/js.js"></script> </head> <body></body> </html> That's it! You're ready to Rock 'n Roll! Instead of ext-debug.js you can use ext-all-debug.js - This file contains the entire Ext JS library. This can be helpful for shortening your initial learning curve, however ext-debug.js is preferred in most cases for actual application development.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validation of DropDownListFor element in MVC3 I use jQuery Unobrtusive Validation with MVC3 to validate a DropDownListFor form element, but it doesn't work. It validates very well if I modify DropDownListFor to TextBoxFor - and it also validates the other fields of the form. I have multiple DropDownListFor elements, based on what's available in the database. Thus the loop. Here's some of my code: ViewModel: public class ParentViewModel { // some other stuff here public List<Children> Children { get; set; } } public class ChildrenViewModel { public SelectList PossibleNames { get; set; } [Required(ErrorMessage = "Select a name")] public int ChosenNameId { get; set; } } View: @for (int i = 0; i < Model.Children.Count; i++) { @Html.LabelFor(model => modell.Children[i].ChosenNameId, "Name") @Html.ValidationMessageFor(model => modell.Children[i].ChosenNameId) @Html.DropDownListFor(model => modell.Children[i].ChosenNameId, Model.Children[i].PossibleNames, "Choose a name") } Hopefully these extracts are enough to identify the error... Any hints on why this doesnt work? A: Try replacing: [Required(ErrorMessage = "Select a name")] public int ChosenNameId { get; set; } by: [Required(ErrorMessage = "Select a name")] public int? ChosenNameId { get; set; } Notice the nullable integer that is being used. You should be using a nullable type when binding a dropdownlist that can have a non-selected value. A: I figured this out myself. This seems to be a bug in MVC3, which causes collections of selectlists not to be validated. The issue has been discussed several times before, for instance: * *http://forums.asp.net/t/1649193.aspx/1/10 *ASP.NET MVC 3 - Validation Question Personally, I solved it by simply manually adding data-val-required and data-val manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UserControl ContentProperty, Content objects are null I created a custom silverlight UserControl. I need to be able to set its content through a "Child" property. So I used the "[ContentProperty("Child")]" class attribute : [ContentProperty("Child")] public partial class SizeableCheckBox : UserControl { public SizeableCheckBox() { InitializeComponent(); } public object Child { get { return contentControl1.Content; } set { contentControl1.Content = value; } } The XAML of the UserControl looks like that : <Grid x:Name="LayoutRoot" > <StackPanel Orientation="Horizontal"> <Border x:Name="brdCheck" /> <ContentControl x:Name="contentControl1" /> </StackPanel ... </Grid> Now if I use my UserControl in my application everything works fine (even in VS2010 design mode) : <my:SizeableCheckBox x:Name="chkTestCheck"> <StackPanel Orientation="Horizontal"> <Image ... /> <Textblock x:Name="txtCheckBoxTest" Text="My Checkbox test" /> </StackPanel> </my:sizeableCheckBox> But in my code I have a reference to the "txtCheckBoxTest" but that object is null on runtime. What am I doing wrong? Thanks A: you should be able to go chkTestCheck.txtCheckBoxTest.Text unless i am misunderstanding the quesiton
{ "language": "en", "url": "https://stackoverflow.com/questions/7585666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get in one query an item and another item having one of its value nearest of the former one? Imagine I have the following table : ID || Order ----------- 1 || 1 2 || 2 3 || 5 4 || 20 5 || 100 6 || 4000 (no specific rule applies to the order value). I want to "move up" ou "move down" items by swapping order values. Ex: a call to MoveItemUp(4) will results in this new table values : ID || Order ----------- 1 || 1 2 || 2 3 || 20 <-- swapped order value 4 || 5 <-- swapped order value 5 || 100 6 || 4000 I want to do this in a single query, but I was not yet successful. The following query works if items order are sequential, with no "hole" (steps of 1 :) UPDATE dbo.ITEMS set ORDER = case when c.ORDER = c2.ORDER then c.ORDER +1 else c.ORDER -1 end from dbo.ITEMS c inner join dbo.ITEMS c2 on c.ORDER = c2.ORDER or c.ORDER = c2.ORDER + 1 where c2.ID=4 However, I was not able to change this query to support hole. I'm trying to do : UPDATE dbo.ITEMS set case when c.ORDER = c2.ORDER then min(c2.ORDER ) else c2.ORDER end FROM dbo.ITEMS c inner join ITEMS c2 on c2.ORDER >= c.ORDER where c2.ID=4 group by c.CAT_ID, c.ORDER having c.ORDER = min(c2.ORDER ) or c.ORDER = c2.ORDER However, this does not works as expected (the query updates all items having a greater order instead of the two orders to swap). PS: I'm working with C# 2.0 on Sybase ASE 4.5, but I assume this question is not specific to this platform. If you have a MSSQL, MySql or Oracle equivalent, I'll put effort to convert it ;) A: NOTE All below solutions assume that ItemOrder is unique EDIT Adding a solution that is more like what OP was trying, and may be more portable to Sybase, this time on Microsoft SQL Server 2008. (See below for solutions using Oracle's analytic functions, that may be more efficient if available.) First the select to get our row selection criteria correct: declare @MoveUpId int set @MoveUpId = 4 select current_row.Id , current_row.ItemOrder , prior_row.id as PriorRowId , prior_row.ItemOrder as PriorItemOrder , next_row.id as NextRowId , next_row.ItemOrder as NextItemOrder from #Items current_row left outer join #Items prior_row on prior_row.ItemOrder = (select max(ItemOrder) from #Items where ItemOrder < current_row.ItemOrder) left outer join #Items next_row on next_row.ItemOrder = (select min(ItemOrder) from #Items where ItemOrder > current_row.ItemOrder) where @MoveUpId in (current_row.id, next_row.id) Then the update based on the above: update current_row set ItemOrder = case when current_row.Id = @MoveUpId then prior_row.ItemOrder else next_row.ItemOrder end from #Items current_row left outer join #Items prior_row on prior_row.ItemOrder = (select max(ItemOrder) from #Items where ItemOrder < current_row.ItemOrder) left outer join #Items next_row on next_row.ItemOrder = (select min(ItemOrder) from #Items where ItemOrder > current_row.ItemOrder) where @MoveUpId in (current_row.id, next_row.id) Id ItemOrder 1 1 2 2 3 20 4 5 5 100 6 4000 10 -1 20 -2 Set @MoveUpId to 20 and rerun above query results in: Id ItemOrder 1 1 2 2 3 20 4 5 5 100 6 4000 10 -2 20 -1 but I assume this question is not specific to this platform. The question may not be specific, but the answer probably is. For example, using Oracle, first, a table and some test data: create table Items (Id number(38) not null , ItemOrder number); insert into items values (1, 1); insert into items values (2, 2); insert into items values (3, 5); insert into items values (4, 20); insert into items values (5, 100); insert into items values (6, 4000); insert into items values (10, -1); insert into items values (20, -2); commit; Next create a query that returns just the rows we want to update with their new values for Order. (Which I named ItemOrder, Order being a reserved word and all.) In Oracle this is simpliest using the analytic functions lag and lead: select * from (select Id , ItemOrder , lead(Id) over (order by Id) as LeadId , lead(ItemOrder) over (order by Id) as LeadItemOrder , lag(ItemOrder) over (order by Id) as LagItemOrder from Items) where 4 in (Id, LeadId) order by Id; ID ITEMORDER LEADID LEADITEMORDER LAGITEMORDER ---------- ---------- ---------- ------------- ------------ 3 5 4 20 2 4 20 5 100 5 Convert that into an update statement. However the above query will not create an updateable view (in Oracle), so use merge instead: merge into Items TRGT using (select Id , ItemOrder , lead(Id) over (order by Id) as LeadId , lead(ItemOrder) over (order by Id) as LeadItemOrder , lag(ItemOrder) over (order by Id) as LagItemOrder from Items) SRC on (SRC.Id = TRGT.Id) when matched then update set ItemOrder = case TRGT.Id when 4 then SRC.LagItemOrder else SRC.LeadItemOrder end where 4 in (SRC.Id, SRC.LeadId); select * from Items order by Id; ID ITEMORDER ---------- ---------- 1 1 2 2 3 20 4 5 5 100 6 4000 10 -1 20 -2 Unfortunately, I do not believe lag and lead are widely implemented. Microsoft SQL Server, as far as I know, has yet to implement them. No experience with ASE, it they have them great. Row_number() is more widely implemented. Row_number() can be used to get something that is gap free. (Row_number() is refered to as an analytic function on Oracle and a windowed function on SQL Server.) First the query: with t as (select Id , ItemOrder , row_number() over (order by Id) as RN from Items) select current_row.id , current_row.ItemOrder , next_row.Id as NextId , next_row.ItemOrder NextItemOrder , prior_row.ItemOrder PriorItemOrder from t current_row left outer join t next_row on next_row.RN = current_row.RN + 1 left outer join t prior_row on prior_row.RN = current_row.RN - 1 where 4 in (current_row.id, next_row.id); ID ITEMORDER NEXTID NEXTITEMORDER PRIORITEMORDER ---------- ---------- ---------- ------------- -------------- 3 5 4 20 2 4 20 5 100 5 Doing the update, again with merge instead of update. (Oracle does allow the update ... from ... join ... syntax, one may be able to get away with update instead of merge on other platforms.) merge into Items TRGT using (with t as (select Id , ItemOrder , row_number() over (order by Id) as RN from Items) select current_row.id , current_row.ItemOrder , next_row.Id as NextId , next_row.ItemOrder as NextItemOrder , prior_row.ItemOrder as PriorItemOrder from t current_row left outer join t next_row on next_row.RN = current_row.RN + 1 left outer join t prior_row on prior_row.RN = current_row.RN - 1 where 4 in (current_row.id, next_row.id)) SRC on (TRGT.Id = SRC.Id) when matched then update set ItemOrder = case when TRGT.Id = 4 then SRC.PriorItemOrder else SRC.NextItemOrder end; select * from Items order by Id; ID ITEMORDER ---------- ---------- 1 1 2 2 3 20 4 5 5 100 6 4000 10 -1 20 -2 NOTE Note the solutions above will write null over OrderItems if matching against the Id for the first row.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AnimationDrawable frame duration problems i need to create an animation frame by frame but i have some problems I have 30 png images that compose my animation, i load my AnimationDrawable with this code: mCurrentAnimation = new AnimationDrawable(); mCurrentAnimation.setOneShot(true); int resId; for (int j = 1; j < 31; j++) { resId = getResources().getIdentifier("resName", "drawable", "com.mindcolorstest.main"); mCurrentAnimation.addFrame(getResources().getDrawable(resId), 1); } And logically "mCurrentAnimation.start()" to start On mdpi device the animation works fine but i have some troubles with duration of every frame, on hdpi emulator or device i have some lag and if i will reduce duration of frames (both on mdpi or hdpi device) the animation will not go faster, like exist a minimum duration for every frame. Some tips and tricks? I don't know what i have to do Q_Q Thanks anyway A: i agree on this, i do more or less the same with a xml animation-list even on the S4 i get a much longer animation time per frame then i have set. (i have set the duration to 3ms per frame). i messured about 16,16ms per frame as minimum average over 30 cycles and 85frames. this may or may not respond to the line scheduleSelf(mAnimationRunnable, now + 1000/60); in animate() in DrawableContainer. just a guess because 1000/60 = 16,66 what should become 16 as int/long cast.. but it could also come from some other limitation in code or hardware speed. i have not checked if the code in this line gets called and is causing this because i can't somehow break there. however i think no display is that fast in reality so it looks clever..
{ "language": "en", "url": "https://stackoverflow.com/questions/7585680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: image saving from a URL problem I am trying to download an image from URL: http://appworld.blackberry.com/webstore/servedimages/340582.png?t=2 I am using HttpWebRequest webRespose Stream BinaryReader FileStream BinaryWriter this works for other websites and images but the url I gave on the above gives me an empty 0 byte file.. which means I cannot save the image from that URL. Is there anybody who can help me? A: I am using HttpWebRequest webRespose Stream BinaryReader FileStream BinaryWriter Why use 6 different classes when you can do the same with only one? string sourceUrl = "http://appworld.blackberry.com/webstore/servedimages/340582.png?t=2"; string localPath = @"C:\foo\bar\340582.png"; using (WebClient wc = new WebClient()) { wc.DownloadFile(sourceUrl, localPath); } If you need to load an image from this URL, you can do that (I assume you're using WinForms/GDI): string sourceUrl = "http://appworld.blackberry.com/webstore/servedimages/340582.png?t=2"; string localPath = @"C:\foo\bar\340582.png"; Image image; using (WebClient wc = new WebClient()) using (Stream stream = wc.OpenRead(sourceUrl)) { image = Image.FromStream(stream); } A: I wonder if you have hit their site way too many times and they are now blocking you for abuse... Most likely they are examining the headers sent and not allowing bots to grab their intellectual property. Two possible solutions come to mind: * *Change your request code to pass believable browser headers. *Call blackberry.com and get permission to reuse their files. You should probably do both. Point is, I doubt it's a code issue and more likely a violation of their terms of service. and for fun: HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url); // Setting the useragent seems to resolve certain issues that *may* crop up. httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; A: I just tested this out and this downloaded and saved the image for me. You will probably need to check for MIME types and all that somewhere along the road. string url = "http://appworld.blackberry.com/webstore/servedimages/340582.png?t=2"; using (System.Drawing.Image img = System.Drawing.Image.FromStream(WebRequest.Create(url).GetResponse().GetResponseStream())) { img.Save("new.jpg"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7585682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Plot n GPS coordinates on the screen with respect to each other and not *NOT* to any map Suppose I am on location M(latitude, longitude), and I have 3 More GPS coordinates A(lat, lon) ,B (lat, lon), and C(lat, lon) which are in range of 500 meters radius around M. NOTE: I want to plot them on screen with respect to each other but NOT to any other map or anything else, and number of gps point around M may increase or decrease but will always be in radius 500 meters around M. M will be at the center of screen. ScreeWidth=320, ScreenHeight=400 I have following information M = 31.484083, 74.392708, A = 31.483552, 74.392386 and distance from M is 66.42 Meters approximately B = 31.483534, 74.392532 and distance from M is 63.23 Meters approximately C = 31.483421, 74.392434 and distance from M is 78.00 Meters approximately M will be drawn at WIDTH/2 and HEIGHT/2 of the screen for A, B and C a CONVERSION FUNCTION is required that will return x and y in pixels with RESPECT to M and screen width and height, keeping in mind these points will always be within 500 meter radius around M. So that I can plot these points as shown in picture below. Here is image : https://picasaweb.google.com/lh/photo/J7PE6RuSqu7Pv9xv9D2PgQ?feat=directlink I only need a conversion function for x and y, I know how to draw them on screen A: Well, you need to implement a method that maps lat/lon to pixels, and pixels to lat lon...or a method that determines distance/azimuth from your reference point M, and then maps that distance/azomith to a pixel value. If you wish to reference by lat/lon -- use a linear pixel map of some set number of degrees per pixel latitude and degrees per pixel longitude. I recommend going to google earth and checking what the different in latitude and longitude are at your area of interest are for 500 meters. latitude is set at 60 nautical miles per degree across all points in the world, and I am pretty sure longitude is something like 60*cos(lat) nautical miles per degree (approximation, google this). If you wish to reference by distance, I recommend using a spherical earth approximation and building a method using haversines to determine distance across the great sphere. The best place to find examples of this is google or mathworks.com in the file exchange if you speak matlab. After you have a way to map lat lon or dist/az to pix values..the rest is just drawing. Good luck Below is code called vreckon and geodistance, you can parse through it yourself if you want to implement in java -- i already did vreckon myself so I will give you the working vreckon java, if you want to do geodistance (check distance between two lat lon points) you will need to do yourself. JAVA CODE FOR VRECKON :::::: hvDistance is the horizontal distance from your lat lon point, latitudeOrigin and longitudeOrigin is your lat/lon position, and azimuth is direction from your origin. The output will be the new latitude and longitude point. You should be able to go through matlab code and do the same with geodistance which is below if you want to implement in java. This is the exact stuff which will get you to the WGS84 standard accuracy. enjoy private void vreckon(){ double rng = hvDistance; double m = 6; double a = 6378137.0; double f = 1/298.257223563; double b = a*(1-f); double lat0 = deg2rad(latitudeOrigin); double lon0 = deg2rad(longitudeOrigin); double az = deg2rad(azimuth); double axa = a*a; double bxb = b*b; double tan_U1 = (1-f)*Math.sin(lat0)/Math.cos(lat0); double U1 = Math.atan(tan_U1); double cos_alfa1 = Math.cos(az); double sig1 = Math.atan2(tan_U1, cos_alfa1); double cos_U1 = Math.cos(U1); double sin_alfa1 = Math.sin(az); double sin_alfa = cos_U1*sin_alfa1; double cos2_alfa = (1-sin_alfa)*(1+sin_alfa); double uxu = cos2_alfa*(axa-bxb)/bxb; double A = 1+uxu/16384*(4096+uxu*(-768+uxu*(320-175*uxu))); double B = uxu/1024*(256+uxu*(-128+uxu*(74-47*uxu))); double sig = rng/(b*A); double change = 1; double twosig_m; double cos_twosig_m; double cos2_twosig_m; double dsig; double sigold; while(Math.abs(change) > 1e-9){ twosig_m = 2*sig1+sig; cos_twosig_m = Math.cos(twosig_m); cos2_twosig_m = cos_twosig_m*cos_twosig_m; dsig = B*Math.sin(sig)*(cos_twosig_m+1/4*B*(Math.cos(sig)*(-1+2.*cos2_twosig_m)-1/6*B*cos_twosig_m*(-3+4*(Math.sin(sig)*Math.sin(sig)))*(-3+4*cos2_twosig_m))); sigold = sig; sig = rng/(b*A)+dsig; change = sig-sigold; } twosig_m = 2*sig1+sig; cos_twosig_m = Math.cos(twosig_m); cos2_twosig_m = cos_twosig_m*cos_twosig_m; double sin_U1 = Math.sin(U1); double cos_sig = Math.cos(sig); double sin_sig = Math.sin(sig); double sin2_alfa = sin_alfa*sin_alfa; double latOut = Math.atan2(sin_U1*cos_sig+cos_U1*sin_sig*cos_alfa1,(1-f)*Math.sqrt(sin2_alfa+(sin_U1*sin_sig-cos_U1*cos_sig*cos_alfa1)*(sin_U1*sin_sig-cos_U1*cos_sig*cos_alfa1))); double lambda = Math.atan2(sin_sig*sin_alfa1,cos_U1*cos_sig-sin_U1*sin_sig*cos_alfa1); double C = f/16*cos2_alfa*(4+f*(4-3*cos2_alfa)); double L = lambda-(1-C)*f*sin_alfa*(sig+C*sin_sig*(cos_twosig_m+C*cos_sig*(-1+2*cos2_twosig_m))); double lonOut = L+lon0; latOut = rad2deg(latOut); lonOut = rad2deg(lonOut); reckonedLatitude = latOut; reckonedLongitude = lonOut; } MATLAB CODE FOR GEODISTANCE ::::: function [r az] = geodistance(lat1,lon1,lat2,lon2,ellip,earthR) %GEODISTANCE: Calculates the distance in meters between two points on earth surface. % % Usage: r = geodistance(lat1,lon1,lat2,lon2, ellipsoid ) ; % % Coordinates values should be specified in decimal degrees. % Method can be an integer between 1 and 23, default is m = 6. % Methods 1 and 2 are based on spherical trigonometry and a % spheroidal model for the earth, respectively. % Methods 3 to 24 use Vincenty's formulae, based on ellipsoid % parameters. % Here it follows the correspondence between m and thge type of % ellipsoid: % % m = 3 -> ANS , m = 4 -> GRS80, m = 5 -> WGS72, % m = 6 -> WGS84, m = 7 -> NSWC-9Z2, % m = 8 -> Clarke 1866, m = 9 -> Clarke 1880, % m = 10 -> Airy 1830, % m = 11 -> Bessel 1841 (Ethiopia,Indonesia,Japan,Korea), % m = 12 -> Bessel 1841 (Namibia), % m = 13 -> Sabah and Sarawak (Everest,Brunei,E.Malaysia), % m = 14 -> India 1830, m = 15 -> India 1956, % m = 16 -> W. Malaysia and Singapore 1948, % m = 17 -> W. Malaysia 1969, % m = 18 -> Helmert 1906, m = 19 -> Helmert 1960, % m = 20 -> Hayford International 1924, % m = 21 -> Hough 1960, m = 22 -> Krassovsky 1940, % m = 23 -> Modified Fischer 1960, % m = 24 -> South American 1969. % % Important notes: % % 1)South latitudes are negative. % 2)East longitudes are positive. % 3)Great circle distance is the shortest distance between two points % on a sphere. This coincides with the circumference of a circle which % passes through both points and the centre of the sphere. % 4)Geodesic distance is the shortest distance between two points on a spheroid. % 5)Normal section distance is formed by a plane on a spheroid containing a % point at one end of the line and the normal of the point at the other end. % For all practical purposes, the difference between a normal section and a % geodesic distance is insignificant. % 6)The method m=2 assumes a spheroidal model for the earth with an average % radius of 6364.963 km. It has been derived for use within Australia. % The formula is estimated to have an accuracy of about 200 metres over 50 km, % but may deteriorate with longer distances. % However, it is not symmetric when the points are exchanged. %*************************************************************************************** % Based loosely from code from orodrig@aulg.pt % Vastly modified and improved. % By J. Sullivan 12/2010 %*************************************************************************************** %% Defensive Programming error(nargchk(4,6,nargin)); if any([isempty(lat1) isempty(lon1) isempty(lat2) isempty(lon2)]); error('One or more input arguments are empty.') end %% Farm out to GPU, if possible if any([numel(lat1) numel(lat2) numel(lon1) numel(lon2)] > 250000) ... && ~any([numel(lat1) numel(lat2) numel(lon1) numel(lon2)] > 6000000) [lat1 lat2 lon1 lon2] = makeIntoGPUArrays(lat1,lat2,lon1,lon2); end %% Prepare the Data r = [ ]; lambda1 = lon1*pi/180; phi1 = lat1*pi/180; lambda2 = lon2*pi/180; phi2 = lat2*pi/180; isEast = lon1 < lon2; L = lambda2 - lambda1; %% Load Earth Ellipsoid Models alla = [earthRadius 0 6378160 6378137.0 6378135 6378137.0 6378145 6378206.4 6378249.145,... 6377563.396 6377397.155 6377483.865,... 6377298.556 6377276.345 6377301.243 6377304.063 6377295.664 6378200 6378270 6378388 6378270 6378245,... 6378155 6378160]; allf = [0 0 1/298.25 1/298.257222101 1/298.26 1/298.257223563 1/298.25 1/294.9786982 1/293.465,... 1/299.3249646 1/299.1528128,... 1/299.1528128 1/300.8017 1/300.8017 1/300.8017 1/300.8017 1/300.8017 1/298.3 1/297 1/297 1/297,... 1/298.3 1/298.3 1/298.25]; %% Choose Ellipsoid if nargin > 4 && length(ellip) == 2; m = inf; a = ellip(1); b = a*cos(ellip(2)); f = (a-b)/a; elseif nargin < 5 m = 6; a = alla(6); f = allf(6); b = a*(1-f); elseif length(ellip) == 1 m = ellip; a = alla(ellip); f = allf(ellip); b = a*(1-f); end samePoint = gather(abs( lambda1 - lambda2 ) < eps) & gather(abs( phi1 - phi2 ) < eps); %% Sheperical Earth if m == 1 % Great Circle Distance, based on spherical trigonometry clear lat1 lat2 lon1 lon2 if nargin < 6; earthR = a; end tmp = sin(phi1).*sin(phi2)+cos(phi1).*cos(phi2).*cos(lambda2-lambda1); tmp(tmp > 1) = 1; r = earthR.*acos(tmp); r = gather(abs(r)); if nargout > 1 az = atan2(cos(phi2).*sin(lambda2-lambda1),cos(phi1).*sin(phi2)... -sin(phi1).*cos(phi2).*cos(lambda2-lambda1)); % Azimuths are undefined at the poles, so we choose a convention: zero at % the north pole and pi at the south pole. az(phi1 <= -pi/2) = 0; az(phi2 >= pi/2) = 0; az(phi2 <= -pi/2) = pi; az(phi1 >= pi/2) = pi; az = gather(rad2deg(az)); end elseif m == 2 % Spheroidal model for the earth % Azimuth Calculations for this model are NOT consistant with a % spheriod. term1 = 111.08956*( lat1 - lat2 + 0.000001 ); term2 = cos( phi1 + ( (phi2 - phi1)/2 ) ); term3 = ( lon2 - lon1 + 0.000001 )/( lat2 - lat1 + 0.000001 ); r = 1000*abs( term1/cos( atan( term2*term3 ) ) ); if nargout > 1 az = atan2(cos(phi2).*sin(lambda2-lambda1),cos(phi1).*sin(phi2)... -sin(phi1).*cos(phi2).*cos(lambda2-lambda1)); % Azimuths are undefined at the poles, so we choose a convention: zero at % the north pole and pi at the south pole. az(phi1 <= -pi/2) = 0; az(phi2 >= pi/2) = 0; az(phi2 <= -pi/2) = pi; az(phi1 >= pi/2) = pi; az = rad2deg(az); end else %% Apply Vincenty's formulae clear lambda1 lambda2 lat1 lat2 lon1 lon2 axa = a^2; bxb = b^2; U1 = atan( ( 1 - f )*tan( phi1 ) ); U2 = atan( ( 1 - f )*tan( phi2 ) ); clear phi1 phi2 lambda = L; lambda_old = sqrt(-1); ntrials = 0; while gather(any(any( abs( lambda - lambda_old ) > 1e-9 ))) ntrials = ntrials + 1; lambda_old = lambda; sin_sigma = sqrt( ( cos(U2).*sin(lambda) ).^2 + ( cos(U1).*sin(U2) - sin(U1).*cos(U2).*cos(lambda) ).^2 ); cos_sigma = sin( U1 ).*sin( U2 ) + cos( U1 ).*cos( U2 ).*cos( lambda ); sigma = atan2( sin_sigma,cos_sigma ); sin_alpha = cos( U1 ).*cos( U2 ).*sin( lambda )./sin_sigma; cos2_alpha = 1 - sin_alpha.^2; cos_2sigmam = cos_sigma - 2.*sin( U1 ).*sin( U2 )./cos2_alpha; C = (f/16).*cos2_alpha.*( 4 + f.*( 4 - 3.*cos2_alpha ) ); lambda = L + ( 1 - C ).*f.*sin_alpha.*( sigma + C.*sin_sigma.*( ... cos_2sigmam + C.*cos_sigma.*( -1 + 2*( cos_2sigmam ).^2 ) ) ); if ntrials > 1000 disp('Convergence failure...') return end end clear C sin_alpha lambda_old L %% Get Distance After Convergence acheived uxu = cos2_alpha.*(axa - bxb)./bxb; clear cos2_alpha bxb axa A = 1 + (uxu/16384).*(4096 + uxu.*(-768 + uxu.*(320 - 175.*uxu))); B = (uxu./1024).*(256 + uxu.*(-128 + uxu.*(74 - 47.*uxu))); clear uxu delta_sigma = B.*sin_sigma.*(cos_2sigmam + (B/4).*(cos_sigma.*... (-1 + 2.*cos_2sigmam.^2) -(B/6).*cos_2sigmam.*(-3 + 4.*sin_sigma.^2)... .*(-3 + 4.*cos_2sigmam.^2))); clear sin_sigma cos_sigma cos_2sigmam B delta_sigma(isnan(delta_sigma)) = 0; r = gather(b.*A.*(sigma - delta_sigma)); clear sigma A delta_sigma %% Same Point Check r(samePoint) = 0; %% Calculate Azimuth if needed if nargout >= 2 lambda(gather(isnan(lambda)) & gather(isEast)) = pi/2; lambda(gather(isnan(lambda)) & ~gather(isEast)) = -pi/2; az = rad2deg(atan2(cos(U2).*sin(lambda),cos(U1).*sin(U2)-sin(U1).*cos(U2).*cos(lambda))); clear U1 U2 lambda az = gather(zero22pi(az)); az(samePoint) = 0; end end % clearvars -except az r A: OK finally I managed to write a conversion function which do the trick for me and works fine as I have tested on different location and with reference to centre point(M) all other points are displayed with perfect proportion. public static POINT XY(double centerLatitude, double centerLongitude, double Latitude, double Longitude, double MetersPerPixel) { double rto = 1/MetersPerPixel; double dLAT = ((centerLatitude - Latitude)/ 0.00001) * rto; double dLNG = -1 * ((centerLongitude - Longitude) / 0.00001) * rto; int y = (int)Math.round(dLAT); int x = (int)Math.round(dLNG); POINT crd = new POINT(x, y ); return crd; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7585683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ Operator Problem I don't know if this question is already answered on stackoverflow. But I simply can not find the right keyword to search for. I inserted some stripped down version of my code below. So basically what I'm trying to do in my main(), is to subtract 122 from t2. I suppose my compiler converts the integer to a Timestamp object automatically and then subtracts it as showed in 'Timestamp.cpp'. But when it arrives at t4 it doesn't convert it and give me the following error: no match for 'operator-' in '722 - t1' I'm 100% sure that it is possible. But how? Maybe I'm totally wrong about converting... So please do hesitate to correct me, I'm trying to learn something. STRIPPED DOWN CODE: main.cpp: #include <iostream> #include <iomanip> #include "Timestamp.h" using namespace std; int main() { Timestamp t3(t2 - 122); cout << "T3 = " << t3 << endl; Timestamp t4(722 - t1); cout << "T4 = " << t4 << endl; return 0; } Timestamp.h #ifndef TIJDSDUUR_H #define TIJDSDUUR_H using namespace std; class Timestamp { public: Timestamp(int); Timestamp operator- (const Timestamp &t); private: int hour; int min; }; Timestamp.cpp Timestamp::Timestamp(int m) : hour(0), min(m) { } Timestamp Timestamp::operator- (const Timestamp &t) { Timestamp temp; temp.hour = hour; temp.min = min; temp.hour -= t.hour; temp.min -= t.min; while(temp.min < 0.00) { temp.hour--; temp.min += 60; } return temp; } A: You need to define the following non-member function: Timestamp operator-(int left, const Timestamp &right) { //define } By the way, make the member operator-() const function as: Timestamp operator-(const Timestamp &t) const; //^^^^^ this makes the function const If you make this const, only the right-left would work, because right is const object, and so only const member function can be invoked on it. I noticed that you've a constructor that takes int as parameter. This constructor can behave like implicit conversion function from int to TimeStamp which means, you don't need to define two operator-() functions (one as member function which you already have defined, and other as non-member function as I suggested above). Instead, you can define only one friend function of this type: Timestamp operator-(const Timestamp &left, const Timestamp &right) { //define } You've to make friend of the class, as it needs to access the private members of the class. However, @David provided a better solution. But I'm keeping this solution only for academic purpose. A: Contrary to what the other answers propose, you do not need to provide an specialized operator- that takes an int and a Timestamp, rather you can (and probably should) make operator- a non-member function: Timestamp operator-( Timestamp lhs, Timestamp const & rhs ); // Returns a timestamp?? really?? That way the compiler is free to apply conversions to both the left hand side and the right hand side operands, and use the implicit conversion from int to Timestamp. You can read a short description on design and implementation of operator overloads here, or you can search in the [C++-faq] tag in SO for "operator overload". A: Two things I see: First, your constructor is taking a parameter of type int. Your operator is returning type TimeStamp, which you're then passing to the constructor. You haven't specified a conversion from TimeStamp to int, so this won't work! Second, your operator is taking a parameter of type timestamp, but you appear to subtracting an int from it when you're actually using it. It has no idea what an int is though, because you didn't tell it! A: Your Timestamp::operator-(int) allows you to subtract an integer from a Timestamp object. It does not allow you to subtract Timestamps from integers. You need to add operator- as a free function Timestamp operator-(int, const Timestamp&); This needs to be a friend of Timestamp as it needs to access the private members.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: What is the format of the deltas in a subversion respository, and how badly can I blow it up if I change them in a pre-commit hook? Help me do some damage! I'm tired of just a half-dozen Google hits that tell me never to do this. Let's muck things up real good! I'm pretty sure that I can get ahold of the actual files in db/transactions, so how can I screw these up in interesting ways? I've looked at SVN::Delta, but I can't even figure out what it's supposed to be doing (letting someone make pretty graphs of changes to a repository? sending coded messages to the CIA?). I really don't care to hear more reasons why not to do this. I work in an environment with 40 or 50 other people who use subversion. And while we're coding, we need some passwords in web.config files, in DataSource.groovy files, you name it. And just refusing the commit because we left them in is as annoying as hell. We have to save the files with the passwords manually deleted (and we have to open up those files, it's not like they're necessarily open), then once we're done committing we have to put them back just to continue to work? This is a good idea I suppose if you just want to bitchslap people every time they commit until they develop a Pavlovian reflex to never commit anything. And why? Because computers aren't supposed to automate tasks? Because the software client won't know that the pre-commit hook didn't actually save the version still on the developer's machine? I'm fairly language agnostic here. Show me an example of how to do what you're never supposed to do... which file do I edit from pre-commit? How do I interpret the gobbledygook after the DELTA # # # line? Are there any libraries that will help with that? Let's have some fun! PS Seriously, no one's created a "bad-ideas" tag? WTF. A: It is your build process that is flawed, not Subversion. If you must not commit passwords, do something like the following: 1 - Web.config files should not be committed. Instead, commit files like Web.config.dev or Web.config.qa. 2 - Have your build script rename the appropriate .config file to Web.config, and then do token replacement so that the proper passwords are inserted. This info can come from another file that is also not commited that says what environment you are in (so it knows which .config file to use), and what the passwords are.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Will clearing an already empty vector lead to undefined behavior? What happens if I clear a vector which was already cleared before? I tried it out in Visual Studio and it did not lead to any run-time errors. But I'm hunting for a possible cause to an exception (below) And wanted to know if this could be the reason? *** glibc detected *** process.out: double free or corruption (out): 0x01a0b588 *** Updating code: bool myclass::Sort(SortType enSortOption) { bool bRet = TRUE; m_oVecOfIntsOrig.clear(); m_oVecOfIntsSorted.clear(); for(int i = 0;i<m_oList.listsize();i++) { m_oVecOfIntsOrig.push_back(i); } m_oVecOfIntsSorted = m_oVecOfIntsOrig; //Just sort the indices switch(enSortOption) { case Alpha: { t_SortStructAlpha sSortAlpha(this); sort( m_oVecOfIntsSorted.begin(), m_oVecOfIntsSorted.end(), sSortAlpha ); } break; case Dist: { t_SortStructDist sSortDist(this); sort( m_oVecOfIntsSorted.begin(), m_oVecOfIntsSorted.end(), sSortDist ); } break; case none: { //Nothing to do return TRUE; } break; default: { bRet = FALSE; } break; } //Update the list based on sorted index vector ListElem oSortedListElements; //this clear function simply clears all the 7 constituent vectors. oSortedListElements.vClear(); if(TRUE == bGetSortedList(oSortedListElements)) { //If successfully copied to temp object, then update member variable //m_oList is what I'm intending to display m_oList.vClear(); m_oList = oSortedListElements; } else { //copy failed bRet = FALSE; } return bRet; } bool myclass::bGetSortedList(ListElem& oSortedListElements) { bool bRet = TRUE; //Creating object from beginning, so clear old contents if any oSortedListElements.vClear(); /* Sort done. Now update the list based on new indices*/ for(int u16Index = 0; u16Index<m_oVecOfIntsSorted.size(); u16Index++) { if( (m_oVecOfIntsSorted.at(u16Index) >= m_oListConstituents.oVec1.size()) || (m_oVecOfIntsSorted.at(u16Index) >= m_oListConstituents.oVec2.size()) || (m_oVecOfIntsSorted.at(u16Index) >= m_oListConstituents.oVec3.size()) || (m_oVecOfIntsSorted.at(u16Index) >= m_oListConstituents.oVec4.size()) || (m_oVecOfIntsSorted.at(u16Index) >= m_oListConstituents.oVec5.size()) || (m_oVecOfIntsSorted.at(u16Index) >= m_oListConstituents.oVec6.size()) || (m_oVecOfIntsSorted.at(u16Index) >= m_oListConstituents.oVec7.size()) ) { //out of bounds check return FALSE; } //m_oListConstituents contains overall list oSortedListElements.oVec1.push_back(m_oListConstituents.oVec1.at(m_oVecOfIntsSorted.at(u16Index))); oSortedListElements.oVec2.push_back(m_oListConstituents.oVec2.at(m_oVecOfIntsSorted.at(u16Index))); oSortedListElements.oVec3.push_back(m_oListConstituents.oVec3.at(m_oVecOfIntsSorted.at(u16Index))); oSortedListElements.oVec4.push_back(m_oListConstituents.oVec4.at(m_oVecOfIntsSorted.at(u16Index))); oSortedListElements.oVec5.push_back(m_oListConstituents.oVec5.at(m_oVecOfIntsSorted.at(u16Index))); oSortedListElements.oVec6.push_back(m_oListConstituents.oVec6.at(m_oVecOfIntsSorted.at(u16Index))); oSortedListElements.oVec7.push_back(m_oListConstituents.oVec7.at(m_oVecOfIntsSorted.at(u16Index))); } return bRet; } A: If what you did amounts to v.clear(); v.clear(); then no, there's no UB: one of the postconditions of v.clear() is that v.size() == 0, so the second call to clear should be a no-op. A: Calling the clear method twice in a row should be fine. Your error looks like you are freeing something which was already freed. This can happen because you called free twice on the same object or possibly put an object in your vector which was then deleted. Calling clear on your vector would then cause that error (this is a problem because clear calls the destructor on any objects contained in the vector). Edit: at returns a reference so deleting something set to a value returned from an at might cause problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there any way how to use Java window and input with Ogre3D and c++? I'm not very familiar with wrapping between Java and C++. But i need to wrap Java window input to c++ and get window context, that i assign to ogre. I know it's possible, because Ogre4J uses something similar. "Use Ogre4j" isn't answer. A: I never tried it because JOGL was easier to use but here, you have an example how to use opengl directly with Java. That should be similar with OGRE. I guess. Or you could look at Ogre4j and see how they get the native context from the Java window.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: List of useful environment settings in Java I've been wondering a long time if there was a comprehensive list of (probably static) methods/fields that store runtime information for the JVM. An incomplete list of examples: * *System.out / System.in *System.currentTimeMillis() *System.getProperty() *System.getConsole() *Runtime.freeMemory() *Etc Does anyone have a link or something? EDIT: I'm not so dumb as to have not checked the docs for System and Runtime :P I was just wondering if there were other classes where similar methods to determine the state of the machine you're running on are stored. A: This class prints quite a few stuff to stdout import java.util.Properties; import java.util.logging.LogManager; import javax.net.ssl.KeyManagerFactory; import java.util.Date; import java.util.Enumeration; import java.util.Locale; import java.util.Map.Entry; import java.awt.DisplayMode; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.ImageCapabilities; import java.io.File; import java.io.PrintStream; import java.nio.file.Paths; import java.security.KeyStore; import java.lang.management.ClassLoadingMXBean; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.net.InetAddress; import java.net.UnknownHostException; public class JavaInfo { public static PrintStream out = System.out; public static void printCurrentTime() { out.println("current date " + new Date()); out.println("nano time "+System.nanoTime()); } public static void printSystemEnvironment() { for (Entry<String,String> e : System.getenv().entrySet()) out.println(e.getKey()+" "+e.getValue()); } public static void printSystemProperties() { Properties props = System.getProperties(); Enumeration<Object> enums = props.keys(); while (enums.hasMoreElements()) { String key = enums.nextElement().toString(); out.println(key + " : " + props.getProperty(key)); } } public static void printRuntimeMemory() { Runtime r = Runtime.getRuntime(); out.println("free memory " + r.freeMemory()); out.println("max memory " + r.maxMemory()); out.println("total memory " + r.totalMemory()); } public static void printCommandLineArguments() { out.print("JVM arguments"); for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) out.print(" "+arg); out.println(); } public static void printClassLoaderInfo() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); out.println("thread context class loader "+cl.getClass().getName()); out.println("system class loader "+ClassLoader.getSystemClassLoader().getClass().getName()); ClassLoadingMXBean cx = ManagementFactory.getClassLoadingMXBean(); out.println("loaded classes count "+cx.getLoadedClassCount()); } public static void printOSInfo() { OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); out.println("OS name "+os.getName()+" version "+os.getVersion()); out.println("architecture "+os.getArch()); out.println("available processors "+os.getAvailableProcessors()); } public static void printCPUUsage() { out.println("Current thread CPU time "+ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime()); out.println("number of threads "+ManagementFactory.getThreadMXBean().getThreadCount()); out.println("system load average "+ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage()); } public static void printDisplayInfo() { int g = 0; for (GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) { out.println("graphics device #"+(++g)+": "+gd.getIDstring()+" type "+gd.getType()); out.println("\tavailable accelerated memory " + gd.getAvailableAcceleratedMemory()); int c = 0; for (GraphicsConfiguration gc : gd.getConfigurations()) { out.println("\tgraphics configuration #"+(++c)+":"); out.println("\t\twidth "+gc.getBounds().getWidth()+" height "+gc.getBounds().getHeight()); out.println("\t\tfull screen "+gc.getBufferCapabilities().isFullScreenRequired()); ImageCapabilities ic = gc.getImageCapabilities(); out.println("\t\tis accelerated "+ic.isAccelerated()); } DisplayMode dm = gd.getDisplayMode(); out.println("\tdisplay mode bit width "+dm.getWidth()+" height "+dm.getHeight()+" bit depth "+dm.getBitDepth()+" refresh rate "+dm.getRefreshRate()); int m = 0; for (DisplayMode d : gd.getDisplayModes()) out.println("\talt display mode #"+(++m)+" bit width "+d.getWidth()+" height "+d.getHeight()+" bit depth "+d.getBitDepth()+" refresh rate "+d.getRefreshRate()); } } public static void printFontsInfo() { out.println("available fonts: "+String.join(",", GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames())); } public static void printLocaleInfo() { out.println("default locale: "+Locale.getDefault().getDisplayName()+" country "+Locale.getDefault().getCountry()+" language "+Locale.getDefault().getLanguage()); out.println("available locales:"); for (Locale l : Locale.getAvailableLocales()) out.println("\t"+l.getDisplayName()+" country "+l.getCountry()+" language "+l.getLanguage()); } public static void printDiskInfo() { System.out.println("Current directory: "+Paths.get(".").toAbsolutePath().normalize().toString()); File[] roots = File.listRoots(); for (File r : roots) { out.println("File system root: " + r.getAbsolutePath()); out.println("\tTotal space (bytes): " + r.getTotalSpace()); out.println("\tFree space (bytes): " + r.getFreeSpace()); out.println("\tUsable space (bytes): " + r.getUsableSpace()); out.println("\tcan write "+r.canWrite()); } } public static void printNetworkInfo() throws UnknownHostException { out.println("host name "+InetAddress.getLocalHost().getHostName()); out.println("host IP address "+InetAddress.getLocalHost().getHostAddress()); } public static void printSecurityInfo() throws UnknownHostException { SecurityManager security = System.getSecurityManager(); if (security != null) { out.println("security manager "+security.getClass().getName()+" in check "+security.getInCheck()); } else { out.println("no security manager"); } } public static void printKeyManagerInfo() { out.println("key manager default algorithm "+KeyManagerFactory.getDefaultAlgorithm()); out.println("key store default type "+KeyStore.getDefaultType()); } public static void printLoggingInfo() { for (String logger : LogManager.getLoggingMXBean().getLoggerNames()) { out.println("logger: \""+logger+"\" level \""+LogManager.getLoggingMXBean().getLoggerLevel(logger)+"\""); } } public static void main(String args []) throws Exception { out.println("****************************************"); out.println("DATE INFO"); printCurrentTime(); out.println(""); out.println("****************************************"); out.println("JVM COMMAND LINE ARGUMENTS"); printCommandLineArguments(); out.println(""); out.println("****************************************"); out.println("ENVIRONMENT"); printSystemEnvironment(); out.println(""); out.println("****************************************"); out.println("SYSTEM PROPERTIES"); printSystemProperties(); out.println(""); out.println("****************************************"); out.println("CLASS LOADER"); printClassLoaderInfo(); out.println(""); out.println("****************************************"); out.println("OPERATING SYSTEM"); printOSInfo(); out.println(""); out.println("****************************************"); out.println("MEMORY"); printRuntimeMemory(); out.println(""); out.println("****************************************"); out.println("CPU"); printCPUUsage(); out.println(""); out.println("****************************************"); out.println("DISK"); printDiskInfo(); out.println(""); out.println("****************************************"); out.println("NETWORK"); printNetworkInfo(); out.println(""); out.println("****************************************"); out.println("SECURITY"); printSecurityInfo(); out.println(""); out.println(""); out.println("****************************************"); out.println("LOG"); printLoggingInfo(); out.println(""); out.println("****************************************"); out.println("KEY MANAGER"); printKeyManagerInfo(); out.println(""); out.println("****************************************"); out.println("DISPLAY DEVICES"); printDisplayInfo(); out.println(""); out.println("****************************************"); out.println("FONTS"); printFontsInfo(); out.println(""); out.println("****************************************"); out.println("LOCALES"); printLocaleInfo(); } } A: General Properties I use this code to get a handle on some of the things known to Java classes that are of particular interest to me. import java.awt.*; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.util.*; import java.security.*; /** A small GUId app. that shows many system and environment properties. Designed to be compatible with Java 1.4+ (hence many requirements like no foreach, no generics, no StringBuilder..). @author Andrew Thompson @version 2008-06-29 */ class SystemProperties { static String sentence = "The quick brown fox jumped over the lazy dog."; static String sep = System.getProperty("line.separator"); static String fontText = sentence + sep + sentence.toUpperCase() + sep + "0123456789 !@#$%^&*()_+ []\\;',./ {}|:\"<>?"; static String[] convertObjectToSortedStringArray(Object[] unsorted) { String[] sorted = new String[unsorted.length]; for (int ii = 0; ii < sorted.length; ii++) { sorted[ii] = (String) unsorted[ii]; } Arrays.sort(sorted); return sorted; } static String dataPairToTableRow(String property, Object value) { String val = valueToString(property, value); return "<tr>" + "<th>" + "<code>" + property + "</code>" + "</th>" + "<td>" + val + "</td>" + "</tr>"; } static String valueToString(String property, Object value) { if (value instanceof Color) { Color color = (Color) value; String converted = "<div style='width: 100%; height: 100%; " + "background-color: #" + Integer.toHexString(color.getRed()) + Integer.toHexString(color.getGreen()) + Integer.toHexString(color.getBlue()) + ";'>" + value.toString() + "</div>"; return converted; } else if (property.toLowerCase().endsWith("path") || property.toLowerCase().endsWith("dirs")) { return delimitedToHtmlList( (String) value, System.getProperty("path.separator")); } else { return value.toString(); } } static String delimitedToHtmlList(String values, String delimiter) { String[] parts = values.split(delimiter); StringBuffer sb = new StringBuffer(); sb.append("<ol>"); for (int ii = 0; ii < parts.length; ii++) { sb.append("<li>"); sb.append(parts[ii]); sb.append("</li>"); } return sb.toString(); } static Component getExampleOfFont(String fontFamily) { Font font = new Font(fontFamily, Font.PLAIN, 24); JTextArea ta = new JTextArea(); ta.setFont(font); ta.setText(fontText); ta.setEditable(false); // don't allow these to get focus, as it // interferes with desired scroll behavior ta.setFocusable(false); return ta; } static public JScrollPane getOutputWidgetForContent(String content) { JEditorPane op = new JEditorPane(); op.setContentType("text/html"); op.setEditable(false); op.setText(content); return new JScrollPane(op); } public static void main(String[] args) { JTabbedPane tabPane = new JTabbedPane(); StringBuffer sb; String header = "<html><body><table border=1 width=100%>"; sb = new StringBuffer(header); Properties prop = System.getProperties(); String[] propStrings = convertObjectToSortedStringArray( prop.stringPropertyNames().toArray()); for (int ii = 0; ii < propStrings.length; ii++) { sb.append( dataPairToTableRow( propStrings[ii], System.getProperty(propStrings[ii]))); } tabPane.addTab( "System", getOutputWidgetForContent(sb.toString())); sb = new StringBuffer(header); Map environment = System.getenv(); String[] envStrings = convertObjectToSortedStringArray( environment.keySet().toArray()); for (int ii = 0; ii < envStrings.length; ii++) { sb.append( dataPairToTableRow( envStrings[ii], environment.get(envStrings[ii]))); } tabPane.addTab( "Environment", getOutputWidgetForContent(sb.toString())); sb = new StringBuffer(header); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gs = ge.getScreenDevices(); for (int j = 0; j < gs.length; j++) { GraphicsDevice gd = gs[j]; sb.append( dataPairToTableRow( "Device " + j, gd.toString() + " " + gd.getIDstring())); GraphicsConfiguration[] gc = gd.getConfigurations(); for (int i = 0; i < gc.length; i++) { sb.append( dataPairToTableRow( "Config " + i, (int) gc[i].getBounds().getWidth() + "x" + (int) gc[i].getBounds().getHeight() + " " + gc[i].getColorModel() + ", " + " Accelerated: " + gc[i].getImageCapabilities().isAccelerated() + " True Volatile: " + gc[i].getImageCapabilities().isTrueVolatile())); } } tabPane.addTab( "Graphics Environment", getOutputWidgetForContent(sb.toString())); String[] fonts = ge.getAvailableFontFamilyNames(); JPanel fontTable = new JPanel(new BorderLayout(3, 1)); // to enable key based scrolling in the font panel fontTable.setFocusable(true); JPanel fontNameCol = new JPanel(new GridLayout(0, 1, 2, 2)); JPanel fontExampleCol = new JPanel(new GridLayout(0, 1, 2, 2)); fontTable.add(fontNameCol, BorderLayout.WEST); fontTable.add(fontExampleCol, BorderLayout.CENTER); for (int ii = 0; ii < fonts.length; ii++) { fontNameCol.add(new JLabel(fonts[ii])); fontExampleCol.add(getExampleOfFont(fonts[ii])); } tabPane.add("Fonts", new JScrollPane(fontTable)); sb = new StringBuffer(header); sb.append("<thead>"); sb.append("<tr>"); sb.append("<th>"); sb.append("Code"); sb.append("</th>"); sb.append("<th>"); sb.append("Language"); sb.append("</th>"); sb.append("<th>"); sb.append("Country"); sb.append("</th>"); sb.append("<th>"); sb.append("Variant"); sb.append("</th>"); sb.append("</tr>"); sb.append("</thead>"); Locale[] locales = Locale.getAvailableLocales(); SortableLocale[] sortableLocale = new SortableLocale[locales.length]; for (int ii = 0; ii < locales.length; ii++) { sortableLocale[ii] = new SortableLocale(locales[ii]); } Arrays.sort(sortableLocale); for (int ii = 0; ii < locales.length; ii++) { String prefix = ""; String suffix = ""; Locale locale = sortableLocale[ii].getLocale(); if (locale.equals(Locale.getDefault())) { prefix = "<b>"; suffix = "</b>"; } sb.append(dataPairToTableRow( prefix + locale.toString() + suffix, prefix + locale.getDisplayLanguage() + suffix + "</td><td>" + prefix + locale.getDisplayCountry() + suffix + "</td><td>" + prefix + locale.getDisplayVariant() + suffix)); } tabPane.add("Locales", getOutputWidgetForContent(sb.toString())); Locale.getDefault(); int border = 5; JPanel p = new JPanel(new BorderLayout()); p.setBorder(new EmptyBorder(border, border, border, border)); p.add(tabPane, BorderLayout.CENTER); p.setPreferredSize(new Dimension(400, 400)); JFrame f = new JFrame("Properties"); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.getContentPane().add(p, BorderLayout.CENTER); f.pack(); f.setMinimumSize(f.getPreferredSize()); f.setSize(600, 500); f.setLocationRelativeTo(null); f.setVisible(true); } } class SortableLocale implements Comparable { Locale locale; SortableLocale(Locale locale) { this.locale = locale; } public String toString() { return locale.toString(); } public Locale getLocale() { return locale; } public int compareTo(Object object2) { SortableLocale locale2 = (SortableLocale) object2; //Locale locale2 = (Locale)object2; return locale.toString().compareTo( locale2.toString()); } } Media Properties related to synthesized and sampled sound, and images. /* <applet code='MediaTypes' width='900' height='600'> <param name='show' value='Sound|Sampled|Mixers|Primary Sound Capture Driver'> </applet> */ import javax.imageio.ImageIO; import javax.sound.sampled.*; import javax.sound.midi.*; import java.awt.*; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.tree.*; import javax.swing.event.*; import javax.swing.text.Position; public class MediaTypes extends JApplet { JTable table; boolean sortable = false; JTree tree; @Override public void init() { Runnable r = () -> { MediaTypes mediaTypes = new MediaTypes(); String show = ""; if (getParameter("show")!=null) { show = getParameter("show"); } JPanel p = new JPanel(); mediaTypes.createGui(p, show); add(p); validate(); }; SwingUtilities.invokeLater(r); } public static void main(String[] args) { Runnable r = () -> { MediaTypes mediaTypes = new MediaTypes(); JPanel p = new JPanel(); mediaTypes.createGui(p); JOptionPane.showMessageDialog(null,p); }; SwingUtilities.invokeLater(r); } public Object[][] mergeArrays(String name1, Object[] data1, String name2, Object[] data2) { Object[][] data = new Object[data1.length+data2.length][2]; for (int ii=0; ii<data1.length; ii++) { data[ii][0] = name1; data[ii][1] = data1[ii]; } int offset = data1.length; for (int ii=offset; ii<data.length; ii++) { data[ii][0] = name2; data[ii][1] = data2[ii-offset]; } return data; } public void createGui(JPanel panel) { createGui(panel, ""); } public String getShortLineName(String name) { String[] lineTypes = { "Clip", "SourceDataLine", "TargetDataLine", "Speaker", "Microphone", "Master Volume", "Line In" }; for (String shortName : lineTypes) { if ( name.toLowerCase().replaceAll("_", " ").contains(shortName.toLowerCase() )) { return shortName; } } return name; } public void createGui(JPanel panel, String path) { //DefaultMutableTreeNode selected = null; panel.setLayout( new BorderLayout(5,5) ); final JLabel output = new JLabel("Select a tree leaf to see the details."); panel.add(output, BorderLayout.SOUTH); table = new JTable(); try { table.setAutoCreateRowSorter(true); sortable = true; } catch (Throwable ignore) { // 1.6+ functionality - not vital } JScrollPane tableScroll = new JScrollPane(table); Dimension d = tableScroll.getPreferredSize(); d = new Dimension(450,d.height); tableScroll.setPreferredSize(d); panel.add( tableScroll, BorderLayout.CENTER ); DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Media"); DefaultTreeModel treeModel = new DefaultTreeModel(rootNode); DefaultMutableTreeNode imageNode = new DefaultMutableTreeNode("Image"); rootNode.add(imageNode); Object[][] data; int offset; String[] columnNames; data = mergeArrays( "Reader", ImageIO.getReaderFileSuffixes(), "Writer", ImageIO.getWriterFileSuffixes() ); columnNames = new String[]{"Input/Output", "Image File Suffixes"}; MediaData md = new MediaData( "Suffixes", columnNames, data); imageNode.add(new DefaultMutableTreeNode(md)); data = mergeArrays( "Reader", ImageIO.getReaderMIMETypes(), "Writer", ImageIO.getWriterMIMETypes() ); columnNames = new String[]{"Input/Output", "Image MIME Types"}; md = new MediaData( "MIME", columnNames, data); imageNode.add(new DefaultMutableTreeNode(md)); DefaultMutableTreeNode soundNode = new DefaultMutableTreeNode("Sound"); rootNode.add(soundNode); DefaultMutableTreeNode soundSampledNode = new DefaultMutableTreeNode("Sampled"); soundNode.add(soundSampledNode); md = new MediaData("Suffixes", "Sound File Suffixes", AudioSystem.getAudioFileTypes()); soundSampledNode.add(new DefaultMutableTreeNode(md)); Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); String[][] mixerData = new String[mixerInfo.length][4]; for (int ii=0; ii<mixerData.length; ii++) { mixerData[ii][0] = mixerInfo[ii].getName(); mixerData[ii][1] = mixerInfo[ii].getVendor(); mixerData[ii][2] = mixerInfo[ii].getVersion(); mixerData[ii][3] = mixerInfo[ii].getDescription(); } columnNames = new String[]{"Name", "Vendor", "Version", "Description"}; md = new MediaData("Mixers", columnNames, mixerData); DefaultMutableTreeNode soundSampledMixersNode = new DefaultMutableTreeNode(md); soundSampledNode.add(soundSampledMixersNode); for (Mixer.Info mixerInfo1 : mixerInfo) { Mixer mixer = AudioSystem.getMixer(mixerInfo1); data = mergeArrays( "Source", mixer.getSourceLineInfo(), "Target", mixer.getTargetLineInfo() ); columnNames = new String[]{ "Input/Output", "Line Info" }; md = new MediaData(mixerInfo1.getName(), columnNames, data); DefaultMutableTreeNode soundSampledMixerNode = new DefaultMutableTreeNode(md); soundSampledMixersNode.add( soundSampledMixerNode ); Line.Info[] source = mixer.getSourceLineInfo(); Line.Info[] target = mixer.getTargetLineInfo(); Line[] all = new Line[source.length + target.length]; try { for (int jj=0; jj<source.length; jj++) { all[jj] = AudioSystem.getLine(source[jj]); } for (int jj=source.length; jj<all.length; jj++) { all[jj] = AudioSystem.getLine(target[jj-source.length]); } columnNames = new String[]{"Attribute", "Value"}; for (Line line : all) { Control[] controls = line.getControls(); if (line instanceof DataLine) { DataLine dataLine = (DataLine)line; AudioFormat audioFormat = dataLine.getFormat(); data = new Object[7+controls.length][2]; data[0][0] = "Channels"; data[0][1] = audioFormat.getChannels(); data[1][0] = "Encoding"; data[1][1] = audioFormat.getEncoding(); data[2][0] = "Frame Rate"; data[2][1] = audioFormat.getFrameRate(); data[3][0] = "Sample Rate"; data[3][1] = audioFormat.getSampleRate(); data[4][0] = "Sample Size (bits)"; data[4][1] = audioFormat.getSampleSizeInBits(); data[5][0] = "Big Endian"; data[5][1] = audioFormat.isBigEndian(); data[6][0] = "Level"; data[6][1] = dataLine.getLevel(); } else if (line instanceof Port) { Port port = (Port)line; Port.Info portInfo = (Port.Info)port.getLineInfo(); data = new Object[2+controls.length][2]; data[0][0] = "Name"; data[0][1] = portInfo.getName(); data[1][0] = "Source"; data[1][1] = portInfo.isSource(); } else { System.out.println( "?? " + line ); } int start = data.length-controls.length; for (int kk=start; kk<data.length; kk++) { data[kk][0] = "Control"; int index = kk-start; data[kk][1] = controls[index]; } md = new MediaData(getShortLineName(line.getLineInfo().toString()), columnNames, data); soundSampledMixerNode.add(new DefaultMutableTreeNode(md)); } } catch(Exception e) { e.printStackTrace(); } } int[] midiTypes = MidiSystem.getMidiFileTypes(); data = new Object[midiTypes.length][2]; for (int ii=0; ii<midiTypes.length; ii++) { data[ii][0] = midiTypes[ii]; String description = "Unknown"; switch (midiTypes[ii]) { case 0: description = "Single Track"; break; case 1: description = "Multi Track"; break; case 2: description = "Multi Song"; } data[ii][1] = description; } columnNames = new String[]{"Type", "Description"}; md = new MediaData("MIDI", columnNames, data); DefaultMutableTreeNode soundMIDINode = new DefaultMutableTreeNode(md); soundNode.add(soundMIDINode); columnNames = new String[]{ "Attribute", "Value"}; MidiDevice.Info[] midiDeviceInfo = MidiSystem.getMidiDeviceInfo() ; for (MidiDevice.Info midiDeviceInfo1 : midiDeviceInfo) { data = new Object[6][2]; data[0][0] = "Name"; data[0][1] = midiDeviceInfo1.getName(); data[1][0] = "Vendor"; data[1][1] = midiDeviceInfo1.getVendor(); data[2][0] = "Version"; String version = midiDeviceInfo1.getVersion(); data[2][1] = version.replaceAll("Version ", ""); data[3][0] = "Description"; data[3][1] = midiDeviceInfo1.getDescription(); data[4][0] = "Maximum Transmitters"; data[5][0] = "Maximum Receivers"; try { MidiDevice midiDevice = MidiSystem.getMidiDevice(midiDeviceInfo1); Object valueTransmitter; if (midiDevice.getMaxTransmitters()==AudioSystem.NOT_SPECIFIED) { valueTransmitter = "Not specified"; } else { valueTransmitter = midiDevice.getMaxTransmitters(); } Object valueReceiver; if (midiDevice.getMaxReceivers()==AudioSystem.NOT_SPECIFIED) { valueReceiver = "Not specified"; } else { valueReceiver = midiDevice.getMaxReceivers(); } data[4][1] = valueTransmitter; data[5][1] = valueReceiver; }catch(MidiUnavailableException mue) { data[4][1] = "Unknown"; data[5][1] = "Unknown"; } md = new MediaData(midiDeviceInfo1.getName(), columnNames, data); soundMIDINode.add( new DefaultMutableTreeNode(md) ); } tree = new JTree(treeModel); tree.setRootVisible(false); tree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION); tree.addTreeSelectionListener((TreeSelectionEvent tse) -> { if (sortable) { output.setText("Click table column headers to sort."); } DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return; Object nodeInfo = node.getUserObject(); if (nodeInfo instanceof MediaData) { MediaData mediaData = (MediaData)nodeInfo; table.setModel( new DefaultTableModel( mediaData.getData(), mediaData.getColumnNames()) ); } }); for (int ii=0; ii<tree.getRowCount(); ii++) { tree.expandRow(ii); } String[] paths = path.split("\\|"); int row = 0; TreePath treePath = null; for (String prefix : paths) { treePath = tree.getNextMatch( prefix, row, Position.Bias.Forward ); row = tree.getRowForPath(treePath); } panel.add(new JScrollPane(tree),BorderLayout.WEST); tree.setSelectionPath(treePath); tree.scrollRowToVisible(row); } } class MediaData { String name; String[] columnNames; Object[][] data; MediaData(String name, String columnName, Object[] data) { this.name = name; columnNames = new String[1]; columnNames[0] = columnName; this.data = new Object[data.length][1]; for (int ii=0; ii<data.length; ii++) { this.data[ii][0] = data[ii]; } } MediaData(String name, String[] columnNames, Object[][] data) { this.name = name; this.columnNames = columnNames; this.data = data; } @Override public String toString() { return name; } public String[] getColumnNames() { return columnNames; } public Object[][] getData() { return data; } } Other You might also investigate: * *InetAddress *KeyStore *Managers * *CookieManager *KeyManagerFactory *LogManager
{ "language": "en", "url": "https://stackoverflow.com/questions/7585699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Add data to sharepoint form programmatically on client I have a need to edit a Sharepoint form programmatically to update a text box on a form. The url of this form is https://sharepointserver/NameOfList/DispForm.aspx?ID=141. Using the sharepoint web services how can I add data to a field called "Description" on the form? A: First - add a web service to your visual studio project to interact with SharePoint from windows/console app: Accessing SharePoint Web-Services with Visual Studio 2008 Then call WssLists.UpdateListItems string strBatch = "<Method ID='1' Cmd='Update'>" + "<Field Name='ID'>141</Field>" + "<Field Name='Description'>My new Description</Field></Method>" + "</Method>"; XmlDocument xmlDoc = new System.Xml.XmlDocument(); System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch"); elBatch.SetAttribute("OnError","Continue"); elBatch.SetAttribute("ListVersion","1"); elBatch.SetAttribute("ViewName", "0d7fcacd-1d7c-45bc-bcfc-6d7f7d2eeb40"); elBatch.InnerXml = strBatch; XmlNode ndReturn = WssLists.UpdateListItems("List_Name", elBatch); You can see on MSDN there are many web services available to interact with SharePoint.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use Aspectj to find List of classes implementing a certain interface Is it possible using AspectJ to find a list of all Classes which implement a certain interface. For e.g I have an interface MatchRule. Then I can have classes DefaultMatchRule and CustomMatchRule concrete clases which implement MatchRule interface. Now at runtime I want to get a list which will have 2 classes DefaultMatchRule and CustomMatchRule public interface MatchRule { } public class DefaultMatchRule implements MatchRule { } public class CustomMatchRule implements MatchRule { } public aspect FindSubClasses { // some thing to find list of classes implementing MatchRule interface } A: AspectJ is not designed to finding classes. Your best option is to scan the classpath and use reflection. If you can live with compile-time information, the Eclipse AJDT plugin offers good graphical information for all AspectJ advises. But if you can live with some limitations, you can find the classes for all objects that is advised by AspectJ. A solution that prints out the class names for all objects of classes that implements MatchRule: @Aspect public class FindSubClassesAspect { @Pointcut("execution(demo.MatchRule+.new(..))") public void demoPointcut() { } @After("demoPointcut()") public void afterDemoPointcut( JoinPoint joinPoint) { FindSubClasses.addMatchRuleImplememtation( joinPoint.getTarget().getClass().getSimpleName()); } } A class that contain the information about all the MatchRule implementations: public enum FindSubClasses { ; private static Set<String> matchRuleImplementations = new HashSet<String>(); public static void addMatchRuleImplememtation(String className) { matchRuleImplementations.add(className); } public static Collection<String> getMatchRuleImplementations() { return matchRuleImplementations; } } A simple driver that demonstrate that the aspect works: public class Driver { public static void main(String[] args) { new DefaultMatchRule(); new CustomMatchRule(); Collection<String> matchRuleImplementations = FindSubClasses.getMatchRuleImplementations(); System.out.print("Clases that implements MatchRule: "); for (String className : matchRuleImplementations) { System.out.print(className + ", "); } } } The output of executing this driver: Clases that implements MatchRule: DefaultMatchRule, CustomMatchRule, I hope this helps! A: The only possible way to do this at runtime is probably scanning all your packages and checking to see whether your classes implement that interface. I can't think of any other way this is possible. In fact, Eclipse has a context menu option that shows the "Implementors" of an interface but they achieve that by scanning the packages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jQuery Mobile URLs are not updated I am using jquery mobile and am finding the when i redirect users to new forms the urls are not updated correctly. I recognize that there is some ajax operations going on however, the ulrs are still not being updated when i disable ajax form submits and/or links. The following js is placed above the link to the mobile-1.0b3.min.js It is almost like the following is not making any difference. <script type="text/javascript"> //http://jquerymobile.com/demos/1.0a3/#docs/api/globalconfig.html $(document).bind("mobileinit", function () { //apply overrides here $.mobile.ajaxLinksEnabled = false; $.mobile.ajaxFormsEnabled = false; //$.mobile.defaultTransition = false; //$.mobile.loadingMessage = "loading3"; //$.mobile.pushStateEnabled = true; }); </script> I have found that only if i disable ajax completely do the urls stay current to the page that the user is on.i.e. $.mobile.ajaxEnabled = false; A: I've been bothered by this for weeks now. I posted a similar question here, and put an answer on it for what works for me... jQuery Mobile/MVC: Getting the browser URL to change with RedirectToAction A: 1) $.mobile.ajaxEnabled = false; for everything after beta 1. 2) The url will only change if the redirect is done on the client side. I've been having this problem as well so when find a good workaround for it I will let you know (I am assuming that you're trying to do a response.redirect("target") in your code instead of attaching it to a button click event, if it isn't working on button click then I don't know if I can help you).
{ "language": "en", "url": "https://stackoverflow.com/questions/7585712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can we know how many albums there are in the iphone's camera library? I have a small question. We want the user to the able to choose an image from his device's library. If he has more albums apart from the camera roll, we use UIImagePickerControllerSourceTypePhotoLibrary, so he could browse all the albums. The problem comes when he only has the camera roll. In that case we want him to go directly to the camera roll screen, instead of showing an albums table with the camera roll as only choice. It is an useful step. The question: Is there way to know that there is only one album (camera roll) in the device, so we use UIImagePickerControllerSourceTypeSavedPhotosAlbum and skip that intermediate case? Is there any other solution? Thanks a lot. A: You can use the ALAssetsLibrary method enumerateGroupsWithTypes:usingBlock:failureBlock: to iterate over all albums in the photo library. It doesn't give you the count directly so you would have to increment your own counter but it should give you the desired result. Check the documentation for enumerateGroupsWithTypes:usingBlock:failureBlock: for more info on the method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does "multiple scopes" mean in when talking about MEF (Managed Extensibility Framework) and .NET 4.5? In What's new in .NET 4.5 microsoft says that MEF will now support "multiple scopes". What does this mean? I can't find documentation on that anywhere. A: I belive you question is anwered fully in this blog: http://blogs.msdn.com/b/bclteam/archive/2011/12/19/sharing-with-compositionscopedefinition-in-mef2-alok.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7585714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android smoothScrollTo not invoking onScrollStateChanged I am using smoothScrollBy() to scroll to a specific position in a ListView. I would like to be notified when the ListView is done scrolling to integrate it with the current onScrollStateChanged() event that is fired off when the user scrolls with their finger. Currently I'm using a Timer that runs 100ms after the duration of the smooth scroll, but that is not as event driven as I would prefer. A: If you have implemented the OnScrollListener for your listview you can watch for when the ScrollState changes. Use a global boolean (isScrolling) set to true when you call smoothScrollBy() and then set it to false once the OnScrollListener registers a ScrollState of SCROLL_STATE_IDLE. sidebar1.smoothScrollToPositionFromTop(currentPosition, 0, 500); isScrolling = true; sidebar1.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { isScrolling = false; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7585718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Namespace value not being set when GAE app invoked from Google Apps I have integrated the app with google apps marketplace. When the app is invoked from drop down "more" link on google apps(universal navigation bar), i expect the apps namespace key to be automatically set to the domain value but it's not happening. The value returned by NamespaceManager.getGoogleAppsNamespace() is "". Any idea what I might be doing wrong? Thank you for your help. public class NamespaceFilter implements Filter { ..... public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { case GOOGLE_APPS_DOMAIN : { NamespaceManager.set(NamespaceManager.getGoogleAppsNamespace()); Update: I am going to try explicitly setting the namespace value to the value carried by com.google.appengine.api.users.UserService.user_organization instead of NamespaceManager.getGoogleAppsNamespace() method. I wish the latter worked but it's not. user_organization is being set correctly to the calling domain on the other hand. A: You have to manage the Namespace in Appengine yourself. AppEngine is not aware of the google apps marketplace. Use the domain parameter to set the Appengine namespace manually. A: The problem might be the way the application is accessed. Is it yourapp.yourcustomerdomain.com, yourapp.appspot.com or even www.yourapp.com? Tested on my own apps the expected results of the method call are following: * *for yourapp.yourcustomerdomain.com it is yourcustomerdomain.com *for yourapp.appspot.com it is empty *for www.yourapp.com it is yourapp.com So given what you've written you need the application deployed the first way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating an Icon with a Tranparent Background I'm using ImageIcons that I downloaded from a free icon site in my JButtons. Two of them have white backgrounds, and the other one has a black background. I would prefer not to have a background color clash, so I want to make all the backgrounds transparent. I've seen ways to make image backgrounds transparent, but I thought it was kinda roundabout to turn my ImageIcons into Images and back again. Is there a way to make the backgrounds of ImageIcons transparent without converting to Images? A: This isn't a Java-solution, but it's a solution I use frequently nonetheless. Download/install Paint.NET and follow this discussion on how to make the background of images transparent. And then use the resulting image for the ImageIcon. A: Another non java solution: with photoshop you can select a small white rectangle of the background part, and then menu "Select" > "Similar" if you want to delete all white pixels, or "Grow" if you want to delete all white pixels touching your existing selection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I need to modify a table structure and need to find specific columns in database I need to modify a database and need to find all the tables that contain the column name of 'sysnames'. I also need to search for views and stored procedures that also contain 'sysnames' in their statements so I can update them accordingly. This is for SQL2000. TIA, DLackey A: Somewhat hacky, but you can use these: select * from information_schema.columns where column_name = 'sysnames' select * from information_schema.views where view_definition like '%sysnames%' select * from information_schema.routines where routine_definition like '%sysnames%' A: After posting this, I just noticed the SQL Server 2000 disclaimer in the question. I've not run this on SQL Server 2000, so it probably won't work there. here are two queries which will do what you need: this will find the column in tables and views, and will give back useful info (ObjectType, DataType, Nullable, etc) SELECT s.name as ColumnName ,sh.name+'.'+o.name AS ObjectName ,o.type_desc AS ObjectType ,CASE WHEN t.name IN ('char','varchar') THEN t.name+'('+CASE WHEN s.max_length<0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length) END+')' WHEN t.name IN ('nvarchar','nchar') THEN t.name+'('+CASE WHEN s.max_length<0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length/2) END+')' WHEN t.name IN ('numeric') THEN t.name+'('+CONVERT(varchar(10),s.precision)+','+CONVERT(varchar(10),s.scale)+')' ELSE t.name END AS DataType ,CASE WHEN s.is_nullable=1 THEN 'NULL' ELSE 'NOT NULL' END AS Nullable ,CASE WHEN ic.column_id IS NULL THEN '' ELSE ' identity('+ISNULL(CONVERT(varchar(10),ic.seed_value),'')+','+ISNULL(CONVERT(varchar(10),ic.increment_value),'')+')='+ISNULL(CONVERT(varchar(10),ic.last_value),'null') END +CASE WHEN sc.column_id IS NULL THEN '' ELSE ' computed('+ISNULL(sc.definition,'')+')' END +CASE WHEN cc.object_id IS NULL THEN '' ELSE ' check('+ISNULL(cc.definition,'')+')' END AS MiscInfo FROM sys.columns s INNER JOIN sys.types t ON s.system_type_id=t.system_type_id and t.is_user_defined=0 INNER JOIN sys.objects o ON s.object_id=o.object_id INNER JOIN sys.schemas sh on o.schema_id=sh.schema_id LEFT OUTER JOIN sys.identity_columns ic ON s.object_id=ic.object_id AND s.column_id=ic.column_id LEFT OUTER JOIN sys.computed_columns sc ON s.object_id=sc.object_id AND s.column_id=sc.column_id LEFT OUTER JOIN sys.check_constraints cc ON s.object_id=cc.parent_object_id AND s.column_id=cc.parent_column_id WHERE s.name LIKE '%sysnames%' find usages in procedures, functions, and triggers SELECT DISTINCT LEFT(s.name+'.'+o.name, 100) AS Object_Name,o.type_desc FROM sys.sql_modules m INNER JOIN sys.objects o ON m.object_id=o.object_id INNER JOIN sys.schemas s ON o.schema_id=s.schema_id WHERE m.definition Like '%sysnames%' ORDER BY 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7585722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: f:convertDateTime not being strict in pattern match? I have a f:convertDateTime with a pattern of mm/dd/yyyy. However, people are able to enter 2/19/78 and it would be 0078 rather then 1978 or 2078. I want to force people to enter in all 4 digits. I tried using a regexPattern validator, but that is complaining because it wants a string and not a Date object. Seems that the converters fire first and validators validate the converted value? I guess I could write a custom converter or validator, but this seems like such a simple thing I figure I'm doing something wrong. The javadocs for the convertor say it is strict in matching the pattern, but I'm not seeing that? Any ideas or suggestions? thanks! A: It's only strict for days/months, not for years. Here's an extract of relevance from SimpleDateFormat javadoc which <f:convertDateTime> is using under the covers: For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D. It's by design indeed not possible to fire validators before converters. Essentially, this one should have thrown a ConverterException because the input is not in the proper format. I'd create a custom converter which validates the pattern beforehand. Something like this: @FacesConverter("validatingPatternDateTimeConverter") public class ValidatingPatternDateTimeConverter extends DateTimeConverter { @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { String regex = getMandatoryAttribute(component, "validateRegex"); String pattern = getMandatoryAttribute(component, "convertPattern"); if (value != null && !value.matches(regex)) { throw new ConverterException(new FacesMessage(String.format("Invalid date, must be in pattern %s", pattern))); } setPattern(pattern); return super.getAsObject(context, component, value); } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { setPattern(getMandatoryAttribute(component, "convertPattern")); return super.getAsString(context, component, value); } private String getMandatoryAttribute(UIComponent component, String name) { String value = (String) component.getAttributes().get(name); if (value == null || value.isEmpty()) { throw new IllegalArgumentException(String.format("<f:attribute name=\"%s\"> is missing.", name)); } return value; } } which is to be used as follows: <h:inputText value="#{bean.date}"> <f:converter converterId="validatingPatternDateTimeConverter" /> <f:attribute name="validateRegex" value="\d{1,2}/\d{1,2}/\d{4}" /> <f:attribute name="convertPattern" value="MM/dd/yyyy" /> </h:inputText>
{ "language": "en", "url": "https://stackoverflow.com/questions/7585728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RenderControl method not rendering self-closing tags Having a strange problem with the RenderControl method. I have UserControl (an ASCX file) with this mark-up: <ul> <asp:Repeater ID="rptImages" runat="server"> <ItemTemplate> <li> <a href="<%# ((Image)Container.DataItem).Url %>"> <img src="<%# ((Image)Container.DataItem).Url %>?mw=80&mh=50" title="<%# ((Image)Container.DataItem).Title %>" alt="<%# ((Image)Container.DataItem).Alt %>" /> <p><%# ((Image)Container.DataItem).Description %></p> </a> </li> </ItemTemplate> </asp:Repeater> </ul> When this code executes in the normal page lifecycle (eg. when it is added to a page), it renders valid XHTML as mark-up: <ul> <li> <a data-fullscreen="/someimage.jpg" href="/another-image.jpg"> <img src="/myimage?mw=80&mh=50" title="Image Title" alt="Alt Text" /> <p></p> </a> </li> </ul> Note how the p tag has a closing tag (even though it is empty), and the image tag also has a closing tag. When I instantiate this control on the server and try to parse it to a string using the RenderControl() method like this: StringBuilder builder = new StringBuilder(); using (StringWriter writer = new StringWriter(builder)) { using (XhtmlTextWriter htmlWriter = new XhtmlTextWriter(writer)) { var control = (GalleryControl)LoadControl("~/layouts/Controls/Gallery/GalleryControl.ascx"); control.Images = m_images; control.RenderControl(htmlWriter); } } return builder.ToString(); Then the XHTML that is returned looks like this: <ul> <li> <a data-fullscreen="/someimage.jpg" href="/another-image.jpg"> <img src="/myimage?mw=80&mh=50" title="Image Title" alt="Alt Text"> <p> </a> </li> </ul> Note how the image tag is missing its closing tag, and the p tag is also not closing, making this XHTML no longer valid. I've spent the entire day on this. I've tried the XhtmlTextWriter instead of the HtmlTextWriter to pass into RenderControl, but this didn't make any difference. Has anyone else ever come across this problem? It's quite bizarre and has a lot of us in the team stumped at the moment! Any help or ideas would be appreciated. EDIT: I probably should have mentioned that this code is being executed in the Sitecore processor stack. It runs in the "renderField" processor stack just before the ExpandLinks processor. A: I suspect this line doesn't execute or an exception is thrown and swallowed not allowing it to finish: <%# ((Image)Container.DataItem).Description %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7585729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to make the MapView a button (iPhone/iPad)? I currently have a map view in my app that is locked so that the user can't interact with it (i.e. scroll, zoom etc.), however I want to make it into a UIButton. The idea being the the can press the map view and it will call a function, the same way pressing a UIButton does. I've had a look around online for ideas on how to achieve this but I haven't found anything yet. I tried making a UIButton over the top of the map view but I can't seem to make it invisible. I also tried linking an IBAction to the map view, however the option to link it doesn't appear in the connections inspector (as I expected to be honest - shot in the dark!). Is there any way to achieve this effect? A: You can place a UIButton over the map, just like you tried before. But to make it invisible, change the button type from Round Rect to Custom. This will make the button invisible unless you explicitly add an image to the button. -Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7585734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What Kind Of Macro Is this? I came across this following code: #include<stdio.h> #define d(x) x(#x[3]) int main(){ d(putchar); } Which prints c as the output. I wonder what does the macro #define d(x) x(#x[3]) does? In C language is there an operator like #? I can see this inside the macro body i.e here x(#x[3]). According to my normal eye it looks something different I see in C language but actually What does this does? Edit : Whats the real use of # in real world? I'm a novice in C and it will be good if the explanation is in simple terms. Thanks in advance. A: The character '#' is a stringizer -- it turns a symbol into a string. The code becomes putchar("putchar"[3]); A: The hash sign means "stringify", so d(x) expands to putchar("putchar"[3]), whence the c. A: From here: Function macro definitions accept two special operators (# and ##) in the replacement sequence: If the operator # is used before a parameter is used in the replacement sequence, that parameter is replaced by a string literal (as if it were enclosed between double quotes) #define str(x) #x cout << str(test); Put simply, it changes the "x" parameter into a string. In this case test becomes a char array containing 't', 'e', 's', 't', '\0'. A: The # is a pre-processor operator which turns a literal into a string. In fact your d macro prints the fourth char of the converted string of your literal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Defining spring security http element in two different files? Is it possible to define the security:intercept-url elements and security:custom-filter elements for a single security:http in two different Spring configuration files? This is so we can cleanly reuse the security:custom-filter definitions which will be common across many applications with intercept rules that will not. I can't simply duplicate the <security:http> element because I get BeanDefinitionParsingException: Configuration problem: Duplicate <http> element detected. I am well well aware of how to split a normal bean file with import A: As requested in comment: Spring Security versions prior to 3.1.x do not allow multiple http element definitions. 3.1 does however. Here is the Jira issue for the feature. This article on 3.1 changes might also be helpful. You can define another context file in your web.xml: <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring-contexts/context1.xml /WEB-INF/spring-contexts/context2.xml </param-value> </context-param> Or you can define a directory where your contexts would be and name them any way you like without having to specify each context file separately: <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring-contexts/* </param-value> </context-param> Regarding Ayusman's answer, you actually can import your security contexts into your bean contexts: <beans> <import resource="classpath*:/security-context-*.xml"/> <bean><!-- blah blah --></bean> </beans> A: use the import in application context file.. custom-filter.appcontext.xml . . <import resource="interceptor-url-file.xml"/> Note that both files need to have the proper spring xml schema details and MUST be valid XML files. A: I have been working on this error for 5 hours. Really stupid problem. This error is a parse error that when you comment some lines in applicationContext-security.xml, files are not generated correctly. Let me explain on an example code. <port-mappings> <port-mapping http="7001" https="7002" /> </port-mappings> <!-- <port-mappings> <port-mapping http="7015" https="7515" /> </port-mappings> --> this lines are generated as, <port-mappings> <port-mapping http="7001" https="7002" /> </port-mappings> <port-mappings> <port-mapping http="7015" https="7515" /> </port-mappings> --> so that, compiler tells you "duplicate element detected". Because generated file includes duplicate elements. I hope to help you .
{ "language": "en", "url": "https://stackoverflow.com/questions/7585743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to pass a parameter of type pointer to PVOID from LabView to DLL? I'm calling a DLL written in C++ from LabView. The function prototype is: ULONG DAQ_Open(PVOID *pHandle); How can I pass the correct parameter from LabView? Is it just impossible to pass parameters of type pointer to pointer from LabView to DLL? A: As long as you're not expecting to pass a pointer to a LabVIEW VI to use as a callback (which is a seperate, and much more difficult answer), the parameter is just a pointer. When you configure your call library node, use the type "numeric" and the data type "unsigned pointer-sized integer" and pass "pointer to value." This should give you a prototype of: void funcName(uintptr_t *arg1); A: For additional examples on calling DLLs from LabVIEW (including pointers, structs, arrays, etc), here's a handy article that links to several other in-depth examples: https://decibel.ni.com/content/docs/DOC-9076 A: You should search for 'dll pointers labview' on NI's website to get an idea. Also, there is an example shipped with LabVIEW called Call DLL.vi which has examples on how you can achieve this. The example VI can be found by navigating to Help -> Find Examples and then searching for DLLs. the Call DLL.vi VI allows you to browse examples of external code (C and C++) data types and how they interface with LabVIEW. Each data type has an example VI that demonstates the use of the Call Library Function Node. To open the example VI for a particular data type, select that data type from the list on the left and then press the "Open Example VI for Current Data Type" button. The function prototype, the function's source code, and any specific details about this example will appear in the External Code Information cluster.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Date (Calendar) calculating the start of a day in local time given a date time All, Having a hard day in the office with this one... I am trying to workout the start of a day in Local Time, i.e. Midnight 00:00:00, given any calendar date. Given the following days, I want to calculate the start of the day at local time midnight: Time Start Day (Local) Start Day (GMT) 2011-03-27 00:00:00 GMT --> 2011-03-27 00:00:00 GMT --> 2011-03-27 00:00:00 GMT 2011-03-27 01:00:00 GMT --> 2011-03-27 00:00:00 GMT --> 2011-03-27 00:00:00 GMT 2011-03-27 02:00:00 GMT --> 2011-03-27 00:00:00 GMT --> 2011-03-27 00:00:00 GMT 2011-04-01 00:00:00 BST --> 2011-04-01 00:00:00 BST --> 2011-03-31 23:00:00 GMT 2011-10-30 00:00:00 BST --> 2011-10-30 00:00:00 BST --> 2011-10-29 23:00:00 GMT 2011-10-30 01:00:00 BST --> 2011-10-30 00:00:00 BST --> 2011-10-29 23:00:00 GMT 2011-10-30 01:00:00 GMT --> 2011-10-30 00:00:00 BST --> 2011-10-29 23:00:00 GMT 2011-11-01 00:00:00 GMT --> 2011-11-01 00:00:00 GMT --> 2011-11-01 00:00:00 GMT At present, I am parsing the String Time into a GregorianCalendar using a SimpleDateFormat. This gives me the GMT/UTC time to calculate from. So I have some code which parses the string into a GregorianCalendar: public GregorianCalendar getCalendar(String dateTime) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(sdf.parse(dateTime, new ParsePosition(0))); return cal; } Now I need to set it to midnight locally: public void setToStartOfDayLocally(GregorianCalendar cal) { ???? } I am not too sure what I need to do at the minute with the Calendar. Unfortunately we are not moving to JODA date in the near future. I am also not accounting for different time zones with my example. Any thoughts? Thanks, Andez A: It sounds like you just want to set all of the time parts to zero. You can use: cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); (Assuming you've got the time zone in the calendar set properly.) Note that that isn't necessarily valid though - in some time zones (e.g. Brazil), at a daylight saving transition midnight either occurs twice or not at all. Personally I'd start making noises about moving to Joda Time though, which makes all of this a lot simpler :) A: I think this code might solve your issue. I am using it to convert from time in local timezone to another. public static Date convertLocalDateToDateTimezone( Date localDate, String timezone ) { TimeZone localTimeZone = TimeZone.getDefault(); TimeZone timezone = TimeZone.getTimeZone( timezone ); long gmtMillis = localDate.getTime(); long result = gmtMillis + timezone.getOffset( gmtMillis ) - localTimeZone.getOffset( gmtMillis ); return new Date( result ); } Hope this helps. A: java.time You are using outmoded classes. In Java 8 and later, use built-in java.time framework. Do not assume the day starts at the time 00:00:00.0. Because of anomalies such as Daylight Saving Time (DST) the start-of-day may vary by time zone. Let the java.time classes determine the correct time with a call to LocalDate::atStartOfDay. Avoid using 3-4 letter zone abbreviations such as BST, EST, and so on. They are neither standardized nor unique. Use proper time zone names. An Instant is a moment on the timeline in UTC. Apply a time zone to get a ZonedDateTime. Extract a date-only value from that date-time, a LocalDate. Apply a time zone with a call to atStartOfDay to get back to a ZonedDateTime set to the first moment of the day in that time zone. Instant now = Instant.now(); ZoneId zoneId = ZoneId.of( "America/Montreal" ); ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId ); LocalDate localDate = zdt.toLocalDate(); ZonedDateTime zdtStart = localDate.atStartOfDay( zoneId ); Tip: Avoid the word “midnight”. Does not have a precise definition. Some people think of trying to determine the last moment of the day which is a problem because of an infinitely divisible fraction of a second. Some people think of the the special string “24:00” to indicate the stroke of midnight which further confuses date-time handling. Experience from the Joda-Time project teaches us that it is best to focus on “first moment of the day” as a clear and precise meaning. Also, be aware that the first moment is not always 00:00:00, due to Daylight Saving Time (DST) and other anomalies in some time zones. That is why we depend on the atStartOfDay method rather than hard-code a zero-time-of-day.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to create a standalone Windows Silverlight Embedded Application for CE 6.0 R3? We are investigating using Silverlight as our UI creator. We can get a subproject running from the Platform builder but would like to pull this code to a standalone VS project. I have an SDK built from Platform builder with Silverlight added in. Currently I am getting unresolved external symbol errors in the project build against this SDK. Error 1 error LNK2019: unresolved external symbol GetXRApplicationInstance referenced in function WinMain SilverlightTestApp.obj SilverlightTestApp Error 2 error LNK2019: unresolved external symbol XamlRuntimeInitialize referenced in function WinMain SilverlightTestApp.obj SilverlightTestApp The library files where XamlRuntime.lib and uuid.lib are located have been included. Any help would be greatly appreciated as I feel like I am running up against a brick wall currently. Edit: The Silverlight runtime that comes with CE6R3 only supports Silverlight 2 functionality. That means you can use either Blend 2 or Blend 3 but you will have to create a Silverlight 2 project. You can use either VS2005 or VS2008 to create your application as long as you use the correct SDK and target the right device. HOWEVER, you will not be able to use WEST since these tools specifically target the Silverlight runtime that comes with CE7 (essentially Silverlight 3). Also you can NOT use the VS2008 project template for silverlight for embedded that installs with WEST and CE7. The code that this template generates is not compatible with CE6R3. So I am not able to use the page below because it is based off of WEST and we are using the CE 6.0R3 A: Follow this tutorial and it should work, probably you haven't converted well the Blend project into a Visual Studio one: http://blogs.msdn.com/b/silverlightforwindowsembedded/archive/2010/07/19/first-silverlight-for-windows-embedded-application.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7585750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CGRectApplyAffineTransform then CGAffineTransformInvert doesn't return to original position This does not seem possible and I'm sure there's a simple solution but I cannot work it out. My High School matrix math is a bit rusty :) I'm building a CGAffineTransform to do translation-rotation-translation of a CGRect and then trying to use the inverse CGAffineTransformInvert to return to the original location. But it doesn't. I've managed to reduce it to this: // start building the transform... // translate so (0,0) is at centre of image CGAffineTransform affine = CGAffineTransformMakeTranslation(-100, -100); // add a rotate affine = CGAffineTransformConcat(affine, CGAffineTransformMakeRotation(M_PI/4)); // get the inverse CGAffineTransform inverseAffine = CGAffineTransformInvert(affine); // now test this: pick a starting CGRect CGRect start = CGRectMake(50, 40, 10, 20); // use my CGAffineTransform to move "start" to "midpoint" CGRect midpoint = CGRectApplyAffineTransform(start, affine); // use the inverse to move "midpoint" to "finish" CGRect finish = CGRectApplyAffineTransform(midpoint, inverseAffine); // what did we get NSLog(@"start %5.1f %5.1f %5.1f %5.1f", start.origin.x, start.origin.y, start.size.width, start.size.height); NSLog(@"midpoint %5.1f %5.1f %5.1f %5.1f", midpoint.origin.x, midpoint.origin.y, midpoint.size.width, midpoint.size.height); NSLog(@"finish %5.1f %5.1f %5.1f %5.1f", finish.origin.x, finish.origin.y, finish.size.width, finish.size.height); The output looks like this: 2011-09-29 ... start 50.0 40.0 10.0 20.0 2011-09-29 ... midpoint -7.1 -77.8 21.2 21.2 2011-09-29 ... finish 40.0 35.0 30.0 30.0 Shouldn't the finish rect be the same as the start? Isn't that what CGAffineTransformInvert is supposed to do? If I do the same thing but with a CGPoint instead of a CGRect it seems to work ok. A: Copied from documentation: You can operate on a CGRect structure by calling the function CGRectApplyAffineTransform. This function returns the smallest rectangle that contains the transformed corner points of the rectangle passed to it. If the affine transform that operates on the rectangle performs only scaling and translation operations, the returned rectangle coincides with the rectangle constructed from the four transformed corners. A: OK I found my mistake. Because affine transforms do not preserve rectangles in general, the function CGRectApplyAffineTransform returns the smallest rectangle that contains the transformed corner points of the rect parameter not some strange twisted non-CGRect-ish thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Rendering UIWebView as Image/PDF Has Visual Artifacts I'm rendering a UIWebView's layer into a graphics context and then using the UIGraphicsBeginPDFPageWithInfo() family of functions to include it in a PDF. My problem is that the output includes an extra set of gray lines that aren't part of my data set. I'm hoping someone can shed some light on where they're coming from. An example of the output is included below. The HTML document that is being rendered contains nothing but the text 'THIS IS A TEST' - the boxes you see are coming from the rendering process somewhere. When rendered on the screen, it's just black text on a white screen - no lines/boxes. Anyone have any ideas what's going on? Thanks! Here's the code I'm using to render this web view as a PDF: NSMutableData *pdfData = [NSMutableData data]; UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil); CGRect viewBounds = webView.bounds; UIGraphicsBeginPDFPageWithInfo(viewBounds, nil); CGContextRef pdfContext = UIGraphicsGetCurrentContext(); [webView.layer renderInContext:pdfContext]; UIGraphicsEndPDFContext(); Also, here's a screenshot of what I'm seeing for output: A: I ran into the same issue. It would happen whenever trying to render the UIWebView into the PDF context, and frame width > 512. I was not able to diagnose the exact issue, but worked around it by rendering the UIWebView into a UIImage, and then rendering the UIImage into the pdf context. Code as: UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kWidth, kHeight), nil); CGContextRef currentContext = UIGraphicsGetCurrentContext(); UIImage* image = nil; UIGraphicsPushContext(currentContext); UIGraphicsBeginImageContext(self.webview.frame.size); { [self.webview.layer renderInContext: UIGraphicsGetCurrentContext()]; image = UIGraphicsGetImageFromCurrentImageContext(); } UIGraphicsEndImageContext(); UIGraphicsPopContext(); [image drawInRect:CGRectMake(0, 0, kWidth, kHeight)];
{ "language": "en", "url": "https://stackoverflow.com/questions/7585762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jasper report pdf name problem I am creating pdf report in spring mvc 3 using dynamic jasper report. I am setting these headers before writting report to stream. response.setHeader("Content-Disposition", "inline; filename=" + fileName); response.setContentType("application/pdf"); Report is generated and display correctly in browser but it misses its name when I try to save it, I set name here fileName. response.setHeader("Content-Disposition", "inline; filename=" + fileName); What could be the issue. A: With attachment, the file will be served with the provided name properly. When inline, browsers seem to ignore filename, and usually give the servletname part of the URL as default name when saving the inline contents. You could try mapping that URL to an appropriate filename, if that is suitable. For example, with <servlet-mapping>. I'm not familiar with spring mvc, so maybe there's an equivalent. Here's a SO related question: Securly download file inside browser with correct filename You may also find this link useful: Filename attribute for Inline Content-Disposition Meaningless?
{ "language": "en", "url": "https://stackoverflow.com/questions/7585769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parsing JSON feed with Ruby on Rails I know this has been covered over and over but I just can't understand how to get started. Am too much of a JSON virgin to know what's going on. I'm trying to get some data from a json feed on a remote server into a rails3 application. I understand I need the json gem but I have no idea how to pull the data. If the url is something like this: http://my-feed.com/json?res=service&s=table&table=User&start=0&max=5&sort=id&desc=true How do I go about getting that from my application? Any help, walk-throughs, tutorials appreciated A: I don't really know the json gem - does it only handle the parsing? If yes, and you only need to pull in the information, try this: require 'open-uri' begin json = open 'http://my-feed.com/json?res=service&s=table&table=User&start=0&max=5&sort=id&desc=true' rescue # a multitude of HTTP-related errors can occur end json_string = json.read # parse A: You are going to need to make an HTTP request for the resource, grab the response, and (potentially) parse it yourself - although I think HTTParty will do the JSON parsing for you. HTTParty would be my suggestion for making requests, though. If you read the README, it links to examples of how to use HTTParty which you should find helpful. The basic example includes how to make a get request, inspect the headers and body, etc. I believe you can also use response.parsed_response to get the parsed response of whatever HTTParty's default parser is. There is also an example of using your own custom parsers (if you prefer another to HTTParty's).
{ "language": "en", "url": "https://stackoverflow.com/questions/7585771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Which is the equivalent of the StringToColor function for a TAlphaColor? I'm looking for the equivalent to the Graphics.StringToColor function to convert a string to an TAlphaColor (Color type used by Firemonkey). I searched in the online Rad Studio help as well as in the related firemokey units without luck :(. I can write easily a function to convert these values but I prefear use a RTL function. Anybody knows if exist any function to convert a String to a TAlphaColor in delphi-xe2? A: Yes exist such function and is called StringToAlphaColor and is declarated in the System.UIConsts unit. function StringToAlphaColor(const Value: string): TAlphaColor;
{ "language": "en", "url": "https://stackoverflow.com/questions/7585773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Delphi XE - SendText through ServerSocket returns Chinese or vietnamese characters on the other end I wrote a simple file transfer program that runs on Windows 7. I run this program as a server on one computer and client on the other. Client sends out a request for a file transfer and then server sends out the name of the file first. Then, client acknowledges that it got the file name and to send the content of the file. This program worked flawlessly on XP. Now we are trying to run it on Windows 7 computers and it has problem. The problem is whenever the server replies back with the filename to the client. Server sends text by calling ServerSocket1.SendText('File1.dat'). What the client gets looks like either Chinese or Vietnamese characters. So, my program fails. My client program has to know the name of the file. So, it knows where to save it in specific location in hardrive. I think, SendText function takes AnsiString and What I am sending is string data. Do you think that's the reason? UPDATE procedure TForm1.ServerSocket1ClientRead(Sender: TObject; Socket: TCustomWinSocket); begin Socket.SendText(AnsiString('calibrate.log')); end; procedure TForm1.ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket); var Buffer:array[0..999] of char; begin Socket.ReceiveBuf(Buffer,Socket.ReceiveLength); end; A: Well, your problems come from the fact that you send your data as AnsiString, and read it with WideChars (Char is an alias of WideChar in Delphi XE). Changing your code for this would most likely fix your problem. procedure TForm1.ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket); var Buffer:array[0..999] of Ansichar; begin Socket.ReceiveBuf(Buffer,Socket.ReceiveLength); end; A: TClientSocket is deprecated since Delphi 6 (see Is Delphi TClientSocket (still) deprecated?) so I would expect problems with Unicode data and in other areas. As written in one of the answers, TClientSocket and TServerSocket also use ineffective design based on Windows messages. So I would try to use Indy or Synapse instead. This also would make it ready for cross-platform usage (Windows messages are obviuousle not available on OSX). A: I resolved my question. I am not sure why it works flawlessly on Windows XP. Anyways, I am sending and receiving texts as follows. I originally was reading the text into array of chars through ReceiveBuf method. Socket.SendText('File.log'); theStr:String; theStr := Socket.ReceiveText; Thanks for helping me realize my own programming issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Role Playing Game program: calling input variables from another class I have been searching for a solution for this for hours and I'm stumped. I'm very new to Java, but I am currently programming a very easy role playing game engine. In this game, the user is to type in the level of his stats. My question is: how can I make a class where this information is stored and easily referenced when the level of the stat is called for? To be a little more specific: I want to create a variable where the user puts in the level for his skill (using the Scanner), and then I want to let the rest of the java program access the value and use it throughout the game. I would prefer keeping the stats in another class than where the stats will be used. Thanks in advance for the answers! A: How about class Stats { private int skillLevel; // ... other stats public void setSkill(int level) { skillLevel = level } public int getSkill() { return skillLevel; } } class Player { private Stats stats; // ... public Stats getStats() { return stats; } } You cant then get skill for a player: Player p; // ... p.getStats().getSkill(); Was it that simple or did I fail to notice something?
{ "language": "en", "url": "https://stackoverflow.com/questions/7585780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why Form_Load event already catches all the Exceptions? Ive put my initialization code at form load, since it is not a good idea to leave it at the constructor because the designer can crash. The problem is that Ive just realized that any exception inside the form load event will be catch internally! Why? How should I overcome that? private void Form1_Load(object sender, EventArgs e) { //This exception will be catch internally (I don't know why and where) throw new Exception("test"); } A: It is a bug and is explained here: The case of the disappearing OnLoad exception – user-mode callback exceptions in x64 http://blog.paulbetts.org/index.php/2010/07/20/the-case-of-the-disappearing-onload-exception-user-mode-callback-exceptions-in-x64/ VS team answer: From here: https://connect.microsoft.com/VisualStudio/feedback/details/357311/silent-exceptions-on-x64-development-machines Posted by Microsoft @ 22/04/2010 17:12 Hello, This bug was closed as "External" because this behavior results from how x64 version of Windows handle exceptions. When a user mode exception crosses a kernel transition, x64 versions of Windows do not allow the exception to propagate. Therefore attached debuggers are unaware of the fact that an exception occurred resulting in the debugger failing to break on the unhandled exception. Unfortunately where is nothing that the Visual Studio team can do to address this, it is the result of operating system design. All feedback regarding this issue should be addressed to the Windows team; however the Windows team considers this to be the "correct" operating system design, and considers the x86 behavior to be "incorrect". Best Regards, Visual Studio Debugger Solution that Im using: Ive put the code that was inside the form load to the constructor and I check if the app is running in designer or not protected static bool IsInDesigner { get { return (Assembly.GetEntryAssembly() == null); } } if (!MainForm.IsInDesigner) LoadControl();
{ "language": "en", "url": "https://stackoverflow.com/questions/7585786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Greendroid import Im trying to use the Greendroid library inside eclipse. In the moment i import it as a library the project brakes. The generated R file disappears and my application cant compile (Due to this behavior). I import the Greendroid framework as a normal android project. When using Greendroid my application starts throwing errors: W/ResourceType( 7692): Bad resource table: header size 0xc or total size 0x12a95 is not on an integer boundary [...] W/ResourceType( 7692): Bad resource table: header size 0xc or total size 0x12a95 is not on an integer boundary [...] ERROR: Unable to parse generated resources, aborting. Any suggestions how to import / install / link against Greendroid properly ? A: I figured out how to solve the problem. It was referenced in a similar post (Android style Resources compile (aapt) failing : Bad resource table: header size 0xc). The problem is located in the styles.xml file. It isn't obvious as the compiler doesn't give a single hint where the compilation went wrong. Styles cant be referenced with a "+" in their declaration in the styles.xml In my styles file i changed <item name="android:id">@+id/background_logo</item> to <!-- <item name="android:id">@+id/background_logo</item> --> and everything went well. If you need such an attribute, use the ids.xml like its shown in the referenced question. This is seriously hard to track, but such an error is caused by this wrong declaration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: is there an easy free way to create test case management in Jira I think the only part I dont get is how you handle the run results. So if I set up a new project in Jira for test cases how would I make it so I can run mark a test case as pass or fail but not close out the jira. So I basically want the original jira to be always open then be able to mark it passed or failed against a specific release. the original jira should stay unchanged just somehow log a result set? I do not have bamboo that make any sense A: We have setup a simple custom workflow in Jira without using Confluence. We added one new issue type - Test Case. And we have a new sub-task - Test Run. Test Case has only three workflow actions: Pass, Fail and Invalid (the last one is to make Test Case redundant). And two statuses - Open and Invalid. Test Run is automatically created when Test Case passes or fails. Users do not manually create test runs. We use one of the plugins to create a subtask on transition. Test Run can be in a Passed or Failed state and has version info, user who passed or failed and a comment. This is it. Here are some links that I used to setup Jira for Test Case Management: * *Test Case Management in Jira *Using Jira for Test Case Manangement *Create On Transition Plugin A: The approach we are following is as follows We use Confluence for implementing our test cases. Each test case has its own page describing the setup, the scenario to run and all possible outcomes. We have a test library page which is the parent of all these test cases. When we want to start a validation cycle on a particular release, we use a script which generates for each test case in confluence, a corresponding 'test run' issue. (@DennisG - JIRA allows to define different issue types, each with its own workflow) The summary is the summary of the testcase The description is the scenario and outcome of the testcase We have a specific confluence link referring the testcase The testrun issue workflow contains 4 stages * *Open *In Progress *Blocked *Closed And 3 resolutions * *Success *Failure *Review testcase We then start validating all 'test run' isuses. Using dashboard gadgets it is easy to see how many testcases still need to be run, how many are blocked, how many have been done, and how many have failed ... In case the resolution is 'review testcase' we have the ability to adapt the testcase itself. Conclusion - JIRA is certainly usable as a test execution management environment. Confluence, as a wiki provides an environment to build the necessary hierarchies (technical, functional). Last point. We start to extensively use Bonfire (a plugin for JIRA) http://www.atlassian.com/en/software/bonfire This shortens the 'manual' testing cycle considerably. For us it had an ROI of a couple of weeks. Hope this helps, Francis PS. If you're interested to use the script send me a note. A: you can use PractiTest, a test management tool that integrates with JIRA. PractiTest covers your entire QA process, so you can use it to create Requirements, Tests and Test sets, and use the integration option to report issues in JIRA. you can also link between the different entities. read more about PractiTest's integration with JIRA A: We are using this test case management called informup. The test case management is integrates with Jira. In addition it has fully integration in the system so in case you want to use it as a test case management and a bug tracking system you can do it as well A: To be honest, I'm not sure that using JIRA (or any other bug/issue tracking tool) as a test management tool is a good idea. The problem with this is that issue trackers usually have a single main entity (the issue), whereas test management tools usually distinguish between test cases and actual tests/results. This way you can easily reuse the same test case for different releases and also store a history of test results. Additional entities such as test runs and test suites also usually make it a lot easier to manage and track your data. So instead of using Jira for test management, you might want to consider using a dedicated test management software that integrates with Jira. There are many test management tools out there, including open source projects: http://www.opensourcetestmanagement.com/ You could also take a look at our tool TestRail, which also comes with Jira integration: http://www.gurock.com/testrail/ http://www.gurock.com/testrail/jira-test-management.i.html A: Have you tried looking in Jira's plugin directory at https://plugins.atlassian.com to see whats available to extend the core functionality. There may be something there that you could be installed. There are tools out there that combine both issue tracking and test management (e.g. elementool.com), however if you are after a more feature rich issue tracking experience, you may need to start looking at dedicated tools. If after looking around you find that there are no suitable solutions to enable you to have things in one place, you may want to take a look at TestLodge test case management, which is a tool I have developed that integrates easily with Jira. A: Why not just integrate JIRA with a test management tool? So, for example, we use Kualitee. It integrates with JIRA and provides traceability from the defect reported to the underlying test case and requirements. So, you can run your entire QA cycle on Kualitee and sync and assign defects to your team in JIRA. You can also generate your test case execution reports and bug reports and export them so you are all set on that front as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: PowerDesigner - vbs script to run other scripts I have a few PowerDesigner 15 vbs scripts that perform various cleansing/transformation tasks on physical data models. I'd like to be able to run all of them at once rather than one at a time (there are 10 scripts now, possibly more in the future). Also, I'd like to avoid copying all the code in one big ugly script. Is there a way to have a script that runs all other scripts? Note: I've tried ExecuteCommand, but it doesn't work; it executes the .vbs outside the context of PowerDesigner, so it cannot access the Model. A: You could store your scripts in an extension (.xem). The main script would attach the extension to the model, use the scripts (as custom methods on the model object for example), and detach the extension at the end? Or you could even always attach the extension to your model (which would allow defining the cleansing scripts as popup menu options).
{ "language": "en", "url": "https://stackoverflow.com/questions/7585790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to mix applicative functors and arrows i read on Andrew Birkett’s blog Applicative arrows for XML &&& return to pure that we could mix arrows and applicative functors. I tried it by my own but i don't have what i expect. i would like this result: [Scenario {scenario = "11111", origin = "333", alarm = "Sonde1"}, Scenario {scenario = "22222", origin = "444", alarm = "Sonde2"}] but i get this instead: [Scenario {scenario = "11111", origin = "333", alarm = "Sonde1"}, Scenario {scenario = "11111", origin = "333", alarm = "Sonde2"}, Scenario {scenario = "11111", origin = "444", alarm = "Sonde1"}, Scenario {scenario = "11111", origin = "444", alarm = "Sonde2"}, Scenario {scenario = "22222", origin = "333", alarm = "Sonde1"}, Scenario {scenario = "22222", origin = "333", alarm = "Sonde2"}, Scenario {scenario = "22222", origin = "444", alarm = "Sonde1"}, Scenario {scenario = "22222", origin = "444", alarm = "Sonde2"}] i think there is a twist in my code but i don't know where to search. Below is my code if anyone can suggest some help. {-# LANGUAGE Arrows, NoMonomorphismRestriction #-} import Text.XML.HXT.Core import Control.Applicative import Text.XML.HXT.Arrow.ReadDocument import Data.Maybe import Text.XML.HXT.XPath.Arrows import Text.Printf data Scenario = Scenario { scenario, origin, alarm :: String } deriving (Show, Eq) xml= "<DATAS LANG='en'>\ \ <SCENARIO ID='11111'>\ \ <ORIGIN ID='333'>\ \ <SCENARIO_S ERR='0'></SCENARIO_S>\ \ <SCENARIO_S ERR='2'></SCENARIO_S>\ \ <ALARM_M NAME='Sonde1'></ALARM_M>\ \ </ORIGIN>\ \ </SCENARIO>\ \ <SCENARIO ID='22222'>\ \ <ORIGIN ID='444'>\ \ <SCENARIO_S ERR='10'></SCENARIO_S>\ \ <SCENARIO_S ERR='12'></SCENARIO_S>\ \ <ALARM_M NAME='Sonde2'></ALARM_M>\ \ </ORIGIN>\ \ </SCENARIO>\ \</DATAS>" parseXML string = readString [ withValidate no , withRemoveWS yes -- throw away formating WS ] string parseVal tag name = WrapArrow $ getXPathTrees (printf "/DATAS/%s" tag) >>> getAttrValue name parseDatas = unwrapArrow $ Scenario <$> parseVal "SCENARIO" "ID" <*> parseVal "SCENARIO/ORIGIN" "ID" <*> parseVal "SCENARIO/ORIGIN/ALARM_M" "NAME" testarr1= runX (parseXML xml >>> parseDatas) A: As pointed out by rampion, the problem is how the list monad works with applicative. Take a look at this: λ *Main > (+) <$> [1,2,3] <*> [1,2,3] [2,3,4,3,4,5,4,5,6] The result is the carthesian product of (+) applied to [1,2,3] and [1,2,3]: the result list has 9 elements. In your code, parseVal "SCENARIO" "ID" will return a list of 2 elements, and so will parseVal "SCENARIO/ORIGIN" "ID" and parseVal "SCENARIO/ORIGIN/ALARM_M" "NAME". Therefore, the result will have 8 elements. Instead, this is how I would change your code: --- parse a generic tag parseVal tag name = WrapArrow $ getXPathTrees (printf "%s" tag) >>> getAttrValue name --- parse a "SCENARIO" xml element parseScenario = unwrapArrow $ Scenario <$> (WrapArrow $ getAttrValue "ID") <*> (parseVal "SCENARIO/ORIGIN" "ID") <*> (parseVal "SCENARIO/ORIGIN/ALARM_M" "NAME") --- parse the XML, extract a list of SCENARIOS and, for each, apply parseScenario testarr1= runX (parseXML xml >>> getXPathTrees (printf "/DATAS/SCENARIO" ) >>> parseScenario) The result is as desired: λ *Main > testarr1 [Scenario {scenario = "11111", origin = "333", alarm = "Sonde1"},Scenario {scenario = "22222", origin = "444", alarm = "Sonde2"}]
{ "language": "en", "url": "https://stackoverflow.com/questions/7585794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JPQL and clausole IN, not found i have the following situation: In the dao class: ... Query q = em.createNamedQuery("myQuery"); q.setParameter("attr", "value"); List<MyObj> listMyObj = q.getResultList(); ... In my file orm.xlm, i defined this query: <named-query name="myQuery"> <query><![CDATA[ select m from MyEntity1 where id_est in (select mm.id from MyEntity2 where mm.id_est = :attr) ]]></query> </named-query> Everything works, there are no configuration problems and / or code, but this query returns 0 elements, when execute the same query in sql returns items expected . Why? There is something i ignore in JPQL? A: In this case, if mm.id_est is a String when you set parameter don't use " 'value' " but use " value " ...this was my problem. Fortunately, thanks to this post I realized that in my code I had written as I wrote here on StackOverflow
{ "language": "en", "url": "https://stackoverflow.com/questions/7585795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Executing Javascript in background using Phonegap I've created an application that will need to fire Javascript events every "X" minutes. I'm using phone gap build to deploy on Android/iPhone/Blackberry, but I'm of course stuck, as the Javascript timer doesn't fire in the background (when they minimize the app). I was wondering if Phonegap had some sort of ability to fire Javascript events while the app is running in the background. Or is there ANY way to accomplish this easily across these major phones? I just need to fire an ajax call with the geolocation info from the phones. A: Yes you can do it, there's a PhoneGap plugin that does exactly what you need: PhoneGap + Background.js https://github.com/jocull/phonegap-backgroundjs Be careful configuring your config.xml A: Currently, phone gap doesn't have this as an option. There are many requests out there for this sort of thing, but I think people are getting tripped up by the TOS for background events for iOS. Regardless, a phone gap plugin would do it as @Chase mentioned, but of course that requires native code writing. I'm assuming you're wanting to push geo locations every x seconds/minutes so that your server knows where the phone is at any point in time (as long as the app is open or minimized)? That's one limitation of Loopt, is that it can't grab those locations in the background - hence the whole 'ping' action in the app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Trying to center my web page Possible Duplicate: page will not align center I'm trying to center my web page using asp.net. When I use the <center> tag it only centers the content placeholder. But when I use the CSS attribute margin: 0 auto, it doesn't do anything. Is there a way to center the whole page? A: In your CSS: body { text-align: center; } #container { width: 900px; /* or some other fixed-width value */ margin: 0 auto; text-align: left; /* reset text-align */ } Edit: guess I should probably show the associated markup as well... ... <body> <div id="container"> <!-- centered content here --> </div> </body> ... A: You need to have all your content with in a wrapping div, and have a set width on that element, along with margin: 0 auto; Example: #wrapper { width: 960px; margin: 0 auto; } A: You can use CSS: * *http://davidwalsh.name/horizontally-center-website-structure-css *http://pmob.co.uk/pob/hoz-vert-center.htm *http://www.dynamicsitesolutions.com/css/center-page-content-horizontally-and-vertically/
{ "language": "en", "url": "https://stackoverflow.com/questions/7585797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there an OR combinator in jQuery/Sizzle? Possible Duplicate: jQuery OR Selector? I would like to for each select in the matched set find the first option that either has a class placeholder or an empty value something along the lines of $(selectorOrJquery).find('select').andSelf().filter('select') .find('(option.placeholder OR option[value=""]):first) That is unfortunately not a valid sizzle (or CSS3) syntax - anyone know if there is a valid way to do this with selectors? Obviously I could write procedural code to find this for me, but I'm hoping for something a bit more slick Edit: To clarify, I do not think a comma simply works. Imagine the following <select> <option class="placeholder" value="0">Select Something</option> <option value="">Legitimate option that gets handled in JS</value> </select> In this case I want only the first selected, NOT both A: I have also run into an issue like this in the past and settled for something like this. $(selectorOrJquery).find('select').andSelf().filter('select') .find('option.placeholder, option[value=""]').eq(0); A: This will return the first option of a select that is either empty or has a class placeholder. $("select option:first").filter(":empty,.placeholder") A: Just use a comma, which is a valid CSS/jQuery Selector. $(selectorOrJquery).find('select').andSelf().filter('select') .find('(option.placeholder, option[value=""]):first) A: the css OR is the comma, so the selector you want would be 'option.placeholder:first, option[value=""]:first'
{ "language": "en", "url": "https://stackoverflow.com/questions/7585798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DMA copy in splice() I am new to linux kernel. And recently, i've went through the sendfile syscall in kernel 2.6.33. The following is the sequence of my journey: do_sendfile() => do_splice_direct() => splice_direct_to_actor() => do_splice_to() => do_splice_from() => splice_read,splice_write Throughout this sequence, I didn't find the place where splice use the DMA copy. So where is the DMA copying taking place? A: Splice doesn't do any DMA copy. In fact the major usage of splice is to avoid copying at all - it tries to pass references to memory pages instead of copying the buffers. The DMA mentioned in relation to splice will happen at the "leaf" - The origin of these pages that splice passes references to around will be created by, for example, a disk controller DMA into the buffer and will be sent by an Ethernet controller DMA of the content of the page as part of the packet - at least in a "perfect" zero copy sceanrio, which is difficult to achieve and rare. Splice doesn't do the DMA - it enables no copying between the first DMA to the last. A: As I understand it the splice_* infrastructure does it's very best to minimise the amount of actual copying that is done. At best the reader is reading from the same set of pages the writer is filling. There are some excellent articles on LWN describing the various bits of splice() including the new system call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: ios programming using uitextview as text editor I'm developing an application for ipad that works like a text editor where you can input text without any limitations into a uitextview. However the problem I have is that after a while when the text gets quiet large (about 20 pages) there is big lag when entering new characters. Is this a problem related to uitextview that can't handle large texts or is this just a limitation based on ipad hardware. Should I be using something else instead of an uitextview to input text? Thank you. A: you may try to cache in and out the UITextView yourself, then it will certainly become faster. I do not know any other object that is more suitable, since all the editing methods are already there. A: Maybe split things up into multiple UITextViews if the text gets too long?
{ "language": "en", "url": "https://stackoverflow.com/questions/7585813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem placing a button inside a MKAnnotationView I'm trying to put a little button in my AnnotationViews to show some info about some places on a map. Sounds super basic? Well. I must be an idiot then... I've looked at multiple examples, searched the whole internet, and I have ripped of 95% of my hair. It just doesn't work! -(MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)theAnnotation; { MKAnnotationView * annotationView = nil; if([theAnnotation class] == [MyAnnotation class]) { annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:theAnnotation reuseIdentifier:@"annotation"]; annotationView.canShowCallout = YES; annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; annotationView.enabled = YES; } return annotationView; } -(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control; { NSLog(@"push %@", control); } Can some one please tell me why calloutAccessoryControlTapped never gets called? I get a nice and pretty annotation, but when I tap the blue button it just closes. I have tried adding a target to the button, nothing. Please help me! PS: I know I should reuse old annotation view and stuff, but i stripped all code that wasn't necessary to be sure that there wasn't something else that was screwing thins up. A: Make sure you have correctly set the delegate responding to the MKMapViewDelegate Protocol. Also, make sure that all the views and superviews have userInterActionEnabled set to YES.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I host a WCF service in an existing ASP.NET application? The service has been debugged and is running in its own website. We already have the SSL certificate and DNS configured for the application. It would save some work if we could host the service in the application. Application is hosted and used behind our firewall. No public access at all . No cross domain security issues. Application and service will be hosted on the same server even if in different websites. That's the plan for now anyway. How do I do this? Or should I just consume the service from the website it’s currently hosted in? A: I would keep the service as a separate ASP.NET application. It allows for more flexibility. But if you wanted to do it, simply copy the .svc file, along with all the service and data contracts to the ASP.NET application and modify web.config to add the <services> section. Or if those data and service contracts are in a separate class library all you need is to reference this class library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Idiomatic functional way to move disc in Towers of Hanoi I am learning Scheme and as a toy example I am doing a solution verifier (not a solver) for Towers of Hanoi. I want to use a purely functional style (just to get into the mindset) and I represent the tower as a simple list of three lists. The starting state can look something like this: '((0 1 2 3 4) () ()) How would I implement a function that takes a state, a source index and a target index and returns the new state? In an imperative style this would be something trivial like: state[target].push(state[source].pop()) But every functional solution I can think of is terribly convoluted. For example: (define (makeMove state source target) (letrec ((recMake (lambda(tower pos disc) (if (null? tower) '() (cons (if (eqv? pos source) (cdr (car tower)) (if (eqv? pos target) (cons disc (car tower)) (car tower))) (recMake (cdr tower) (+ pos 1) disc)))))) (recMake state 0 (car (list-ref state source))))) This seems to work, but there must be a better way. I suppose a map would be somewhat better than recursion, but still too much. Would it be easier if I represented state differently? Also, feel free to criticize my code. I don't really know what I am doing. EDIT: If possible, I prefer that you not assume that the number of towers are always 3. A: Here's a super-straightforward way. I'm not sure what the significance of the disc "numbers" are in your implementation, but I made it behave the same as your answer does, pushing and popping them. (define (make-move state source target) (define (alter-tower tower index disc) (cond ((= index source) (cdr tower)) ; remove a disc ((= index target) (cons disc tower)) ; add a disc (else tower))) ; this tower wasn't changed (let ((disc (car (list-ref state source)))) (let ((s0 (alter-tower (list-ref state 0) 0 disc)) (s1 (alter-tower (list-ref state 1) 1 disc)) (s2 (alter-tower (list-ref state 2) 2 disc))) (list s0 s1 s2)))) If you assume the existence of a map-with-index function, which comes standard in many languages and libraries but is not built into Scheme, then you could roll up the bottom set of operations on each tower into a call to that, and it would be much cleaner. In general, try to come up with pure functions down to the lowest level possible which do what you want. In this solution, I invented a pure function "alter-tower" which can return the result of your command on a single tower, and that's what makes the rest of the solution very straightforward. Since you asked for feedback, I note that = is identical for eqv? when applied to numbers, that internal defines work in Scheme and act as you'd expect (e.g. you can call them recursively) and that the usual naming convention in Lisp is to separate multi-word identifiers with hyphens, instead of using camel-case. Good luck! EDIT: Here's a version, for example, that uses Racket's list comprehensions: (define (make-move state source target) (define (alter-tower tower index disc) (cond ((= index source) (cdr tower)) ; remove a disc ((= index target) (cons disc tower)) ; add a disc (else tower))) ; this tower wasn't changed (let ((disc (car (list-ref state source)))) (for/list ([(tower idx) (in-indexed state)]) (alter-tower tower idx disc)))) Many functional languages have a map that can take a predicate which consumes the index, so those two lines might instead look like: (map (lambda (tower idx) (alter-tower tower idx disc)) state) So depending on your Scheme dialect and libraries it might be different. (I don't think there's an SRFI for this, but I might be mistaken.) Or you could always write the above version of map yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I cancel an asynchronous operation in Silverlight/WCF? I am calling an asynchronous service from my Silverlight app and I want to be able to cancel that call after it is made. There is an option for e.Cancelled once the service has finished (i.e. If e.Cancelled Then), but how to you set that cancelled to true after you have called it? How do you cancel that asynchronous call? Let me clarify a bit... what I am trying to do is call the SAME method twice, one right after the other, and get the results of the last call into my collection. If I call an asynchronous method twice there is no guarantee that the second call will return first, so I may end up with the results of the first call coming in last and having the wrong results in my collection. So what I would like to do is cancel the first call when I make the second so I don't get results back from the first call. Seeing as how there is a Cancelled flag in the completed event args I figure you should be able to do this. But how? A: It's async... the transfer is passed off to a remote server and it does not return until the server is done with it. Basically the server will keep going, but you don't have to wait for the response. Disconnect your service completed event handler and pretend it was never called. That will give the effect of cancelling the operation. If you really need to cancel something in progress on the server you would need to make another call to the server to cancel the first call. Assuming the first call is a very slow one, this might be possible. Update (as question changed) In the case you specify, it will be up to the server to cancel a operation in progress if a second one comes through, not up to the client. e.Cancelled is set server-side. However... :) You have exposed a client usability issue. Shouldn't you also delay sending any service request until an idle delay has passed. That way rapid selections will not result in multiple service calls. Also... :> You may also want to send a sequence number to your service calls and return that as part of the result. Then you will know if it is the latest request or not. A: It sounds like what you really want to do is ignore the responses of all but the most recent call. Set a unique ID (could be request #, a Guid, timestamp, or whatever) with the request, and make sure the service sends that same value back. Keep around the ID of the most recent request and ignore response that don't match that ID. This will be safer than cancelling the first request, since if the service has already started sending the response before the cancel request happens, you still get your error condition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: 500KB json file parsed in Android environment I need to find a faster solution to parse a json file with 500KB. the structure is something like { "response": { "code": 0, "msg": "OK", "searchparameter": { "bikes": { … }, "cars": { "a":{ values[{...}] }, "b":{}, "c":{}, "d":{}, "e":{}, ... } } } } I tried gson.fromJson(jsontxt, Response.class), but it causes me like more than 5 mins to parse.. Is there any solutions that is suitable for me? How can I do JSONReader by gson in this case? and would it be helpful? any helps would be appreciated. thanks a lot!! A: Try using a streaming API: * *For Gson, https://sites.google.com/site/gson/streaming *Or switch to Jackson: Parsing huge JSON object in Android? A: you can use Gson itself but to make it useful try it in using Asyntask so you can tell the user to wait by showing progressDialog
{ "language": "en", "url": "https://stackoverflow.com/questions/7585825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android googledocs app component name I am planning to provide menus for my app similar to the sliding menu shown in the below image when clicking on the button in the list view. Could you give me some pointers on, how it can be achieved. Is it SubMenu ? http://static5.businessinsider.com/image/4db84baeccd1d58435080000/google-docs-for-android.jpg A: I got it, the behavior or pattern name is QuikActions. Useful introductory article for the beginners like me is available in the following link http://www.londatiga.net/it/how-to-create-quickaction-dialog-in-android/
{ "language": "en", "url": "https://stackoverflow.com/questions/7585827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SDL OpenGL C++ problem I'm trying to make a simple game of pong using SDL and OpenGL in C++ and I'm having trouble displaying any sort of OpenGL image onto the screen and was wondering if anybody could help: Initialization: void init_everything() { SDL_Init( SDL_INIT_EVERYTHING ); SDL_SetVideoMode( width_of_screen, height_of_screen, bpp_of_screen, SDL_OPENGL ); glClearColor( 0, 0, 0, 0 ); // Sets the projection glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho( 0, width_of_screen, height_of_screen, 0, 1, -1 ); // initalises the modelview matrix glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); SDL_WM_SetCaption( "Pong - By Michael Clover", NULL ); } After this I call the class function: void paddle::show() { //Move to offset glTranslatef( x, y, 0 ); //Start quad glBegin( GL_QUADS ); //Set color to white glColor4f( 1.0, 1.0, 1.0, 1.0 ); //Draw square glVertex3f( 0, 0, 0 ); glVertex3f( paddle_width, 0, 0 ); glVertex3f( paddle_width, paddle_height, 0 ); glVertex3f( 0, paddle_height, 0 ); //End quad glEnd(); //Reset glLoadIdentity(); } I then put this in my main function: int main( int argc, char **argv ) { bool quit = false; init_everything(); paddle playerpaddle; while (quit == false ) { while( SDL_PollEvent( &event ) ) { playerpaddle.handle_input(); if (event.type == SDL_QUIT) { quit = true; } } playerpaddle.move(); glClear( GL_COLOR_BUFFER_BIT ); playerpaddle.show(); SDL_GL_SwapBuffers(); } clean_up(); return 0; } All I get is a constant black background screen that I set within a 640 by 480px SDL screen. Sorry for the huge amount of text and I would be extremely grateful for any insight on what the problem could be here, I'm guessing I'm making a silly mistake somewhere. A: I think glOrtho might be set up wrong. The last 2 parameters are near and far clipping planes. Your near plane should be less than zero if you don't want to clip your paddle. And your far plane should be greater than zero. So try this: glOrtho( 0, width_of_screen, height_of_screen, 0, -1, 1 ); A: Just 2 things to check now that you've ruled out errors: * *Try removing the glTranslatef call. It may be too far off for you to see the scene. *Are you creating your vertices in a clockwise order? I can't tell by the variables you used, but if paddle_height is > 0 or paddle_width < 0, it's not going to be clockwise (which it needs to be). A: Try this for your projection instead (if you want 0,0,0 at your center). double range = 4.0; // Set this to whatever you want for the range of the display. double ratio = double(displayWidth) / double(displayHeight); glOrtho(-range* ratio, range* ratio, -range, range, -1.0, 1.0); Temporarily try to render a square from -1.0,-1.0 to 1.0,1.0 to see if your display is working.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CDN Images don't Load (OpenGraph) I setup in my wordpress blog OpenGraph. For image I insert this code (wordpress): http://dl.dropbox.com/u/21385868/codeog.jpg the result in site page (html is): http://dl.dropbox.com/u/21385868/resog.jpg if I share article on the facebook, image don't appear. But, if I disable my cdn, image appear on the facebook. What is the problem? A: In Advanced CDN settings add to Rejected User Agents FacebookExternalHit/1.1 FacebookExternalHit/1.0 A: Facebook blocks images that are hosted on CDNs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split only text on special characters, but not on numbers with decimal points I'm thinking about a special regexp problem in PHP, but I can't find an solution. I try to split some text into terms to get simple words, numbers and web addresses. So i decided to split on every non alphanumeric character ( \w ). To work with different languages, I use \w with additional letters, like Ää éèÈ and so on. Example: 20,000 15.20 This is at Text. Right?! www.google.com Jean Béraud Until now, i use the following regexp to split the text: [^\w(äÄüÜöÖßèé)] http://regexr.com?2uq98 Which works well in 80% of cases, but splits 20,000 into 20 and 000 also www.google.com into www google com So i tried to hold the numbers together, but still split on points, like Text. to get Text To match 15.20, the following works: (\d+\.\d+), but how do I combine the negation with the other regexp string? The following will not work: (\d+\.\d+)|[^\w(äÄüÜöÖßèé)]? And: how do I handle the web address? A: Something like this? $result = preg_split('/\W*\s+/', $string, NULL, PREG_SPLIT_NO_EMPTY); Demo, Result: array(10) { [0]=> string(6) "20,000" [1]=> string(5) "15.20" [2]=> string(4) "This" [3]=> string(2) "is" [4]=> string(2) "at" [5]=> string(4) "Text" [6]=> string(5) "Right" [7]=> string(14) "www.google.com" [8]=> string(4) "Jean" [9]=> string(7) "Béraud" } Q: Why does \w matches é in my example? A: That's based on the local of the system the PCRE library is used on, from the PHP Manual: A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w. Alternatively it might be helpful to specify the regex as working with UTF-8: $result = preg_split('/\W*\s+/u', $string, NULL, PREG_SPLIT_NO_EMPTY); Ensure $string is UTF-8 encoded. As UTF-8 is international, specific locale settings might not needed to be taken into account. Give it a try. A: Based upon the answer from @hakre and your example, I believe you should combine the two expressions in this way: $result = preg_split('/[^\wäÄüÜöÖßèé]*\s+[^\wäÄüÜöÖßèé]*/', $string, NULL, PREG_SPLIT_NO_EMPTY); Your original expression successfully matched the appropriate characters (the [^\w(äÄüÜöÖßèé)] part). The expression from @hakre added that there could be ANY NUMBER of these characters (even none of the characters) and should also be followed by one or more instances of whitespace (the \s+ part). When you combine the two ideas, you get [^\wäÄüÜöÖßèé]*\s+[^\wäÄüÜöÖßèé]*, which basically translates to any number of characters that are not in this character class, followed by at least one whitespace character, then possibly followed by any number of characters that are not in this character class or one or more whitespace characters, and any number of characters that are not in this character class, either before or after As a test, I used this text sample (I assume you want to match French characters): 20,000 15.20 This is at Text. Right?! www.google.com Comme son élève, où dois-je aller voir Jean Béraud? and this regular expression: EDITED /[^\wßàâäèéêëîïôöœùûüÿç]*(^|$|\s+)[^\wßàâäèéêëîïôöœùûüÿç]*/i through the same site that @hakre used: http://codepad.viper-7.com/MqztVt END EDIT This test showed that the expression will split even if the word begins or ends with one of the special characters. I added the /i switch at the end of the expression to make the match case-insensitive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Connecting 2 Textboxes values temporarily I want to create 2 Textboxes (txt1, txt2) and when I write in txt1 then txt2 should reflect the same text what i typed in txt1. For ex. When we create a new Solution in Visual Studio Professional, what name we give to Project, same name appears for Solution. But if we edit solution name, link between the 2 textboxes breaks. I do have some idea about it, to do it with textChange event or in fact many similar events, but not sure that they are the best methods. I am using Winforms, C# 4.0, Visual Studio 2010 (if this info matters) If my question is not clear, just make a comment I will try to elaborate. Thanks. A: Consider adding an event handler for txt1_TextChanged and txt2_KeyPress. txt1_TextChanged would assign txt2.Text: txt2.Text = "c:\" + txt1.Text; txt2_KeyPress would unsubscribe txt1_TextChanged: txt1.TextChanged -= txt1_TextChanged;. A: With the given definition of the requirement, adding TextChanged EventHandlers is the way to go. private void txt1_TextChanged(object sender, EventArgs e) { txt2.Text = txt1.Text; } private void txt2_TextChanged(object sender, EventArgs e) { txt1.Text = txt2.Text; } A: I solved it, so thought to post it here txt1_TextChanged(obje....) { txt2.Text = txt1.Text; } txt2_TextChanged(objec...) { if(txt2.Focused) { txt1.TextChanged -= new EventHandler(txt1_TextChanged); } } Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTTP ETag reproduction Having recently discovered problems relating to the HTTP ETag and our CDN I've tried to capture some in Fiddler for well known sites. However it appears that whatever combination of browser / website I use I'm not seeing any pass by. Is there any reason for this? Can you suggest a combination in which I can see them? Perhaps they're not widely used anymore? A: They are definitely widely used, I've used it myself often. The most common usecase is conditional requests (always check if there's new content, but only send the content back from the server if it has changed). However, Last-Modified can also do this instead and it's not needed if you don't force the browser to always check for new content (no must-revalidate). The reason your CDN isn't using them is one of the following: * *They are using Last-Modified instead *They don't force a revalidation and set an expiry time well in the future *They couldn't determine a ETag for a particular piece of content *Misconfiguration
{ "language": "en", "url": "https://stackoverflow.com/questions/7585853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JQuery / XML - problem with & character in XML attribute I'm trying to parse an XML document that has an attribute called "link" which provides a URL string. The problem is, whenever the URL string includes an & symbol - for example: http://www.site.com/segment/page.html#/?view=viewName&model=4 The xml parsing breaks and won't parse anything beyond this node. Here's my code: parseVehicles: function(xmlNode) { $j(xmlNode).children().each(function() { console.log(supertree.vehicleCount); supertree.vehicleCount++; }); }, How do I keep this from breaking? A: If your XML looks like this: <foo link="http://www.site.com/segment/page.html#/?view=viewName&model=4" /> Then that's simply invalid XML. The & should be escaped: <foo link="http://www.site.com/segment/page.html#/?view=viewName&amp;model=4" /> Fix whatever's creating the invalid XML.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to view and remove cron jobs in drupal 7 I'm new to drupal 7 and I need to see what cron is running. I had a cron Feeds scheduled to run once a day and it is no longer needed. I deleted the feed but the cron is still running. Thanks A: Drupal has an auto-cron implementation, to disable it go to mysite.com/admin/config/system/cron and set 'Run cron every' to 'Never'. If that doesn't work check there are no lingering jobs scheduled in your server's crontab. Hope that helps EDIT Just to add, you can't 'see' what jobs are running in Drupal as such because there is only one - the job you can cancel by setting the afore-mentioned setting to 'Never' A: Use for this module ultimate_cron you may read extended log message and control of all cron jobs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with id tweet, when tweet has been delete (Jtwitter) My code is: for(int i=0;i<listTweetId.size();i++){ if((status = twitter.getStatus(listTweetId.get(i)))!=null){ ... My problem is that exist some tweetId into listTweetId that are Id of tweets deleted and I don't know how it verify, because my if not works for this case. Finally in this case it spears a error, that is follows : Exception in thread "main" winterwell.jtwitter.TwitterException$E404: Not Found HTTP/1.1 404 Not Found {"error":"No status found with that ID.","request":"/1/statuses/show/112779914381492224.json?include_entities=1&"} P.S.: Tweets are not empty A: I'm not entirely sure what your question is, but if the issue is that getting the status for a non-existent tweet throws an exception, you need to wrap that part in a try/catch to avoid dropping out of the loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to fetch rss feed month wise from other website I have a question regarding RSS feeds. I am using wordpress ver 3.2.1 and using other website rss feeds in my website. My requirement is to fetch the feeds month wise and to show in my website side bar. Currently i am using rss widget and showing the feeds in sidebar but they are coming in below format: * *Thu 9-29 4:30pm Elementary Quest - Parent Information Night *Thu 10-6 -All Day- Half-Day: Elementary Conferences I will be very thankful for your help. Thanks in advance. Update: Mar 13 2012 This code is present in index.php <h2><?php _e('Recent news from Some-Other Blog:'); ?></h2> <?php // Get RSS Feed(s) include_once(ABSPATH . WPINC . '/feed.php'); // Get a SimplePie feed object from the specified feed source. //$rss = fetch_feed('http://example.com/rss/feed/goes/here'); $rss = fetch_feed('http://lakewashington.intand.com/index.php?type=export&action=rss&schools=48&groups=884,876,874,996'); print_r($rss); if (!is_wp_error( $rss ) ) : // Checks that the object is created correctly // Figure out how many total items there are, but limit it to 5. $maxitems = $rss->get_item_quantity(5); // Build an array of all the items, starting with element 0 (first element). $rss_items = $rss->get_items(0, $maxitems); endif; ?> <ul> <?php if ($maxitems == 0) echo '<li>No items.</li>'; else // Loop through each feed item and display each item as a hyperlink. foreach ( $rss_items as $item ) : ?> <li> <a href='<?php echo esc_url( $item->get_permalink() ); ?>' title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'> <?php echo esc_html( $item->get_title() ); ?></a> </li> <?php endforeach; ?> </ul> A: You can do it manually. Just use wordpress native function fetch_feed. You even have an example in there: <h2><?php _e('Recent news from Some-Other Blog:'); ?></h2> <?php // Get RSS Feed(s) include_once(ABSPATH . WPINC . '/feed.php'); // Get a SimplePie feed object from the specified feed source. $rss = fetch_feed('http://example.com/rss/feed/goes/here'); if (!is_wp_error( $rss ) ) : // Checks that the object is created correctly // Figure out how many total items there are, but limit it to 5. $maxitems = $rss->get_item_quantity(5); // Build an array of all the items, starting with element 0 (first element). $rss_items = $rss->get_items(0, $maxitems); endif; ?> <ul> <?php if ($maxitems == 0) echo '<li>No items.</li>'; else // Loop through each feed item and display each item as a hyperlink. foreach ( $rss_items as $item ) : ?> <li> <a href='<?php echo esc_url( $item->get_permalink() ); ?>' title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'> <?php echo esc_html( $item->get_title() ); ?></a> </li> <?php endforeach; ?> </ul> You just need to put that in your sidebar.php, wherever you need to show the feed. Edit the line: $rss = fetch_feed('http://example.com/rss/feed/goes/here'); ...and point the url to the correct feed. And: $maxitems = $rss->get_item_quantity(5); ...to specify how many items to show (five in the example) Then check the foreach inside the UL, there you can style how the feed are shown. By default, fetch_feed function will cache the feeds for 12 hours. If you need to do it every 30 days, you can use the wordpress's Transients API to accomplish that without hassle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do i get different information in a field based on what i select in a dropdown menu? I want to add this functionality to my form. when a option from a dropdown menu is selected i want it to input the text field above with the corresponding info. For example: <form name="form1" action="formhandler"> <input type="text" name="typecar"> <select name="BMWCars"> <option value="Sedan">Sedan</option> // when this option is chosen put string "5-series" in textfield above <option value="Convertible">Convertible</option> // when this option is chosen put string "6-series" in textfield above <option value="Truck">Truck</option> // when this option is chosen put string "X5" in textfield above <option value="Coupe">Coupe</option> // when this option is chosen put string "3-series" in textfield above <option value="Hatchback">Hatchback</option> // when this option is chosen put string "5-series GT" in textfield above </select> </form> How can this be done with and without having to connect to the to get strings? A: The code is tidier if you make your HTML conform to what you need. http://jsfiddle.net/TgM2W/3/ <form name="form1" id="form1" action="formhandler"> <input type="text" name="typecar" id="typecar"> <select name="BMWCars" id="BMWCars"> <option value="">Select one...</option> <option value="5-series">Sedan</option> <option value="6-series">Convertibles</option> <option value="X5">Truck</option> <option value="3-series">Coupe</option> <option value="5-series GT">Hatchback</option> </select> </form> JavaScript (without jQuery): window.onload = function() { document.forms['form1'].elements['BMWCars'].onchange = function() { var opts = this.options; document.forms['form1'].elements['typecar'].value = opts[opts.selectedIndex].value; }; }; or using jQuery: $(document).ready(function() { $('#BMWCars').change(function() { var opts = $(this)[0].options; $('#typecar').val(opts[opts.selectedIndex].value); }); }); However, if you can't change the HTML, just use an object to store the values and reference that: objBMW = { "Sedan":"5-series", "Convertible":"6-series", "Truck":"X5", "Coupe":"3-series", "Hatchback":"5-series GT" }; window.onload = function() { document.forms['form1'].elements['BMWCars'].onchange = changer; }; function changer() { var opts = this.options; document.forms['form1'].elements['typecar'].value =objBMW[opts[opts.selectedIndex].value]; }; A: Jan. This is what you have to do: * *Add identifier to all your referenced items in the HTML. *Write an small Javascript code to detect changes in the dropdown and update the textfield accordly. <form name="form1" action="formhandler"> <input type="text" name="typecar" id="typecar" /> <select name="BMWCars" id="dropdown"> <option value="5-series">Sedan</option> <option value="6-series">Convertible</option> <option value="X5">Truck</option> <option value="3-series">Coupe</option> <option value="5-series GT">Hatchback</option> </select> </form> <script type="text/javascript"> var dropdown = document.getElementById( 'dropdown' ); dropdown.onchange = function() { document.getElementById( 'typecar' ).value = dropdown.value; }; </script> A: You're going to want to do it in jQuery (or javascript). $("option").change(function() { var value; //Do some logic to get the value you want to put in the textbox $("input[name='typecar']").val(value); }); Depending on the complexity of your site, there's a couple different ways you can grab the value to put in your textbox. If it will only ever be those 5 options, I would suggest a switch...case. Like this: $("option".change(function() { var value; switch($(this).val()) { case "Sedan": value = "5-series"; break; case "Convertible": value = "6-series"; break; case "Truck": value = "X5"; break; case "Coupe": value = "3-series"; break; case "Hatchback": value = "5-series GT"; break; } $("input[name='typecar']").val(value); }); A: $('select').change(function() { var value = $(this).val(); $("#typecar").val(value); }); Should do it. Add an ID of typecar to your input field first however.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's a recommended way to put CouchDB views under source control? I'm writing a node CRUD app that requires a few CouchDB views (I'm using express and cradle). I've got the node app itself controlled with git, but my DB views are currently uncontrolled. What's the recommended way to put these under source control? I don't want to put the entire database (including data) under source control. A: Take a look at couchapp, http://couchapp.org/. You can use that to push your version-controlled design docs to a database. A: Maybe useful: also CouchApp may push some docs in db. For example, doc(s) of configure or demo. For that put file in folder '_docs' (the same level with 'lists', 'shows', etc.) in JSON format. File: 'any-configure.json' { "_id": "any-configure", "fieldA": "...", "fieldB": "...", ... } A: As pointed, using couchapp could make it easier to work with design documents. I have implemented a similar approach in a Java project, an example here and the class that manages these documents.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Upgrading Android application data with multiple tables (without destroying unaffected tables) In my Android application; I have a single database with multiple tables. Each table is more-or-less separate from each other, but figured (for best practice?) to just have one DB file. When it comes to Upgrades, it's currently an all or nothing affair. On upgrade, it "DROP"'s all the tables and re-creates them. However, this is rather harsh if only one of the tables has changed as all the other tables' data is also lost. Is there a built-in way to auto-upgrade just the tables that have changed? (e.g. using a version number per/table?) If not, I guess I can see two options: * *Use separate databases/files for each table, to use built-in version upgrade functionality. *Use the database version number to know when the "schema" has changed, but have a separate table to store the current TABLE_VERSIONS and manage my own upgrade by checking the version number of each table against the current build and DROP/CREATE Tables where needed. (I'd rather not re-invent the wheel here, so I'm hoping I'm missing something simple...) A: You need an abstract class that implements the upgrade process described here. Then you extend this abstract class for each of your tables. In your abstract class you must store you tables in a way(list, hardcoded) so when the onUpgrade fires you iterate over the table items and for each table item you do the described steps. They will be self upgraded, keeping all their existing details. Please note that the onUpgrade event fires only once per database, that's why you need to iterate over all your tables to do the upgrade of all of them. You maintain only 1 version number over all the database. * *beginTransaction *run a table creation with if not exists (we are doing an upgrade, so the table might not exists yet, it will fail alter and drop) *put in a list the existing columns List<String> columns = DBUtils.GetColumns(db, TableName); *backup table (ALTER table " + TableName + " RENAME TO 'temp_" + TableName) *create new table (the newest table creation schema) *get the intersection with the new columns, this time columns taken from the upgraded table (columns.retainAll(DBUtils.GetColumns(db, TableName));) *restore data (String cols = StringUtils.join(columns, ","); db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s from temp_%s", TableName, cols, cols, TableName)); ) *remove backup table (DROP table 'temp_" + TableName) *setTransactionSuccessful (This doesn't handle table downgrade, if you rename a column, you don't get the existing data transfered as the column names do not match). . public static List<String> GetColumns(SQLiteDatabase db, String tableName) { List<String> ar = null; Cursor c = null; try { c = db.rawQuery("select * from " + tableName + " limit 1", null); if (c != null) { ar = new ArrayList<String>(Arrays.asList(c.getColumnNames())); } } catch (Exception e) { Log.v(tableName, e.getMessage(), e); e.printStackTrace(); } finally { if (c != null) c.close(); } return ar; } public static String join(List<String> list, String delim) { StringBuilder buf = new StringBuilder(); int num = list.size(); for (int i = 0; i < num; i++) { if (i != 0) buf.append(delim); buf.append((String) list.get(i)); } return buf.toString(); } A: If you're using the Android SQLite helper classes (i.e. SQLiteOpenHelper) then you only have one version number representing the database schema. Personally, I put all the schema creation code in my instance of SQLiteOpenHelper and keep the upgrade logic simple: @Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) { // Alter all the tables so the schema is brought up-to-date. if (oldVersion < newVersion) { db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER NOT NULL"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7585878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error publishing Website VS 2005 I'm trying to publish a ASP.NET Website using VS 2005 and i am running into some trouble. The Publish always fails and it does not present any error messages. The Output is as follows: ... Publishing folder bin/pt/_vti_cnf... Publishing folder bin/ru... Publishing folder bin/ru/_vti_cnf... Publishing folder bin/tr-TR... Publishing folder bin/tr-TR/_vti_cnf... Publishing folder bin/zh-CHS... Publishing folder bin/zh-CHS/_vti_cnf... Publishing folder bin/zh-CHT... Publishing folder bin/zh-CHT/_vti_cnf... Publishing folder bin/_vti_cnf... ========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ========== ========== Publish: 0 succeeded, 1 failed, 0 skipped ========== The error list is empty (some warnings but as long as they are warnings it should be ok, right?) and i have no idea what might be causing the error. Can anyone shed some light over this? UPDATE: I deleted all the vti_cnf folders and it didn't change anything. At least with success. The message is now: Publishing folder bin/ru... Publishing folder bin/tr-TR... Publishing folder bin/zh-CHS... Publishing folder bin/zh-CHT... ========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ========== ========== Publish: 0 succeeded, 1 failed, 0 skipped ========== Inside this zh-CHT folder there's only a Ajax Control Toolkit .dll as in zh-CHS folder and tr-TR and so on. A: It is possible a file is read only, locked by the OS, or a security rights issue. Try publishing to another folder and see if you still get that same error. A: Check the things below; * *If your target folder is opened in anywhere ( because windows can't write data in opened folders) *If you published it before there will be files in obj folder delete them and republish Hope that helps. A: I'm concerned about the _vti_cnf folders. Those are typically configuration files for front page and have absolutely no reason to be deployed out of visual studio. At the very least you need to exclude those from your local project or, better yet, flat out delete them (again, from local). If you are not using FrontPage extensions, which I highly recommend you turn off anyway, then delete them from the server as well and have frontpage extensions disabled. There are MANY much better ways of deploying a site. Note, Dreamweaver also uses FP extensions for deployment. However, those files are also not stored locally as they have no place in your application. Most likely the problem is simply that you are trying to overwrite server files that you have no reason to actually be publishing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: splitting a string in VB I have a ComboBox which I assign to a variable: Dim var as String = ComboBox1.SelectedValue Dim name As String = var.Split(",") This gives me the error Value of type '1-dimensional array of string' cannot be converted to String Any ideas as to where I'm going wrong? A: Split returns an array of strings. Your variable needs to be changed to an array, not just a single string. A: name needs to be declared as an array. dim name() as string = var.split(",") The split() method will break up the string based on the given character and put each newly created string into an array and return it. This is what your error message is telling you: Value of type '1-dimensional array of string' cannot be converted to String The method returns an array of string, but your trying to put it into just a string! EDIT: In response to your answer... So far you've managed to split the string yourself with the split method. To output this to your message box, you need to concatenate the two elements in the proper order: msgbox(name(1) & " " & name(0)) Notice I indexed the array twice! Element 1 is the first name, element 0 is the last name. Remember you got this name in lname,fname format. Passing the array itself doesn't make sense! Remember, a datatype is not equal to an array of that type, they are two different things. Therefore a string is not compatible with a string array. However, each individual element of the array is a string, and so each of those are compatible with the string type (because they're the same thing)! A: My VB is a bit rusty, but I think you have to make name an array: Dim name() As String = var.Split(",") A: Dim var As String = ComboBox1.SelectedValue Dim temp() As String = Split(var, ",", -1, CompareMethod.Binary) Dim name As String = temp(0) A: Or maybe "name" isn't an array and the goal is to populate "name" with everything up until the first comma, in which case the fix would be: Dim name as String = var.Split(",")(0) Note: assumes that var is not Nothing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I get rid of this nasty query in my Rails view template? Yuck. It's bringing me down. In my controller: @assessor = Assessor.find(params[:id]) @assessor.answers.build if @assessor.answers.empty? In my view: = simple_form_for @assessor do |f| - @assessor.candidates.each do |candidate| - @assessor.assessment_competencies.each do |competency| - if @assessor.answers.all?{|a| a.new_record?} - competency.behaviors.each do |behavior| = f.fields_for :answers do |f| - @assessor.standard_answer_choices.each do |choice| = f.input :assessor_id, :as => :hidden, :input_html => {:value => @assessor.id} = f.input :candidate_id, :as => :hidden, :input_html => {:value => candidate.id} = f.input :behavior_id, :as => :hidden, :input_html => {:value => behavior.id} = f.input :competency_id, :as => :hidden, :input_html => {:value => competency.id} = f.association :answer_choice, :collection => [choice], :as => :radio - else - competency.behaviors.each do |behavior| - answer = Answer.find_or_create_by_behavior_id_and_assessor_id_and_candidate_id(behavior.id, @assessor.id, candidate.id) = f.fields_for :answers, answer do |f| = f.input :assessor_id, :as => :hidden, :input_html => {:value => @assessor.id} = f.input :candidate_id, :as => :hidden, :input_html => {:value => candidate.id} = f.input :behavior_id, :as => :hidden, :input_html => {:value => behavior.id} = f.input :competency_id, :as => :hidden, :input_html => {:value => competency.id} = f.association :answer_choice, :collection => [choice], :as => :radio A: Oof, that is a gnarly one. At the very least you can yank that repeated fields_for block out into a helper: module AssessorsHelper def answers_fields f, candidate, behavior, competency, answer=nil assessor = f.object f.fields_for :answers, answer do |f| f.hidden_field :assessor_id, :value => assessor.id f.hidden_field :candidate_id, :value => candidate.id f.hidden_field :behavior_id, :value => behavior.id f.hidden_field :competency_id, :value => competency.id f.association :answer_choice, :collection => [choice], :as => :radio end end end That'll cut your view down to this: = simple_form_for @assessor do |f| - @assessor.candidates.each do |candidate| - @assessor.assessment_competencies.each do |competency| - if @assessor.answers.all?{|a| a.new_record?} - competency.behaviors.each do |behavior| = answers_fields f, candidate, behavior, competency - else - competency.behaviors.each do |behavior| - answer = @assessor.answers.find_or_create_by_behavior_id_and_candidate_id behavior, candidate = answers_fields f, candidate, behavior, competency, answer If you wanted you could break it down into a helper for each inner loop, but you get the idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: looking for a slight variant of GROUP BY I have a table like so: id attr 1 A 2 A 3 C 4 C 5 D 6 F I want a count of all the A's B's (but not the C's D's, etc..) Note that my table has zero B's. So I want a command like this: SELECT count(attr=A, attr=B) FROM table; or this: SELECT count(*) FROM table GROUP_BY attr IN (A, B); and get: attr count A 2 B 0 My actual table has about a thousand attrs. I want to do a group_by-ish thing on maybe a hundred or so of them. It's important that i get the count of zero for certain attrs and that i can correlate the attr to the count. I know this is a basic question and I'm not surprised if this has been asked before. I searched.. But my apologies anyway.. A: SELECT T.attr, COUNT(Y.id) FROM (SELECT 'A' AS attr UNION ALL SELECT 'B') AS T LEFT JOIN YourTable Y ON Y.attr = T.attr GROUP BY T.attr A: This should work for you. SELECT T.Attr,Count(A.ID) FROM ( SELECT CONVERT('A',char) AS Attr UNION SELECT CONVERT('B',char) AS Attr ) AS T LEFT JOIN MyTable AS A ON T.Attr=MyTable.Attr GROUP BY T.Attr ORDER BY T.Attr; The Convert part may not be necessary but was necessary in my testing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to select date from date fileds using watin framework Can any one tell me how to select a date in these date fields automatically by using WatiN (http://www.meanfreepath.com/javascript_calendar/livedemo.html) I have given this site as an example. I have tried to select a random date as foreach (SelectList sl in lists) { OptionCollection oc = sl.Options; temp = random.Next(oc.Count); oc[temp].Select(); } It doesn't work as date fields are not selection lists first of all date fields are not selection lists Is there any other way to solve this puzzle by clicking on the date field an selecting a random value from it? A: You've got a couple options: You can use the Filter method or do a for loop through all the tablecells. I'll be using Filter below as it takes fewer lines of code. Looking through the code for the Calendar, you should see it is a basic HTML table and that the cells are well defined by CSS classes. Goal of the example Pick a random day in the current month Pseudocode * *Go to the page *Figure out the number of days in the current month *Generate a random number base on the number of days in the month *Pick the day by filtering on the CSS class and the expected text being the random number Actual Code Settings.HighLightElement = false; //If you don't do this, the calendar colors won't work correctly. ie = new IE(true); ie.GoTo("http://www.epoch-calendar.com/javascript_calendar/livedemo.html"); ie.Table("bas_cal_calendar").WaitUntilExists(5); int totalDaysInMonth = ie.Table("bas_cal_calendar").TableCells.Filter(Find.ByClass(new Regex(@"wkday|wkend|wkday\scurdate"))).Count; Random random = new Random(); int randomDay = random.Next(1,totalDaysInMonth + 1); ie.Table("bas_cal_calendar").TableCell(Find.ByClass(new Regex(@"wkday|wkend|wkday\scurdate")) && Find.ByText(randomDay.ToString())).Click(); Note: I'm guessing the CSS class when the current date is a weekend day would be wkend curdate. This would need to be verified and RegExs updated as needed. Note: After you click on a day, the CSS class changes to *cell_selected*. The above is tested and good using WatiN 2.1 and IE8
{ "language": "en", "url": "https://stackoverflow.com/questions/7585893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaScript library for logic programming Do you know of any good javascript library for logic programming? I'm interested in something like jsprolog, but I want to use javascript to communicate with the lib, and not a different language (such as prolog in this case). Many thanks. A: In addition to jsprolog, there are several JavaScript libraries for logic programming: * *chr.js is a constraint logic programming library for JavaScript. It is an implementation of the Constraint Handling Rules programming language. *There are several JavaScript implementations of Datalog such as DataScript. *Yield Prolog allows Prolog programs to be embedded directly in JavaScript. This is especially useful because it allows JavaScript functions to be used in Prolog predicates, and vice-versa. *LogicJS is a JavaScript library that is based on MiniKanRen, which has been implemented in many programming languages, including JavaScript. *JavaScript-Logic-Programming-System is another logic programming system for JavaScript. *There is another Prolog implementation that was written in less than 200 lines of JavaScript code. Of course, there are also several C++ libraries for logic programming that could be automatically ported into JavaScript using Emscripten. A: There are a bunch of other languages that compile to javascript: https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS It is possible (although not probable!) one of those has a javascript friendly API AND a suitable library that can by "compiled" into JavaScript. Exactly what you aren't looking for, and probably a time waster :) A: Please check out (JSL) https://www.npmjs.com/package/lib-jsl. From the overview document, JSL is a JSON based logic programming library meant for embedded use in JS programs. It uses JSON as its syntax as well as I/O method A: There is a new tool, a generic compiler adding any effect to JS, including logic programming, there is an example of prolog append: https://github.com/awto/mfjs-samples/tree/master/unify
{ "language": "en", "url": "https://stackoverflow.com/questions/7585903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Understanding a Big and Complicated ASP.NET Web Application You might not like these kinds of questions, but I rely on the professionalism of StackOverFlow. I have a very big ASP.NET web application, it contains many projects, a container (father) project, and multiple module projects. Obviously it's connected to a big SQL Server database as well. This application doesn't have a specific documentation. Is there a way (special tools, advices...) that would help me in understanding the functionality of the application gradually? I meant by special tools, those that might be representing the structure of the system in diagrams or so. I cannot find a way to start with. Note: I'm using Visual Studio 2010, the application is built using .NET 3.5 Thank you for your opinions. A: Personally, I usually prefer to start by looking at the database design. Depending on how it was set up, you should be able to create a database diagram which will show you all of the relationships between the tables. Once you have a grasp of the database design, you should have a basic understanding of what the system is doing, which should give some context to the different processes and work flows throughout the web application. If the application has a Sitemap, I would examine it throughly, as it should help you to better understand the flow of the application. If available, you should also look at the class diagram to see how the different classes relate to one another. Without any kind of documentation, you'll probably have to use bits and pieces to understand how the application works. I'm not sure, but there may be some plugins available that can help you with this. Something like CodeRush or Resharper might be helpful. There's also a plugin called GhostDoc that might come in handy too. Hope this helps. A: Visual studio 2010 has architectural analysis it can perform on your projects with the ultimate version. This can help you in understand the app, what crosses layers, etc. See: http://msdn.microsoft.com/en-us/gg465276 http://www.slideshare.net/bgervin/visual-studio-2010-ultimate-architecture-experience-toronto-code-camp-2010-barry-gervin A: You can have a look at this MSDN page, which will show you how to generate a UML diagram from your codebase. This will give you a rough overview of how things fit together, and what communicates with what (I haven't used this tool so I'm unsure of how much information is provided, or whether it is configurable). Also, make sure you ask your teammates, or anybody else who has worked on this application before (there have to be a few such people around if it's such a huge project). They should definitely make the time to explain things to you, or at least answer specific questions you have.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSV Writer writing over itself I am trying to create a CSV file with a list of URLs. I am pretty new to programming, so please excuse any sloppy code. I have a loop that runs through a list of places to get the list of URLs. I then have a loop within that loop that exports the data to a CSV file. import urllib, csv, re from BeautifulSoup import BeautifulSoup list_of_URLs = csv.reader(open("file_location_for_URLs_to_parse")) for row in list_of_URLs: row_string = "".join(row) file = urllib.urlopen(row_string) page_HTML = file.read() soup = BeautifulSoup(page_HTML) # parsing HTML Thumbnail_image = soup.findAll("div", {"class": "remositorythumbnail"}) Thumbnail_image_string = str(Thumbnail_image) soup_3 = BeautifulSoup(Thumbnail_image_string) Thumbnail_image_URL = soup_3.findAll('a', attrs={'href': re.compile("^http://")}) This is the part that isn't working for me: out = csv.writer(open("file_location", "wb"), delimiter=";") for tag in soup_3.findAll('a', href=True): out.writerow(tag['href']) Basically the writer keeps on writing over itself, is there a way to jump to below the first empty row on the CSV and start writing? A: Don't put this inside any loop: out = csv.writer(open("file_location", "wb"), delimiter=";") Instead: with open("file_location", "wb") as fout: out = csv.writer(fout, delimiter=";") # put for-loop here Notes: * *open("file_location", "wb") creates a new file, destroying any old file of the same name. This is why it looks like the writer is overwriting old lines. *Use with open(...) as ... because it automatically closes the file for you when the with-block ends. This makes explicit when the file is closed. Otherwise, the file remains open (and maybe not completely flushed) until out is deleted or reassigned to a new value. It's not really your main problem here, but using with is too useful not to mention. A: Are you closing the file after every write, or opening the file before every write? Just check that. Also, try using "ab" mode instead of "wb". "ab" will append to the file. A: The open("file_location", "wb") call, which you are doing once for every URL, is wiping out what you did to that file previously. Move it outside your for loop so that it is only opened once for all the URLs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Connect to Team Server on launch of VS? I deal with multiple Team Foundation Servers and collections. Is there a command line I can send to VS so I don't have to manually switch between the TFS servers every time I launch VS? A: The way I do it is use the start page from Visual Studio. It lists my recent projects and you can even pin them so they do not scroll out of view when you do not use them for a while. Activating a project from the start page will automatically connect your Visual Studio environment to the correct TFS collection, because the solution you open is bound to one of them. Works like a charm!
{ "language": "en", "url": "https://stackoverflow.com/questions/7585910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Help with Date Conversion in JavaScript I have a string in the format MM/DD/YYYY. Can someone tell me how to convert it to: January 1, 2011? A: If you haven't already, check out date.js - http://www.datejs.com/ It's great for any date related functions, and has tons of examples on their site to do everything you can imagine. Update: Ok some people doubt my mad coding skillz :) <script src="http://www.datejs.com/build/date.js" type="text/javascript"></script> <script language="Javascript"> var d = Date.parse('03/08/1980'); window.alert(d.toString('MMMM d, yyyy')); </script> A: var str = "01/01/2011", date = new Date(str), months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], converted = months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear(); See it in action. A: var str = "1/1/2011"; var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var parts = str.split("/"); var formatted = monthNames[parseInt(parts[0], 10)-1] + " " + parts[1] + ", " + parts[2]; A: I hope this helps var dat = new Date("01/01/2011"); var monthNames = [ "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December" ]; var stringDate = monthNames[dat.getMonth()] + ", " + dat.getDate() + ", " + dat.getFullYear(); A: I wrote a date library similar to DateJS, only it's smaller, faster, and doesn't modify the Date.prototype. It handles parsing, manipulating, and formatting, including timeago. I see that you only need english, but there is support for i18n in underscore.date. https://github.com/timrwood/underscore.date With underscore.date, this is how you would solve your problem. _date('01/01/2011', 'MM/DD/YYYY').format('MMMM D, YYYY');
{ "language": "en", "url": "https://stackoverflow.com/questions/7585912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to redirect to paypal with Soap instead of Simple Form I have my own shopping cart. When the client click on Submit Order, I Redirect the user to paypal page where the client will be able to pay the order. Here is my form <form name="paypalform" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_cart"> <input type="hidden" name="upload" value="1"> <input type="hidden" name="invoice" value="<? echo $idInvoice; ?>"> <input type="hidden" name="business" value="aa_aaa_biz@hotmail.com"> <input type="hidden" name="notify_url" value="http://domaine.com/catalog/IPNReceip"> <? $cpt = 1; foreach($ordering as $k => $v) { ?> <input type="hidden" name="item_number_<? echo $cpt?>" value="<? echo$v->Product->id; ?>"> <input type="hidden" name="item_name_<? echo $cpt?>" value="<? echo$v->Product->ProductNumber; ?>"> <input type="hidden" name="quantity_<? echo $cpt?>" value="<? echo $v->Qty; ?>"> <input type="hidden" name="amount_<? echo $cpt?>" value="<? echo $v->Price ?>"> <? $cpt++; } ?> <input type="hidden" name="currency_code" value="CAD"> <input type="hidden" name="tax_cart" value="<? echo $taxes;?>"> <input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - it's fast, free and secure!"> </form> I would like to do the samething but within the code behind. Somebody have an idea. I don't want to use form anymore to redirect to paypal. Thanks A: The first thing you'll want to decide is decide which products suits you best. What you describe, would be easiest to accomplish with Express Checkout. Express Checkout consists of three API calls: SetExpressCheckout, GetExpressCheckoutDetails and DoExpressCheckoutPayment. * *SetExpressCheckout prepares the transaction and returns a token. You must take this token from the API response and append it to a url to which you'll redirect the buyer. *Once the buyer has agreed to the purchase on the PayPal page, he/she is redirected back to the URL you specified in the RETURNURL parameter of the SetExpressCheckout API call. *On this return page, you need to call GetExpressCheckoutDetails or (optionally) look at 'PayerID' in the $_GET array for the return URL. *Once you have the token and the PayerID; either through GetExpressCheckoutDetails or as part of the GET data, call DoExpressCheckoutPayment to finalize the payment. This can be accomplished on the same return page, or can be actioned after the buyer clicks a 'Buy now' button on your return page. See also the general Express Checkout page on X.com, Getting Started with Express Checkout and the Express Checkout Integration Guide (PDF). Some sample code for SetExpressCheckout, GetExpressCheckoutDetails and DoExpressCheckoutPayment is available on https://www.x.com/developers/PayPal/documentation-tools/code-sample/78 as well. Hope this helps! Let me know if anything is unclear. A: Robert's answer is a great option - Express Checkout cannot be altered because its server to server and users need your API credentials - but if you want to stick with Website Payments Standard (WPS) see below: Your concern is that your button can be tampered with. Yes this is possible if the buttons on your website are unhosted/unencrypted buttons. There are tools (like tamper data) that edit HTTP POST's before they are sent to the receiving address, or users can download the HTML form and alter it, then click the button (the referring URL would be different, but could be spoofed); unencrypted buttons are vunerable. I would advise either using one of the options below to prevent this from occurring in the future: * *The button manager API to create dynamic hosted buttons for payments *Create and use hosted buttons *Create and use encrypted website payment buttons
{ "language": "en", "url": "https://stackoverflow.com/questions/7585915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: List of Records in F#? How do you work with a List of Records in F#? How would you even pass that as an argument in a function? I want to do something like this: type Car = { Color : string; Make : string; } let getRedCars cars = List.filter (fun x -> x.Color = "red") cars; let car1 = { Color = "red"; Make = "Toyota"; } let car2 = { Color = "black"; Make = "Ford"; } let cars = [ car1; car2; ] I need a way to tell my function that "cars" is a List of Car records. A: Your code works just fine. It can also be written: let getRedCars cars = List.filter (function {Color = "red"} -> true | _ -> false) cars If you're ever concerned the wrong signature is being inferred, you can add type annotations. For example: let getRedCars (cars:Car list) : Car list = //...
{ "language": "en", "url": "https://stackoverflow.com/questions/7585917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Can a class still be pure abstract if it has a non-pure destructor? I am working on an exercise which asks me to take a base class Rodent and make it a pure abstract class. My understanding of a pure abstract class is that it acts as an interface and only contains pure virtual functions. Although this is an easy exercise I have a problem with the solution provided by the book: class Rodent { public: virtual ~Rodent() {cout << "Destroy rodent" << endl;} virtual void run() = 0; virtual void squeak() = 0; }; As you can see the author has added a dummy definition for the destructor. Does the adding of this definition not mean that this is an abstract class and not a 'pure' abstract class? A: An Abstract class must contain atleast one pure virtual function. Your class already has two pure virtual functions run() and squeak(), So your class is Abstract because of these two pure virtual functions. You cannot create any objects of this class. EDIT: A pure abstract class, is a class that exclusively has pure virtual functions (and no data). Since your destructor is not pure virtual your class is not Pure Abstract Class. A: A destructor is required for every class by the rules of C++. If you don't provide one, the compiler will generate one for you. In my opinion this is still a pure abstract class, because the destructor is an exception to the rule. A: The virtual keyword means something a bit different for destructors. When a base class's dtors are virtual, it means all dtors in the inheritance hierarchy are called. You can't really override it as such. Usually you'd expect it to be empty: class Rodent { public: virtual ~Rodent() {} virtual void run() = 0; virtual void squeak() = 0; }; I see very little difference. It is possible that because the empty body is a no-op the compiler can ignore it through some language lawyer statute. I don't think you'd confuse anyone by calling yours pure virtual. A: As far as I understand, the C++ standard does not specify a pure abstract class. The C++0x (n3290) however specifies abstract class. 10.4/2 A class is abstract if it has at least one pure virtual function. The pure abstract class is a conventional term and describes an abstract class that; * *does not have of data members *does not have of any non-pure virtual functions *does not have of any concrete functions specified by user. So, according to this convention, the class Rodent is not a pure abstract class. A: Consider implementing your interface like so class Rodent { public: virtual ~Rodent() = 0; virtual void run() = 0; virtual void squeak() = 0; }; inline Rodent::~Rodent() {} Specifying your destructor as pure virtual and inlining the implementation avoids the following warning in MSVC2010 when exporting subclasses: warning C4275: non dll-interface class 'A' used as base for dll-interface class 'B' A: Yes, it is not a pure class anymore. A pure, abstract class has no functionality in it, it just provides a framework. cout is functionality.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }