text
stringlengths
8
267k
meta
dict
Q: How does fill-paragraph (M-q) in emacs work inside LaTeX equations? I have not really understood how this works (and maybe it works differently in Aquamacs and GNU emacs on linux) - sometimes it does not fold long lines inside equations. I would like to know if there is a nice way to fold equations with M-q.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Rails 3.1 absolute URL to an image I'm using Rails 3.1. I'm trying to figure this out, and to my surprise, it is starting to seem that rails does not come with this method at all. Maybe im wrong. Can anyone show how I can get a full absolute URL to an image? I use asset_path(image.png) which gives me the relative path to use within the app. I tried doing a root_url + asset_path(image.png) but that just gives me a http://localhost:3000//assets/image.png with the double slashes Anyone have an efficient way of doing this? A: In my config/environments/*.rb I already have this tailored for each environment: config.domain = 'mysite.dev' So it was a simple matter of adding config.action_controller.asset_host = "http://" + config.domain to each file. Then asset_path will miraculously behave as if it were asset_url. A: See the Using asset hosts section in the documentation. You need to specify an asset_host. You can also construct it dynamically from the request chaining "#{request.protocol}#{request.host_with_port}" A: put this in application_helper.rb def asset_url asset "#{request.protocol}#{request.host_with_port}#{asset_path(asset)}" end then you can use asset_url in your views. A: For Rails 4, and maybe earlier, use: config.action_mailer.asset_host = 'https://assets.com' per https://github.com/fphilipe/premailer-rails/issues/16 A: Example folder structure. app/ assets/ flags/ 32x32/ en.png 256x256/ en.png If you want to generate absolute flag image path we can add in to our ApplicationHelper two methods: module ApplicationHelper # Generate flag path by locale # - locale. Can be "en", "it", etc. # - flag_size. Will be used to set folder size. Folder size can be "32x32", "256x256". # Return flag image path. Path will absolute def generate_flag_path_by_locale(locale, folder_size = "32") folder = "#{flag_size}x#{flag_size}" domain_absolute_path = generate_domain_absolute_path flag_path = ("#{domain_absolute_path}/assets/flags/#{folder}/#{locale}.png") return flag_path end # Generate domain absolute path def generate_domain_absolute_path request_protocol = request.protocol request_host_with_port = request.host_with_port domain_absolute_path = request_protocol + request_host_with_port return domain_absolute_path end end Into our apps/view/products.html.erb. We must to call only: <% flag_path = generate_flag_path_by_locale("en") %> Final result: http://my_domain.com:3000/assets/flags/32x32/en.png A: You need to use 'asset_url' instead *asset_path*. Bcz '_path' always return relative path and '_url' will return absolute url. A: Could you just do: root_url[0..-2] + asset_path(image.png) ...to trim the trailing slash in the root url?
{ "language": "en", "url": "https://stackoverflow.com/questions/7597127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Drawing a line in Animation I have an invisible Polyline containing a lot of points in a canvas. <Polyline x:Name="plinePath" Stroke="#00000000" StrokeThickness="3"> <Polyline.Points> <Point X="0" Y="0" /> <Point X="10" Y="10" /> <Point X="10" Y="20" /> <Point X="20" Y="20" /> ... ... ... </Polyline.Points> </Polyline> Now I need to render the line in runtime like someone was drawing it in red. I'd like to do that in a Storyboard if I can. Any hints on how I could do that? A: If the polyline were always heading in one general direction you could just animate a clipping rectangle attached to your plinePath to expose it smoothly. The problem you have with other methods of "drawing" it is that the individual line segments need to be resized individually along the length of their extent. That is non-trivial, but possible. There are issues over constant speed of drawing vs. interpolating X & Y that need to be calculated for each segment. Basically take the line length (of each segment) then linearly interpolate the end-x and end-y to their final position in a time determined by the line length. A: OK, what I finally did is create my own customcontrol that has a Canvas and a Polyline in it. My control has two main public properties : * *PathPoints (List<Points>) : List of all points in the path *CurrentPoint (int) : Show all the points in the PathPoints that are less or equal to that number. Now I can use a Storyboard with a DoubleAnimation based on the "CurrentPoint" property to animate my path.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Run self extracting exe after extraction C# - DotNetZip I am trying to create a self extracting exe. Creating it is no problem. Where I am facing problems is * *Setting the extraction path where the exe exists *Running the extracted exe. For the second part, it is most probable that I must have the extraction path correct. I am using the following modified code from DotNetZipLibrary zip.AddDirectory(DirectoryPath, "putty.exe"); zip.Comment = "This will be embedded into a self-extracting console-based exe"; SelfExtractorSaveOptions options = new SelfExtractorSaveOptions(); options.Flavor = SelfExtractorFlavor.ConsoleApplication; options.DefaultExtractDirectory = ""; options.PostExtractCommandLine = "..\\putty.exe"; options.RemoveUnpackedFilesAfterExecute = true; zip.SaveSelfExtractor("archive.exe", options); A: I see two problems. First, you are calling zip.AddDirectory(DirectoryPath, "putty.exe"); The AddDirectory() method adds a directory into the zip archive. The overload that accepts 2 inputs, the one you are using, names that directory in the zip archive with the second argument. Therefore after making this call you will have in the zip archive, all the files that can be found in DirectoryPath on your filesystem. The root directory name used in the zip archive will be "putty.exe". This is at the very least a confusing name for a directory. I think you are probably not intending this. If you want to add a file to the archive, use AddFile(), not AddDirectory(). Second, according to the documentation, the post-extract command is run ...using the extract directory as the working directory for the process, ... So if your zip has a file called "putty.exe" in the root of the archive, then the command you want to run is probably "putty.exe", not "..\putty.exe". I suggest that during development, you take out the part that saves to a self-extractor, and replace it with a save to a regular zip file. Examine the zip file you produce to make sure it looks like you want it to look. When you get it right, put the SaveSelfExtractor() part back in, and you will have a proper SFX.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change schema.xml in solr Can any help me how to change schema.xml in apache Solr server? I deployed my Solr in tomcat server. Then I added a field in schema.xml but on running my java application. How can I index a csv file or xml file into Solr server using Solrj? I want to add fields like classname, packagename and url etc. I added fields like. <field name=packagename" type="text" indexed="true" stored="true"/> <field name="classname" type="text" indexed="true" stored="true"/> The content ogf log file is SEVERE: Exception during parsing file: schema:org.xml.sax.SAXParseException: The end-tag for element type "field" must end with a '>' delimiter. at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source) at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source) at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanEndElement(Unknown Source) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) at org.apache.xerces.parsers.DOMParser.parse(Unknown Source) at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source) at org.apache.solr.core.Config.<init>(Config.java:159) at org.apache.solr.schema.IndexSchema.readSchema(IndexSchema.java:420) at org.apache.solr.schema.IndexSchema.<init>(IndexSchema.java:125) at org.apache.solr.core.CoreContainer.create(CoreContainer.java:461) at org.apache.solr.core.CoreContainer.load(CoreContainer.java:316) at org.apache.solr.core.CoreContainer.load(CoreContainer.java:207) at org.apache.solr.core.CoreContainer$Initializer.initialize(CoreContainer.java:130) at org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:94) at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:295) at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:422) at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:115) at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4071) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4725) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601) at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:943) at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:778) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:504) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1315) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1061) at org.apache.catalina.core.StandardHost.start(StandardHost.java:840) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463) at org.apache.catalina.core.StandardService.start(StandardService.java:525) at org.apache.catalina.core.StandardServer.start(StandardServer.java:754) at org.apache.catalina.startup.Catalina.start(Catalina.java:595) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37) at java.lang.reflect.Method.invoke(Method.java:599) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) It contains many such things that I can't post here because of the limitation in words. A: Try to run a xml validator on your schema file. Looks like you are missing a closing ">" brace somewhere in the schema that could have been introduced when you added these 2 fields.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Casting a List (where T : IBar) to ICollection fails I have classT, implementing interfaceIBar. I have a variable list of type List<T>. Two questions for enhancing my understanding of the language: * *Why doesn't this work? var foo = (ICollection <IBar>)list; // fails! *How to work around it (if possible)? A: Why doesn't this work?: var foo = (ICollection <IBar>)list; Let's say T = Foo and there's a second class Foo2 : IBar. Then you could continue like this: var foolist = (ICollection <IBar>)list; foolist.Add(new Foo2()); // compiles, since Foo2 also implements IBar Wham! You have a type violation at runtime, since you tried to add a Foo2 to a List<Foo>. To avoid this, ICollection<Foo> is not a subtype of ICollection<IBar>, even though Foo is a subtype of IBar. The theory behind this is co- and contravariance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems with Thread, can't change the value of an external TextView I have an android thread class that must change the value of an external TextView, but it doesn't change it :S. I debug it and I can see that the thread executes the line that changes the value of the TextView, but it doesn't get reflected on the value. public class AugmentedRealitySampleActivity extends Activity { private TextView tv2; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tv2=new TextView(getApplicationContext()); tv2.setText("Test2"); myThread t = new myThread(); t.start(); } public class myThread extends Thread { public void run() { Looper.prepare(); tv2.append("\n AAA"); Looper.loop(); } } } EDIT; code posted in full mode: private class myAsyncTask extends AsyncTask<Void, Void, Void> { boolean condition = true; protected Void doInBackground(Void... params) { while( condition ) try { publishProgress(); Thread.sleep( 1000 ); }catch (InterruptedException e) {e.printStackTrace();} return null; } protected void onProgressUpdate(Void... values) { //Update your TextView if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) //si el GPS está desactivado { boolean visible=false; float a = 80; //a=bearingTo float b =azimuth; float d = Math.abs((a - b)) % 360; float r = d > 180 ? 360 - d : d; if (Math.abs(r)<21 && Math.abs(inclination)<30) visible=true; if (visible) { tv2.append("\nIs Visible?: true "+ r); poi.setVisibility(View.VISIBLE); ////////CALCULAMOS COORDENADA X DEL POI/////// float leftSideFovDegree=azimuth-21; if (leftSideFovDegree<0) leftSideFovDegree+=360; float dist=anglesDistance(leftSideFovDegree,a); float xCoordPercent=(dist*100)/42; //xCoordPercent es el porcentaje de X respecto al horizontal de la pantalla, en el que estará el objeto if (a<0)//si el bearingTo es negativo, entonces la cordenada X se invierte xCoordPercent=100-xCoordPercent; tv2.append("\nxCoordPercent: "+ xCoordPercent); ////////CALCULAMOS COORDENADA Y DEL POI/////// //float yCoordPercent= (float)(42.7377 * Math.pow(Math.E,(0.0450962*inclination))); float yCoordPercent= (float)(33.0459 * Math.pow(Math.E,(0.056327*inclination))); tv2.append("\nyCoordPercent: "+ yCoordPercent); Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int w = display.getWidth(); int h = display.getHeight(); RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); position.leftMargin = (int)(w*(xCoordPercent/100)); position.topMargin = (int)(h*(yCoordPercent/100)); poi.setLayoutParams(position); } else { tv2.append("\nIs Visible?: false "+ r); poi.setVisibility(View.GONE); } } } } A: This is probably because your Thread is not the UI-thread. All updating of Views must be done on the UI-thread. Try doing this: runOnUiThread( new Runnable() { @Override public void run() { tv2.append("\n AAA"); } }); Or better yet - convert your thread to an AsyncTask like this: private class myAsyncTask extends AsyncTask<Void, Void, Void> { boolean condition = true; @Override protected Void doInBackground(Void... params) { while( condition ) try { // Do your calculations publishProgress(); Thread.sleep( 200 ); } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(Void... values) { //Update your TextView } } And instead of creating a new Thread you do: new myAsyncTask().execute(); A: This is because your thread is not running on the UI thread. There is only one UI thread, and you can only modify UI elements from within it. One solution would be: public void run() { Looper.prepare(); runOnUiThread(new Runnable() { public void run() { tv2.append("\nIs Visible?: false "+ r); } }); Looper.loop(); } Although a neater solution could be reached with a Handler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Uncaught ReferenceError in AJAX script First... I've been trying to solve this myself for the last 3 evenings... I've look at posts with similar topics to mine but have not come across an answer that helps me... I'm a little new to AJAX & JS but Not new to web programming... I have a standard Automotive select list ... one select list feeds another... Select Year and it gives a Select list of makes, Select the make and get a select list of models select a model & get a select list of trim styles... Pretty common stuff really... I have the script to do all of this (found it online) it covered the year. make & Model part... I had to add the extra bit to do the Trim... Everything works as it is supposed to down until I get the Trim part (my Part :) ) . When I select the model (which should then give me an appropriate Trim list) I get the following error in the Chrome error console: "Uncaught ReferenceError: chevrolet is not defined (anonymous function) onchange" What make this confusing to me by comparison to the other similar topics I've read is that "chevrolet" is the Make parameter - Not a function.... My Script is (you may recognize it...): <script language="javascript" type="text/javascript"> var xmlhttp=false; try{ xmlhttp=new XMLHttpRequest(); } catch(e) { try{ xmlhttp= new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){ try{ xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e1){ xmlhttp=false; } } } return xmlhttp; } function getMake(yearId) { var strURL="/vehicles/getmake/"+yearId+"/"; var req = getXMLHTTP(); if (req) { req.onreadystatechange = function() { if (req.readyState == 4) { // only if "OK" if (req.status == 200) { document.getElementById('makediv').innerHTML=req.responseText; } else { alert("There was a problem while using XMLHTTP:\n" + req.statusText); } } } req.open("GET", strURL, true); req.send(null); } } function getModel(yearId,makeId) { var strURL="/vehicles/getmodel/"+yearId+"/"+makeId+"/"; var req = getXMLHTTP(); if (req) { req.onreadystatechange = function() { if (req.readyState == 4) { // only if "OK" if (req.status == 200) { document.getElementById('modeldiv').innerHTML=req.responseText; } else { alert("There was a problem while using XMLHTTP:\n" + req.statusText); } } } req.open("GET", strURL, true); req.send(null); } } function getSub(yearId,makeId,modelId) { var strURL="/vehicles/gettrim/"+yearId+"/"+makeId+"/"+modelId+"/"; var req = getXMLHTTP(); if (req) { req.onreadystatechange = function() { if (req.readyState == 4) { // only if "OK" if (req.status == 200) { document.getElementById('trimdiv').innerHTML=req.responseText; } else { alert("There was a problem while using XMLHTTP:\n" + req.statusText); } } } req.open("GET", strURL, true); req.send(null); } } the refereneced html in the pages in each function respectively is: for the make: <label for="make" class="select">Make_ch:</label> <select placeholder="Select a Year First" name="make" id="make" autocapitalize="off" autocorrect="off" autocomplete="off" onchange="getModel(<?php echo $year ?>,this.value)"> <?php foreach($vehicle_make->result() as $row) { echo '<option value = "'.$row->model_make_id.'">'.$row->model_make_id.'</option>'; } ?> for the model: <label for="model" class="select">Model_ch:</label> <select placeholder="Select a Make First" name="model" id="model" autocapitalize="off" autocorrect="off" autocomplete="off" onchange="getSub(<?php echo $year ?>,<?php echo $make ?>,this.value)"> <?php foreach($vehicle_model->result() as $row) { echo '<option value = "'.$row->model_name.'">'.$row->model_name.'</option>'; } ?> for the trim: <label for="trim" class="select">Trim_ch:</label> <select placeholder="Select a Model First" name="trim" id="trim" autocapitalize="off" autocorrect="off" autocomplete="off"> <?php foreach($vehicle_trim->result() as $row) { echo '<option value = "'.$row->model_trim.'">'.$row->model_trim.'</option>'; } ?> As I said... The year, Make, Model part all work correctly... I have verified that the Trim select list will display what it is supposed to if it receives all the correct parameters... Does anyone se anything I'm missing? Thanks in advance.... Russ A: in your html model part, you should put your php tag between ' '. Example: onchange="getSub('<? php echo $year ?>','<?php echo $make ?>',this.value)">
{ "language": "en", "url": "https://stackoverflow.com/questions/7597142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UITableView - Grouped Table. iOS (Cocoa Touch), Objective-C I found a tutorial for a UITableView – Drill down table view, source code, but I would like to add a little upgrade. My goal is to add grouped table view with 2 sections in level 0 (CurrentLevel == 0). So I started with: * *Change table view style (at RootViewController.xib) from Plain to Grouped. (Works fine). *Changes at RootViewController.m: - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; to - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { if(CurrentLevel == 0) return 2; else return 1; *Add new key to data.plist named: Other. After that CurrentLevel 0 returns 2 sections with same data for objectForKey:@"Rows". I don't know hot to change -(void)viewDidLoad, -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section, -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath methods to load data from data.plist for my new key @"Other", where key @"Other" means 2nd section of the table in CurrentLevel 0 table view. This is the source code for: DrillDownAppAppDelegate.h // // DrillDownAppAppDelegate.h // DrillDownApp // // Created by iPhone SDK Articles on 3/8/09. // Copyright www.iPhoneSDKArticles.com 2009. // #import <UIKit/UIKit.h> @interface DrillDownAppAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; UINavigationController *navigationController; NSDictionary *data; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UINavigationController *navigationController; @property (nonatomic, retain) NSDictionary *data; @end DrillDownAppAppDelegate.m // // DrillDownAppAppDelegate.m // DrillDownApp // // Created by iPhone SDK Articles on 3/8/09. // Copyright www.iPhoneSDKArticles.com 2009. // #import "DrillDownAppAppDelegate.h" #import "RootViewController.h" @implementation DrillDownAppAppDelegate @synthesize window; @synthesize navigationController; @synthesize data; - (void)applicationDidFinishLaunching:(UIApplication *)application { NSString *Path = [[NSBundle mainBundle] bundlePath]; NSString *DataPath = [Path stringByAppendingPathComponent:@"data.plist"]; NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:DataPath]; self.data = tempDict; [tempDict release]; // Configure and show the window [window addSubview:[navigationController view]]; [window makeKeyAndVisible]; } - (void)applicationWillTerminate:(UIApplication *)application { // Save data if appropriate } - (void)dealloc { [data release]; [navigationController release]; [window release]; [super dealloc]; } @end RootViewController.h // // RootViewController.h // DrillDownApp // // Created by iPhone SDK Articles on 3/8/09. // Copyright www.iPhoneSDKArticles.com 2009. // #import <UIKit/UIKit.h> @interface RootViewController : UITableViewController { NSArray *tableDataSource; NSString *CurrentTitle; NSInteger CurrentLevel; } @property (nonatomic, retain) NSArray *tableDataSource; @property (nonatomic, retain) NSString *CurrentTitle; @property (nonatomic, readwrite) NSInteger CurrentLevel; @end RootViewController.m // // RootViewController.m // DrillDownApp // // Created by iPhone SDK Articles on 3/8/09. // Copyright www.iPhoneSDKArticles.com 2009. // #import "RootViewController.h" #import "DrillDownAppAppDelegate.h" #import "DetailViewController.h" @implementation RootViewController @synthesize tableDataSource, CurrentTitle, CurrentLevel; - (void)viewDidLoad { [super viewDidLoad]; if(CurrentLevel == 0) { //Initialize our table data source NSArray *tempArray = [[NSArray alloc] init]; self.tableDataSource = tempArray; [tempArray release]; DrillDownAppAppDelegate *AppDelegate = (DrillDownAppAppDelegate *)[[UIApplication sharedApplication] delegate]; self.tableDataSource = [AppDelegate.data objectForKey:@"Rows"]; self.navigationItem.title = @"Zvolte trasu"; } else self.navigationItem.title = CurrentTitle; } #pragma mark Table view methods - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { if(CurrentLevel == 0) return 2; else return 1; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.tableDataSource count]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } // Set up the cell... NSDictionary *dictionary = [self.tableDataSource objectAtIndex:indexPath.row]; cell.textLabel.text = [dictionary objectForKey:@"Title"]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; UIImage *rowImage = [UIImage imageNamed:[dictionary objectForKey:@"Image"]]; cell.imageView.image = rowImage; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //Get the dictionary of the selected data source. NSDictionary *dictionary = [self.tableDataSource objectAtIndex:indexPath.row]; //Get the children of the present item. NSArray *Children = [dictionary objectForKey:@"Children"]; if([Children count] == 0) { DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]]; [self.navigationController pushViewController:dvController animated:YES]; [dvController release]; } else { //Prepare to tableview. RootViewController *rvController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:[NSBundle mainBundle]]; //Increment the Current View rvController.CurrentLevel += 1; //Set the title; rvController.CurrentTitle = [dictionary objectForKey:@"Title"]; //Push the new table view on the stack [self.navigationController pushViewController:rvController animated:YES]; rvController.tableDataSource = Children; [rvController release]; } } - (void)dealloc { [CurrentTitle release]; [tableDataSource release]; [super dealloc]; } @end Edit: My attempt: RootViewController.h // // RootViewController.h // DrillDownApp // // Created by iPhone SDK Articles on 3/8/09. // Copyright www.iPhoneSDKArticles.com 2009. // #import <UIKit/UIKit.h> @interface RootViewController : UITableViewController { NSArray *tableDataSource; NSArray *otherDataSource; NSString *CurrentTitle; NSInteger CurrentLevel; } @property (nonatomic, retain) NSArray *tableDataSource; @property (nonatomic, retain) NSArray *otherDataSource; @property (nonatomic, retain) NSString *CurrentTitle; @property (nonatomic, readwrite) NSInteger CurrentLevel; @end RootViewController.m // // RootViewController.m // DrillDownApp // // Created by iPhone SDK Articles on 3/8/09. // Copyright www.iPhoneSDKArticles.com 2009. // #import "RootViewController.h" #import "DrillDownAppAppDelegate.h" #import "DetailViewController.h" @implementation RootViewController @synthesize tableDataSource, otherDataSource, CurrentTitle, CurrentLevel; - (void)viewDidLoad { [super viewDidLoad]; if(CurrentLevel == 0) { //Initialize our table data source NSArray *tempArray = [[NSArray alloc] init]; self.tableDataSource = tempArray; self.otherDataSource = tempArray; [tempArray release]; DrillDownAppAppDelegate *AppDelegate = (DrillDownAppAppDelegate *)[[UIApplication sharedApplication] delegate]; self.tableDataSource = [AppDelegate.data objectForKey:@"Rows"]; self.otherDataSource = [AppDelegate.data objectForKey:@"Other"]; self.navigationItem.title = @"Root"; } else self.navigationItem.title = CurrentTitle; } #pragma mark Table view methods - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { if(CurrentLevel == 0) return 2; else return 1; } // Customize the number of rows in the table view. //Not sure about this. When I select some cell from section 1, what will appear at didSelectRowAtIndexPath? - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if(section == 0 && CurrentLevel == 0) return [self.tableDataSource count]; if(section == 1 && CurrentLevel == 0) return [self.tableDataSource count]; else return [self.tableDataSource count]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { if(section == 0 && CurrentLevel == 0) return nil; else return nil; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } // Set up the cell... don't know how. //here is only tableDataSource NSDictionary *dictionary = [self.tableDataSource objectAtIndex:indexPath.section]; cell.textLabel.text = [dictionary objectForKey:@"Title"]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; UIImage *rowImage = [UIImage imageNamed:[dictionary objectForKey:@"Image"]]; cell.imageView.image = rowImage; return cell; } //same problem - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //only tableDataSource NSDictionary *dictionary = [self.tableDataSource objectAtIndex:indexPath.row]; //Get the children of the present item. NSArray *Children = [dictionary objectForKey:@"Children"]; if([Children count] == 0) { DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]]; [self.navigationController pushViewController:dvController animated:YES]; [dvController release]; } else { //Prepare to tableview. RootViewController *rvController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:[NSBundle mainBundle]]; //Increment the Current View rvController.CurrentLevel += 1; //Set the title; rvController.CurrentTitle = [dictionary objectForKey:@"Title"]; //Push the new table view on the stack [self.navigationController pushViewController:rvController animated:YES]; rvController.tableDataSource = Children; [rvController release]; } } - (void)dealloc { [CurrentTitle release]; [tableDataSource release]; [otherDataSource release]; [super dealloc]; } @end A: * *Create a second array to hold the data for the second section *Populate this array in viewDidLoad using your @"Other" key *Use indexPath.section in the relevant datasource methods so that you know which section your table view is asking you about, and return the object / count of the relevant array. indexPath.section will be 0 for the first section and 1 for the second section. *Wherever you are using tableDataSource, you need to check what section you are in. This is either passed in as an integer (section) or as part of the indexpath (so you can get it via indexPath.section). If you are in section 0, use tableDataSource, else if you are in section 1, use otherDataSource.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Url.Action not outputting URL I'm using Url.Action so that I can create more complex HTML links as ActionLink doesn't allow HTML inside them. Example: <a class="uiButton" href="@Url.Action("Areas","Organisations","Manage","Create")" title="New Organisation"> <span class="icon organisations-new">New Organisation</span> </a> However the URL doesn't appear in the href? Any ideas why ? :/ A: You are using this overload of Url.Action public string Action( string actionName, string controllerName, Object routeValues, string protocol ) And you are definitely using it wrong (no protocol like "Create"). Use any of appropriate overloads for you. For example, if you've got OrganizationsController and Create action, this code will be enough: @Url.Action("Create", "Organisations") If you want to route to another area, supply routeValues object like new {Area = "anotherAreaName"}. @Url.Action("Create", "Manage", new {Area = "Organizations"}) This will route to Organizations area, Create action on ManageController A: In my case I had an empty string because "area" parameter was wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Parent to sub-domain AJAX POST requests with JQuery I'll start by saying i have spent the last 3 days looking for an answer to this and have yet to find a solution that works! :( I would like to be able to POST from www.example.com to api.example.com preferably using JQuery. I have managed to get GET requests to work using document.domain and <base href="example.com"/> This is all secured using SSL. I have read about using an iFrame to load a page on the subdomain and post the forms from the parent domain using javascript but i don't really want to pursue this route (if possible). Also if cross-domain POSTing isn't viable, when using https are there any security benefits with using POST as compared to GET? Thanks, Jamie A: If you set the document domain in the main domain and the subdomain, you should be able to make Ajax calls between the two. Parent Page <script type="text/javascript"> document.domain = "example.com"; </script> <iframe src="setDocumentDomain.html" style="display:none"></iframe> iframe setDocumentDomain.html code <!DOCTYPE html> <html> <head> <script type="text/javascript"> document.domain = "example.com"; </script> <title>Set Domain</title> </head> <body> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7597161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Displaying detailed #error informations SSRS report without using BIDS How can i get any informations about #error that occured in cell without debugging it localy in BIDS? Is there any possibility to show error message inside report? I haven't found anything usefull on google related to #error in cell. Im interested only in cell #error, of properly generated report... A: Run the report from VS by pushing F5 or Debug->Start Debugging. The expression errors will be written out in the Output window. A: There's no way to get the info from the usual VB handler. You'll have to write your own handlers to get this. For example, you could write either custom code embedded in the report, or better, a custom assembly, that returns a string for your cell's value. This code would need to perform all the work that might be returning the #error in your current function. But the code could check for problems or catch exceptions and still return a valid string. You could put your own error messages in this string. (That's why I like the assembly: there you could easily catch all exceptions and still return a string. I know C# better than VB.) So not too easy, but if you are comfortable with coding, not a big stretch.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Root authority in xulRunner I need to embed my own Trusted Root Authority for SSL connections in my XulRunner app. Unfortunatelly I can't find how to do this... cert_override.txt can't help my because I don't know all the server links nor all the certificates that must be accepted, but they are signed by the corporate authority.. A: You cannot change the "built-in" authorities because they are compiled into nssckbi.dll. Unless you use a custom XULRunner build of course and change its source code. You can add a new authority to the user profile however, the relevant file is cert8.db. You could use Firefox to add a new root certificate (Options / Advanced / Encryption / View certificates / Authorities / Import) and then take the resulting cert8.db file for your XULRunner profile. You can add it to the default profile - copy it into the defaults/profile directory of your application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Security Exception running dotless I'm getting a Security Exception when I attempt to access a .less file in IIS7. The exception text is: Security Exception The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file. I've added the following to my web.config file: <configSections> <section name="dotless" type="dotless.Core.configuration.DotlessConfigurationSectionHandler,dotless.Core" requirePermission="false" /> </configSections> <httpHandlers> <remove verb="*" path="*.asmx" /> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false" /> <add type="dotless.Core.LessCssHttpHandler,dotless.Core" path="*.LESS" verb="*" validate="false" /> </httpHandlers> <dotless minifyCss="false" cache="false" /> <system.webServer> <handlers> <add name="dotLess" path="*.less" verb="*" type="dotless.Core.LessCssHttpHandler" resourceType="Unspecified" preCondition="integratedMode" /> </handlers> </system.webServer> Any ideas? I'm running a MVC2 .Net application. A: have you added the MIME type to IIS? if no add extension .less MIME type 'text/css'
{ "language": "en", "url": "https://stackoverflow.com/questions/7597172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I update an mxml property dynamically in Flex? I'm using Flex 4.0, with the Halo theme, and a custom component that I have the source of. I want to call the component with a parameter to hide or show some items. The parameter is dynamic, meaning it is set in a method after the mxml has loaded. Snippet: <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="de.aggro.components.*" width="100%" height="100%" initialize="init();" > <mx:Script> <![CDATA[ [Bindable] public var allowwindowmanipulation:Boolean = true; internal function init():void { allowwindowmanipulation = false; } ]]> </mx:Script> <mx:states> <mx:State name="st"> ... <ns1:CollapsableTitleWindow width="956" height="395" x="294" y="484" id="wnd" title="title" allowClose="{allowwindowmanipulation}"> </mx:State> </mx:states> </mx:Application> CollapsableTitleWindow code (snippet): public class CollapsableTitleWindow extends Panel implements ICTWindow { public var allowClose:Boolean = true; function CollapsableTitleWindow(){ super(); addEventListener(FlexEvent.CREATION_COMPLETE, initializeHandler); } protected override function createChildren():void{ super.createChildren(); //Create the Buttons closeButton = new Sprite(); if(allowClose==true){ titleBar.addChild(closeButton); drawCloseButton(true); } } } Now, when I run this code, the value given to the constructor of CollapsableTitleWindow is true for the allowClose variable. So when createChildren() is called, the button is drawn. How can I change the behaviour? I don't mind if the button first gets drawn then later gets removed, if need be, but I don't know how I do this binding of parameter values. When I for instance change the title property to {allowClose}, the boolean value of false gets shown, even though probably a true is passed at first. A: Note: edited to reflect feedback Since you're using Flex 4, you should probably do this with a skin and States within the skin. But if you want to do it through code, try something like this: protected var _allowClose:Boolean=true; protected var _allowCloseChanged::Boolean=true; protected var _closeButton:Sprite = new Sprite(); public function get allowClose():Boolean { return _allowClose; } public function set allowClose(value:Boolean):void { if (value != _allowClose) { _allowClose=value; _allowCloseChanged=true; invalidateProperties(); } } override protected function commitProperties():void { if (_allowCloseChanged) { if (_allowClosed) { titlebar.addChild(_closeButton); drawCloseButton(true); } else { titleBar.removeChild(_closeButton); } //you need to set this back false...sorry I left that out _allowCloseChanged=false; } super.commitProperties(); } Note: in this case, you no longer need to override createChildren
{ "language": "en", "url": "https://stackoverflow.com/questions/7597179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accesing the wso2 stratos services defined in the service-stubs file From the wso2 stratos source files there is a 'service stubs' (wso2-stratos-1.5.1-src/service-stubs) section. Normally we can not access to these web services and after building the source the services are hidden. Is there a way to access to these web services outside of carbon api? A: Do you want to invoke these back end services directly? As you may now, All the WSO2 products has a concept of Front end and back End. FE always talk to back end using a web service call. We use service stubs for that. Stubs --> web service. Therefore you can always access those back end services by directly calling the BE with your client. This article[1] describes such access instances with the relevant samples. if you want to access these services as a tenant you can add /a/ to url eg. services/a/amila.com/MessageBoxAdmin [1] http://wso2.org/library/articles/2011/08/messaging-eventing-soa
{ "language": "en", "url": "https://stackoverflow.com/questions/7597181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: htaccess mod-rewrite to subdomain I'm using the following to redirect wildcard sub domains to corresponding folders: RewriteCond %{REQUEST_URI} !^/users/ [NC] RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$ [NC] RewriteCond %1 !=www [NC] RewriteRule ^(.*)$ /users/%1/$1/? [L] I would like to add a rewrite rule that redirects anyone that accesses the direct /users/ path back to the sub-domain version like this: www.domain.com/users/username/../../ => username.domain.com/../../ Thank you in advance! A: Something like this: RewriteEngine On RewriteCond %{http_host} ^domain.com [nc] RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,NC] RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC] RewriteRule ^users/([a-z0-9\-_\.]+)/?(.*)$ http://$1.domain.com/$2 [QSA,NC,R,L] Do you have other rules than the one listed on the question? if yes, put these before the other one. eg: http://www.domain.com/users/abc?q=test => http://abc.domain.com/?q=test http://www.domain.com/users/abc/sub1/sub2 => http://abc.domain.com/sub1/sub2 http://www.domain.com/users/abc/sub1/?q=test => http://abc.domain.com/sub1/?q=test
{ "language": "en", "url": "https://stackoverflow.com/questions/7597182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Neater way to filter Object containing other Objects by value I've got a JavaScript object that looks like this: var options = { 'user1' : { 'house1' : ["lat1", "lng1"] }, 'user2' : { 'house2' : ["lat2", "lng2"] }, 'user3' : { 'house1' : ["lat3", "lng3"] } }; Say I want to look up all the users associated with house1, and return an array of their usernames and their positions. What's the clearest and most efficient way to do this? Currently I've written a rather unwieldy custom lookup, as follows: function returnByValues(options, housenum): var results = []; for (var username in options) { var properties = options[username]; for (var housekey in properties) { if (housekey === housenum) { var result = {}; result[username] = properties; results.push(result); } } } return results; Is there a neater way? It's not exactly readable code! A: I don't think you need the middle loop, assuming each user is only associated with one house as per your example. So: function returnByValues(options, housenum): var results = []; for (var username in options) { var properties = options[username]; if (housenum in properties) { var result = {}; result[username] = properties; results.push(result); } } return results; } You don't often see the if (housenum in properties) syntax, but it's a more elegant equivalent of if (properties[housenum] != undefined). By the way, your code: result[username] = properties; gives result == {"user1" : { 'house1' : [lat, lng] } } - is that your intention? Because your description of what you want was "an array of their usernames and their positions" which I would take to be this: result[username] = properties[housenum]; giving result == {"user1" : [lat, lng] } A: I guess you search for sth like this: filteredArray = array.filter( ... return a.xyz == b.xyz ) If so, take a look at this: http://www.tutorialspoint.com/javascript/array_filter.htm A: function returnByValues(options, housenum){ var results = []; for (var username in options) if(housenum in options[username]) results.push(function(){ var obj={}; obj[username] = options[username]; return obj; }); return results; } A: If you wanted to use linq.js, you could do things along the lines of function returnByValues(users, house) { return Enumerable.From(users).Where("'" + house + "' in $.Value") .ToObject("$.Key", "$.Value"); } where this var searchResult = returnByValues(options, "house1"); /* yields: { "user1": { "house1": ["lat1", "lng1"] }, "user3": { "house1": ["lat3", "lng3"] } } */ Look at a working example on jsFiddle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET Repeater User Control DataSource I have a user control that contains a repeater. It seems that data cannot be assigned to it's DataSource property, I have tried a few different data sources but the following error is displayed: (I have debugged it and there are data items in the datasource) Object reference not set to an instance of an object Here's the aspx for the repeater: <asp:Repeater ID="repeater1" runat="server" > <HeaderTemplate> <ul> </HeaderTemplate> <ItemTemplate> <li> <%# Eval("Name") %> </li> </ItemTemplate> <FooterTemplate> </ul> </FooterTemplate> </asp:Repeater> I create an instance of the user control in the code behind of the file I want to display the repeater in - I can't type repeater1.DataSource and assign it in that page so I added an attribute to the user control which takes IEnumerable as the datasource. Any ideas why this isn't working? A: You should do such things in the DataBind() method like shown below: public override void DataBind() { this.repeater.DataSource = ... this.repeater.DataBind(); ... } So it will bind whilst parent page calling Page.DataBind() as well Control.DataBind Method: Use this method to bind data from a source to a server control. This method is commonly used after retrieving a dataset through a database query. Most controls perform data binding automatically, which means that you typically do not need to call this method explicitly. A: Try this: Inside the user controls where is the repeater located, in the OnLoad() method do this : repeater1.DataSource = MyIEnumerableProperty; repeater1.DataBind();
{ "language": "en", "url": "https://stackoverflow.com/questions/7597197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pattern design for a WebService Client I'm making an android application that will contact with a WebServices that exists already. I'm looking for a pattern to create the client part (Android application). Since the webservices are in .net (WSDL), I have to create the WSClient manually. So, I'm thinking How I can do it. I thought that may be nice a WS Client class and for that, a singleton pattern. With that class, I could contact with all the services from any part for the application, but I don't know if this is the best choise. Any suggerence please? Thanks! A: You can use the service locator, dependency Injection and inversion of Control, patterns. A good paper is to Inversion of Control Containers and the Dependency Injection pattern by M. Fowler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to programmatically determine all valid XML nodes from a schema Is there an existing Java library that will let me determine all valid nodes for a point in an XML document (specified by XPath, or otherwise), given an XML schema? A: This isn't a very helpful answer - hopefully something better will come along. I don't think what you want is out there in an easily usable form. Obviously, the functionality is embedded in various editors, but not necessarily in a form that's easily and/or legally reusable. If you were to try to roll your own, you'd probably want to start with a pre-built XSD object model if possible. There are three that I'm aware of. I've used none - just thought I was going to but ended up not. XSOM is the one best wrapped for reuse. FWIW, it's by the enviably prolific Kohsuke Kawaguchi, creator of Hudson/Jenkins and a bunch of other stuff. There's also one embedded in Xerces, and one in the Eclipse XML support. In both cases, my ill-informed opinion is that documentation is sketchy and reuse, while theoretically possible, is not something the authors have paid much attention to supporting. A: check javax.xml.validation and the XPath libraries at javax.xml.xpath
{ "language": "en", "url": "https://stackoverflow.com/questions/7597200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Difference between jQuery code structures What is the difference between these jQuery code structures, or is there no difference. Are they both an alias for $(document).ready(function(){ and if so, why the dollar in the first code snippet? jQuery(function($){ // stuff }); AND $(function() { // stuff }); A: The $ parameter in the first block is unneeded in that context. Where you would see it is in a block like this: (function ($) { // stuff })(jQuery); In that context it would allow you to always use the $ alias even if there was a conflicting library. Ignoring that, there is no difference. $ is just an alias for jQuery. Both are shortcuts for $(document).ready(function(){ A: What BNL said and yes, they are both an alias for $(document).ready(function(){ you could also write jQuery(document).ready(function(){ :) A: if you only are using jQuery then both $ and jQuery is the same, but if you are using another javascript library that uses $ as a shortcut then they wont be the same. But if its just jQuery then its just like you and @BNL have written its, its the same. A: The first code snipped serves the purpose of avoiding conflicts with other JS libraries that may be using the $ symbol. Wrapping the jQuery code in this manner allows you to use $ inside without worrying about conflicts. It's a good practice e.g. if you are writing a jQuery plugin to protect against conflicts in this manner. Otherwise, normally jQuery is a synonym for $. Also have a look here for some additional info on avoiding conflicts with other libraries: http://api.jquery.com/jQuery.noConflict/
{ "language": "en", "url": "https://stackoverflow.com/questions/7597203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Query to a MySQL database from shell I need to make several queries to MySql database. My question is the following: * *Do I add the following in a file and then execute the file: echo "Check " mysql -h 192.168.100.1 -t -u umane -pass tablename < query.sql echo "Check " mysql -h 192.168.100.1 -t -u umane -pass tablename < query2.sql echo "Check " mysql -h 192.168.100.1 -t -u umane -pass tablename < query3.sql echo "Check " mysql -h 192.168.100.1 -t -u umane -pass tablename < query4.sql * *Or I create a single "query.sql" file that contains all the sql querys. If so, can I in any way echo the "Check" statments somehow? A: username="my_sql username" password="my_sql password" result=`mysql -h 192.168.100.1 --port=$port -u $username --password=$password -e 'select * from database.table_name'` echo $result A: You could create one sql file and then add some SELECT statements like this // Does not print anyting CREATE TABLE test (col1 int, col2 varchar(2)); // Prints a non-existing table with 1 column and 1 row SELECT "CHECK 1" AS "Test result"; // This does prints some output DESCRIBE test; // Prints the check 'table' again SELECT "CHECK 2" AS "Test result"; The result of this looks like my@server:~$ mysql -t -u root databasename < sqltest +-------------+ | Test result | +-------------+ | CHECK 1 | +-------------+ +-------+------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+------------+------+-----+---------+-------+ | col1 | int(11) | YES | | NULL | | | col2 | varchar(2) | YES | | NULL | | +-------+------------+------+-----+---------+-------+ +-------------+ | Test result | +-------------+ | CHECK 2 | +-------------+ -- edit, yeah the same as Dimitre's suggestion A: Put all your sql statements in source.sql and you redirect the output into output.txt mysql -t -uuserid -ppassword -hhostname < source.sql > output.txt A: You can add text (and timestamp) selects in the SQL code: % mysql -NBe "select now(); select 'check'; select now();select 'check'" 2011-09-29 14:46:15 check 2011-09-29 14:46:15 check So your single SQL file would look like: --- queries from sql1... SELECT NOW() SELECT 'check'; -- queries from sql2...
{ "language": "en", "url": "https://stackoverflow.com/questions/7597204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's a good strategy to get a decent overview of big correlation matrices or pairs? Often some data.frame contains 20+ variables and you want to get a first overview (of the correlation structure). Even on a 30" screen you run quickly out of space and it remains hard to grasp the message. Are there any established strategies to highlight what's important? I am aware this question is somewhat general, but I wondered over and over again and never had the panacea to cure it. And yup, I heard of summary. A: With pairs you can generate some scatterplot matrices quickly. If too many variables are present you could use on of the tools of Rattle: Other examples at: http://rattle.togaware.com/rattle-screenshots.html In fact rattle itself does not do most of the analysis (as dwin pointed out correctly), but it offers (imho) easy tools to quickly run a pca, correlation tree, correlation matrix like above without having to manipulate your dataset to make sure that eg only numeric variables are present in the dataset, ... A: What about doing a PCA on the correlation matrix? Then the angle between variables show their correlation. library(HSAUR) heptathlon round(cor(heptathlon[,-8]),2) # correlations [without score] require(vegan) PCA <- rda(heptathlon[,-8], scale=TRUE) # run a PCA biplot(PCA, display = "species") # correlation biplot # The angles between descriptors in the biplot reflect their correlations A: Often, the column structure of a matrix can be presented in a random order. In that case, I'd look to do some reordering. For visualizing and working with sparse matrices, I often do some sort of reordering, such as Reverse Cuthill-McKee or some other form of bandwidth reordering, and this could be applied to other contexts to make visualizations easier. For a correlation matrix, you can squash low magnitude correlations (e.g. within (-eps,+eps)) to create sparsity, then reorder to examine the structure. What is nice is if you can find blocks of related objects. This reordering plus the heatmaps (using one color gradient for negative correlation, another for positive correlation) can be very helpful. A: Well I just have to post about my own package here:) You can use qgraph to visualize a correlation matrix as a network. This will plot variables as nodes and correlations as edges connecting the nodes. Green edges indicate positive correlations and red edges indicate negative correlations. The wider and more saturated the edges the stronger the absolute correlation. For example (this is the first example from the help page), the following code will plot the correlation matrix of a 240 variable dataset. library("qgraph") data(big5) data(big5groups) qgraph(cor(big5),minimum=0.25,cut=0.4,vsize=2,groups=big5groups,legend=TRUE,borders=FALSE) title("Big 5 correlations",line=-2,cex.main=2) You can also cluster strongly correlated nodes together (uses Fruchterman-Reingold) which creates quite a clear image of what the structure of your correlation matrix actually looks like: And alot more. For some more examples take a look at my site: http://sachaepskamp.com/?page_id=73 A: I have used heatmap() (or, rather, the underlying image() function) for that purpose. I do not have the code handy anymore, and as I recall I had to fiddle with the colormap to get something that made sense for the [-1, 1] range. Here is a simple example: R> set.seed(42) R> X <- matrix(rnorm(100*20), nrow=100) R> XC <- cor(X) R> image(XC) # color range could do with improvements here You play further tricks by blanking one lower or upper triangle and putting text there. The PerformanceAnalytics package has a function chart.Correlation() that does that (from the raw data matrix) but it is much slower and will not scale to large matrices as per your original question. I am sure there are others...
{ "language": "en", "url": "https://stackoverflow.com/questions/7597216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Why can't I write Nullable>? The definition of Nullable<T> is: [SerializableAttribute] public struct Nullable<T> where T : struct, new() The constraint where T : struct implies that T can only be a value type. So I very well understand that I cannot write: Nullable<string> a; //error. makes sense to me Because string is a reference type, not a value type. But I don't really understand why can't I write Nullable<Nullable<int>> b; //error. but why? Why is it not allowed? After all, Nullable<int> is a value-type, and therefore, it can be type argument to Nullablle<T>. When I compiled it on ideone, it gives this error (ideone): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as type parameter 'T' in the generic type or method 'System.Nullable' Compilation failed: 1 error(s), 0 warnings A: From section 4.1.10 of the C# language spec: A non-nullable value type conversely is any value type other than System.Nullable<T> and its shorthand T? (for any T), plus any type parameter that is constrained to be a non-nullable value type (that is, any type parameter with a struct constraint). The System.Nullable<T> type specifies the value type constraint for T (§10.1.5), which means that the underlying type of a nullable type can be any non-nullable value type. The underlying type of a nullable type cannot be a nullable type or a reference type. For example, int?? and string? are invalid types. A: From §10.1.5 of the C# 4 spec: The value type constraint specifies that a type argument used for the type parameter must be a non-nullable value type. All non-nullable struct types, enum types, and type parameters having the value type constraint satisfy this constraint. Note that although classified as a value type, a nullable type (§4.1.10) does not satisfy the value type constraint. A type parameter having the value type constraint cannot also have the constructor-constraint. A: As others have said, the spec prohibits this. Digging deeper, it's worth realising that you can make your own struct that allows this pattern: struct Nestable<T> where T : struct { /* ... */ } new Nestable<Nestable<int>>(); // This works just fine The prohibition of nested nullables can not be expressed using the type system available to you and me. It is only enforced by a special case in the compiler (CS0453). Aside: The new() constraint shown in the question doesn't actually exist on System.Nullable<T>. new() constraints are prohibited when using the struct constraint. CS0451: The 'new()' constraint cannot be used with the 'struct' constraint All structs support default initialisation anyway. A: This isn't exactly an answer, but just food for thought. Round 1 Nullable<Nullable<int>> a; error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable' Intellisense hints... The name can be simplified Round 2 Nullable<int?> a; error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable' Intellisense hints... The name can be simplified Round 3 int?? a; error CS1519: Invalid token '??' in class, struct, or interface member declaration error CS1525: Invalid expression term '??' Conclusion int? is essentially just a short-hand evaluation of Nullable<int>, but there's no such thing as int?? which is the only way I can see of representing Nullable<Nullable<int>> in short-hand. Plus int?? borrows the null-coalescing operator, so I'm glad it's not possible because it looks dreadful. Imagine int????????????? a; How pointless. Finally, since the reference source for Nullable does not yield any constraints for enforcing this, my guess is that this constraint was baked into the CLR as a special case when nullable value types were introduced into C#. A: Because it's in the C# spec (section 4.4.4): If the constraint is the value type constraint (struct), the type A must satisfy one of the following: * *A is a struct type or enum type, but not a nullable type. Note that System.ValueType and System.Enum are reference types that do not satisfy this constraint. *A is a type parameter having the value type constraint (§10.1.5).
{ "language": "en", "url": "https://stackoverflow.com/questions/7597218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: What implementation of cycle is better? I wonder, what implementation is better from reading and performance sides. 1) for (DateTime dayStart = GetDayStart(today), dayEnd = GetDayEnd(today); dayStart < endOfPeriod; dayStart = dayStart.AddDays(1), dayEnd = dayEnd.AddDays(1)) { // ... } 2) DateTime dayStart = GetDayStart(today), dayEnd = GetDayEnd(today); while (dayStart < endOfPeriod) { // ... dayStart = dayStart.AddDays(1); dayEnd = dayEnd.AddDays(1); } 3) Or, may be any another? Thanks in advance. A: Personally, I find the second one the most readable. Multiple statements in a for-loop are more error-prone and less clear to an objective reader of your code. A: For readability I would go with the second choise. The for statement is great for simpler loops, but it gets harder to follow when it gets more complicated. For performance there should be no difference at all. The compiler will likely produce the exact same code from the two different source codes. A: If you looking for minor variations of your approach you could also look at using Timespan... DateTime dayStart = GetDayStart(today); TimeSpan days = GetDayEnd(today) - dayStart; while (dayStart < endOfPeriod) { DateTime dayEnd = dayStart.Add(days); // ... dayStart = dayStart.AddDays(1); } Only reason I like this more is because I didn't like the fact you had to increment both dates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to create a network topology diagram using SNMP? I'm struggling to come up with a topic for my final year project/dissertation at University. I've had an idea but I'm not sure if it's a.) possible and b.) feasible in my timeframe. My idea is to create a piece of software which uses SNMP to get information (perhaps from ARP tables/routing tables) and construct a visual topology map (GUI). I'm not sure how reliable SNMP would be in this respect and to be honest I'm not sure how it'd work overall. Obviously I'd be willing to research it heavily if it could work. Also it's a lot to do to write an app that uses sockets and can parse SNMP in to useable application data, AS WELL as create graphics. For these reasons I'm uncertain in my own abilities to create the app itself. Any feedback, ideas or help are greatly appreciated, Cheers, Dan A: If your network is running OSPF, then yes it is possible and pretty easy. You could get the entire topology from a single node. Using SNMP you can get the OSPF link state database from the router and use it to draw the topology (because of the way OSPF works, you have info about all the links). Of course, if your network consists of more than one OSPF area, then it could get tricky. For OSPF, take a look at this MIB: http://www.oidview.com/mibs/0/RFC1253-MIB.html That should be a good start. If you're not running OSPF or some other link state routing algorithm it may be a bit more difficult since a single router won't know the entire topology.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: "Interface Builder was unable to determine the type of "MainStoryboard_iPhone.storyboard"" error in MonoDevelop In MonoDevelop I'm creating a 'MonoTouch Single View Application - Universal (Storyboard)', when I compile the solution I get the following error: Compiling interface definitions /Developer/usr/bin/ibtool --errors --warnings --notices --output-format human-readable-text "/Users/dev/Projects/JScanner/JScanner/MainStoryboard_iPhone.storyboard" --compile "/Users/dev/Projects/JScanner/JScanner/bin/iPhoneSimulator/Debug/JScanner.app/MainStoryboard_iPhone.storyboardc" --sdk "/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk" /* com.apple.ibtool.errors */ /Users/dev/Projects/JScanner/JScanner/MainStoryboard_iPhone.storyboard: error: Interface Builder was unable to determine the type of "MainStoryboard_iPhone.storyboard". ibtool exited with code 1 Build complete -- 1 error, 0 warnings This is just the basic solution, so I haven't added any new source files or views into it yet. A: This error will be fixed in the next version of MonoDevelop. For now, I would suggest you use xib-based projects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading comma in content of csv file (E.g. $1,23,456) Using C# program I am reading CSV File with value like (Name, Salary, Age) (A, $1,200, 27) (B, 2300, 27) In the header row there are three columns. I want to validate that the number of columns in data rows is also three. (C, 28) should be an invalid file. Currently I am doing this by counting the number of commas. But when the content itself is having comma ($1,200), this logic is failing. How do I solve this issue? A: Use library for reading csv files. Why are you wrintg it on yourown when someone already did it for you?. Last time i was reading csv i used CsvHelper. A: As a fast answer why don you split by (", ") var s = "Name, Salary, Age"; var t = "A, $1,200, 27"; var x = "B, 2300, 27"; string[] stringSeparators = new string[] {", "}; s.Split(stringSeparators, StringSplitOptions.None).Dump(); t.Split(stringSeparators, StringSplitOptions.None).Dump(); x.Split(stringSeparators, StringSplitOptions.None).Dump(); Not the best solution but it's one that fits.... As was commented by @Tim Pietzcker it's not a valid csv file.... Anyway.... A: Could you perhaps do this?...where fileLine would be "A, $1,200, 27". This is assuming that each column is delineated by a comma then a space. int lastCommaIdx = fileLine.LastIndexOf(","); string agePart = fileLine.Substring(lastCommaIdx + 1, fileLine.Length - (lastCommaIdx + 1)).Trim(); int age = Convert.ToInt32(agePart); fileLine = fileLine.Substring(0, lastCommaIdx); int dollarIdx = fileLine.LastIndexOf("$"); string salary = fileLine.Substring(dollarIdx, fileLine.Length - dollarIdx).Trim(); string name = fileLine.Substring(0, dollarIdx).Trim().TrimEnd(new char[1] { ',' }); Debug.WriteLine(string.Format("Name={0}, Salary={1}, Age={2}", name, salary, age));
{ "language": "en", "url": "https://stackoverflow.com/questions/7597236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Listbox multiitem selection on selectedindex change? I have a list box in which i have multiple value <asp:ListBox ID="lstbox" runat="server" SelectionMode="Multiple" Width="120px"> <asp:ListItem Value="0">None</asp:ListItem> <asp:ListItem Value="8">Rohan</asp:ListItem> <asp:ListItem Value="16">Jems</asp:ListItem> <asp:ListItem Value="64">Tena</asp:ListItem> <asp:ListItem Value="4">Marry</asp:ListItem> <asp:ListItem Value="2">Pinky</asp:ListItem> <asp:ListItem Value="32">Coral</asp:ListItem> <asp:ListItem Value="1">Dev</asp:ListItem> <asp:ListItem Value="128">Sam</asp:ListItem> </asp:ListBox> at once i want to select either one item or more than one and one selected index change i am calling a method protected void lstbox_SelectedIndexChanged(object sender, EventArgs e) { Presenter.getRoles();//filling a grid from database call } public void getRoles() { int proid = 0; int per=0; if (View.UPrivileges.Count > 0) { proid = Convert.ToInt32(View.UPrivileges.SelectedValue);//listbox selection per= Convert.ToInt32(View.Products.SelectedValue);// i have a ddl product checking the value } if (proid != 0 || per !=0) { View.Ownerid = per.ToString(); View.Role = (CRole)proid; List<User> list = new List<User>(); list.AddRange(userDao.GetUserRolesForItems(View.Role, View.Ownerid));// query method call View.UserListItems.List = list; View.UserListItems.TotalRowCount = list.Count; } } when i am selecting 1 value then its working fine but for more than one items giving error, I want to know whether its possible with selectedIndexChange or not, if yes how if not then how to do it on one button click A: this may help foreach (ListItem item in lstbox.Items) { if (item.Selected) { //code here } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Instantiating classes dynamically? Let's say I have this array: String[] names = {"stack1", "stack2", "stack3"}; Is it possible to instantiate Stack dynamically using those names, so there will be 3 objects named stack1, stack2, and stack"? Later in the code, I'd like to call stack1.pop(), or stack3.empty(), for example. I've been told to take a look at reflection, and still not sure how. A: You can create objects via reflection if you have the class name in a String, for example. You can not "dynamically" create "variables". For example: String s = "foo"; // some magic that creates a variable identified by s foo.callSomeMethod(); That won't work. Variables in Java (fields, local variables and parameters) can only be created at compile time. What you can do (and which is sometimes the correct approach) is to create a Map<String,YourType> and hold each newly created object via this map with a given String: Map<String,MyType> map = new HashMap<String,MyType>; String s = "foo"; map.put(s, new MyType()); // ... map.get("foo").callSomeMethod(); A: Unless stack1 is a class in the default package you won't be able to create classes of that "type". If it is just a variable name, you're missing the type anyways. Have a look at the Java Compiler API that should allow you to dynamically create sources and then compile and use them. I haven't used it myself yet, but maybe this article could help: http://www.javabeat.net/articles/73-the-java-60-compiler-api-1.html Additionally, if you could elaborate a bit on what exactly you are trying, this would be helpful. A: Why not just use a map? Map<String, Stack<String>> m = new HashMap<String, Stack<String>>(); m.put("stack1", new Stack<String>()); m.get("stack1").push("Hello!");
{ "language": "en", "url": "https://stackoverflow.com/questions/7597245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: vim script: how to execute a command in a vim function Why does the following: let s:colorschemes = ['synic', 'ir_black'] let s:colorscheme_idx = 0 function! RotateColorscheme() let s:colorscheme_idx += 1 let s:name = s:colorschemes[s:colorscheme_idx] echo s:name colorscheme s:name endfunction not execute the colorscheme? Vim complains with the following error 'cannot find colorschem s:name'. How do I tell it that I want it to derefence that variable and not apply it literally to :colorscheme? A: Have a look at this script from vim.wikia.com which does pretty much what you are asking for. Key-line seems to be this one: let nowcolors = 'elflord morning desert evening pablo' execute 'colorscheme '.split(nowcolors)[i]
{ "language": "en", "url": "https://stackoverflow.com/questions/7597249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Nested form not updating the database I have a nested form that does not update the database. Models: User: has_many :designs, :dependent => :restrict accepts_nested_attributes_for :designs attr_accessible :designs_attributes Design: belongs_to :user Designs Controller: def update @design = Design.find(params[:id]) @user = User.find_by_id(@design.user_id) @points = (@user.points + 5000) if @design.update_attributes(params[:design]) flash[:success] = "Design aproved" redirect_to designindex_path else @title = @design.name + %(, created by ) + @design.user.username render 'edit' end end And here is the form: <%= form_for @user, :html => { :multipart => true } do |f| %> <%= f.hidden_field(:points, {:value => @points}) %> <%= f.fields_for :designs, @design do |d| %> <div class="field"> <%= d.label :total_price, %(New price) %><br /> <%= d.text_field :total_price %> </div> <%= d.hidden_field(:aproved, {:value => 1}) %> <% end %> <div class="actions"> <%= f.submit "Submit" %> </div> <% end %> Also, when I push Submit button, it redirects me to root_path. Looking in the console output I found this: Started POST "/users/101" for 127.0.0.1 at 2011-09-29 15:31:16 +0200 Processing by UsersController#update as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"N16nb5i/PUPftGHs3uvnnLwrp8e/PQB88w0OU6DLGko=", "user"=>{"points"=>"7500", "designs_attributes"=>{"0"=>{"total_price"=>"20", "aproved"=>"1", "id"=>"66"}}}, "commit"=>"Submit", "id"=>"101"} The problem here seems to be the following: An user has_many designs, but when doing the POST request the controller does not specify which one is being updated. Anyway, the users.points attribute is neither updated. Update Ok, I got the problem, I have this in users_controller.rb: before_filter :authenticate, :only => [:index, :edit, :update, :destroy] before_filter :correct_user, :only => [:edit, :update] And I'm trying to update another user's information from an admin account. Can I do this in any way? Here is the code for those: def correct_user @user = User.find(params[:id]) redirect_to(root_path) unless current_user?(@user) end def current_user?(user) user == current_user end def authenticate deny_access unless signed_in? end def signed_in? !current_user.nil? end A: You'll want to do: <%= f.fields_for :designs, @design do |d| %> ... <% end %> This will make sure it uses the designs_attributes attribute (and will default to 0 index I believe). Can't remember if you'll need to wrap the @design in an array ([@design]), don't believe you do. Your params should look like {:user => {:designs_attributes => { '0' => {:id => 1, ... } } } } A: Ok, got it working, just modified correct_user function as follows def correct_user @user = User.find(params[:id]) redirect_to(root_path) unless current_user?(@user) || current_user.admin end
{ "language": "en", "url": "https://stackoverflow.com/questions/7597252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Extract Text from URL the problem is I need to extract just text content of a given URL. I should insist that I just need the text content. there is many methods on the internet which return all content of a web page without any text separation. I need the code in c# language. thanks for any answer A: With HTML there is no such thing as "just text". Text you see on a webpage is rendered according to how the markup is defined. You could manually strip all HTML tags between the <body></body> tags, then you'd have something like all text on the page. This will be error-prone, however. Most solutions you'll find online will opt for a regular expression (something like Regex.Replace(str, "<(.|\n)*?>", string.Empty);), but if you use that you're likely to shoot yourself in the foot one day. A: Well You need to Use some Parsing Technique to get Text like , you can use Xpath, or Regular Expression for getting Text from giving Url's Html
{ "language": "en", "url": "https://stackoverflow.com/questions/7597255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: javascript regular expression replacement doesnt work? why this regular expression replacement doesnt work? var url = 'http://myweb.com/page/1/id/2'; newUrl = url.replace('/page\/[0-9]+/', 'page/2'); //it must become http://myweb.com/page/2/id/2 A: You need to do two things: * *change str.replace to url.replace *remove the ' around the regex var url = 'http://myweb.com/page/1/id/2'; newUrl = url.replace(/page\/[0-9]+/, 'page/2'); Example: http://jsfiddle.net/fhqXn/ A: Use url rather than str, if you want to replace something in the String stored in the url variable. A: You have a naming misspell. Rename your url var to str or change the str.replace to url.replace: newUrl = url.replace('/page\/[0-9]+/', 'page/2');
{ "language": "en", "url": "https://stackoverflow.com/questions/7597259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get the tail of a std::string? How to retrieve the tail of a std::string? If wishes could come true, it would work like that: string tailString = sourceString.right(6); But this seems to be too easy, and doesn't work... Any nice solution available? Optional question: How to do it with the Boost string algorithm library? ADDED: The method should be save even if the original string is smaller than 6 chars. A: This should do it: string str("This is a test"); string sub = str.substr(std::max<int>(str.size()-6,0), str.size()); or even shorter, since subst has string end as default for second parameter: string str("This is a test"); string sub = str.substr(std::max<int>(str.size()-6,0)); A: There is one caveat to be aware of: if substr is called with a position past the end of the array (superior to the size), then an out_of_range exception is thrown. Therefore: std::string tail(std::string const& source, size_t const length) { if (length >= source.size()) { return source; } return source.substr(source.size() - length); } // tail You can use it as: std::string t = tail(source, 6); A: You can use iterators to do this: #include <iostream> #include <string> using namespace std; int main () { char *line = "short line for testing"; // 1 - start iterator // 2 - end iterator string temp(line); if (temp.length() >= 8) { // probably want at least one or two chars // otherwise exception is thrown int cut_len = temp.length()-6; string cut (temp.begin()+cut_len,temp.end()); cout << "cut is: " << cut << endl; } else { cout << "Nothing to cut!" << endl; } return 0; } Output: cut is: esting A: Since you also asked for a solution using the boost library: #include "boost/algorithm/string/find.hpp" std::string tail(std::string const& source, size_t const length) { boost::iterator_range<std::string::const_iterator> tailIt = boost::algorithm::find_tail(source, length); return std::string(tailIt.begin(), tailIt.end()); } A: Using the substr() method and the size() of the string, simply get the last part of it: string tail = source.substr(source.size() - 6); For handling case of a string smaller than the tail size see Benoit's answer (and upvote it, I don't see why I get 7 upvotes while Benoit provides a more complete answer!) A: You could do: std::string tailString = sourceString.substr((sourceString.length() >= 6 ? sourceString.length()-6 : 0), std::string::npos); Note that npos is the default argument, and might be omitted. If your string has a size that 6 exceeds, then this routine will extract the whole string. A: Try substr method. A: I think, using iterators is C++ way Something like that: #include <string> #include <iostream> #include <algorithm> #include <iterator> using namespace std; std::string tail(const std::string& str, size_t length){ string s_tail; if(length < str.size()){ std::reverse_copy(str.rbegin(), str.rbegin() + length, std::back_inserter(s_tail)); } return s_tail; } int main(int argc, char* argv[]) { std::string s("mystring"); std::string s_tail = tail(s, 6); cout << s_tail << endl; s_tail = tail(s, 10); cout << s_tail << endl; return 0; } A: Try the following: std::string tail(&source[(source.length() > 6) ? (source.length() - 6) : 0]); A: string tail = source.substr(source.size() - min(6, source.size()));
{ "language": "en", "url": "https://stackoverflow.com/questions/7597260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Odd JS console error in firefox web developer (about chrome though...?) Error: [Exception... "'JavaScript component does not have a method named: "handleEvent"' when calling method: [nsIDOMEventListener::handleEvent]" nsresult: "0x80570030 (NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED)" location: "JS frame :: chrome://global/content/bindings/popup.xml :: hidePopup :: line 108" data: no] Source File: chrome://global/content/bindings/popup.xml Line: 108 Anyone ever seen this? Any idea where it could be coming from? A: Don't upgrade. With an upgrade from Mozilla 4.6 you may see this line below before it crashes: Script: chrome://browser/content/tabbrowser.xml:1636
{ "language": "en", "url": "https://stackoverflow.com/questions/7597261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to change the columns data automatically in sql server tables based on the changing day? I am creating bank application project in this project i am using sql server2008, vs2010(.net) now my problem is account login page, user enter 3 time wrong password account is blocked today only , next day(date changing) automatically activate that account how to write the code pls help me. Thank u hemanth A: Have a column AccountLockedUntil (which is a DATETIME NULL or similar), and set it to the following midnight when the threshold is reached. When validating the credentials, check to make sure it is either NULL or that the current time is past whatever is stored there. When the user logs in successfully, set it to NULL. To keep track of the number of failed logins, I would have a complete audit log table (logging both successful and failed attempts) plus a corresponding field on the user accounts table which counts the current number of failed logins. Strictly speaking this is a violation of database normalization, but the audit table will get huge very quickly so you don't want to have to search through that more than necessary, and certainly not on every login attempt. A: Create a table called LoginEvents. When a user attempts to login create an entry here (with the user id, date and a success/fail flag). When you load the log in page, check this table for three (or more) entries that have fail = true and that have date >= today's date - 1. If there is are three or more show them an error message saying their account is blocked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: ninject and enterprise library service locator dependant assemblies I am using the Microsoft.Practices.ServiceLocation assembly in conjunction with ninject to aid in service loaction. I register my ninject kernel into the servicelocator provider method: var kernel = new StandardKernel(); //do bindings var locator = new NinjectServiceLocator(kernel); ServiceLocator.SetLocatorProvider(() => locator); The above code all works fine on machines that have the enterprise library installed (via the msi executable). I am not in a position to run the installer in production, so i have the dll locally in the bin directory, hoping this will work. However it does not work. I dont get any assembly not found exceptions, instead i get an object reference not set exception from call to: 'at Microsoft.Practices.ServiceLocation.ServiceLocator.get_Current()'. I have read in a few places that this assembly doesn't have any dependencies http://msdn.microsoft.com/en-us/library/ff664422%28v=PandP.50%29.aspx and a local dll should do the trick, but it doesnt seem to. I've tested on a few boxes and the error occurs consistently until i run the installer. Interestingly, after i uninstall the library, it still works (i guess it's cached somewhere). Has anyone got any experience with type of issue? A: the issue turned out to be that the servicelocator.current was empty because one of the binding modules i was auto registering was missing a dll. because the bootstrapper was being called from the global.asax i had error handling that was supposed to be logging any exceptions and continuing (wouldnt want the whole site to stop for this one page). so i never got the reg error and my bootstrapper was failing without telling me. var kernel = new StandardKernel(); //do bindings -> throw error here without reaching below two lines to regiester the service locator var locator = new NinjectServiceLocator(kernel); ServiceLocator.SetLocatorProvider(() => locator);
{ "language": "en", "url": "https://stackoverflow.com/questions/7597263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: With default bean scope as singleton, isn't it going to be bad when concurrent calls occur? I have declared a Spring bean, which polls my email server every so and so seconds. If there is mail, it fetches it, and tries to extract any attached files in it. These files are then submitted to an Uploader which stores them safely. The uploader is also declared as a Spring bean. A third bean associates the email's sender with the file's filename and stores that in a DB. It turned out that when a few people tried to send emails at the same time, a bunch of messy stuff happened. Records in the DB got wrong filenames. Some did not get filenames at all, etc. I attributed the problem to the fact that beans are scoped to singleton by default. This means that a bunch of threads are probably messing up with one and the same instance at the same time. The question is how to solve this. If I synchronize all the sensitive methods, then all threads will stack up and wait for each other, which is kind of against the whole idea of multithreading. On the other hand, scoping the beans to "request" is going to create new instances of each of them, which is not really good either, if we speak about memory consumption, and thread scheduling I am confused. What should I do? A: I agree with both @Bozho and @stivio answers. The preferred options are to either pass store no state in a singleton scoped beans, and pass in a context object to the methods, or to use a prototype / request scoped beans that get created for every processing cycle. Synchronization can be usually avoided, by choosing one of these approaches, and you gain much more performance, while avoiding deadlocks. Just make sure you're not modifying any shared state, like static members. There are pros and cons for each approach: * *Singlton beans are act as a service-like class, which some may say are not a good Object-Oriented design. *Passing context to methods in a long chain of methods may make your code messy, if you're not careful. *Prototype beans may hold a lot of memory for longer than you intended, and may cause memory exhaustion. You need to be careful with the life cycle of these beans. *Prototype beans may make your design neater. Make sure you're not reusing beans by multiple threads though. I tend to go with the service approach in most simple cases. You can also let these singleton beans create a processing object that can hold it's state for the computation. This is a solution that may serve you best for the more complexed scenarios. Edit: There are cases when you have a singleton bean depending on prototype scoped bean, and you want a new instance of the prototype bean for each method invocation. Spring supplies several solutions for that: The first is using Method Injection, as described in the Spring reference documentation. I don't really like this approach, as it forces your class to be abstract. The second is to use a ServiceLocatorFactoryBean, or your own factory class (which needs to be injected with the dependencies, and invoke a constructor). This approach works really well in most cases, and does not couple you to Spring. There are cases when you also want the prototype beans to have runtime dependencies. A good friend of mine wrote a good post about this here: http://techo-ecco.com/blog/spring-prototype-scoped-beans-and-dependency-injection/. A: Otherwise just declare your beans as request, don't worry about the memory consumption, the garbage collection will clear it up, as long there is enough memory it won't be a performance problem too. A: Speaking abstractly: if you'e using Spring Integration, then you should build your code in terms of the messages themselves. Eg, all important state should be propagated with the messages. This makes it trivial to scale out by adding more spring Integration instances to handle the load. The only state (really) in Spring Integration is for components like the aggregator, which waits and collects messages that have a correllation. In this case, you can delegate to a backing store like MongoDB to handle the storage of these messages, and that is of course thread safe. More generally, this is an example of a staged event driven architecture - components must statelessly (N(1) no matter how many messages) handle messages and then forward them on a channel for consumption by another component that does not know about the previous component from which the message came. If you are encountering thread-safety issues using Spring Integration, you might be doing something a bit differently than intended and it might be worth revisiting your approach... A: Singleton-scoped beans should not hold any state - that solves the problem usually. If you only pass data as method parameters, and don't assign it to fields, you will be safe. A: Singletons should be stateful and thread-safe. If a singleton is stateless, it's a degenerate case of being stateful, and thread-safe is trivially true. But then what's the point of being singleton? Just create a new one everytime someone requests. If an instance is stateful and not thread-safe, then it must not be singleton; each thread should exclusively have a different instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Bit order in C/C++ I have to implement a protocol which defines data in 8bit words, which starts with the least significant bit (LSB) first. I want to realize this data with unsigned char, but I don't know what's the bit order of LSB and most significant bit (MSB) in C/C++, that could possible require swapping the bits. Can anybody explain me how to find out an unsigned char is encoded: with MSB-LSB or LSB-MSB? Example: unsigned char b = 1; MSB-LSB: 0000 0001 LSB-MSB: 1000 0000 A: There is no such thing in C/C++. The least significant bit is -- well -- the least significant bit. Since the bits don't have addresses, there is no other ordering. A: Endian-ness is platform dependent. Anyway, you don't have to worry about actual bit order unless you are serializing the bytes, which you may be trying to do. In which case, you still don't need to worry about how individual bytes are stored while they're on the machine, since you will have to dig the bits out individually anyway. Fortunately, if you bitwise AND with 1, you get the LSB, regardless of storage order; bit-AND with 2 and you get the next most significant bit, and so on. The compiler will sort out what constants to generate in the machine code, so that level of detail is abstracted away.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: VS Web Setup Project alternatives? Can anyone recommend a better installer for web-applications? What do you use to deploy/install your web-apps? PS. What I personally dislike about "Web Setup Project" is that it requires the "IIS 6.0 Management Capability Feature" to be present on the target machine. This frustrates many of our customers. A: I've used Advanced Installer in the past and it worked well for me. The IIS features are in the Pro edition or above, which makes it pretty cheap as well ($299 for Pro). http://www.advancedinstaller.com/internet-information-services.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7597277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Handling Right Click/Left Click of Task-bar Button in c# I have a form (having Taskbar button shown in Taskbar) and I want to handle left/right clicks of this Task-bar button. I searched everywhere but could find the right answer. There are some related queries posted in stack-overflow as well: * *Using wndproc in C# to minimize form on leftclick of taskbar *How to Detect Right Click on the Taskbar But, nobody seems to have given a proper answer to "How to do" it? Is there any pointers or code snippet how to do it? Please note that I am talking about Task-bar app button (please don't confuse with Systray menu or Notification area). I have explicitly stated it because I have seen this confusion several places. A: Your application doesn't get a say in how the task bar button is handled. The task bar is owned by windows, and is used by windows to control display and positioning of your application's windows. Basically your request is out-of-bounds in the windows playground. Sorry. A: what you can do is to use TaskbarManager out of the ApicodePack library Windows 7 Taskbar C# Quick Reference where you are able to handle such events.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Windsor Typed Factory Not Releasing Children I have a factory and component registered in Windsor 2.5.1 like so: interface IFooFactory{ IFoo CreateFoo(); } interface IFoo { void DoSomething(); } class ConcreteFoo : IFoo, IDisposable { public void Dispose(){ Log.info("Going now, bye!") } } container.Register( Component.For<IFooFactory>().AsFactory().Lifestyle.PerWebRequest, Componenet.For<IFoo>().ImplementedBy<ConcreteFoo>().Lifestyle.Transient ); But what I am noticing is the instances of IFoo (could be 100 or so per request) are not being released or having their dispose method called. I assumed from the documentation here: http://docs.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx that if the factory was PerRequest then that would release the objects which it created at the end of the request. If I pass the factory itself to my component, and call a releasing method like so: interface IFooFactory{ IFoo CreateFoo(); void Releaser(IFoo foo); } interface IFoo { void DoSomething(); } class ConcreteFoo : IFoo, IDisposable { IFooFactory fact; public ConcreteFoo(IFooFactory fact).... public void DoSomething(){ fact.Releaser(this); //Do the rest } public void Dispose(){ Log.info("Going now, bye!") } } Then my components get released as expected. Any advice on whether this is a bug or I am mis-understanding something. My solution works at the end of the day, but not as nice as I had hoped. A: Following the comments below the main question, Krzysztof has released an update to fix this in Windsor. If you see these issues, then either upgrade to 2.5.4 or even better, Windsor 3 if you can.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Textbox lag with a lot of data? (Silverlight 4) I have a textbox bound to a string in my ViewModel via TwoWay binding that often contains hundreds of lines if not more. When the textbox contains a lot of text, input lag can become apparent when entering text. So, I'm now trying to track the source of this performance hit and I'm wondering if it could be a limitation of the control itself. Any thoughts? Thanks! Edit: In my tests I have 800 lines of 211 characters each when I begin to see noticable lag. And the more I add text, the more it lags. Here's some code: <TextBox x:Name="rightTextBox" Text="{Binding Source={StaticResource ViewModel}, Path=Text, Mode=TwoWay}" AcceptsReturn="True" /> And my textbox is bound to this string: private string text; public string Text { get { return this.text; } set { if (this.text != value) { this.text= value; NotifyPropertyChanged("Text"); } } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } A: So basically you asking the TextBox (which is designed to do things like "Please enter your first name") to handle 300KB worth of text and now your seeing some lag. Hmmm... Have you tried creating an empty Silverlight application containing a single TextBox, assigning that amount of text directly to its Text property and then start editing. Do you stil see lag? If so then it sounds like you're pushing the limits of the ability of text box. I don't know of a serious alternative perhaps something Third-party might help. Its possible that the RichTextBox may not suffer the same problem since its clearly designed for that sort of text editing. However its not easy to bind to and handles a strange dialect of Xaml rather than straight text.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to add two or more repository controls in devepxress grid control Hey i am dealing with winform(c#) application. i am using Devexpress Grid Control. Is it possible to have two or more repository controls in grid control column for edit purpose. eg.. say like a textbox and combo box in a grid column.(this is possible in web application by adding item templates to the grid column) Is this possible or any other way to get this done? A: You can set the GridColumn.ColumnEdit property to specifying the editor used to edit a column's value
{ "language": "en", "url": "https://stackoverflow.com/questions/7597308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Slow uploads to running Android emulator I have searched but not found any queries or answers for my specific circumstance. I have a fast new machine with plenty of memory running Windows 7. I'm using the latest Eclipse and Android SDK. When I run an app the emulator takes about 45 seconds to start (blazingly fast for the emulator!) from run initiation to running my app. If I then change the app and re-run it on the still-running emulator, the time increases to 70+ seconds! As opposed to all other complaints people have, in my case restarting the emulator is faster than using the existing instance. I don't like that. Here are the times: 2011-09-29 13:07:13 - hello Uploading hello.apk onto device 'emulator-5554' 2011-09-29 13:07:18 - hello Installing hello.apk... 2011-09-29 13:07:37 - hello Success! on rerunning after changing the app to get it to reload: 2011-09-29 13:08:18 - hello Uploading hello.apk onto device 'emulator-5554' 2011-09-29 13:09:16 - hello Installing hello.apk... 2011-09-29 13:09:24 - hello Success! As you can see, the upload to the emulator takes a mere 5 seconds when the emulator is freshly started. It takes nearly a minute with a running emulator! This is the cause of the extended re-running time. This doesn't change even when I uninstall the app on the emulator before re-running it. Any ideas on what I could try to solve this? It appears to be some kind of communication problem, possibly with adb. A: My new discovery is a small "hack" how you can make your upload faster. I realized that the cases when the upload was faster were caused by my interaction. So when I upload new app without active working with emulator, it is slow. But when I work with it (testing my application, exiting, opening applications list, etc.), the upload is MUCH faster - in my case approx. 15seconds instead nearly 2 minutes. So I think, that the problem is somehow in performance settings of the emulator. When I do nothing, it thinks no big performance is needed, emulator is switched to some economic state, so also my upload is slow. A: A better solution: Go to Run -> Run Configurations... -> Target Tab -> Additional Emulator Command Line Options. Add there: -netspeed full -netdelay none Now close the emulator and run it again. After doing this the time for uploading went from 2 minutes to 8 seconds. Edit: I have also found that quitting Skype makes my emulator upload much faster. A: I have the same problem, I'm developing an android application which is like 4,6MB and it takes me like maybe 50-60 seconds to upload it on emulator and run it.I don't think this is a problem with the communication. The JVM is slow, that's why you need a time to upload your apk and run it.I don't think you can do anything about it, except you start testing your application on a device. A: Play with the emulator while uploading your application. I totally agree with teepee. It reduced my waiting time from 4 minutes to 30 secs. A: The fastest emulator you can get it's a VMWare machine with Android. While developing my game, Elastic World, I was suffering from the same problem. After waiting minutes for the emulator to startup, the game was running at 20 FPS maximum. Even on low end android devices I could easily get 60 FPS. The upload speed was very slow. So I moved to a VMWare Android machine, following the instructions from this site: http://www.android-x86.org/documents/installhowto/ The same game loop now runs at 250 FPS. (it's not playable at this speed and I have the game limited to max 60 FPS, but overriding this limitation it gives 250 FPS) When Eclipse ends the build process I just have to wait 1 to 5 seconds for the game to appear on the virtual machine. And I'm running an old Core2Duo A: This is not an issue with the AVD, it's eclipse the problem and I don't know if there is a way to change it within what we could call the jungle of parameters. To be brief you can launch an emulator all by yourself in a console command using the following : emulator.exe -avd MyAVDName -netspeed full -netdelay none Nice the parameters, why isn't Eclipse using it? Some Eclipse coder should make it the default. Another solution is to switch to IntelliJ IDEA. It will gloriously replace your old clunky IDE with a fresh and better one. A: I know this is an old topic, but I think I actually have a solution to this issue. First you need to boot the emulator without the netspeed arguments like follows: emulator -avd <name> Once it's started log in to the emulator using telnet. You can get the port from the top of the emulator window or by running adb devices and looking at the serial for the emulator which is in the form emulator-port (this is usually 5554 in most cases) telnet localhost 5554 After you've logged in using telnet you need to issue the following command to force the emulator to use a very high network speed network speed 500000 You can then check this setting in telnet using the following command network status Which should return Current network status: download speed: 500000000 bits/s (61035.2 KB/s) upload speed: 500000000 bits/s (61035.2 KB/s) If you now try to install the APK you should find the performance is dramatically increased. In my case it went from 260s to 18s. A: As others have posted, just clicking around in the emulator while uploading drastically improves the upload speed. I had the same problem and Googled for an answer, and trying out this trick helped me. I'm running a 2.3.3 AVD. A: Just thinking out loud: I don't know this for a fact, but I'm wondering if this slow down is because Android applications each have their own instance of the Dalvik VM and run as a separate user and process. When you "think" you have closed your application, Android may be keeping the process (definitely the VM) alive in case you restart the application. This is similar to the pre-fetch behavior in windows. When you re-run the application, after modifying the sources, Android perhaps has to destroy the cached instance. The additional delay you notice in the case of re-deployment in the same emulator instance may be because of the costs incurred in gracefully shutting down the VM and the application. A: I get the same problem, but I'm convinced it has something to do with the O.S., because I uploaded the same application using a MacBook Pro and a Dell laptop, which is more powerful, given the hardware spec, however the upload time is significantly lower on the Mac. On this Dell laptop with Windows, however, uploads to actual Android devices are way, way faster. I thought it might be related to the "Google USB Driver package", that I haven't installed before, but after installing it, nothing really changed. A: Try to set your emulator RAM to 1024. A: Elaborating on what teepee said in an earlier post, I've found that if I muck with the already-running AVD during the uploading phase, it finishes MUCH quicker (5 seconds vs 60 seconds) and I'm installed and running in a fraction of the time. This is with a 4.0.3 AVD. Haven't tried the others yet. A: The alternative ways: Setting up a FTP server on your pc for hosting apk files, now you can download apk files by android emulator web browser and install app directly whitout using adb. or Install a samba client on android emulator and share apk files on your pc, then copy apk files to emulator and install app directly whitout using adb. All of above ways are faster than adb install. A: Silly question - did you try it on several AVDs? It is possible your one AVD is messed up in some way. A: Do as much interaction with emulator as you can while uploading the apk on emulator, if you press random buttons of emulator while uploading it will upload early, before it took 5-6 mins to upload but now it take only 15 - 20 secs. A: I have seen this too. Here is something that helped, assuming you've been using the same AVD. Wipe the user data on the AVD. After doing this, it would load the app much faster again, a couple of seconds. A: In a terminal/console I shell into the AVD with adb -e shell then go to the tmp directory where the apk is being uploaded cd /data/local/tmp then do ls -l to see the current file size. I've found that if I sit there and keep hitting up arrow then enter to quickly repeat the ls -l the upload speeds up dramatically. You can watch the progress as the file size increases. This is probably similar to the effect of clicking around in the AVD others have mentioned. I'm on a Mac. Not sure if it's the same on Windows or Linux. A: This might work on windows, start the Task manager --> processes tab--> look for emulator.exe, right click and set priority to high dont forget to set it to normal after your work is done. also closing unwanted applications which require a lot of memory like chrome and firefox can be closed when not needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "43" }
Q: Invoking a Google Chrome extension from Javascript There is an excellent extension called Blipshot which takes page screenshots. I need to invoke the extension with page level javascript, instead of clicking its icon. Is this possible? A: You cannot invoke any methods of an extension from within a web page. However, it's possible to inject a content script into the web page, and use sendMessage and onMessage, or onConnect and connect. To edit an extension: Visit chrome://extensions page, and enable the Developer mode. Unpack an extension and/or visit the extension's directory. Edit the manifest.json file, and add the necessary lines (see here). Add an event event listener at the background page. Add a poller in the content script, eg: // Content script var poller = window.setInterval(function() { if (document.documentElement.getAttribute('extensionCalled')) { chrome.extension.sendMessage({"anyname": "anything"}, function() { /*optional callback function.*/alert("Something happened") }); clearInterval(poller); } }, 200); // Background chrome.extension.onMessage.addListener(function(request, sender, callback) { if (request.anyname == "anything") { function_logic_here(); //Optionally, callback: callback(); } }); See also * *Chrome extension - retrieving Gmail's original message - Using DOM events to communicate between a page and extension (recommended) *MDN: postMessage - It can be used to communicate between a page and extension (this method may cause conflicts when the page itself is also using the message events). References: * *Extension messaging *Content scripts *Content scripts in extensions A: It would only be possible if the extension provides an interface to do it. Extensions run in an isolated environment, so you don't have direct access to any of their functions. The closest they get is content scripts, which have access to the DOM. Because of that, you can communicate using events, but obviously the extension would need to set up event handlers for them, so it completely depends on the extension.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Strategy for Creating Fork of Android on GitHub I'm trying to create a fairly low-level change in Android source -- changing the package manger. I want to get the whole source using the repo tool described in source.android.com. I have a fork of the platform_frameworks_base project on github. So, the question is how do I go about getting my platform_frameworks_base instead of the one provided by Android. I just want to be able to clone my own fork, create a branch in there and then push it in my own github. I can worry about pull requests to the main repo later. Any help on the strategy/method of doing this? p.s. My "workflow" is aimed to be similar to this: http://appanalysis.org/download.html A: probably a bit late :) , but for the records, you might be want to take a look into this http://www.primianotucci.com/blog/fork-android-on-github
{ "language": "en", "url": "https://stackoverflow.com/questions/7597313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Grid View Combo Box Column I am working on a Windows Form. I have a ComboBox and on it's SelectedIndexChanged, I need to bind values to a GridViewComboBox Column. Suppose I have bound all the states in the ComboBox, then when a state is selected, I need to bind all the districts coming under the particular state. How can I do it? A: I am not sure of the question truly. Somewhere you wrote Combobox and sometimes GridViewComboBox. Still if you want what I am thinking: datagridview dg; string[] district = { "dis1", "dis2", "dis3" }; for (int i = 0; i < dg.Rows.Count; i++) { DataGridViewComboBoxCell cc = (DataGridViewComboBoxCell)dg["dgc", i]; cc.DataSource = country; cc.Value = country[0]; } dgc = Column name of DatagridViewComboboxColumn. Here, putting the following code in State Combobox TextChanged event. String array district are district source. Tweak this concept according to your need, I think you will get what you are looking for. Need any more clarity, add a comment. Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Integrate LWUIT with Blackberry JDE I am trying to make an integration between LWUIT and Blackberry JDE. I am importing the LWUIT .jar file into a library project and setting the dependencies of this library with another project. I am then creating a new LWUIT form and running the project. I am alwas getting a "ClassDefError". How to integrate the LWUIT with blackberry? Anyone has a clue? A: Why you don't use NetBeans?. I suggest you can use NetBeans for Blackberry development with LWUIT. And you can easily integrate Blackberry JDE with NetBeans.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Displaying jQuery UI dialog with multiple checkboxes I'm trying to display multiple checkboxes and then submit the selected checkboxes as HTTP GET (i.e. as parameters in URL string) to the same script: Here is my simplified test code - test.php: <html> <head> <style type="text/css" title="currentStyle"> @import "http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css"; </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script> <script type="text/javascript"> $(function() { $('#name').dialog({ autoOpen: false, modal: true }); }); </script> </head> <body> <form> <p><input type="button" value="Select name" onclick="$('#name').dialog('open');"></p> <div id="name" title="name"> <?php $NAMES = array( 'project one', 'project two', 'project three', ); foreach ($NAMES as $name) { printf('<p><label><input type="checkbox" name="name" value="%s">%s</label></p>', urlencode($name), htmlspecialchars(substr($name, 0, 120)) ); } ?> </div> <input type="submit"> </form> </body> </html> But for some reason, when I select the first 2 checkboxes click the "Submit" button (sorry for the non-English name in the screenshot), then the script http://myserver/test.php? is being submitted and not http://myserver/test.php?name=project+one&name=project+two as I would expect. If I get rid of all JQuery UI stuff, then it works. What am I doing wrong? (besides using name="name" which is because that's a database table column name and doesn't seem to be the reason for this problem anyway) UPDATE: In my real program (not the above test case) I actually have several such dialogs and would like to set some settings in each dialog and only after that that click a Submit button. So the Submit button must be outside the dialog(s). Thank you! A: Assuming all the form inputs are checkboxes you can use the following to compile and submit the details as a GET. using your original code add the following function function compileInputs(){ var string = ''; var inputs = new Array(); //loop through all checkboxes $(':checkbox').each(function(){ if($(this).is(':checked')){ inputs.push($(this).attr('name')+"="+$(this).val()); } }); string = "?"+inputs.join("&"); window.location.replace(string); } you will need to change the names of the inputs from name='name' to name='name[]' then change the submit to a button as follows: <input type="button" onClick='compileInputs()' value='submit'> you will no longer need the <form> tags for a more selective approach: //get all checkboxes from div#name $('div#name :checkbox').each(function(){ if($(this).is(':checked')){ inputs.push($(this).attr('name')+"="+$(this).val()); } }); //get all checkboxes from div#appsversion $('div#appsversion :checkbox').each(function(){ if($(this).is(':checked')){ inputs.push($(this).attr('name')+"="+$(this).val()); } }); //get all checkboxes from div#osversion $('div#osversion :checkbox').each(function(){ if($(this).is(':checked')){ inputs.push($(this).attr('name')+"="+$(this).val()); } }); A: You may need to wrap the whole form in a div and then dialog the new div in the dialog rather than just the div #name A: Try this: $("#submitButton").click(function(){ $("#formId").submit(); }); A: Assuming the dialog is actually the problem, you may have to have your dialogs populate some hidden fields on the page to actually submit. Here is a very simple sample to get you started. http://jsfiddle.net/jUH9g/ When you click ok in the dialog it populates the 'names' textbox inside the form that actually gets submitted. In your real code you would change input type="textbox" to input type="hidden" $("#dlg").dialog({autoOpen: false, buttons: { "OK": function () { var names = ""; $("input:checkbox").each(function () { if (this.checked) { names += $(this).val() + ","; } }); $("#names").val(names); } } }); A: Should you not do name="name[]" . Then on the form submit (however you submit it (AJAX or non AJAX), you can get the "name" array as your post variable and handle it as you may wish. Correct me if I am wrong
{ "language": "en", "url": "https://stackoverflow.com/questions/7597320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Export Image column from SQL Server 2000 using BCP I've been tasked with extracting some data from an SQL Server 2000 database into a flat format on disk. I've little SQL Server experience. There is a table which contains files stored in an "IMAGE" type column, together with an nvarchar column storing the filename. It looks like there are numerous types of files stored in the table: Word docs, XLS, TIF, txt, zip files, etc. I'm trying to extract just one row using BCP, doing something like this: bcp "select file from attachments where id = 1234" queryout "c:\myfile.doc" -S <host> -T -n This saves a file, but it is corrupt and I can't open it with Word. When I open the file with word, I can see a lot of the text, but I also get a lot of un-renderable characters. I've similar issues when trying to extract image files, e.g. TIF. Photo software won't open the files. I presume I'm hitting some kind of character encoding problems. I've played around with the -C (e.g. trying RAW) and -n options within BCP, but still can't get it to work. The table in SQL Serer has a collation of "SQL_Latin1_General_CP1_CI_AS" I'm running BCP remotely from my Windows 7 desktop. Any idea where I'm going wrong? Any help greatly appreciated. A: I got this working by changing the default options which BCP asks you about when you invoke the command: The one that made the difference was changing the prefix-length field from 4 to 0. A: bcp "select file from attachments where id = 1234" queryout "c:\myfile.doc" -S -T -n after this [image] : I (enter capital "I"] 0 0 Enter save file Y kallas.. ur file is there
{ "language": "en", "url": "https://stackoverflow.com/questions/7597321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to test Push Notification is working in my application - in iPad I already have asked about how to test Push notification in iPhone. Now I have to test the same in iPad. I found that the tool PushMeBaby does not work in iPad. When I tried to do so it is showing some Socket error(5). Is there any other tool which helps me to test this? Or Can I fix this error in PushMeBaby tool and make it workable to test the same in iPad? Thanks in advance. A: I am adding this answer just for those who may do the same mistake I have done. It was giving me error sometime otherwise it was neither giving any error nor any push message is displayed. The Problem was in Device Token. Since I did not copy/paste it but added it manually it was very difficult to find the miss characters. When I replaced it with copy/paste data and re-execute it, it is sending a push message for each click. Those who believe that PushMeBaby tool is only for iPhone/iPod are wrong (including me before today). It is meant for all the devices. Hats Off to PushMeBaby.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Directions API not providing exact steps I'm using Google Directions API to get directions between 2 locations. I'm able to get the Webservice response (json) and draw a line over the map. However, I noticed that the direction steps are quite less in the response thus making the lines not follow exact road curves. This is for any location, for example. When I search the locations on Google Maps, I can see lines drawn exactly over road curves. A: The steps received in the Webservice response are the turn points where the user's direction will change. I now tried to get the polyline from the webservice response and extracted coordinates with code provided here. Problem resolved!
{ "language": "en", "url": "https://stackoverflow.com/questions/7597323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add event handler in c#? I'm totally new to Events and delegates in C#. I want to handle a data read event in one class (ex. program) and port reading is done in another class(ex. transfer). I know how to do it with delegates alone,but don't know how to do it in events. Could you give me a simple sample. Thanks. A: look at this example public class TimerManager : INotifyPropertyChanged { private readonly DispatcherTimer dispatcherTimer; private TimeSpan durationTimeSpan; private string durationTime = "00:00:00"; private DateTime startTime; private bool isStopped = true; readonly TimeSpan timeInterval = new TimeSpan(0, 0, 1); public event EventHandler Stopped; public TimerManager() { durationTimeSpan = new TimeSpan(0, 0, 0); durationTime = durationTimeSpan.ToString(); dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Tick += DispatcherTimerTick; dispatcherTimer.Interval = timeInterval; dispatcherTimer.IsEnabled = false; DefaultStopTime = new TimeSpan(17, 30, 0); } public TimerManager(TimeSpan defaultStopTime) : this() { DefaultStopTime = defaultStopTime; } #region Properties public TimeSpan ElapsedTime { get { return durationTimeSpan; } } public string DurationTime { get { return durationTime; } set { durationTime = value; OnPropertyChanged("DurationTime"); } } public DateTime StartTime { get { return startTime; } } public bool IsTimerStopped { get { return isStopped; } set { isStopped = value; OnPropertyChanged("IsTimerStopped"); } } public TimeSpan DefaultStopTime { get; set; } #endregion #region Start Stop Timer public void StartTimer() { dispatcherTimer.Start(); durationTimeSpan = new TimeSpan(0,0,0); startTime = DateTime.Now; IsTimerStopped = false; } public void StopTimer() { dispatcherTimer.Stop(); IsTimerStopped = true; if (Stopped != null) { Stopped(this, new EventArgs()); } } #endregion public void DispatcherTimerTick(object sender, EventArgs e) { // durationTimeSpan = DateTime.Now - startTime; durationTimeSpan = durationTimeSpan.Add(timeInterval); DurationTime = string.Format("{0:d2}:{1:d2}:{2:d2}", durationTimeSpan.Hours, durationTimeSpan.Minutes, durationTimeSpan.Seconds); if (DateTime.Now.TimeOfDay >= DefaultStopTime) { StopTimer(); } } } in this class we have the Timer Stopped event public event EventHandler Stopped; in the Method we call the event handler if it is not null public void StopTimer() { dispatcherTimer.Stop(); IsTimerStopped = true; if (Stopped != null) { //call event handler Stopped(this, new EventArgs()); } } for use this class and timer stop event look at the code var timer = new TimerManager(); timer.Stopped += TimerStopped; void TimerStopped(object sender, EventArgs e) { // do you code } A: If I nright understood what you're asking for, you can do something like this: public class MyClass { ... public void delegate MuCustomeEventDelegate( ...params...); public event MuCustomeEventDelegate MuCustomeEvent; ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: failwith in the explicit object constructor using F# The following code type A (b) = new () = if true then A 4. else failwith "" gives an error: This is not a valid object construction expression. Explicit object constructors must either call an alternate constructor or initialize all fields of the object and specify a call to a super class constructor. This works: type A (b) = new () = if true then A 4. else failwith ""; A 4. Simple question. What is so bad about failwith in the constructor? A: The issue is not failwith per se. As the error indicates, non-primary constructors are restricted. This is to encourage putting all initialization logic in the primary constructor. Your example seems contrived. If you show more of what you're trying to do perhaps someone can offer a solution. Here's one way to rework your code: type A (b) = new () = A(4.0) then if true then failwith "" then acts like a do binding in non-primary constructors. See the MSDN page on Constructors for more options. EDIT kvb made a good point regarding primary constructors with side effects. If that's the case you may want to consider moving your logic to a static method. This makes it obvious that other work may be done prior to calling the constructor. type A (b) = static member Create() = if true then failwith "" else A(4.0) A: The problem you are seeing is not specific to failwith; it would also occur with any other expression of type A other than a constructor call, such as Unchecked.defaultof<A>. As the error message indicates, constructors have restrictions on the kinds of expressions that can be used within them to ensure that types are always initialized soundly. As I mentioned in a comment on Daniel's answer, if you want to fail fast in certain cases you could do something like: new() = if true then failwith "" A 4.0 This will throw an exception before it gets a chance to execute the chained constructor call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can I create an instance of a class from AS3 just knowing his name? Can I create an instance of a class from AS3 just knowing it's name? I mean string representation, like FlagFrance A: Yes, use getDefinitionByName: import flash.utils.getDefinitionByName; var FlagFranceClass:Class = getDefinitionByName("FlagFrance"); var o:* = new FlagFranceClass(); A: Create instances of classes dynamically by name. To do this following code can be used: //cc() is called upon creationComplete private var forCompiler:FlagFrance; //REQUIRED! (but otherwise not used) private function cc():void { var obj:Object = createInstance("flash.display.Sprite"); } public function createInstance(className:String):Object { var myClass:Class = getDefinitionByName(className) as Class; var instance:Object = new myClass(); return instance; } The docs for getDefinitionByName say: "Returns a reference to the class object of the class specified by the name parameter." The above code we needed to specify the return value as a Class? This is because getDefinitionByName can also return a Function (e.g. flash.utils.getTimer - a package level function that isn't in any class). As the return type can be either a Function or a Class the Flex team specified the return type to be Object and you are expected to perform a cast as necessary. The above code closely mimics the example given in the docs, but in one way it is a bad example because everything will work fine for flash.display.Sprite, but try to do the same thing with a custom class and you will probably end up with the following error: ReferenceError: Error #1065: Variable [name of your class] is not defined. The reason for the error is that you must have a reference to your class in your code - e.g. you need to create a variable and specify it's type like so: private var forCompiler:SomeClass; Without doing this your class will not be compiled in to the .swf at compile time. The compiler only includes classes which are actually used (and not just imported). It does so in order to optimise the size of the .swf. So the need to declare a variable should not really be considered an oversight or bug, although it does feel hackish to declare a variable that you don't directly use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: WP7 read file from phone I am building an app on Windows Phone 7 to transfer photos on wifi. Firs the user select photos (that works fine) & I store paths in variable that I can use later. When I am trying to send photo, I've got null on my stream like shown below: To be specific, I launch the next photo transfer when the progress bar has changed, so threads are not concurrent. public transferPage() { InitializeComponent(); // Get smartphone unique ID object DeviceUniqueID; byte[] DeviceIDbyte = null; if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out DeviceUniqueID)) DeviceIDbyte = (byte[])DeviceUniqueID; deviceId = Convert.ToBase64String(DeviceIDbyte); nbPhotos = photoContainer.photosUri.Count; photoContainer.index = 0; index = 0; transferPhoto(); } private void ProgressBarValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { Thread.Sleep(3000); if (photoContainer.photosUri.Count > 0) transferPhoto(); } private void transferPhoto() { string url = String.Format(photoContainer.urlTransfer, nbPhotos, deviceId); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest); } private void GetRequestStreamCallback(IAsyncResult asynchronousResult) { HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState; // End the stream request operation Stream postStream = webRequest.EndGetRequestStream(asynchronousResult); var fs = Application.GetResourceStream(new Uri(photoContainer.photosUri[0], UriKind.RelativeOrAbsolute)).Stream; A is Null exception is raised on the last line. It is never raised on the first file, sometimes the second and always the third. photoContainer.photosUri[0] still a good file path which I confirmed in the debugger. A: I'm confused. If you're uploading pictures why are you using Application.GetResourceStream? That method only accesses resources embedded within the application XAP. Shouldn't you be using MediaLibrary.Pictures to access pictures on the phone instead? Either way, Application.GetResourceStream returns null when given an unknown resource identifier. Spend some time getting familiar with Silverlight's relative Uris, how they relate to the files' build action and how to properly formulate them. For an embedded resource the relative Uri is "/assemblyName;component/folderInProject/fileName.fileExtension" and for "Build Action = Content" file it'll be "folerInProject/fileName.fileExtension".
{ "language": "en", "url": "https://stackoverflow.com/questions/7597348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery - Is there a more efficient way to do this? http://jsfiddle.net/bGDME/ Basically, I want to show only whatever is selected in the scope and hide the rest. The way I did it seems so.. I don't know. Tedious. I was hoping to get some ideas of making it better. A point in the right direction would be very much appreciated, too. Thanks. A: You can minimize the code by using toggle() instead of your if/else statements Working Example: http://jsfiddle.net/hunter/bGDME/1/ $('#scope').change( function(){ var type = $('option:selected', this).val(); $('#grade').toggle(type == 2 || type == 3); $('#class').toggle(type == 3); }); .toggle(showOrHide) showOrHide: A Boolean indicating whether to show or hide the elements. A: what about this?? $(document).ready( function() { $('#grade, #class').hide(); $('#scope').change( function(){ var type = $('option:selected', this).text(); alert(type); $('select').next().not('#'+type).hide(); $('#'+type).show(); }); }); DEMO A: This seems fine to me, unless you have lots of or dynamic controls. However u can use JQuery addClass / removeClass, switch statement, multiple Selector $('#grade, #class').show(); to minimize the code A: you can also use a switch state: http://jsfiddle.net/bGDME/3/ A: This will do what you're looking for: http://jsfiddle.net/bGDME/30/ You simply use the val() of the scope within the eq() method to determine which sibling select should remain shown. If 'school' is chosen from the first dropdown, then neither get shown: $(document).ready( function() { var additionalSelects = $('#grade, #class'); $('#scope').change(function(){ var selectedVal = $(this).val(); additionalSelects.hide(); if(selectedVal > 1){ additionalSelects.eq(selectedVal - 2).show(); } }); }); A: Here's an approach using HTML5 data attributes to declaratively set "scope levels" on the select boxes: http://jsfiddle.net/bGDME/6/ And the updated JavaScript: var $scopedSelects = $('#grade, #class').hide(); $('#scope').change( function(){ var scopeLevel = $(this).val(); $scopedSelects.each(function() { var $this = $(this); $this[$this.data('scope-level') <= scopeLevel ? 'show' : 'hide'](); }); }); The primary advantage this one might have is that the code stays the same regardless of how many "scoped selects" you have (assuming you update the initial selector, of course). A: Its very simple, $(document).ready( function() { $("select[id!='scope'][id!='school']").hide(); $('#scope').change( function(){ $("select[id!='scope']").hide(); var ken=$(this).val(); $("#"+ken).show(); }); }); A: If you want to make it a bit more dynamic by not touching the javascript when you want to add more select elements, then you can do small changes to your javascript code and HTML and you will only need to edit the HTML Javascript: $(document).ready(function() { $('#scope').change(function() { var type = $(this).val().split(','); $('.values select').hide(); for (x in type) { $('.values').find('#'+type[x]).show(); } }); }); HTML: <select id='scope'> <option value=''>Select</option> <option value='school'>school</option> <option value='school,grade'>grade</option> <option value='school,grade,class'>class</option></select>
{ "language": "en", "url": "https://stackoverflow.com/questions/7597355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error in creating temp files on mac os Om mac OS 10.6.7, I am creating some files in the temp directory. After a while I start getting failure in open syscall and error returned is 24 which means disk full. I checked the disk space and still 80GB is available. Are there any restrictions or special quota on temporary directory? I used following flags to open the file: open(path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR) The RAM usage is fairly high during this point, (around 90%), but I dont think it should affect the file open especially when it says disk full as the returned error. Did anyone face such a situation? A: Error 24 is EMFILE meaning too many open files. A: this error code 24 is for EMFILE which indicates that maximum files are already open by current process so now more files can not be opened. So changes some how the maximum limit of opened file per process in your system or try to close files after usages if possible then if i remember then maximum files open at a time in one process is 20 by default.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android AlarmManager did not work after process stops I want to set an alarm via AlarmManager class. Normally, It works fine and everything is OK. But if my application process stops or Phone turns off and turns on again, The alarm wont start. Any help? or other service that android provides? thanks A: Android will erase all intent of alarm manager if you will restart your phone. You have to create a receiver for start BOOT_COMPLETED and then you will get onReceive() method when your device will start.In this method you can create all alarm again. You have to declare receiver in manifest <receiver android:name=".MyStartupIntentReceiver" android:enabled="true" android:exported="false"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> And your receiver will be import java.util.Calendar; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class MyStartupIntentReceiver extends BroadcastReceiver{ @Override public void onReceive(final Context context, Intent intent1) { // You can update pending intent here } } A: For startup, try http://www.anddev.org/launch_activity_on_system-emulator_startup-t428.html and for your process stop, try Android: How to auto-restart application after it's been "force closed"?
{ "language": "en", "url": "https://stackoverflow.com/questions/7597358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Symfony2 sending XML to a remote URL I would like to send XML data to a remote URL. How to do this in a proper way using Symfony2? Equivalent in flat PHP using curl would be: $ch = curl_init("http://website"); $request["queue"] = file_get_contents("file_to_send.xml"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $request); $response = curl_exec($ch); curl_close ($ch); A: Well, from here it looks like a good way to do it. Don't forget, keep it simple. You might want to wrap it in some class that would manager communication with other servers. This way it would be more testable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change UISwitch name in iphone? Possible Duplicate: How to customize UISwitch button in iphone? How to change name of UISwitch (like on,off) i am creating UISwitch in Xib so i want to change the name like yes or no. A: You will have to create a custom switch... http://www.catamount.com/blog/1063/uicustomswitch-customizing-uiswitch-color-it-change-labels/ this should help A: There is no public API method for changing the text on an UISwitch You should use a UISegmentedControl or a Custom UISwitch A: This one I found is very useful for creating the custom switch http://osiris.laya.com/projects/rcswitch/ You can create the custom switch and there will not be any problem in apple approval.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to configure unit tests with an IoC container in ASP.NET? I have configured Unity in my ASP.NET application and the configuration is loaded when the first request is received in Application_BeginRequest. then the Unity container is stored in the Global.ascx as a property so that my other class can access it: public static IUnityContainer ContainerHolder { get; set; } IUnityContainer IContainerAccessor.Container { get { return ContainerHolder; } } ContainerHolder, holds the container instance across application and Container property allows access to this property in each session. Then I have a UnityLocator class which enables me access this property across the application: public static class UnityLocator { private static IUnityContainer Container { get { return ((IContainerAccessor)HttpContext.Current.ApplicationInstance).Container; } } } Everything works fine! I have also a method to access the instance from Unity: UnityLocator.GetInstance<IThemeManager>(); protected Repository(ICustomCacheManager customCacheManager) { this.Cache = customCacheManager; } protected Repository() : this(UnityLocator.GetInstance<ICustomCacheManager>()) { } this has been used in my app so that I can retrieve an existing instance from Unity so that I can inject it to other classes. For example my view (asp.net page) injects this to its Presenter class as a dependency. Now, I'd like to configure my Unit tests to run. How could I do that?! global.ascx doesn't exist there obviously so I thought I should create a BaseTest class and let all my tests inherit it. then at the constructor of this BaseTest class, I build up my instances. Is it the right way to do it? How to configure unit tests with Unity now? Thanks UPDATE: UnityLocator.GetInstance added. A: You shouldn't worry about accessing your IoC container. That is a violation of Unit Tests. Unit tests you should not worry about any concrete implementation or dependency (other than the class under test). To me, having your IoC globally available is a bad design choice. You should have your dependencies injected via properties or constructors. A: Probably using the global application class for storing the service locator was not a good idea. Why don't you use the built-in ServiceLocator class? It is available from anywhere in the code and doesn't depend on global application / HttpContext. Whether or not using the container in unit tests is another story. Personally I am not against it as long as you put stub implementations of your services into the container. Edit: the way to configure your container using ServiceLocator: private void ConfigureUnity() { UnityServiceLocator locator = new UnityServiceLocator( ConfigureUnityContainer() ); ServiceLocator.SetLocatorProvider( () => locator ); } private IUnityContainer ConfigureUnityContainer() { IUnityContainer container = new UnityContainer(); // this loads container's configuration, comment or uncomment container.LoadConfiguration(); return container; } You can then access the container from within the locator like: var container = ServiceLocator.Current.GetInstance<IUnityContainer>(); A: In your page, try doing things like this: public class DepartmentReportPage : Page { private readonly DepartmentReportPresenter _presenter; public DepartmentReportPage() { this._presenter = UnityLocator.GetInstance<DepartmentReportPresenter>(); this._presenter.View = this; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails fixtures or similar for creating data within an app I want to populate a preferences table when a user is created. I can make a lash up version within the controller easily enough but would like something neater. Can one do the same sort of thing with fixtures within a running application? If so how? A: You could search for a gem. I've used https://github.com/FooBarWidget/default_value_for some time ago for a similar thing. It's a nice and clean solution. A: In the end I simple defined an array in the model and array.each -ed it. Not perhaps the most elegant but still have all the values in one place for editing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQLAlchemy: Dynamically loading tables from a list I am trying to create a program that loads in over 100 tables from a database so that I can change all appearances of a user's user id. Rather than map all of the tables individually, I decided to use a loop to map each of the tables using an array of objects. This way, the table definitions can be stored in a config file and later updated. Here is my code so far: def init_model(engine): """Call me before using any of the tables or classes in the model""" meta.Session.configure(bind=engine) meta.engine = engine class Table: tableID = '' primaryKey = '' pkType = sa.types.String() class mappedClass(object): pass WIW_TBL = Table() LOCATIONS_TBL = Table() WIW_TBL.tableID = "wiw_tbl" WIW_TBL.primaryKey = "PORTAL_USERID" WIW_TBL.pkType = sa.types.String() LOCATIONS_TBL.tableID = "locations_tbl" LOCATIONS_TBL.primaryKey = "LOCATION_CODE" LOCATIONS_TBL.pkType = sa.types.Integer() tableList = ([WIW_TBL, LOCATIONS_TBL]) for i in tableList: i.tableID = sa.Table(i.tableID.upper(), meta.metadata, sa.Column(i.primaryKey, i.pkType, primary_key=True), autoload=True, autoload_with=engine) orm.mapper(i.mappedClass, i.tableID) The error that this code returns is: sqlalchemy.exc.ArgumentError: Class '<class 'changeofname.model.mappedClass'>' already has a primary mapper defined. Use non_primary=True to create a non primary Mapper. clear_mappers() will remove *all* current mappers from all classes. I cant use clear_mappers as it wipes all of the classes and the entity_name scheme doesn't seem to apply here. It seems that every object wants to use the same class, although they all should have their own instance of it. Does anyone have any ideas? A: Well, in your case it *is the same Class you try to map to different Tables. To solve this, create a class dynamically for each Table: class Table(object): tableID = '' primaryKey = '' pkType = sa.types.String() def __init__(self): self.mappedClass = type('TempClass', (object,), {}) But I would prefer slightly cleaner version: class Table2(object): def __init__(self, table_id, pk_name, pk_type): self.tableID = table_id self.primaryKey = pk_name self.pkType = pk_type self.mappedClass = type('Class_' + self.tableID, (object,), {}) # ... WIW_TBL = Table2("wiw_tbl", "PORTAL_USERID", sa.types.String()) LOCATIONS_TBL = Table2("locations_tbl", "LOCATION_CODE", sa.types.Integer())
{ "language": "en", "url": "https://stackoverflow.com/questions/7597386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: automatic reference disable in ios How can i disable automatic reference for specific files in IOS. I have a facebook API, where it isn't automatic reference and so I want to disable it for facebook api files A: Head to the compile sources section of the build phases and add the "-fno-objc-arc" to the files you want to disable ARC for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using dependency injection with Apache Commons IO I have a class 'a' that uses the FileUtils class of Apache Commons IO to copy a directory. Because I have to write a unit test for class 'a', I need to be able to inject all dependencies to mock them in the test. But how to inject the FileUtils class? There is no interface and all methods are abstract. A: All methods of the utility classes are static. You can't mock them (well, you can, with bytecode manipulation, but it's ugly). The proper way to handle that is to provide an abstraction over these utilities. For example implement a FileService, which you declare as a bean, and inject it. Then you can mock its methods. A: You could create your own implementation of FileUtils by extending it OR use a mocking library like jMockit or EasyMock. A: You can always wrap it in a file handling layer and create a stub implementation for your unit tests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Git link to repository folder I do have a question: How can I link within a git repository to a folder of another repository. I have the following structure: Repository One .git Folder A Folder B Repository Two .git Folder C Folder D So what I now want is, that within my repository One and its Folder B, Folder D of Repository Two is referenced. It's important that I do not reference the whole repository C, but just the Folder D of it. I would really appreciate any help! Thanks in advance Alex A: The simplest way, if your Os supports it (and even Windows does since Vista), is to use a symlink for referring to folder D from folder B. But you would maintain the two repos separate. git submodule wouldn't be adapted to your case, since it refers to the all repo as a module.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to build parse tree? Have found C++ BNF and there next lines selection-statement: if ( condition ) statement if ( condition ) statement else statement Now trying to write parser. Need to build parse tree. On input i have BNF and source file. But i'm stucked in how i can point my parser what if condition evaluated to true, then it need to execute first statement otherwise else block? Thanks. A: First of all, you need to distinguish between the usual passes of a compiler: * *The lexing, that is recognizing words and removing comments, *the parsing, that is structuring of the linear input stream into an abstract syntax tree, and *the evaluation or code generation. Do the first things first, then you'll understand the rest. Look at boost::spirit for the first two steps. A: Conditional statements have a simple recursive structure. The corresponding recursive descent parser has a similarly simple recursive structure. Abstractly, the interior conditionals are parsed as follows: <cond> -> if <expression> then <statement> [else <statement>] cond : a = parse expression b = parse statement if is_else(token) then c = parse statement return conditional(a,b,c) else return conditional(a,b) In your example, conditional statements contain blocks of conditionals the last of which contains an else clause. Assuming that the tokenized input sequence has this form and syntactic errors were detected during lexical analysis, the outer conditional is parsed as follows: <conditional> -> selection_statement: {<cond>} <cond> conditional : b = new block while (iscond(next)) s = parse cond b = insert(s,b) return b Of course, the actual implementation will be significantly more detailed and tedious. However, the preceding describes in outline the construction of a parse tree of a conditional statement having the required form from a tokenized input sequence. I just realized you were talking about evaluating the abstract syntax tree. The structure of the function that evaluations a conditional statement is similar to the function that parses a conditional statement. Abstractly, cond(input) : a = evaluate(if_part(input)) if is_true(a) then evaluate(then_part(input)) else if(is_else(input)) then evaluate(else_part(input)) else return In order to determine which portion of the conditional to evaluate, you must first evalute the "if" part of the conditional to a Boolean value. If the Boolean value is "true," the "then" part of the conditional is evaluated. If the Boolean value is "false," then the "else" part of the conditional is evaluated. If there is no "else" part, there is nothing to evaluate. Of course, the implementation will be more detailed than the above. A: There are a variety of programs that take a BNF grammar and output a proper parser: http://en.wikipedia.org/wiki/Backus-Naur_form#Software_using_BNF If you are writing your own parser, there is an excellent overview online here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to handle csv download prompt through a post request in Rails I have a servlet (java) returning a csv file. So in my controller I send a post request, def handleCsvRequest response = RestClient.post theUrlPathTotheServlet queryParams end Now how do I handle the response so that it prompts the user to download this csv file. I know you can do this via a form and hidden Iframe but i'd like to do it through rails. I am looking through fastercsv but i am not finding great examples. Many thanks. I have tried the following: i have tried the following csv_string = RestClient.post url, json, :content_type => :json csv_file = CSV.generate do |csv| csv << [csv_string] end send_data csv_file, :type => 'text/csv; charset=iso-8859-1; header=present', :disposition => "attachment; filename=report.csv" but i don't get prompt for a file download? any ideas? A: Use send_file or send_data to send the csv data back to the browser. A typical example of send_data is something along the lines: csv_data = CSV.generate do # block to generate CSV text end send_data csv_data, :filename => 'your_data.csv' A typical example of send_file is @csv_filename ="#{RAILS_ROOT}/tmp/your_data.csv" send_file @csv_filename, :filename => "your_data.csv" This should work in development. If this does not work in production, and you are using an Apache server, you have to comment out the following line in config/environments/production.rb config.action_dispatch.x_sendfile_header = "X-Sendfile" Hope this helps. A: Do have a look at 1> http://fastercsv.rubyforge.org/ - For Documenation 2> http://supriya-surve.blogspot.com/2010/02/using-fastercsv-to-import-data.html - As an e.g.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: BitBlt from a color hDC to a monochrome hDC? I am doing BitBlt from one 8 bit color DC to a monochrome DC. The problem is only pixel with values 255 are converted to white in the monochrome DC. How do I specify threshold value, so that any pixel with value greater than 128 is displayed as white in the monochrome DC. A: You can't. According to the MDSN page of MFC CDC::BitBlt : To convert color to monochrome, BitBlt sets pixels that match the background color to white and sets all other pixels to black. BitBlt uses the foreground and background colors of the color device context to convert from color to monochrome. and CDC::BitBlt calls ::BitBlt: _AFXWIN_INLINE BOOL CDC::BitBlt(int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, DWORD dwRop) { ASSERT(m_hDC != NULL); return ::BitBlt(m_hDC, x, y, nWidth, nHeight, pSrcDC->GetSafeHdc(), xSrc, ySrc, dwRop); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Conditional position-check in XSLT I have an XSLT file which renders articles. I'm passing a variable into the XSLT file which is supposed to limit the number of records output. The trouble is, this 'limit' variable is optional - if it's not there the XSLT file needs to output all values; if the 'limit' variable is a number, then it needs to only output that number of items (presumably using a position() test). Here's my code: <xsl:variable name="limit" select="/macro/limit"/> <xsl:template match="/"> <xsl:variable name="allNodes" select="$localSiteRoot/descendant-or-self::*[articles != '']"/> <xsl:for-each select="$allNodes"> <div class="articleItem"> <h3><xsl:value-of select="./articleHeader"/></h3> <xsl:if test="./articleSubheader != ''"> <h4><xsl:value-of select="./articleSubheader"/></h4> </xsl:if> </div> </xsl:for-each> </xsl:template> Clearly I could just do an XSLT choose around this and say <xsl:choose> <xsl:when select="$limit!= ''"> <xsl:if test="position() &lt; $limit"> But then I'd need to repeat the code twice. There must be a better way, perhaps using templates, but I just can't figure out how it would work and my XSLT isn't great. Could anyone point me in the right direction with the best/neatest way to approach this? Thanks! A: Just use: <xsl:for-each select="$allNodes[not(position() > $limit)]"> Explanation: * *If the value of $limit is castable to a number, then the expression in the select attribute above selects not more than $limit nodes. *If the value of $limits isn't castable to a number (e.g. empty or 'abc') then it is converted to NaN. By definition comparisons involving NaN are always false(), therefore the predicate not(position() > $limit is true() and in this case all nodes in $allNodes are selected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: F# Script SharePoint 2010 API doesn't work I am trying something really simple in F# to try and test interaction with the SharePoint 2010 API. I think I am running into a general problem with F#. Is there anyway that an F# script can access the SharePoint 2010 API? I think my problem is due to the F# scripts running 32bit, and the SharePoint API is in 64bit. An example of the code I'm trying to run is as follows: #r "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.sharepoint.dll" #r "System.ServiceModel.dll" open System open Microsoft.SharePoint let GetListByUrl (listUrl:string) = use site = new SPSite(listUrl) use web = site.OpenWeb() let list = if not (web = null) then web.GetList(listUrl) list In the visual studio editor it says the following error: The Type System.ServiceModel.ChannelFactory`1 is required here and is unavailable. You must add a reference to assembly ... When the script is ran it gives the message: System.IO.FileNotFoundException: The Web application at... could not be found. Verify that you have typed the URL correctly... Which is the error message I get if I try to access the SharePoint 2010 API from a 32bit c# console program. If I change the c# console program to Any CPU that message doesn't appear. However I'm trying to do this in an F# script which I guess is 32bit, so how would I work around that? Also since this is probably a general problem with F# scripts and 64bit dlls, how would you work around the problem of needing to reference 64bit dlls in F# scripts? Edit I used corflags.exe in the visual studio cmd prompt to modify the fsi.exe to 64bit. I followed this guide: http://ig2600.blogspot.com/2010/05/making-fsharp-interpreter-fsi-run-in.html. That seemed to work, though the F# interactive window seemed slower. However when I ran the code above in the now 64bit fsi it said sharepoint does not work with .net 4.0. How would you run the F# interactive window in .net 3.5? Edit Because of the answer posted by F.Aquino in which he said I needed to add a reference to System.ServiceModel I have updated the code to add that. That fixes the visual studio editor complaints that keep appearing with red squiggly lines everywhere. When the script is ran the results are the same, the script cannot access the sharepoint 2010 API which is the problem I am having. A: You need to add a reference to System.ServiceModel
{ "language": "en", "url": "https://stackoverflow.com/questions/7597426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Wordpress using Post titles as navigation I'm trying to create a navigation based around post titles. The main navigation at the top is the Categories, in a sidebar will be the Post Titles from that relevant Category. The code I'm using works up until a point (i got it from List wordpress posts by category which match page title). But I have 2 problems. The main issue is when you get to the single post it just lists that post in the sidebar and no others from the same category. The second minor issue, is it is listing pages when I don't need it to. <p>below lists the right posts for the right cats but fails at the single post stage</p> <?php $test = get_the_title(); $args = array( 'cat_name' => $test ); $args = array_merge( $args , $wp_query->query ); get_posts( $args ); while (have_posts()) { the_post(); ?> <div class="post" id="post-<?php the_ID(); ?>"> <ul> <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li> </ul> <?php } ?> Any help would be appreciated. Thanks A: for you second issue you can add one argument 'post_type' => 'post' it will only display posts. $test = get_the_title(); $args = array( 'cat_name' => $test,'post_type' => 'post' ); $args = array_merge( $args , $wp_query->query );
{ "language": "en", "url": "https://stackoverflow.com/questions/7597432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTTPS URLs for photos All photo URLs in the FQL photo table are HTTP-URLs and not HTTPS-URLs. It's not possible to rewrite the URL with https instead of http. How do I do to get the HTTPS-URLs instead? Why: Internet Explorer is warning users with a pop-up when they load a HTTPS page which includes objects with HTTP-URLs. Since Facebook requires apps to have HTTPS support and since Facebook supports Internet Explorer fully (I guess but I'm actually not sure about this), there should be a way to get HTTPS-URLs to photos. Example FQL query: SELECT pid, src_small FROM photo WHERE pid IN ('xxx'); A: In your API call, add a return_ssl_resources=1 parameter, which will cause the image URLs to come back as HTTPS URLs A: Try this: `$params = array( 'return_ssl_resources'=>1, 'method' => 'fql.query', 'query' => "SELECT pid, src_small FROM photo WHERE pid IN ('xxx')", ); $result = $facebook->api($params);`
{ "language": "en", "url": "https://stackoverflow.com/questions/7597434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to design model with two, independent and optional relations to the same model? I've got a problem with designing my User model and making a decent form for it. I just want to ensure myself that I'm doing it wrong :) So it goes like this: User has got two Addresses: * *a mandatory Address for identification and billing, *an optional shipping Address that he could fill in or leave blank I tried like this: class User < ActiveRecord::Base has_one :address has_one :shipping_address, :class_name => 'Address', :foreign_key => 'shipping_address_id' accepts_nested_attributes_for :address accepts_nested_attributes_for :shipping_address #validations for user end and: class Address < ActiveRecord::Base #validations for address end And then I make a form for User using form_for and nested fields_for. Like this: = form_for @user, :url => '...' do |a| = f.error_messages ... = fields_for :address, @user.build_address do |a| ... But then, despite that f.error_messages generates errors for all models, fields for Addresses don't highlight when wrong. Also I have problems with disabling validation of the second address when the user chose not to fill it in. And I have doubts that my approach is correct. I mean the has_one relation and overall design of this contraption. So the question: Am I doing it wrong? How would You do that in my place? A: What is wrong in your form is that it will build a new address every time the view is rendered, thus losing all validation errors. In your controller, in the new action you should do something like @user.build_address and in your view write: = fields_for :address, @user.address do |a| Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL: How can I select table entries within the next three available dates? To clarify the question further... I have the following Table ORDERS_TAB with some example information: |Order| Launch_Date | | 1 | 27-Sep-11 | | 2 | 29-Sep-11 | | 3 | 30-Sep-11 | | 4 | 03-Oct-11 | | 5 | 28-Oct-11 | | 8 | 10-Oct-11 | | 7 | 29-Sep-11 | I want to select all orders that have a LAUNCH_DATE value within the next three available days including the current day. So, as today is 29-Sep-11 the three available dates from the table would be 29-Sep-11, 30-Sep-11 and 03-Oct-11. Thus the query would return the result: |Order| Launch_Date | | 2 | 29-Sep-11 | | 3 | 30-Sep-11 | | 4 | 03-Oct-11 | | 7 | 29-Sep-11 | So I assume I would need to check what the current date is in the system, search for this date or the next available one and then find the next two available dates after that.. the problem is I have no idea how to do this! All I am looking for is a simple SELECT statement with some conditions but any help is much appreciated, Thank-you. :) A: SELECT * FROM ( SELECT DENSE_RANK() OVER (ORDER BY Launch_Date) available_date_index, * FROM ORDERS_TAB WHERE Launch_Date >= TRUNC(Sysdate) ) WHERE available_date_index <= 3 EDIT As there is confusion about how DENSE_RANK() works, here is the OP's example... |Order| Launch_Date | Available_Date_Index | 1 | 27-Sep-11 | <excluded by WHERE clause> | 2 | 29-Sep-11 | 1 | 3 | 30-Sep-11 | 2 | 4 | 03-Oct-11 | 3 | 5 | 28-Oct-11 | 5 | 8 | 10-Oct-11 | 4 | 7 | 29-Sep-11 | 1 This means that the returned Orders will be 2,3,4,7. Exactly as described by the OP. A: select * from ORDERS_TAB where Launch_Date in (select Launch_Date from (select distinct Launch_Date from ORDERS_TAB where Launch_Date >= '2011-09-29' order by Launch_Date) WHERE rownum <= 3) A: select * from order_tab where launch_date in ( select launchdate from ( select launchdate from order_tab where launch_date >= SysDate -- Check this order by launch_date ) where rownum <= 3 ) How does that look ? A: Edit: As the comments point out, the following doesn't work maybe go for SELECT * FROM ORDERS_TAB WHERE LaunchDate IN ( SELECT TOP(3) LaunchDate FROM ORDERS_TAB ((possibly WHERE LaunchDate > GETDATE()?)) ORDER BY LaunchDate DESC ) A: Try this: SELECT * FROM ORDERS_TAB WHERE sysdate - launch_date <= 3 A: SELECT * FROM ORDERS_TAB where Launch_Date between '29-sep-11' and ADDDATE('2007-09-01', 3); try this, hope this help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using core data in an existing project I need to use core data to persist data for my project, what I have done so far compiles well, but when I actually start storing things using core data, the program just quits, and I don't know the reason. I set up all the required components for core data in the appDelegate file, and I want to store data in a viewController called DetailViewController. Here is what I have done: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. // Set the tab bar controller as the window's root view controller and display. self.window.rootViewController = self.tabBarController; [self.window makeKeyAndVisible]; //this is what I added, reference managedObjectContext in the detail view controller. detailViewController = [[DetailViewController alloc] init]; detailViewController.managedObjectContext = [self managedObjectContext]; return YES; } All components for core data have been implemented - (NSManagedObjectContext *) managedObjectContext { if (managedObjectContext != nil) { return managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { managedObjectContext = [[NSManagedObjectContext alloc] init]; [managedObjectContext setPersistentStoreCoordinator: coordinator]; } return managedObjectContext; } - (NSManagedObjectModel *)managedObjectModel { if (managedObjectModel != nil) { return managedObjectModel; } managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain]; return managedObjectModel; } - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (persistentStoreCoordinator != nil) { return persistentStoreCoordinator; } NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"MyProjectName.sqlite"]]; NSError *error = nil; persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) { /*Error for store creation should be handled in here*/ } return persistentStoreCoordinator; } - (NSString *)applicationDocumentsDirectory { return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; } When I try to call a method in the detail view to store data, the program quits. -(IBAction) addItem { Info *info = [NSEntityDescription insertNewObjectForEntityForName:@"Info" inManagedObjectContext:managedObjectContext]; info.name = item.name; } item is the current object in the detail view, Info is the model class file. Do I miss something here? Thanks! Update: The error message in the console is: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Info'' But I do have a Info.xcdatamodel file in the "Resources" folder, and entity name is "Info". A: Did you call [self.managedObjectContext save:&error]? Also, perhaps your bundle loading routine does not work correctly. Try loading the managedObjectContext like this: NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"ModelName" withExtension:@"momd"]; __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return __managedObjectModel; A: My guess would be that in your detail view controller you either aren't synthesizing managedObjectContext or you aren't initializing it when creating your detail view controller. Check that both of those are being done. If that doesn't solve the problem, please check the console output after the crash and post any relevant information there in an update to your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ThreadSafeClientConnManager not multithreading I've been asked to fix up a Servlet that sits in between two applications. It's purpose is to convert SAML authorisation request to and from SAML v2.0 / SAML 1.1. So it: * *receives a HTTP SAML v2.0 authorisation request from one app *converts the request into SAML v1.1 *sends the request to the second app *receives the SAML v1.1 response from the second app *converts the response into SAML v2.0 *sends the response back to the first app Don't worry about the SAML stuff, it's the HTTP stuff that's the problem. The code does it's job, but it suffers greatly under load. I've found through testing that even though the code utilises a ThreadSafeClientConnManager from Apache httpcomponents, each request that hits the servlet is being handled in a single-threaded manner. To put it more accurately, the second the code reaches the HTTPClient.execute() method the first thread to create a connection will run through the entire rest of the process before any other thread begins working. For example: * *15 requests hit the servlet at the same time *servlet spawns 15 threads to service the requests *all 15 threads retrieve their respective request data *all 15 threads convert their respective data from SAML v2.0 to SAML v1.1 *Thread 1 calls HTTPClient.execute() * *Thread 1 sends the request on to the second app *Thread 1 receives the response from the second app *Thread 1 decodes the response and converts it from SAML v1.1 to SAML v2.0 *Thread 1 sends the response back to the first app *Thread 2 calls HTTPClient.execute() *... and so on ... I've included the code below. From what I can see all the necessary items are present. Can anyone see anything wrong or missing that would prevent this servlet from servicing multiple requests at the same time? public class MappingServlet extends HttpServlet { private HttpClient client; private String pdp_url; public void init() throws ServletException { org.opensaml.Configuration.init(); pdp_url = getInitParameter("pdp_url"); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(); HttpRoute route = new HttpRoute(new HttpHost(pdp_url)); cm.setDefaultMaxPerRoute(100); cm.setMaxForRoute(route, 100); cm.setMaxTotal(100); client = new DefaultHttpClient(cm); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long threadId = Thread.currentThread().getId(); log.debug("[THREAD " + threadId + "] client request received"); // Get the input entity (SAML2) InputStream in = null; byte[] query11 = null; try { in = request.getInputStream(); query11 = Saml2Requester.convert(in); log.debug("[THREAD " + threadId + "] client request SAML11:\n" + query11); } catch (IOException ex) { log.error("[THREAD " + threadId + "]\n", ex); return; } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { log.error("[THREAD " + threadId + "]\n", ioe); } } } // Proxy the request to the PDP HttpPost httpPost = new HttpPost(pdp_url); ByteArrayEntity entity = new ByteArrayEntity(query11); httpPost.setEntity(entity); HttpResponse httpResponse = null; try { httpResponse = client.execute(httpPost); } catch (IOException ioe) { log.error("[THREAD " + threadId + "]\n", ioe); httpPost.abort(); return; } int sc = httpResponse.getStatusLine().getStatusCode(); if (sc != HttpStatus.SC_OK) { log.error("[THREAD " + threadId + "] Bad response from PDP: " + sc); httpPost.abort(); return; } // Get the response back from the PDP InputStream in2 = null; byte[] resp = null; try { HttpEntity entity2 = httpResponse.getEntity(); in2 = entity2.getContent(); resp = Saml2Requester.consumeStream(in2); EntityUtils.consumeStream(in2); log.debug("[THREAD " + threadId + "] client response received, SAML11: " + resp); } catch (IOException ex) { log.error("[THREAD " + threadId + "]", ex); httpPost.abort(); return; } finally { if (in2 != null) { try { in2.close(); } catch (IOException ioe) { log.error("[THREAD " + threadId + "]", ioe); } } } // Convert the response from SAML1.1 to SAML2 and send back ByteArrayInputStream respStream = null; byte[] resp2 = null; try { respStream = new ByteArrayInputStream(resp); resp2 = Saml2Responder.convert(respStream); } finally { if (respStream != null) { try { respStream.close(); } catch (IOException ioe) { log.error("[THREAD " + threadId + "]", ioe); } } } log.debug("[THREAD " + threadId + "] client response SAML2: " + resp2); OutputStream os2 = null; try { os2 = response.getOutputStream(); os2.write(resp2.getBytes()); log.debug("[THREAD " + threadId + "] client response forwarded"); } catch (IOException ex) { log.error("[THREAD " + threadId + "]\n", ex); return; } finally { if (os2 != null) { try { os2.close(); } catch (IOException ioe) { log.error("[THREAD " + threadId + "]\n", ioe); } } } } public void destroy() { client.getConnectionManager().shutdown(); super.destroy(); } } Thanks in advance! A: The HttpClient.execute() does not return until the called server send out all of the http headers. Your code works fine. I think the called service is the real bottleneck. I've created a simple proof of concept code (based on your snippet) for it: import java.io.IOException; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; public class MyHttpClient { private static final String url = "http://localhost:8080/WaitServlet"; private final DefaultHttpClient client; public MyHttpClient() { final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(); final HttpRoute route = new HttpRoute(new HttpHost(url)); cm.setDefaultMaxPerRoute(100); cm.setMaxForRoute(route, 100); cm.setMaxTotal(100); client = new DefaultHttpClient(cm); } public void doPost() { final HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse; try { httpResponse = client.execute(httpPost); } catch (final IOException ioe) { ioe.printStackTrace(); httpPost.abort(); return; } final StatusLine statusLine = httpResponse.getStatusLine(); System.out.println("status: " + statusLine); final int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { httpPost.abort(); return; } } } And a test: import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.Test; public class HttpClientTest { @Test public void test2() throws Exception { final ExecutorService executorService = Executors.newFixedThreadPool(16); final MyHttpClient myHttpClient = new MyHttpClient(); for (int i = 0; i < 8; i++) { final Runnable runnable = new Runnable() { @Override public void run() { myHttpClient.doPost(); } }; executorService.execute(runnable); } executorService.shutdown(); executorService.awaitTermination(150, TimeUnit.SECONDS); } } Finally, the called WaitServlet: import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WaitServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { Thread.sleep(30 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } final PrintWriter writer = resp.getWriter(); writer.println("wait end"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Multi select filter in layered navigation I have a custom multi select attribute which I'd like to take part in filtering of products. The attribute is set as used in Layered Navigation however doesn't appear in the list of available filters. Could be due to custom model implementation? Anyone have some tips where to check why it doesn't appear? Attribute is set for several products Magento version used is EE 1.11 Thanks A: NOTE: I'm adding this in a new answer to use the code format. How it was said, the problem is with multiselect attributes using a custom source model. Solution: Rewrite the class Mage_Catalog_Model_Resource_Product_Indexer_Eav_Source Override the method: _prepareMultiselectIndex add this code after the $options array is filled with the default code (check line 200 in original file) foreach($attrIds as $attId){ if( ! isset($options[$attId])){ $options[$attId] = $this->_getOptionsFromSourceModel($attId); } } add this method too: protected function _getOptionsFromSourceModel($attId) { $options = array(); /** @var Mage_Eav_Model_Entity_Attribute_Abstract $attribute */ $attribute = Mage::getResourceSingleton('catalog/product')->getAttribute($attId); /** @var Mage_Eav_Model_Entity_Attribute_Source_Abstract $source */ $source = $attribute->getSource(); $sourceOptions = $source->getAllOptions(); if($sourceOptions){ foreach($sourceOptions as $sourceOption){ if(isset($sourceOption['value'])){ $options[$sourceOption['value']] = true; } } } return $options; } I couldn't find a less intrusive way to fix this. A: For those who will struggle with this in the future: the problem is in Mage_Catalog_Model_Resource_Product_Indexer_Eav_Source file on line 191. By default multi select attribute values are being pulled from eav_attribute_option and if your custom attribute uses custom source model the attribute will not be indexed. I don't know as of yet if it's intended but I couldn't find a better solution than overriding that model in local pull and adding required values in $options array. Hope this helps someone, someday A: What is the backend_type. i.e. are the values stored in the catalog_product_entity_varchar or catalog_product_entity_text table? The backend_type has to match the checks in Mage_Catalog_Model_Resource_Eav_Attribute::isIndexable(), so text wouldn't work without rewriting the attribute model. Is the is_filterable and/or is_filterable_in_search attribute property set? The Mage_Catalog_Model_Product_Indexer_Eav::_registerCatalogAttributeSaveEvent() checks for those when updating the index for the layered navigation. Are the methods getFlatColums(), getFlatIndexes() and getFlatUpdateSelect() implemented in the custom source model? This actually is only required for building and updating the flat catalog product tables (so the used_in_product_listing or is_filterable property needs to be set in order for Magento to pick up the attribute). Check the class Mage_Eav_Model_Entity_Attribute_Source_Table as a reference on what these there methods are supposed to return.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: getline() reads an extra line ifstream file("file.txt"); if(file.fail()) { cout<<"Could not open the file"; exit(1); } else { while(file) { file.getline(line[l],80); cout<<line[l++]<<"\n"; } } I am using a two dimensional character array to keep the text (more than one line) read from a file to count the number of lines and words in the file but the problem is that getline always reads an extra line. A: Your code as I'm writing this: ifstream file("file.txt"); if(file.fail()) { cout<<"Could not open the file"; exit(1); } else { while(file) { file.getline(line[l],80); cout<<line[l++]<<"\n"; } } The first time getline fails, you still increment the line counter and output the (non-existing) line. Always check for an error. extra advice: use std::string from the <string> header, and use its getline function. cheers & hth. A: The problem is when you're at the end of the file the test on file will still succeed because you have not yet read past the end of file. So you need to test the return from getline() as well. Since you need to test the return from getline() to see if it succeeded, you may as well put it right in the while loop: while (file.getline(line[l], 80)) cout << line[l++] << "\n"; This way you don't need a separate test on file and getline(). A: Does the file end with a newline? If it does, the EOF flag will not be triggered until one extra loop passes. For example, if the file is abc\n def\n Then the loop will be run 3 times, the first time it will get abc, the second time it will get def and the third time it will get nothing. That's probably why you see an additional line. Try checking the failbit on the stream AFTER the getline. A: Only do the cout if file.good() is true. The extra line you're seeing comes from the last call to file.getline() which reads past the end of the file. A: This will solve your problem: ifstream file("file.txt"); if(!file.good()) { cout<<"Could not open the file"; exit(1); } else { while(file) { file.getline(line[l],80); if(!file.eof()) cout<<line[l++]<<"\n"; } } Its more robust
{ "language": "en", "url": "https://stackoverflow.com/questions/7597449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why doesn't my TextBlock/TextBox apply values from a Base Style? It's not uncommon for me to write something like below for styling a data entry form, but my problem is that TextBox and TextBlock don't seem to implement the Setters that are in the BaseElementStyle. Usually I need to define them separately. Why is this? And is there a way around it? I am guessing it has to do with the fact they are usually used in other control templates (for example TextBlock is used in most controls and TextBox is used in DatePickers and ComboBoxes) <Style x:Key="BaseElementStyle" TargetType="{x:Type FrameworkElement}"> <Setter Property="Margin" Value="5" /> <Setter Property="VerticalAlignment" Value="Center" /> </Style> <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource BaseElementStyle}" /> <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource BaseElementStyle}" /> <Style TargetType="{x:Type Label}" BasedOn="{StaticResource BaseElementStyle}" /> <Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource BaseElementStyle}" /> <Style TargetType="{x:Type DatePicker}" BasedOn="{StaticResource BaseElementStyle}" /> <Style TargetType="{x:Type CheckBox}" BasedOn="{StaticResource BaseElementStyle}" /> A: I would like to suggest the two possible workarounds. It seems that each of Key and Type can be used but both of them cannot be used together as your question case, x:Key="BaseElementStyle" TargetType="{x:Type FrameworkElement}". * *using x:Key <Style x:Key="BaseElementStyle"> <Setter Property="FrameworkElement.Margin" Value="5" /> <Setter Property="FrameworkElement.VerticalAlignment" Value="Center" /> </Style> <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource BaseElementStyle}" /> <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource BaseElementStyle}" /> <Style TargetType="{x:Type Label}" BasedOn="{StaticResource BaseElementStyle}" /> <Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource BaseElementStyle}" /> <Style TargetType="{x:Type DatePicker}" BasedOn="{StaticResource BaseElementStyle}" /> <Style TargetType="{x:Type CheckBox}" BasedOn="{StaticResource BaseElementStyle}" /> *using x:Type <Style TargetType="{x:Type FrameworkElement}"> <Setter Property="Margin" Value="5" /> <Setter Property="VerticalAlignment" Value="Center" /> </Style> <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /> <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /> <Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /> <Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /> <Style TargetType="{x:Type DatePicker}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /> <Style TargetType="{x:Type CheckBox}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /> A: Also keep in mind that WPF considers a ControlTemplate to be an inflation boundary and does NOT apply default styles inside of templates. The exception to the rule: anything that inherits from Control WILL BE inflated with the default style. Since TextBlock inherits from FrameworkElement and not from Control, if you use of it inside of a ControlTemplate you will also have to apply it's style manually. This is true for both TextBlocks that are added by hand, or by TextBlocks added by WPF for string Content. A quick example: <Window x:Class="ImplicitStyles.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <StackPanel> <StackPanel.Resources> <Style x:Key="BaseElementStyle"> <Setter Property="FrameworkElement.Tag" Value="Hello World" /> </Style> <Style TargetType="{x:Type Button}" BasedOn="{StaticResource BaseElementStyle}" /> <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource BaseElementStyle}" /> <!-- Default style for TextBlock will not be applied, Tag will be null --> <ControlTemplate x:Key="MyContentControlTemplateOne" TargetType="{x:Type ContentControl}"> <Border BorderBrush="Red" BorderThickness="2"> <TextBlock Text="{Binding RelativeSource={RelativeSource Self}, Path=Tag}" /> </Border> </ControlTemplate> <!-- Default style for Button will be applied, Tag will be Hello World --> <ControlTemplate x:Key="MyContentControlTemplateTwo" TargetType="{x:Type ContentControl}"> <Border BorderBrush="Red" BorderThickness="2"> <Button Content="{Binding RelativeSource={RelativeSource Self}, Path=Tag}" /> </Border> </ControlTemplate> </StackPanel.Resources> <ContentControl Template="{StaticResource MyContentControlTemplateOne}" /> <ContentControl Template="{StaticResource MyContentControlTemplateTwo}" /> </StackPanel> </Window> For more information, see this blog post: http://blogs.msdn.com/b/wpfsdk/archive/2009/08/27/implicit-styles-templates-controls-and-frameworkelements.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7597455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: ItemsControl ItemsSource lazy loading Image you are creating a custom control behaving like ComboBox in WPF. As a source of items you provide IQueryable<T> (or any kind of IEnumerable collection), but you don't want to allow the control to call GetIterator() and iterate through it (some kind of a lazy loading). Let's say you inherit from the (because you want all the funcionality of that control) System.Windows.Controls.Primitives.Selector class. The Selector class inherits from System.Windows.Controls.ItemsControl class which provides a the well known dependency property ItemsSource. public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(ItemsControl), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(ItemsControl.OnItemsSourceChanged))); private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ItemsControl control = (ItemsControl) d; IEnumerable oldValue = (IEnumerable) e.OldValue; IEnumerable newValue = (IEnumerable) e.NewValue; ItemValueStorageField.ClearValue(d); if ((e.NewValue == null) && !BindingOperations.IsDataBound(d, ItemsSourceProperty)) { control.Items.ClearItemsSource(); } else { control.Items.SetItemsSource(newValue); // PROBLEM } control.OnItemsSourceChanged(oldValue, newValue); } If I see it correctly, this is the place where it iterates. internal void SetItemsSource(IEnumerable value) { if ((!this.IsUsingItemsSource && (this._internalView != null)) && (this._internalView.RawCount > 0)) { throw new InvalidOperationException(SR.Get("CannotUseItemsSource")); } this._itemsSource = value; this._isUsingItemsSource = true; this.SetCollectionView(CollectionViewSource.GetDefaultCollectionView(this._itemsSource, this.ModelParent)); } So I've decided to override metadata of ItemsSourceProperty and point it to my own static method, where I'm planing not co call SetItemsSource (rather delay it). How should it be done in your opinion? Thank you A: Your best bet would be to probably add a new dependency property, say DelayedItemsSource of type IEnumerable. Then you could bind ItemsSource to DelayedItemsSource after your delay.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Alfresco's MMT vs Integrated Deployment When developing for Alfresco, are there any advantages to using the MMT over Integrated Deployment? Is there anything you can develop using one method, but not the other? Browsing through Alfresco's SDK examples, I noticed many of them used integrated deployment, and the same went for all of the Share webscripts I saw on Google Code. Right now I'm just using the Integrated Deployment method, and everything seems to be working well, but I'm curious if I'm missing out on anything by not using the MMT. A: Modules and integrated deployments are exactly the same in terms of code capabilities. The main difference is about distributing your customization: if you need/want to * *provide your customizations to the external world or *reusing them across different projects or *port them to different Alfresco versions then modules are the way to go, especially if you're not releasing the source code. The only downside of AMPs is that they write something in the DB but you currently can't uninstall them, even if there are some tricks you can try out. I personally still prefer using AMPs as much as I can for my customization, leaving to embedded changes only stuff that can't go into an AMP (e.g. overriding original Alfresco files). The maven way also helps (and drives you a little) towards this practice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone download images and display correct ratio I'm downloading a bunch of images from a server and displaying them on the screen. I have about 320x450 to work with. Each image size has a different size, how do i correctly resize images so that they fit on the iphone screen and retain the correct ratio and the same time? A: Use UIImageViews of whatever size you can fit and set them to scale with contentMode: myUIImageView.contentMode = UIViewContentModeScaleAspectFit; A: Try this: UIImage *img = [UIImage imageNamed:@"image.png"]; imageview.frame=CGRectMake(x,y,img.size.width,img.size.height); [self.view addSubView imageview]; A: Try that, adapting to your image file type : UIImage *img = [[UIImage imageNamed:@"image.png"] _imageScaledToSize:CGSizeMake(32.0f, 32.0f) interpolationQuality:1];
{ "language": "en", "url": "https://stackoverflow.com/questions/7597464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Groovy iterate Nodes with XMLHolder i want to Iterate over Nodes of an XML-File with the XML-Holder. def reader = groovyUtils.getXmlHolder(test1 ); let's say the XML looks like the following: <xml> <node> <val1/> <val2/> </node1> <node> <val1/> <val2/> </node2> </xml> i want to read the values from the different nodes. (val1, val2). So i tried like that: for( node in reader.getNodeValues( "//ns1:node" )) {} It really iterates over the nodes, but i don't know how the get access to the values inside them. Thanks a lot for your help! john A: Instead of getNodeValues, you probably want to call getDomNodes instead. That will return you standard Java DOM nodes of class org.w3c.dom.Node. From there you can traverse the child nodes starting with getFirstChild and iterating with getNextSibling. Groovy's DOMCategory adds some convenient helper methods that make it much less painful. For example: use (groovy.xml.dom.DOMCategory) { for( node in reader.getDomNodes( "//ns1:node" )) { node.children().each { child -> println child } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to turn off HTML5 Offline caching I've been using HTML5 Offline caching on my website for a while and for some reasons I am considering turning it off. To my surprise it doesn't work. This is how I've implemented HTML5 Offline caching. In my index.html I give path to the manifest file <html manifest="app.manifest"> In the app.manifest file I list all the js/css/png file that I would like to be cached by the browser for offline usage. Every time I deploy updates, I update the app.manifest file, which causes the browser to fetch latest version of all the files listed in the manifest file. In order to turn off the offline caching, I changed my index.html's opening tag to <html> I made a dummy change to app.manifest file, so that browser (which has already cached my website), will detect the change and download latest version of all the files (including index.html). What I noticed is, the browser indeed gets the latest version of all the files. I see the new <html> tag in the updated version without the manifest declaration, however the behavior of the browser for future changes does not change. i.e. I now expect the browser to immediately fetch the new version of the index.html file, when it's changed on server. However that doesn't happen. The browser doesn't download updated index.html until I make any changes to the manifest file. Thus it appears to me that the browser has permanently associated app.manifest file with my website URL and it won't get rid of it even when I don't mention it in <html> tag. I have tested this on both Google Chrome and Firefox, same results. I also tried restarting Chrome, but it won't forget that my site ever had app.manifest defined for it. I haven't found any discussion on this aspect of offline caching on the web. Update: I managed to get rid of the behavior in Chrome by clearing all the browsing data (by going to settings). But that's not something I can tell the users to do. A: Make the manifest URL return a 404 to indicate you don't want offline web applications anymore. According to Step 5 of HTML5 §5.6.4, this marks the cache as obsolete, and will remove it. You can also manually delete the offline web application in Chrome by going to about:appcache-internals.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Mixing template specialisation and enable_if in a function template with only a templated return type I have the following code that fails to compile on VC2010: #include <type_traits> using namespace std; template <class C> typename enable_if<true, C>::type foo() { return C(); } template <> bool foo() { return true; } // error C2785: 'enable_if<true,_Type>::type foo(void)' // and 'bool foo(void)' have different return types int main() { auto a = foo<int>(); auto b = foo<bool>(); } The error message seems erroneous, as the first version of foo() seems functionally identical to template <class C> C foo(); which happily compiles. Is there a way to mix-and-match enable-if'd function templates and explicit template specialisations? A: The problem is just the syntax of the full specialization. It should be: template <> bool foo<bool>() { return true; } ^^^^^^ A: A function template specialization is (thankfully!) not required to return the same type as the non-specialized template, so this is not the issue here. In fact, enable_if has nothing to do with your error, your code is simply missing the template arguments list in the specialization: template <> bool foo<bool>() { return true; } On a sidenote, why are you using enable_if if the condition is always true? (I guess this is not the case in your real code, but I just want to be sure :)!)
{ "language": "en", "url": "https://stackoverflow.com/questions/7597474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android, Is this a right way of using MyLocationOverlay for getting user location to send it to server...? I am new to android. I have learned about MyLocationOverlay. It can get user location and draw a blue point on that location. I want to get user location and send it to server. Is it possible by using MyLocationOverlay to get user location. If it is, then is this a right way of getting user location using MyLocationOverlay...??? A: Is it possible by using MyLocationOverlay to get user location. Yes, you can call getMyLocation(). However, as with getLastKnownLocation() on LocationManager, this may be null. If it is, then is this a right way of getting user location using MyLocationOverlay...??? Personally, I would rather use LocationManager directly, so I have more control over how that location is determined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I use Jquery to implement a drag drop file from outside into web page (inter-Window drag drop) (like gmail attachment)? Can I use Jquery to implement a drag drop file into web page (like gmail attachment)? Research so far has not shown existing examples: * *https://stackoverflow.com/search?q=drag+and+drop *jQuery Drag and Drop Upload (yup, use Jquery, no sh**, sherlock, but HOW?) *http://ask.metafilter.com/48575/Drag-and-drop-across-browser-windows (It's possible, but discussion here a bit vague *Are there any good jQuery drag and drop file upload plugins? (Question asks for gmail drag and drop, but answer is drag drop items within same browser page window, not from outside, from another window as in gmail) A: Did you try the plugin listed from the 'jQuery Drag and Drop Upload' link? If you do then there's a how to on gcode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I access a game controller via USB? Problem I am working on modifications to one of my applications that communicates with a telescope. One of the most annoying problems due to nothing else but reckless poor design, is the GOTO controller and its keypad. If anyone of you remember the Sinclair Spectrum you know what I mean. As well as the rubber keys, the crucial keys for guiding and slewing the telescope are awkward to locate when your eye is trying to adapt to the view. All it takes is the wrong key and you spend another 30 minutes or so re-aligning the telescope. Workaround My solution is a game controller such as a wingman, it fits neatly into your hands and is easy to locate the buttons. Also there is no risk of reseting the mount. Question My question is this, how does Delphi interact with game controllers because tthere is no mention in the documentation? Otherwise how do I access a gameport when it is connected through a USB dongle? A: Working with the game controller is part of the Windows API. JEDI's JVCL has a Human Interface Device (HID) constroller (TJvHIDDeviceController) component that does what you want. A: Delphi applications running on "NT" line operating systems (NT, 2000, XP, Vista, 7, 2003, 2008...) can't access hardware devices directly. Only drivers can, because the I/O ports required to access them can be accessed only by code running at the right IOPL level (which is 0 in Windows). There are some generic drivers available that open any I/O port (thus creating a security hole) that user code can call. But tt's far better to rely on device drivers, and use the HID API to interact with them. Windows will recognize most older devices (like the serial/game port Wingman), while newer USB ones or use the standard drivers that come with Windows, or come with their own. Once the system recognizes the devices, you can use them in a standard way with no need to dig in the low-level details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: GData youtube video upload missing audio I am using GData Api to upload video on youtube from ios application. It successfully uploads the video but audio is missing from that. I am using .mp4 format of video. Do any one has a clue? Thanks -(BOOL) setupWriter{ NSError *error = nil; // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); // NSString *documentsDirectory = [paths objectAtIndex:0]; // NSURL * url = [NSURL URLWithString:documentsDirectory]; // url = [url URLByAppendingPathComponent:@"om.mp4"]; // NSString *path = [documentsDirectory stringByAppendingPathComponent:@"om.mp4"]; // [data writeToFile:path atomically:YES]; NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/movie.mp4"]]; _videoWriter = [[AVAssetWriter alloc] initWithURL:[NSURL fileURLWithPath:path] fileType:AVFileTypeQuickTimeMovie error:&error]; NSParameterAssert(_videoWriter); // Add video input NSDictionary *videoCompressionProps = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithDouble:128.0*1024.0], AVVideoAverageBitRateKey, nil ]; NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys: AVVideoCodecH264, AVVideoCodecKey, [NSNumber numberWithInt:192], AVVideoWidthKey, [NSNumber numberWithInt:144], AVVideoHeightKey, videoCompressionProps, AVVideoCompressionPropertiesKey, nil]; _videoWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings] retain]; float angle = M_PI/2; //rotate 180°, or 1 π radians _videoWriterInput.transform = CGAffineTransformMakeRotation(angle); NSParameterAssert(_videoWriterInput); _videoWriterInput.expectsMediaDataInRealTime = YES; // Add the audio input AudioChannelLayout acl; bzero( &acl, sizeof(acl)); acl.mChannelLayoutTag = kAudioChannelLayoutTag_Mono; NSDictionary* audioOutputSettings = nil; // Both type of audio inputs causes output video file to be corrupted. if( NO ) { // should work from iphone 3GS on and from ipod 3rd generation audioOutputSettings = [NSDictionary dictionaryWithObjectsAndKeys: [ NSNumber numberWithInt: kAudioFormatMPEG4AAC ], AVFormatIDKey, [ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey, [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey, [ NSNumber numberWithInt: 64000 ], AVEncoderBitRateKey, [ NSData dataWithBytes: &acl length: sizeof( acl ) ], AVChannelLayoutKey, nil]; } else { // should work on any device requires more space audioOutputSettings = [ NSDictionary dictionaryWithObjectsAndKeys: [ NSNumber numberWithInt: kAudioFormatAppleLossless ], AVFormatIDKey, [ NSNumber numberWithInt: 16 ], AVEncoderBitDepthHintKey, [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey, [ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey, [ NSData dataWithBytes: &acl length: sizeof( acl ) ], AVChannelLayoutKey, nil ]; } _audioWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType: AVMediaTypeAudio outputSettings: audioOutputSettings ] retain]; _audioWriterInput.expectsMediaDataInRealTime = YES; // add input [_videoWriter addInput:_videoWriterInput]; [_videoWriter addInput:_audioWriterInput]; return YES; } this is setup writer I am using to capture audio is something wring in this???? A: From the CamStudio Support Forum: .MOV / .MP4 / .3GPP files MOV /MP4 /3GPP files are index based. Simply put, this means that there is an index in the file that tells us the specific location of where in the file the video and audio frames are present. Without the index, it is almost impossible to know where the data for a specific video or audio frame is. This index is contained in what is called a 'moov' atom in the file. Now, if the index is at the beginning of the file, it will enable processing of the video as and when successive bytes of the file are uploaded. On the other hand, if the index is at the end, processing the video cannot begin until the entire upload is complete - since the index is needed to interpret the file. Hence, for MOV / MP4 / 3gpp files, we prefer the "moov" atom in the beginning of the file - also known as a "fast start"MP4 / MOV file. There are tools available on the web to flatten your MOV file. Usually the video editing/export software will have options to create your files with the moov atom in the beginning rather than the end of your file. If you are using Apple editing tools, then see this article on how to produce a "fast start" MP4/MOV file./p> Here's a list of some well-known formats that YouTube supports: WebM files - Vp8 video codec and Vorbis Audio codecs .MPEG4, 3GPP and MOV files - Typically supporting h264, mpeg4 video codecs, and AAC audio codec .AVI - Many cameras output this format - typically the video codec is MJPEG and audio is PCM .MPEGPS - Typically supporting MPEG2 video codec and MP2 audio .WMV .FLV - Adobe-FLV1 video codec, MP3 audio A: I have been working with the GData API the last few days and had no similar Problems. I would suggest you checkout the filetypes supported by Youtube: http://www.google.com/support/youtube/bin/answer.py?answer=55744. Can you verify the file you are uploading actually has audio? What does Quicktime say about the Format of your Audio track? Youtube recommends using AAC (as far as I can tell).
{ "language": "en", "url": "https://stackoverflow.com/questions/7597483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WPF UserControl Focus I have a UserControl subclass that contains a Grid, which in turn contains a couple TextBlocks and a Border (which also contains a TextBlock). See code below. <UserControl x:Class="ProjectNS.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:my="clr-namespace:ProjectNS" mc:Ignorable="d" Height="49" Width="150" BottomResizeLocked="True" TopResizeLocked="True" MoveLocks="Vertical" Margin="0,-4" Focusable="True"> <my:MyUserControl.Resources> <Style x:Key="BorderStyle" TargetType="Border"> <Setter Property="Background" Value="Blue"/> <Setter Property="BorderBrush" Value="Blue"/> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type my:GanttBar}}, Path=IsKeyboardFocusWithin}" Value="True"> <Setter Property="Background" Value="{StaticResource SelectedGanttBarBackGroundBrush}"/> <Setter Property="BorderBrush" Value="{StaticResource SelectedGanttBarBorderBrush}"/> </DataTrigger> </Style.Triggers> </Style> </my:MyUserControl.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="2*" /> <RowDefinition Height="3*" /> <RowDefinition Height="2*" /> </Grid.RowDefinitions> <Label FontSize="8.5" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="4,0,0,0" Foreground="Green" /> <Border Grid.Row="1" CornerRadius="5" BorderThickness="1.5" Style=" {StaticResource BorderStyle}" FocusVisualStyle="{StaticResource SelectedBorderStyle}" Focusable="True" > <Label FontSize="10" HorizontalAlignment="Center" FontWeight="Bold" VerticalAlignment="Top" Foreground="White" Margin="0,2,0,0" /> </Border> <Label HorizontalAlignment="Right" FontSize="8.5" Grid.Row="2" VerticalAlignment="Top" Margin="0,0,4,0" Foreground="Red" /> </Grid> </my:MyUserControl> I'm trying to get the color of the embedded Border to change color when my UserControl receives focus, but I can't for the life of me figure out what actually receives focus when I click on the control. I've tried using the GotFocus event for every control, and nothing fires once the program is running. A: Use a DataTrigger on the property IsKeyboardFocusWithin. I'm not positive the exact syntax, but it should look something like this: <Style TargetType="{x:Type Border}"> <Setter Property="BorderBrush" Value="Red" /> <Style.Triggers> <!-- Will change Border color when KeyboardFocus inside Border --> <Trigger Property="IsKeyboardFocusWithin" Value="True"> <Setter Property="BorderBrush" Value="Green" /> </Trigger> <!-- Will change Border color when UserControl contains KeyboardFocus --> <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MyUserControl}}, Path=IsKeyboardFocusWithin}" Value="True"> <Setter Property="BorderBrush" Value="Blue" /> </DataTrigger> </Style.Triggers> </Style>
{ "language": "en", "url": "https://stackoverflow.com/questions/7597484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check if a string is a number I have conversion to Map problem in Core Java. Below is requirement: Given a String array below String str[] = {"abc","123","def","456","ghi","789","lmn","101112","opq"}; Convert it into a Map such that the resultant output is below Output ====== ====== key Value ====== ====== abc true 123 false def true 456 false The above should be printed for each element in the array. I have written the code but it's not working and I'm stuck. Please let me know how it can be resolved. Thanks in advance. import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class CoversionToMap { /** * @param args */ public static void main(String[] args) { String str[] = {"abc","123","def","456","ghi","789","lmn","101112","opq"}; Map m = new HashMap(); for(int i=0;i<str.length;i++){ if(Integer.parseInt(str[i]) < 0){ m.put(str[i],true); }else{ m.put(str[i],false); } } //Print the map values finally printMap(m); } public static void printMap(Map mp) { Iterator it = mp.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); System.out.println(pairs.getKey() + " = " + pairs.getValue()); } } } exception: Exception in thread "main" java.lang.NumberFormatException: For input string: "abc" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at CoversionToMap.main(CoversionToMap.java:22) A: Everyone is suggesting using exception handling for this, there is nothing exceptional here to warrant using exceptions like this, you don't try turning left in your car and if you crash go right do you? Something like this should do it Map<String, Boolean> m = new HashMap<String, Boolean>(); for (String str: strs) { m.put(str, isInteger(str)); } public boolean isInteger(String str) { int size = str.length(); for (int i = 0; i < size; i++) { if (!Character.isDigit(str.charAt(i))) { return false; } } return size > 0; } Much clearer and more efficient that catching throwing exception, even when there are 99% integers as the integer value is not even needed so no conversion required. A: Integer.parseInt(..) throws an exception for invalid input. Your if clause should look like this: if (isNumber(str[i])) { ... } else { ... } Where isNumber can be implemented in multiple ways. For example: * *using try { Integer.parseInt(..) } catch (NumberFormatException ex) (see this related question) *using commons-lang NumberUtils.isNumber(..) A: You check if parseInt returns a number smaller than 0 to see if the input is non-numeric. However, that method doesn't return any value at all, if the input is non-numeric. Instead it throws an exception, as you have seen. The simplest way to do what you want is to catch that exception and act accordingly: try { Integer.parseInt(str[i]); // str[i] is numeric } catch (NumberFormatException ignored) { // str[i] is not numeric } A: If you want to check if the string is a valid Java number you can use the method isNumber from the org.apache.commons.lang.math (doc here: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/NumberUtils.html). This way you won't have to write your own implementation of isNumber A: You need to use a try/catch block instead of testing the return value for parseInt. try { Integer.parseInt(str[i]); m.put(str[i],true); } catch(NumberFormatException e) { m.put(str[i],false); } A: Your error occurs here: if(Integer.parseInt(str[i]) < 0){ Integer.parseInt throws a NumberFormatException when the input isn't a number, so you need to use a try/catch block, for example: try{ int number = Integer.parseInt(str[i]); m.put(str[i],false); }catch NumberFormatException nfe{ m.put(str[i],true); } A: Assuming you won't use any external libraries, you can also use a Regular Expression Matcher to do that. Just like for (String element : str) { m.put(element, element.matches("\\d+")); } Note that this works only with non-negative integers, but you can adapt the regular expression to match the number formats you want to map as true. Also, if element is null, you'll get a NullPointerException, so a little defensive code is required here. A: Here is an improved answer which can be used for numbers with negative value, decimal points etc. It uses Regular Expressions. Here it it: public class StringValidator { public static void printMap(Map<String, Boolean> map) { Iterator it = map.entrySet().iterator(); for(Map.Entry<String, Boolean> entry:map.entrySet()){ System.out.println(entry.getKey()+" = "+ entry.getValue()); } } } class ValidateArray{ public static void main(String[] args) { String str[] = {"abcd", "123", "101.112", "-1.54774"}; Map<String, Boolean> m = new HashMap<String, Boolean>(); for (String s : str) { m.put(s, isNumber(s)); } StringValidator.printMap(m); } public static boolean isNumber(String str) { Pattern pattern = Pattern.compile("^-?\\d+\\.?\\d*$"); Matcher matcher = pattern.matcher(str); return matcher.matches(); } } A: Replace your parseInt line with a call to isInteger(str[i]) where isInteger is defined by: public static boolean isInteger(String text) { try { new Integer(text); return true; } catch (NumberFormatException e) { return false; } } A: I would like to enter the contrary view on 'don't use exception handling' here. The following code: try { InputStream in = new FileInputStream(file); } catch (FileNotFoundException exc) { // ... } is entirely equivalent to: if (!file.exists()) { // ... } else try { InputStream in = new FileInputStream(file); } catch (FileNotFoundException exc) { // ... } except that in the former case: * *The existence of the file is only checked once *There is no timing-window between the two checks during which things can change. *The processing at // ... is only programmed once. So you don't see code like the second case. At least you shouldn't. The present case is identical except that because it's a String there is no timing window. Integer.parseInt() has to check the input for validity anyway, and it throws an exception which must be caught somewhere anyway (unless you like RTEs stopping your threads). So why do everything twice? The counter-argument that you shouldn't use exceptions for normal flow control just begs the question. Is it normal flow control? or is it an error in the input? [In fact I've always understood that principle to mean more specifically 'don't throw exceptions to your own code' within the method, and even then there are rare cases when it's the best answer. I'm not a fan of blanket rules of any kind.] Another example detecting EOF on an ObjectInputStream. You do it by catching EOFException. There is no other way apart from prefixing a count to the stream, which is a design change and a format change. So, is EOF part of the normal flow, or is it an exception? and how can it be part of the normal flow given that it is only reported via an exception? A: Here's a more general way to validate, avoiding exceptions, and using what the Format subclasses already know. For example the SimpleDateFormat knows that Feb 31 is not valid, as long as you tell it not to be lenient. import java.text.Format; import java.text.NumberFormat; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; public class ValidatesByParsePosition { private static NumberFormat _numFormat = NumberFormat.getInstance(); private static SimpleDateFormat _dateFormat = new SimpleDateFormat( "MM/dd/yyyy"); public static void printMap(Map<String, Boolean> map) { for (Map.Entry<String, Boolean> entry : map.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); } } public static void main(String[] args) { System.out.println("Validating Nums with ParsePosition:"); String numStrings[] = { "abcd", "123", "101.112", "-1.54774", "1.40t3" }; Map<String, Boolean> rslts = new HashMap<String, Boolean>(); for (String s : numStrings) { rslts.put(s, isOk(_numFormat, s)); } ValidatesByParsePosition.printMap(rslts); System.out.println("\nValidating dates with ParsePosition:"); String dateStrings[] = { "3/11/1952", "02/31/2013", "03/14/2014", "05/25/2014", "3/uncle george/2015" }; rslts = new HashMap<String, Boolean>(); _dateFormat.setLenient(false); for (String s : dateStrings) { rslts.put(s, isOk(_dateFormat, s)); } ValidatesByParsePosition.printMap(rslts); } public static boolean isOk(Format format, String str) { boolean isOK = true; int errorIndx = -1; int parseIndx = 0; ParsePosition pos = new ParsePosition(parseIndx); while (isOK && parseIndx < str.length() - 1) { format.parseObject(str, pos); parseIndx = pos.getIndex(); errorIndx = pos.getErrorIndex(); isOK = errorIndx < 0; } if (!isOK) { System.out.println("value \"" + str + "\" not parsed; error at char index " + errorIndx); } return isOK; } } A: boolean intVal = false; for(int i=0;i<str.length;i++) { intVal = false; try { if (Integer.parseInt(str[i]) > 0) { intVal = true; } } catch (java.lang.NumberFormatException e) { intVal = false; } m.put(str[i], !intVal); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Best practice for AJAX/jQuery adding to a form and updating a list on the same page I am working on a page that has a form that puts data into one table, and also a list of items that come from that table. I want to show the newest items on top of the list after the form is added. Rigth now, the form makes an AJAX call, I get the data, send it back to jQuery in case of success, than I loop through the data. But here I am confused about how to display the data. If I use the append function, it will append to the bottom (I need it to go on top of the list). If I completely replace the list and repopulate it, is that the better solution? Seems heavy-handed. What is the best pattern here to accomplish what I am trying to do? A: jQuery has a prepend() function which is essentially the opposite of append(); rather than adding to the bottom, it adds to the top. From the information you've given that should work for your particular use. A: Try .prepend() instead of append(); jquery site .prepend() I hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add more existing sources to Java project In Netbeans I can create a project using existing sources of Java files. If I want to add additional sources to a project how can I do so? A: NetBeans 8.0 You can copy complete packages including sub-packages to the projects /src/-folder. Then Source » Scan for External Changes and the new sources will be added automatically. Have fun. A: * *right click on project *"Properties" *"Sources" (top left in the tree) *"Source Package Folders:" on the left side of the dialog *"Add Folder" A: You can attach a source JAR. You also can use the Import Sources module ("File -> Import Sources") to import source files from the file system. A: I had a similar problem where I added files directly to the project path from a file manager and NetBeans did not show them in my project tree. I found a good solution for my needs using git. As it is good practice to use a repository for code tracking code changes and I will be doing it regardless. Anyway my resolution to the issue is: Check the "Diff to HEAD" on the main project folder from within the NetBeans interface and the new files are now found...While your there double check your changes and commit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Compute the tortuosity of a polyline I have series of (x, y) coordinates, if joined this represent a polyline. This polyline is a geographic track. All that I need is to get the polyline tortuosity. It should be usefull a sort of percentage. E.g. The path has x% tortuosity. A: well, it all depends on how you define tortuosity. there is a wikipedia article regarding tortuosity, which may shed some light on the subject. an interesting sentence in the article tells us that: "roughness (or tortuosity) could be measured by relative change of curvature". that makes a good starting point. your polyline is made of adjacent line segments. you can compute the angle between each adjacent line segment. using this information you can get a good idea of tortuosity for your polyline. for example, let seg(n) be the line segment between point n and point n+1: tortuosity = sum(abs(angle(seg(n), seg(n+1))) for n in 1 to number of segment) (computing the angle between 2 line segments is left as an exercise, but does not require a degree in mathematics) the above measure is not scaled: the more points you have, the higher the value might be. you can easily scale this result according to the number of line segments you have: unit_tortuosity = tortuosity / (n * pi) (the maximum angle between 2 line segments is pi, adjust your angle() function so that it returns a result between 0 and pi. so your tortuosity would be at most n*pi, hence the above scaling factor which allows to have a value between 0 and 1 with 0 representing a perfectly straight polyline)
{ "language": "en", "url": "https://stackoverflow.com/questions/7597496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Scala - method precedence I am new to Scala. I wonder whether it is possible to define some precedence with method calls. For example, if I have the chain of method calls: someObject method1 param1 method2 param2 method3 param3 can this be equivalent to the following: someObject.method1(param1).method2(param2.method3(param3)) or someObject method1 param1 method2 (param2 method3 param3) So I want method3 to take precedence over method2... The reason I want to do this is that I want to develop a DSL, so I want to avoid using dots and parentheses as much as possible. If you guys find another solution for me, feel free to let me know. A: This behavior is defined in chapter 6.12.3 Infix Operations of The Scala Language Specification. In short: methods are invoked from left to right by default with some exceptions. These exceptions were only introduced to support mathematical operators precedence. So when you have two functions named * and +: a + b * c This will always be translated to: a.+(b.*(c)) Here the first name of the function controls the precedence. However for ordinary functions you cannot control the order. Think about it - this would actually cause havoc and terribly unmaintainable code. See also (not quite duplicate?): Operator precedence in Scala. A: You'll have to use methods with special operator characters to influence precedence as implied by Tomasz. This is partly why lots of Scala DSL make heavy use of operators. Also why some DSL are hard to read if you don't work with them daily. Given method with using only letters, underscore and digits - you won't be able to influence things, here is what I put together for myself after reading the spec: * *Any method which takes a single parameter can be used as an infix operator: a.m(b) can be written a m b. *Any method which does not require a parameter can be used as a postfix operator: a.m can be written a m. *Postfix operators have lower precedence than infix operators, so foo bar baz means foo.bar(baz) while foo bar baz bam means (foo.bar(baz)).bam and foo bar baz bam bim means (foo.bar(baz)).bam(bim). So without knowing at all what your method signatures are, the following code (because it's all alphanumeric): someObject method1 param1 method2 param2 method3 param3 will be parsed as: someObject.method1(param1).method2(param2).method3(param3) If you rename method3 to |*| or +:+ or whatever operator makes sense, you can achieve what you want: someObject method1 param1 method2 param2 |*| param3 // same as someObject.method1(param1).method2(param2.|*|(param3)) For example to see the difference: implicit def pimp(s:String) = new { def |*|(t:String) = t + s def switch(t:String) = t + s } scala> "someObject" concat "param1" concat "param2" |*| "param3" res2: java.lang.String = someObjectparam1param3param2 scala> "someObject" concat "param1" concat "param2" switch "param3" res3: java.lang.String = param3someObjectparam1param2
{ "language": "en", "url": "https://stackoverflow.com/questions/7597501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }