text
stringlengths
8
267k
meta
dict
Q: How Do I Get RouteData Values from a Web Service in .Net 4.0 I am trying to extract an id number from a URL using a web service so that it can be used as a parameter for a where clause in a select statement that produces data from a database based on the id number of a record. That data will then be passed back to the page to populate an element in a jQuery modal popup widow. Everything works fine with a static id number (ex: string postid = "120"), but I don't know how to get the id number from the URL. I'm using Routing in .Net 4 and the method for accessing Routing in pages does not work in a web service. In pages I just do stuff like var id = RouteData.Values["id"]; and that gets the id, but when i did it in a web service I got an error: CS0120: An object reference is required for the non-static field, method, or property 'System.Web.Routing.RouteData.Values.get' Summary: I have web service accessed form a details page where I want to get RouteData for the page making the request. I want to do this just as easily as I can on a page using RouteData.Values which is just as easy as the now the obsolete Request.Querystring. Now I am more confused because although I could easily add a new route for the web service I don't know I would call that using jQuery Ajax because of the webservice.asmx/webmethod syntax. Right now I have URL: "../webservices/googlemaps.asmx/GetGoogleMap" in my jQuery Ajax, but that is not a real URL. It only exists in jQuery somewhere and the way to call the service using just JavaScript is no a real URL either, its webservice.webmethod() which in this case would be googlemaps.GetGoogleMap(). I will try registering a route for webservices/googlemaps.asmx/GetGoogleMap/postid, but I doubt it will work because GetGoogleMap is not a directory or a querystring. A: Get current http request and use RequestContext property to get request context - it has current routing data. For example, var id = HttpContext.Current.Request.RequestContext.RouteData.Values["id"]; In case of WCF based web service, make sure that service is participating in ASP.NET pipeline (see ASP.NET Compatibility) EDIT: Sorry for misleading answer - the above will not work unless web service url is registered in routing engine. However, it may not solve your issue of retrieving the id - what kind of service implementation are you using? Are you making a GET request or POST request? Typically, web service handler (asmx) or WCF pipeline should convert GET/POST parameters to method parameters. Post your web service code and how you invoke it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why use prototype for methods instead of this.methodName Possible Duplicate: Advantages of using prototype, vs defining methods straight in the constructor? Why use: Person.prototype.toString = function() { return this.name; } over Function Person(name) { this.name = name; this.toString = function() { return this.name; } } A: Well, you should use prototypes because of code reuse and inheritance. Basically, if you bind a method to the this keyword, you are providing that method to only that particular instance, while with prototype, you write the method for all instances of that class. ex: function Person(name) { this.name = name; this.toString = function() { return this.name; } } var bob = new Person('Bob'); var jim = new Person('Jim'); jim.toString = function() { return "I have amnesia, I forgot my name!"; }; Now, although bob and jim are both persons (instances of the same class), they behave differently, because they have their own set of rules (methods) that they rely on. If you were to use a prototype: function Person(name) { this.setName(name); } Person.prototype = { name : 'default name', setName : function(name) { this.name = name; }, toString : function() { return this.name; } }; var bob = new Person('Bob'); var jim = new Person('Jim'); Person.prototype.toString = function() { return "I have amnesia, I forgot my name!"; }; Now, all of your persons behave the same. Using prototypal inheritance is benefic for code reuse and it won't load the memory with unnecessary duplicate things. + Updating classes is muuuch more easy this way. A: One reason is because it will update/add that function to objects of that type that have already been created. function Person(name) { this.name = name; } var person = new Person("Test"); alert(person.toString()); // alerts [object Object] Person.prototype.toString = function() { return this.name; }; alert(person.toString()); // alerts Test http://jsfiddle.net/28puy/ A: In javascript, methods are objects. In your second Person constructor, you're creating a new instance of the toString function for each instance of Person. By using the prototype object, there is just one instance of the toString function that will be shared among all instances of Person.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: text shows appears through fixed div I made a fixed div that stays at the top of the page. but when you scroll text shows up through the div. You can have a look at it here. Just scroll down to where the forum categories are. The css for the whole div is located here A: Add the css-property z-index to the toolbar. Something like this: z-index: 999; This will make sure your toolbar is always on top.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to detect a tablet device in Android? I am trying to port my application developed for smartphones to the tablets with minor modifications. Is there an API in Android to detect if the device is tablet? I can do it by comparing the screen sizes, but what is the correct approach to detect a tablet? A: I don't think there are any specific flags in the API. Based on the GDD 2011 sample application I will be using these helper methods: public static boolean isHoneycomb() { // Can use static final constants like HONEYCOMB, declared in later versions // of the OS since they are inlined at compile time. This is guaranteed behavior. return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; } public static boolean isTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; } public static boolean isHoneycombTablet(Context context) { return isHoneycomb() && isTablet(context); } Source A: I would introduce "Tablet mode" in application settings which would be enabled by default if resolution (use total pixel threshold) suggests it. IFAIK Android 3.0 introduces real tablet support, all previous versions are intended for phones and tablets are just bigger phones - got one ;) A: Thinking on the "new" acepted directories (values-sw600dp for example) i created this method based on the screen' width DP: /** * Returns true if the current device is a smartphone or a "tabletphone" * like Samsung Galaxy Note or false if not. * A Smartphone is "a device with less than TABLET_MIN_DP_WEIGHT" dpi * * @return true if the current device is a smartphone or false in other * case */ protected static boolean isSmartphone(Activity act){ DisplayMetrics metrics = new DisplayMetrics(); act.getWindowManager().getDefaultDisplay().getMetrics(metrics); int dpi = 0; if (metrics.widthPixels < metrics.heightPixels){ dpi = (int) (metrics.widthPixels / metrics.density); } else{ dpi = (int) (metrics.heightPixels / metrics.density); } if (dpi < TABLET_MIN_DP_WEIGHT) return true; else return false; } public static final int TABLET_MIN_DP_WEIGHT = 450; And on this list you can find some of the DP of popular devices and tablet sizes: Wdp / Hdp GALAXY Nexus: 360 / 567 XOOM: 1280 / 752 GALAXY NOTE: 400 / 615 NEXUS 7: 961 / 528 GALAXY TAB (>7 && <10): 1280 / 752 GALAXY S3: 360 / 615 Wdp = Width dp Hdp = Height dp A: place this method in onResume() and can check. public double tabletSize() { double size = 0; try { // Compute screen size DisplayMetrics dm = context.getResources().getDisplayMetrics(); float screenWidth = dm.widthPixels / dm.xdpi; float screenHeight = dm.heightPixels / dm.ydpi; size = Math.sqrt(Math.pow(screenWidth, 2) + Math.pow(screenHeight, 2)); } catch(Throwable t) { } return size; } generally tablets starts after 6 inch size.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges. Is the error message i get. here are the two functions i use... public IList<string> GenerateVersions(decimal id, decimal fId, string folderName, string filename, string objFile) { List<string> generatedFiles = new List<string>(); foreach (var tCmdSets in db.IMG_SETTINGS_CMDSETS.Where("it.SETTINGS_FOLDER_ID = @folderid", new ObjectParameter("folderid", id))) { var strDestinationPath = ImageResizer.Util.PathUtils.RemoveExtension(Path.Combine(tmpDefaultFolder, tCmdSets.SETTINGS_CMDSET_DESTINATION, filename)); ResizeSettings objResizeCommand = new ResizeSettings(tCmdSets.SETTINGS_CMDSET_COMMAND); var strCreatedFile = ImageBuilder.Current.Build(objFile, strDestinationPath, objResizeCommand, false, true); generatedFiles.Add("### File created: (" + folderName + " » " + tCmdSets.SETTINGS_CMDSET_NAME + " ») " + Path.GetFileName(strCreatedFile)); IMG_UPLOAD_GENERATED_FILES tObjGenerated = new IMG_UPLOAD_GENERATED_FILES(); tObjGenerated.UPLOAD_GENERATED_FILE_NAME = Path.GetFileName(strCreatedFile); tObjGenerated.UPLOAD_GENERATED_PATH = Path.GetDirectoryName(strCreatedFile); tObjGenerated.SETTINGS_CMDSET_ID = tCmdSets.SETTINGS_CMDSET_ID; tObjGenerated.UPLOAD_FILE_ID = fId; dbHandler.IMG_UPLOAD_GENERATED_FILES.AddObject(tObjGenerated); dbHandler.SaveChanges(); } return generatedFiles; } public ActionResult UploadBulkFiles(decimal id) { IMG_SETTINGS_FOLDERS img_settings_folders = db.IMG_SETTINGS_FOLDERS.Single(i => i.SETTINGS_FOLDER_ID == id); string strBulkDirectory = Path.Combine(tmpDefaultFolder, img_settings_folders.SETTINGS_FOLDER_BULK); string[] objFiles = Directory.GetFiles(strBulkDirectory); List<string> lstOuput = new List<string>(); foreach (var tFile in objFiles) { System.IO.File.Move(tFile, Path.Combine(tmpDefaultFolder, "masters", img_settings_folders.SETTINGS_FOLDER_NAME, Path.GetFileName(tFile))); lstOuput.Add("### File moved to masters (" + img_settings_folders.SETTINGS_FOLDER_NAME + " ») " + Path.GetFileName(tFile)); IMG_UPLOAD_FILES tObjUploadedFile = new IMG_UPLOAD_FILES(); tObjUploadedFile.UPLOAD_FILE_NAME = Path.GetFileName(tFile); tObjUploadedFile.SETTINGS_FOLDER_ID = img_settings_folders.SETTINGS_FOLDER_ID; dbHandler.IMG_UPLOAD_FILES.AddObject(tObjUploadedFile); dbHandler.SaveChanges(); var objGeneratedFiles = GenerateVersions(img_settings_folders.SETTINGS_FOLDER_ID,tObjUploadedFile.UPLOAD_FILE_ID, img_settings_folders.SETTINGS_FOLDER_NAME, Path.GetFileName(tFile), Path.Combine(tmpDefaultFolder, "masters", img_settings_folders.SETTINGS_FOLDER_NAME, Path.GetFileName(tFile))); lstOuput.AddRange(objGeneratedFiles); } if (lstOuput.Count > 0) { return PartialView("UploadSingleFile", lstOuput); } else { return PartialView("NoUploads"); } } DATA MODEL IMG_UPLOAD_FILE * *UPLOAD_FILE_ID (PK) *UPLOAD_FILE_NAME *SETTINGS_FOLDER_ID IMG_UPLOAD_GENERATED_FILES * *UPLOAD_GENERATED_FILE_ID (PK) *UPLOAD_GENERATED_FILE_NAME *UPLOAD_GENERATED_FILE_PATH *SETTINGS_CMDSET_ID *UPLOAD_FILE_ID A: I had the exact same scenario with Entity Model based on Oracle database. The implementation of Identity is done by trigger so when adding the tables to the model it does not set the StoreGenertedPattern property of the identity column to Identity since it doens't aware that this column is identity. There is a need to open model editor, locate the entity in the model, click on the key column and set the StoreGenertedPattern property to 'Identity' manually. A: The closest I can come to finding an answer is: Because Oracle uses a Sequence + Trigger to make "Auto Ident" values, it seems like when the entity framework adds an object at saves it, the value return is still 0, because the trigger/sequence haven't updated it yet. Because of the 0 number, the ObjectMannager will think that multiple objects with the entity key of 0 are in conflict. I don't have a "bullet proof" solutions, but have rewritten my solutions to handle it another way. \T A: This might not be related to your problem but I was getting this problem on a web page with an ajax manager running until I did this: ... private static _objectContext; protected void Page_Init(object sender, EventArgs e) { _objectContext = new ObjectContext(); } ... protected void _ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e) { e.Context = _objectContext; } protected void _ContextDisposing(object sender, EntityDataSourceContextDisposingEventArgs e) { e.Cancel = true; } Creating the ObjectContext in Page_Load when not a postback caused that very exception for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is it possible to abort a synchronous XmlHttpRequest? I have written a JavaScript function that asynchronously calls a web service using XmlHttpRequest. I have been asked to make this function finish its work before the page is rendered. I thought I could make the AJAX request synchronous but I don't want this to make the page hang too long - I'd like to abort the request after, say, 1 second if a response isn't received. Is it possible to abort a synchronous XmlHttpRequest? A: You can't: http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX sais: "Synchronous AJAX (Really SJAX -- Synchronous Javascript and XML) is modal which means that javascript will stop processing your program until a result has been obtained from the server. While the request is processing, the browser is effectively frozen. The browser treats the call like an alert box or a prompt box only it doesn't wait for input from the user, but on input by the remote server" Once the browser runs the sync request, it will wait until it will get a response. A: First of all, synchronous AJAX calls are evil because they are blocking the whole JavaScript browser engine (which you are aware of). Is simply doing the call asynchronously and discarding the result if it arrives later than after a second is not enough? If you really want to wait for the result you can still use setTimeout() (jQuery for convenience, not required): var result; var xhr = $.ajax('/url', function(response) { result = response; }); setTimeout(function() { if(result) { //AJAX call done within a second, proceed with rendering } else { //One second passed, no result yet, discard it and move on xhr.abort(); } }, 1000); With this approach you are not blocking the browser while still you don't have to wait for the AJAX call. A: XMLHttpRequest support abort method, you can get more details about it here: http://www.w3.org/TR/XMLHttpRequest/#the-abort-method But you need to check how many browserы support it. For example, abort was introduced in Windows Internet Explorer 7 and above. Before or after calling send() method of XMLHttpRequest object you can setup a timer for n-seconds delay which will interrupt an asynchronous operation which is in progress. A: It is possible in IE.Use the timeout property. the code below worked for me xmlhttp.open("method","url",false); xmlhttp.timeout="time in ms"; xmlhttp.ontimeout=function(){}; xmlhttp.send();
{ "language": "en", "url": "https://stackoverflow.com/questions/7511342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Combination of Mapview , phonegap and sancha touch Is it possible to use android native MapView with the combination of Phonegap and Sancha Touch (for fancy UI) Just like Zillow's new android version , in which they are using MapView to show locations and for screens they have used fancy UI Video
{ "language": "en", "url": "https://stackoverflow.com/questions/7511346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Eclipse-Marketplace Error Once i go to Eclipse Marketplace option i get this error message: MarketplaceDiscoveryStrategy failed with an error Unable to read repository at http://marketplace.eclipse.org/api/p?product=org.eclipse.epp.package.java.product&os=linux&runtime.version=3.6.0.v20100505&client=org.eclipse.epp.mpc.core&java.version=1.6.0_26&product.version=1.3.2.20110218-0812& ws=gtk. No route to host This in my linux machine can i know why am i getting this message, i am not able to choose any new softwares from Marketplace A: Please, add this line on eclipse ini, restart eclipse, open Marketplace and good installations: -Dorg.eclipse.epp.internal.mpc.core.service.DefaultCatalogService.url=https://marketplace.eclipse.org/catalogs/api/p This problem is that link without ssl is not working. For me that is working normal. A: Try removing RelaventKnowledge software from your machine. Mine is Windows 10. I am not getting that error once i removed that software from the machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: load specific image before anything else I'm a creating a loading screen for website I am making. The website loads many images, scripts, etc. The HTML and CSS part is great, but I need a way to guarantee that the "loading..." image will be loaded before anything else. I'm using jQuery, and everything is initiated within $(function () { ... });. I imagine that the code for this would need to be called before/outside that block, and the code to remove the loading screen will be called at the very end of that block. Currently, the loading image is set as a DIV background, which is the way I prefer it. However, if it's completely necessary, I will settle for an IMG tag. Update: (solution) I was able to answer my own question by using a combination of Robin and Vlad's responses. Both were very good, and excellent answers, however the problem is that they were aimed to load an image before another image, rather than load an image before anything else. (CSS, JS, etc...) Here's the dirty version of what I came up with: var files = [new Image(), document.createElement('link'), document.createElement('script')]; files[0].setAttribute('src', 'images/loading.gif'); files[1].setAttribute('rel', 'stylesheet'); files[1].setAttribute('type', 'text/css'); files[1].setAttribute('href', 'test.css'); files[2].setAttribute('type', 'text/javascript'); files[2].setAttribute('src', 'js/jquery-1.5.1.min.js'); window.onload = function (e) { document.getElementsByTagName('head')[0].appendChild(files[1]); document.getElementsByTagName('head')[0].appendChild(files[2]); } Taking a look at the load sequence on the network tab of Chrome's developer console shows that 'loading.gif' is loaded first, then 4 dummy images, then 'test.css', and then 'jquery.1.5.1.min.js'. The CSS and JS files don't begin to load, until they've been inserted into the head tag. This is exactly what I want. I'm predicting that I may begin to have some problems, however, when I begin to load a list of files. Chrome reports that sometimes the JS file is loaded first, but the majority of the time the CSS file is loaded first. This isn't a problem, except when I begin to add files to load, I will need to ensure that jQuery is loaded before a script file that uses jQuery. If anyone has a solution for this, or a way to detect when the CSS/JS files are finished loading, using this method, then please comment. Though, I'm not sure that it's going to be a problem yet. I may need to ask a new question in the future about this, if I start to run into problems. Thank you to every who has helped with this issue. Update: (glitch fix) I ended up running into a lot of problem with this method, because the script files were being loaded asynchronously. If I would clear the browser cache, and then load the page, it would finish loading my jquery dependent files first. Then if I refreshed the page, it would work, because jquery was loaded from cache. I solved this by setting up an array of files to load, then putting the load script into a function. Then I would step through each array item using this code: element.onload = function() { ++i; _step(); } element.onreadystatechange = function() { if (("loaded" === element.readyState || "complete" === element.readyState)) { ++i; _step(); } } A: As long as the "loading..." image is positioned before any other html elements, it should load first. This of course depends on the size of the image. You could put the loading div right after the tag and position it using 'position:absolute'. Regarding the code to remove the loading screen, one method is to do the following. * *Put all the images, scripts that need to be loaded in a hidden div (display: none) *Set up a variable that will hold the total of the images / scripts to be loaded *Set up a counter variable *Attach to each image / script the "onload" event *Everytime the "onload" event is triggered it will call a function that will increment the counter variable and check if the value of the counter equals the value of the total variable *If all resources have been loaded, fire a custom event that will show the div with the images, and hide the div with the loading screen. The code below isn't tested so it might not work. Hope it helps var totalImages = 0; var loadCounter = 0; function incrementLoadCounter() { loadCounter++; if(loadCounter === totalImages) { $(document).trigger('everythingLoaded'); } } function hideLoadingScreen() { $('#loadingScreen').hide(); $('#divWithImages').show(); } $(document).ready(function(e) { $('#loadingScreen').bind('everythingLoaded', function(e) { hideLoadingScreen(); }); var imagesToLoad = $('img.toLoad'); totalImages = imagesToLoad.length; $.each(imagesToLoad, function(i, item) { $(item).load(function(e) { incrementLoadCounter(); }) }); }) A: I'm not sure if it's possible to enforce. If it is, try adding this in the head-tag: <script type="text/javascript"> if(document.images) (new Image()).src="http://www.image.com/example.png"; </script> In theory that may load and cache that image before anything else. A: You can reuse resource prealoding browser support. I'm not sure it works across all browsers but in my case this approach helps me to load images first. Also it allows to define concrete images so UI specific could be skipped First define in header what resource you want to preload and define resource priority <link rel="preload" href="link-to-image" as="image"> or <link rel="preload" href="link-to-image"> Second line allow to increase loading priority across all object types (scripts / images / styles). First line - only through images. Then define in body link to image as usual: <img src="link-to-image" alt=""> Here is my working example https://jsfiddle.net/vadimb/05scfL58/ A: I think if you place the IMG tag at the top of your html body it will be loaded first. If you do not want to move your div just use a copy of the image tag. Once the images is loaded it will be shown in every image tag which shows the same picture. A: Or you could use spin.js as loading image. It display this "loading cycle image" via javascript. Check it out under: http://fgnass.github.com/spin.js/
{ "language": "en", "url": "https://stackoverflow.com/questions/7511352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Change iPhone splash screen time How would I make the splash screen stay for longer, 5 seconds, for example? A: You need to create a view controller for displaying the splash screen as done below. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [self generateRandomSplashScreen]; [self performSelector:@selector(removeSplashScreen) withObject:nil afterDelay:SPLASHSCREEN_DELAY]; [self otherViewControllerLoad]; // the other view controller [self.window makeKeyAndVisible]; return YES; } -(void) generateRandomSplashScreen { splashScreenViewController = [[SplashScreenController alloc] initWithNibName:@"SplashScreenController" bundle:[NSBundle mainBundle]]; [self.window addSubview:self.splashScreenViewController.view]; } -(void) removeSplashScreen { [splashScreenViewController.view removeFromSuperview]; self.window.rootViewController = self.tabBarController; [splashScreenViewController release]; } A: Write sleep(5.0) in your - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method. A: Probably the splash screen you are talking about is "default.png" file. As JustSid mentioned, this file is not intended to be splash screen, rather to be used as a first screen snapshot to improve user experience concerning application loading time. Check human interface guideline http://developer.apple.com/library/ios/documentation/userexperience/conceptual/mobilehig/IconsImages/IconsImages.html#//apple_ref/doc/uid/TP40006556-CH14-SW5 If you want to implement splashscreen, you should use ie. NSTimer and UIView components. A: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { /*this will pause main thread for x interval seconds. put on the top of application:didFinishLaunchingWithOptions, so it will not proceed to show window until sleep interval is finished.*/ [NSThread sleepForTimeInterval:5]; //add 5 seconds longer. //other code.... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Software-design only with interfaces? Is it good approach when in software-designing the class interactions are describe only with interfaces? If yes, should I always use this approach? I must design class library that should have a high testability (I use C#). This library have one facade and some amount of classes with different interactions in the background. In the case of optimizing this library for good testability I've replace most part of my classes with interfaces. And when I did this, I saw in a connection diagram (Visual Studio class diagram) only interfaces. Is it normal decision of my problem? or there should be some another approach? P/S: Maybe it's well known way in software-design but I can't find some confirmation in books that I have. A: Yes this is good practice. It allows you to focus about the responsibilities of each class without getting concerned with implementation details. It allows you to see the method call stack and as you say gives a high level of testability and maintainability. You're on the right track as far as I see :) A: Yes, that is generally a good practice. I would recommend you to read a good design patterns book, for example this one. it is targeted for Java developers but I had no trouble understanding all the examples as a C# developer. A: By using interfaces you can decompose your applications into subsystems to make it maintenable and easily expandable. Some uses cases can be: * *application may need to communicate more than one web service endpoints to to fullfill same functions such as direct billing or payment interfaces from different providers *data access layer class that execute SQLs to different Databases with different drivers. *processing different objects that implements the same interface using the same thread pool from the same queue
{ "language": "en", "url": "https://stackoverflow.com/questions/7511354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Why is std::bitset<8> 4 bytes big? It seems for std::bitset<1 to 32>, the size is set to 4 bytes. For sizes 33 to 64, it jumps straight up to 8 bytes. There can't be any overhead because std::bitset<32> is an even 4 bytes. I can see aligning to byte length when dealing with bits, but why would a bitset need to align to word length, especially for a container most likely to be used in situations with a tight memory budget? This is under VS2010. A: The most likely explanation is that bitset is using a whole number of machine words to store the array. This is probably done for memory bandwidth reasons: it is typically relatively cheap to read/write a word that's aligned at a word boundary. On the other hand, reading (and especially writing!) an arbitrarily-aligned byte can be expensive on some architectures. Since we're talking about a fixed-sized penalty of a few bytes per bitset, this sounds like a reasonable tradeoff for a general-purpose library. A: I assume that indexing into the bitset is done by grabbing a 32-bit value and then isolating the relevant bit because this is fastest in terms of processor instructions (working with smaller-sized values is slower on x86). The two indexes needed for this can also be calculated very quickly: int wordIndex = (index & 0xfffffff8) >> 3; int bitIndex = index & 0x7; And then you can do this, which is also very fast: int word = m_pStorage[wordIndex]; bool bit = ((word & (1 << bitIndex)) >> bitIndex) == 1; Also, a maximum waste of 3 bytes per bitset is not exactly a memory concern IMHO. Consider that a bitset is already the most efficient data structure to store this type of information, so you would have to evaluate the waste as a percentage of the total structure size. For 1025 bits this approach uses up 132 bytes instead of 129, for 2.3% overhead (and this goes down as the bitset site goes up). Sounds reasonable considering the likely performance benefits. A: The memory system on modern machines cannot fetch anything else but words from memory, apart from some legacy functions that extract the desired bits. Hence, having the bitsets aligned to words makes them a lot faster to handle, because you do not need to mask out the bits you don't need when accessing it. If you do not mask, doing something like bitset<4> foo = 0; if (foo) { // ... } will most likely fail. Apart from that, I remember reading some time ago that there was a way to cramp several bitsets together, but I don't remember exactly. I think it was when you have several bitsets together in a structure that they can take up "shared" memory, which is not applicable to most use cases of bitfields. A: I had the same feature in Aix and Linux implementations. In Aix, internal bitset storage is char based: typedef unsigned char _Ty; .... _Ty _A[_Nw + 1]; In Linux, internal storage is long based: typedef unsigned long _WordT; .... _WordT _M_w[_Nw]; For compatibility reasons, we modified Linux version with char based storage Check which implementation are you using inside bitset.h A: Because a 32 bit Intel-compatible processor cannot access bytes individually (or better, it can by applying implicitly some bit mask and shifts) but only 32bit words at time. if you declare bitset<4> a,b,c; even if the library implements it as char, a,b and c will be 32 bit aligned, so the same wasted space exist. But the processor will be forced to premask the bytes before letting bitset code to do its own mask. For this reason MS used a int[1+(N-1)/32] as a container for the bits. A: Maybe because it's using int by default, and switches to long long if it overflows? (Just a guess...) A: If your std::bitset< 8 > was a member of a structure, you might have this: struct A { std::bitset< 8 > mask; void * pointerToSomething; } If bitset<8> was stored in one byte (and the structure packed on 1-byte boundaries) then the pointer following it in the structure would be unaligned, which would be A Bad Thing. The only time when it would be safe and useful to have a bitset<8> stored in one byte would be if it was in a packed structure and followed by some other one-byte fields with which it could be packed together. I guess this is too narrow a use case for it to be worthwhile providing a library implementation. Basically, in your octree, a single byte bitset would only be useful if it was followed in a packed structure by another one to three single-byte members. Otherwise, it would have to be padded to four bytes anyway (on a 32-bit machine) to ensure that the following variable was word-aligned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What is standard resolution of android tablet? What is standard resolution for android tablet?or an emulator? A: You shouldn't only develop you application for one resolution. Take a look at this, it's very helpful. http://developer.android.com/guide/practices/screens_support.html A: below are unique resolution for Smartphone and Tablet of Android Sr. Resolution 1 2560*1600 2 1366*768 3 1280*800 4 1280*768 5 1024*768 6 1024*600 7 960*640 8 960*540 9 854*480 10 800*600 11 800*480 12 800*400 13 640*360 14 640*240 15 480*320 16 400*240 17 320*240 and I think 1024*600 800*480 are standard resolution Ref 1 Ref 2 Ref 3
{ "language": "en", "url": "https://stackoverflow.com/questions/7511357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Uploading multi-line records into SQL Server We receive fixed length datasets from a client that look something like this: 1 SOMEFILE 20110922 2 20110101ABC999 3 JOHN SMITH 19800201 4 5000000 1000 2 20060101DEF999 3 JANE KOTZE 19811001 4 200000 800 5 5200000 1800 where the number in the first position on each line indicates the type of information in the line. The types are: 1 Header record (only appears once, in the first line) 2 Contract record 3 Person record 4 Amounts record 5 Trailer record (only appears once, in the last line) The information in 2, 3 and 4 all actually relate to one record, and I need to find a way at upload stage to combine them into one. There are no identifiers that explicitly specify which combinations of 2, 3 and 4 belong with one another, but in all cases they have been ordered in the raw data to appear directly below one another. What I need is a preprocessing step that will take the original data and then combine the correct 2,3 and 4 lines into one record (and then output again as a txt file), like this: 20110101ABC999JOHN SMITH 198002015000000 1000 20060101DEF999JANE KOTZE 19811001200000 800 I have thought of bcp'ing into SQL (or even just using Access) and assigning an auto-incremented integer as PK. i.e: PK Type Record 1 1 SOMEFILE 20110922 2 2 20110101ABC999 3 3 JOHN SMITH 19800201 4 4 5000000 1000 5 2 20060101DEF999 6 3 JANE KOTZE 19811001 7 4 200000 800 8 5 5200000 1800 and then doing something like: select type2.[record]+type3.[record]+type4.[record] from (select [record] from uploaded where [type]=2) as type2 join (select [record] from uploaded where [type]=3) as type3 on type2.PK + 1 = type3.PK join (select [record] from uploaded where [type]=4) as type4 on type2.PK + 2 = type4.PK But what I am worried about is that this is entirely dependent on SQL Server assigning the PKs in the order that the data appears in die input file; I am not sure that this would necessarily be the case. Does anyone know? Or know of a better way to do this? Thanks Karl A: Edit: added second solution Solution 1: You can not be sure regarding SQL Server insert order. You have to do some text file processings before importing your data in SQL Server. For example, you can use PowerShell to add a PK into file thus: $rows = GET-CONTENT -PATH D:\BD\Samples\MyData.txt for($i=0; $i -lt $rows.length; $i++) { $row = $rows[$i] $temp=("00000"+[string]($i+1)) $rows[$i]=$temp.substring($temp.length-5)+" "+$row } SET-CONTENT -PATH D:\BD\Samples\MyDataResults.txt $rows Before (MyData.txt content): 1 SOMEFILE 20110922 2 20110101ABC999 3 JOHN SMITH 19800201 4 5000000 1000 2 20060101DEF999 3 JANE KOTZE 19811001 4 200000 800 5 5200000 1800 After PowerShell processing (MyDataResults.txt content): 00001 1 SOMEFILE 20110922 00002 2 20110101ABC999 00003 3 JOHN SMITH 19800201 00004 4 5000000 1000 00005 2 20060101DEF999 00006 3 JANE KOTZE 19811001 00007 4 200000 800 00008 5 5200000 1800 In both PS scripts I assume you can insert max. 99999 rows. Solution 2: $rows = GET-CONTENT -PATH D:\BD\Samples\MyData.txt $rows[0]="00000 "+$row $rows[$rows.length-1]="99999 "+$row $groupid=0 for($i=1; $i -lt $rows.length-1; $i=$i+3) { $groupid++ $row = $rows[$i] $temp=("00000"+[string]$groupid) $rows[$i]=$temp.substring($temp.length-5)+" "+$row $row = $rows[$i+1] $temp=("00000"+[string]$groupid) $rows[$i+1]=$temp.substring($temp.length-5)+" "+$row $row = $rows[$i+2] $temp=("00000"+[string]$groupid) $rows[$i+2]=$temp.substring($temp.length-5)+" "+$row } SET-CONTENT -PATH D:\BD\Samples\MyDataResults2.txt $rows Results: 00000 4 200000 800 00001 2 20110101ABC999 00001 3 JOHN SMITH 19800201 00001 4 5000000 1000 00002 2 20060101DEF999 00002 3 JANE KOTZE 19811001 00002 4 200000 800 99999 4 200000 800
{ "language": "en", "url": "https://stackoverflow.com/questions/7511359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does iOS store persistent data with encryption? Can an iPhone app encrypt its stored data? So that even a user with a Jailbroken iOS device cannot access the file. For example, game-center may sync with local data, you do not want the user manipulating the scores. You do not want your IAP be circumvented either. Is there a simple way to encrypt your data before writing to the device? Maybe my questions are not very clear. Indeed they are: * *When I'm using things like: [array writeToFile:path atomically:YES]; is there any auto-encryption that ensures only my app can access the file correctly? *If not, what is the simplest way to achieve it? PS: now I found NSData can do the job, but the NSDataWritingFileProtectionComplete flag requires #if __IPHONE_4_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED. I wonder what happens on not-supported devices? A: More information on iOS encryption in @GrahamLee's answer to this question and on other iOS tagged questions on security.stackexchange.com. Basic summary is - based on iPhone controls alone: * *If someone has the device and it isn't locked, they can access all the data *If someone has the device and it is locked, they can get most of the data, and possibly all (some exceptions may apply) You could obfuscate, and use encryption within your app when storing data, but an attacker could reverse engineer that encryption code to decrypt. You need to work out the value of such DRM techniques and decide whether they are worthwhile in this scenario. A: That docs will help you to find more accurate answer: * *http://sit.sit.fraunhofer.de/studies/en/sc-iphone-passwords.pdf *http://sit.sit.fraunhofer.de/studies/en/sc-iphone-passwords-faq.pdf
{ "language": "en", "url": "https://stackoverflow.com/questions/7511376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: BIRT using log4J by default do BIRT by default uses log4j.properties file? if my aplication log4j path is same as birt log path.. then birt log is using my application log only.. i dont want this A: No, BIRT use java logging (not a log4j). Details are here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Browser-like tabs - Jquery UI Tab positioning I'm working on JQuery UI tab Add/Remove function. My html is <div id="dialog" title="Tab data"> <form> <fieldset class="ui-helper-reset"> <label for="tab_title">Title</label> <input type="text" name="tab_title" id="tab_title" value="" class="ui-widget-content ui-corner-all" /> <label for="tab_content">Content</label> <textarea name="tab_content" id="tab_content" class="ui-widget-content ui-corner-all"></textarea> </fieldset> </form> </div> <button id="add_tab">Add Tab</button> <div id="tabs"> <ul> </ul> </div> My JQuery is $(function() { var $tab_title_input = $( "#tab_title"), $tab_content_input = $( "#tab_content" ); var tab_counter = 2; // tabs init with a custom tab template and an "add" callback filling in the content var $tabs = $( "#tabs").tabs({ tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>", add: function( event, ui ) { var tab_content = $tab_content_input.val() || "Tab " + tab_counter + " content."; $( ui.panel ).append( "<p>" + tab_content + "</p>" ); } }); // modal dialog init: custom buttons and a "close" callback reseting the form inside var $dialog = $( "#dialog" ).dialog({ autoOpen: true, modal: true, buttons: { Add: function() { addTab(); $( this ).dialog( "close" ); }, Cancel: function() { $( this ).dialog( "close" ); } }, open: function() { $tab_title_input.focus(); }, close: function() { $form[ 0 ].reset(); } }); // addTab form: calls addTab function on submit and closes the dialog var $form = $( "form", $dialog ).submit(function() { addTab(); $dialog.dialog( "close" ); return false; }); // actual addTab function: adds new tab using the title input from the form above function addTab() { var tab_title = $tab_title_input.val() || "Tab " + tab_counter; $tabs.tabs( "add", "#tabs-" + tab_counter, tab_title ); tab_counter++; } // addTab button: just opens the dialog $( "#add_tab" ) .button() .click(function() { $dialog.dialog( "open" ); }); // close icon: removing the tab on click $( "#tabs span.ui-icon-close" ).live( "click", function() { var index = $( "li", $tabs ).index( $( this ).parent() ); $tabs.tabs( "remove", index ); }); }); What I want is to switch to newly created tab Automatically & also position add "new tab" button next to tabs like we have in browsers these days. I tried inserting "Add tab" button inside tabs <ul> but then, tab doesn't work properly. Any Help would be appreciated ! UPDATE Here is working solution : http://jsfiddle.net/SjW4f/20/ A: http://jsfiddle.net/SjW4f/4/ I changed two things. I added a 'select' method after you add the tab. I also changed your live event to a delegate event. A: Here is it: http://jsfiddle.net/SjW4f/21/ You will need to work a little with reordering tabs on add event to make add tab the lastest. UPDATED TO WORKING VERSION
{ "language": "en", "url": "https://stackoverflow.com/questions/7511382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse regex for finding the following string I want to search all files in my project in eclipse and replace all occurences of ConnectionID="lettersandnumbers" what is the regex for the bit between the quotation marks(including the quotations)? A: assuming you want to replace the String contents, look for (ConnectionID=").*?(") and replace with $1replacement$2 where replacement is what you want to replace the String with :-) A: Try this: ConnectionID="[\p{L}\p{N}]*" This will match all Unicode letters and numbers. Remember, à is a letter too. A: Put this in your search box: ConnectionID=\"[\w]+\" A: I would search for: ConnectionID="(.*)" If you're not interested in keeping the chars between quotes you can use ConnectionID=".*"
{ "language": "en", "url": "https://stackoverflow.com/questions/7511384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: move app to sd (totally) How can I let the user move an app to SD card, but totally? I've used android:installLocation="auto" in the android manifest, but it seems that it not move the entire app, only a piece. Can you explain me how to let it move totally? A: There is no way you can move app "totally" to the external storage. What you are using is your best possible bet. If your app consumes lot of memory due to data such media content etc or user created media. Write code which uses the external storage to store such data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I know whether app is terminated by user? How can I know whether app is terminated by user? (Double-clicking Home button and press red minus '-' button) I need sample or pseudo code... A: Sometimes you do get the UIApplicationWillTerminateNotification (you can also implement the applicationWillTerminate: method in your app delegate), but it's not guaranteed that you do get any notification at all in this case. So don't rely on it. You won't receive the notification if your app is "suspended", that is it is in background but not running. In the suspended case you simply get killed with the non-catchable SIGKILL. Same for when you get killed due to out-of-memory. From the documentation for applicationWillTerminate: (emphasis mine): For applications that do not support background execution or are linked against iOS 3.x or earlier, this method is always called when the user quits the application. For applications that support background execution, this method is generally not called when the user quits the application because the application simply moves to the background in that case. However, this method may be called in situations where the application is running in the background (not suspended) and the system needs to terminate it for some reason. A: Try this: - (void)applicationWillTerminate:(UIApplication *)application { /* Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. */ } You should implement the method above in your class that implements UIApplicationDelegate Some more notes: that method won't be called if you are stopping your app via Xcode (stop debug button). So be patient when testing. A: When user kills the app: - (void)applicationWillTerminate:(UIApplication *)application{ } Application will enter inactive state: - (void)applicationWillResignActive:(UIApplication *)application { NSLog(@"Application Did Resign Active"); } User pushes Home button: - (void)applicationDidEnterBackground:(UIApplication *)application { NSLog(@"Application Did Enter Background"); } A: Also there is this: - (void)applicationDidEnterBackground:(UIApplication *)application { } Could be helpful if you want to know did it enter background ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7511388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Equivalent of get_or_create for adding users Is there a simpler way to add a user than with the following pattern? try: new_user = User.objects.create_user(username, email, password) except IntegrityError: messages.info(request, "This user already exists.") else: new_user.first_name = first_name # continue with other things A: I don't think so. But you can proxify the Django User: class MyUser(User): class Meta: proxy = True def get_or_create(self, username, email, password, *args, **kwargs): try: new_user = User.objects.create_user(username, email, password) except IntegrityError: return User.objects.get(username=username, email=email) else: new_user.first_name = kwargs['first_name'] # or what you want ...etc... return new_user A: In Django 1.4, get_or_create() exists for User. from django.contrib.auth.models import User _user = User.objects.get_or_create( username=u'bob', password=u'bobspassword', ) A: It is better not to catch IntegrityError as it can happen for other reasons. You need to check if user exists, excluding the password. If user already exists, set the password. user, created = User.objects.get_or_create(username=username, email=email) if created: user.set_password(password) user.save() A: This method should solve this problem but keep in mind that in the database, password is kept as a hash of the password, and as pointed before, "get_or_create" makes an exact lookup. So before the lookup actually happens, we "pop" the password from the kwargs. This method on your custom UserManager: def get_or_create(self, defaults=None, **kwargs): password = kwargs.pop('password', None) obj, created = super(UserManager, self).get_or_create(defaults, **kwargs) if created and password: obj.set_password(password) obj.save() return obj, created
{ "language": "en", "url": "https://stackoverflow.com/questions/7511391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: haskell: output non-ascii characters I'd like to output non-ascii characters in WinGHCi, but this is what I get: Prelude> "δ" "\948" Prelude> putStr "\948" *** Exception: <stdout>: hPutChar: invalid argument (character is not in the code page) I am using WinGHCi 7.0.3 on windows xp. What do I have to do so that WinGHCi prints a nice little delta? A: This is a WinGHCI bug. Use GHCI (the console, non-GUI version). UPD: this is apparently not entirely correct (works for me with Greek letters and not e.g. Cyrillic). A: Works on OSX! Prelude> putStrLn "\948" δ Sounds like this is a windows problem with nothing to do with haskell...
{ "language": "en", "url": "https://stackoverflow.com/questions/7511393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Android ADT r12 for MAC I am getting an error message regarding a styles.xml on my Eclipse for MAC OS X. Below is the error message: error: Error retrieving parent for item: No resource found that matches the given name 'android:WindowTitleBackground'. I googled this issue and found out that I will require an SDK r11 update to solve this problem. But since the latest SDK is r12, I downloaded using my Eclipse. But I still see this problem. I am new to Android, so I do not really know how to troubleshoot this problem. I am hoping you guys can help me. Do let me know if I need to provide more information. Thanks in advance. A: Here is a bug report where everything is explained: http://code.google.com/p/android/issues/detail?id=18659 WindowTitleBackground is a private resource and thus you cannot inherit from it, instead you should copy the parent resource. A: Try this: @android:style/WindowTitleBackground You need to specify which type this @android is, so adding style should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery: Control page reloads or moving away from the current page If a user moves away from the current page by using mouse (clicking on a link) or keyboard (hitting enter while having a form element focused) interactions, i want to do be able to run JavaScript/jQuery commands beforehand. Exemplary workflow: * *User clicks on any link or hits a key which will result in loading a new page in the browser *A JavaScript event gets fired and does something (for example console.log()) *Finally, the page load is executed Furthermore, it would be great if that also works with user events that trigger a page reload (like pressing F5). I realize that there is something similar here on Stackoverflow. It shows an alert before loading another page if there is unsaved content in an answer box. That may be the same functionality i ask for. A: $( window ).unload(function() { return "Handler for .unload() called."; }); Reference: JQuery unload().
{ "language": "en", "url": "https://stackoverflow.com/questions/7511396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: output from AbsoluteTiming This is just a curiosity - I don't have a real question. The output of AbsoluteTiming has a definite pattern; can anyone confirm/explain ? xxx = RandomReal[NormalDistribution[0, 1], 10^6]; Sin[#] & /@ xxx; // AbsoluteTiming (* {0.0890089, Null} *) Max[Exp[#] - 0.5, 0] & /@ xxx; // AbsoluteTiming (* {0.1560156, Null} *) $Version 8.0 for Microsoft Windows (64-bit) (February 23, 2011) A: Yep. Let´s check if the time quantum is consistent: Differences@ Round[10^5 Sort@ Union[AbsoluteTiming[ Sin[#] & /@ RandomReal[NormalDistribution[0, 1], #];][[1]] & /@ RandomInteger[10^6, 100]]] (* -> {1562, 1563, 1563, 1562, 1562, 1563, 1563, 1562, 1562, 1563, 1563, \ 1562, 1562, 1563, 1563, 1562, 1562} *) Edit Better code Differences@ Sort@Union[ Round[10^5 AbsoluteTiming[ Sin[#] & /@ RandomReal[NormalDistribution[0, 1], #];][[1]] & /@ RandomInteger[10^6, 100]]] A: According to the Documentation, "AbsoluteTiming is always accurate down to a granularity of $TimeUnit seconds, but on many systems is much more accurate." So evaluating $TimeUnit probably can elucidate this issue. A: Presumably your system's clock only has granularity to some fraction of a second that happens to produce a repeating decimal. I have never noticed this on my Macs. It's cool, though. EDIT Now that I am home I can confirm this must be system-specific: here is my output from the code in belisarius's answer: {56, 119, 28, 25, 33, 397, 35, 82, 185, 67, 41, 67, 218, 192, 115, \ 28, 74, 16, 187, 222, 194, 8, 129, 399, 68, 75, 71, 34, 5, 37, 62, \ 64, 137, 173, 24, 98, 135, 308, 63, 155, 208, 861, 22, 72, 72, 184, \ 609, 564, 112, 1011, 118, 81, 158, 90, 351, 33, 35, 68, 10, 126, 39, \ 194, 7, 108, 278, 75, 37, 214, 34, 166, 119, 10, 335, 141, 4, 988, \ 90, 121, 71, 130, 117, 186, 33, 123, 111, 110, 57, 64, 213, 217, 210, \ 204, 98, 247, 20, 1421, 28, 2003, 353}
{ "language": "en", "url": "https://stackoverflow.com/questions/7511397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to remove encoding="UTF-8" standalone="no" from xml Document object in Java I want to create XML in Java. DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder; docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); but Java automatically creates declaration like this <?xml version="1.0" encoding="UTF-8" standalone="no"?> How can I remove encoding="UTF-8" standalone="no" so it will be <?xml version="1.0"?> Thanks! A: Why do you need to remove an encoding? But.. doc.setXmlStandalone(true); will erase standalone="no" A: transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); This would resolve your issue, verified at JDK 6 A: I think there is no legal way to exclude theese attributes from generation. But after it's generated you can use XSLT to remove this. I think this is a good way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: keeping count and storing of text instances I would like to make a simple code that counts the top three most recurring lines/ text in a txt file then saves that line/ text to another text file (this in turn will be read into AutoCAD’s variable system). Forgetting the AutoCAD part which I can manage how do I in VB.net save the 3 most recurring lines of text each to its own text file see example below: Text file to be read reads as follows: APG BTR VTS VTS VTS VTS BTR BTR APG PNG The VB.net program would then save the text VTS to mostused.txt BTR to 2ndmostused.txt and APG to 3rdmostused.txt How can this be best achieved? A: Since I'm C# developer, I'll use it: var dict = new Dictionary<string, int>(); using(var sr = new StreamReader(file)) { var line = string.Empty; while ((line = sr.ReadLine()) != null) { var words = line.Split(' '); // get the words foreach(var word in words) { if(!dict.Contains(word)) dict.Add(word, 0); dict[word]++; // count them } } } var query = from d in dict select d order by d.Value; // now you have it sorted int counter = 1; foreach(var pair in query) { using(var sw = new StreamWriter("file" + counter + ".txt")) sw.writer(pair.Key); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get key value in django template? Django template system - how to get python dictionary value from key? I have two dictionaries which represent different data but both have same key so that I am able to access different data from the same key. First dict is: {**'Papa, Joey C'**: {'Office Visit Est Pt Level 3 (99213)': 32, 'LAP VENTABD HERNIA REPAIR (49652)': 2, 'INSERT TUNNELED CV CATH (36561)': 4, 'Office Visit New Pt Level 2 (99202)': 4, 'PUNCTURE/CLEAR LUNG (32420)': 1, 'REPAIR SUPERFICIAL WOUND S (12011)': 1, 'DEBRIDE SKINTISSUE (11042)': 29, 'Office Visit New Pt Level 3 (9 9203)': 11, 'IDENTIFY SENTINEL NODE (38792)': 2, 'MAST MOD RAD (19307)': 1, 'EXC FACE LES SC < 2 CM (21011)': 1, 'ACTIVE WOUND CARE20 CM OR (97597)': 4, 'RPR UM BIL HERN, REDUC > 5 YR (49585)': 3, 'REMOVE LESION BACK OR FLANK (21930)': 2}} Second dictionary is: {**'Papa, Joey C'**: {'10140': 1, '10061': 1, '99214': 1, '99215': 1, '12011': 1, '97606': 1, '49080': 1, '10120': 1, '49440': 1, '49570': 1}, 'Bull, Sherman M': {'99211': 1, '99214': 1, '99215': 1, '99231': 1, '99236': 1, '12051': 1, '15004':1, '47100': 1, '15430': 1, '15431': 1}} On django template, I am using... {% for key1,value1 in mydict.items %} <br><br> <br><br> <table border="1"><tr><td>Provider Name</td><td width="70%">{{key1}}</td></tr></table> <br><br> <table class="report_by_provider"><thead><tr><th>CPT Discription</th><th>Total</th></tr></thead> <tbody> {% for key2,val2 in value1.items %} <tr> <td>{{key2}}</td> <td>{{val2}}</td> </tr> {% endfor %} </tbody> </table> <table class="report_by_provider"><thead><tr><th>CPT Code</th><th>CPT Discription</th><th>Vol</th></tr></thead> <tbody> {% for key3,val3 in mydict1.key1%} {% for key,val in val3.items %} <tr> <td>{{key1}}</td> <td>{{val}}</td> <td>{{val}}</td> </tr> {% endfor %} {% endfor %} But the second dictionary is not printing. A: mydict = {'Papa, Joey C': {'10140': 1, '10061': 1, '99214': 1, '99215': 1, '12011': 1, '97606': 1, '49080': 1, '10120': 1, '49440': 1, '49570': 1}, 'Bull, Sherman M': {'99211': 1, '99214': 1, '99215': 1, '99231': 1, '99236': 1, '12051': 1, '15004':1, '47100': 1, '15430': 1, '15431': 1}} {% for mykey,myvalue in mydict.items %} {{ mykey }} : {{ myvalue }} {% endfor %} A: Given the dictionary: {'papa': {'name': 'Papa, Joey C', 'values': {'10140': 1, ... you can access the values from the keys using {{ mydict1.papa.name }} Knowing directly use the key in the template if it contains use spaces or specials chars, you could either change your structure (like i just did for the example) or create a custom templatetag/filter which you could use like {{ mydict1|get_key:"Papa, Joey C"}}. If you want a complete example for a filter just let me know. A: dic_1 is a dictionary. i need the key and value. we can do loop and get the key and value like this. {% for key, value in dic_1.items %} {{key}} {{value}} {% endfor %}
{ "language": "en", "url": "https://stackoverflow.com/questions/7511405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Issue with wrong controller being called in jquery ajax call My issue is for some strange reason it seems stuck in the page controller so instead of getting out and going into the ajax controller I have it trying to go down that route in the page controller 1st try http://localhost:2185/Alpha/Ajax/GetBlah_Name/?lname=Ge&fname=He 2nd try http://localhost:2185/Patient/~/Ajax/GetBlah_Name/?lname=Ge&fname=He Objective http://localhost:2185/Ajax/GetBlah_Name/?lname=Ge&fname=He Page button to call jquery <a style="margin-left: 310px;" href="javascript:void(0)" onclick="getBlah()" class="button"><span>Lookup</span></a> Jquery code 1st try { $.getJSON(callbackURL + 'Ajax/GetBlah_Name/?lname=' + $('#Surname').val() + '&fname=' + $('#FirstName').val(), null, GetResults) } 2nd try { $.getJSON(callbackURL + '~/Ajax/GetBlah_Name/?lname=' + $('#Surname').val() + '&fname=' + $('#FirstName').val(), null, GetResults) } In summary I don't know why it won't break out of the controller and go into the Ajax controller like it has done so in all the other projects I've done this in using the 1st try solution. A: There are a couple of issues with your AJAX call: * *You are hardcoding routes *You are not encoding query string parameters Here's how I would recommend you to improve your code: // Always use url helpers when dealing with urls in an ASP.NET MVC application var url = '@Url.Action("GetBlah_Name", "Ajax")'; // Always make sure that your values are properly encoded by using the data hash. var data = { lname: $('#Surname').val(), fname: $('#FirstName').val() }; $.getJSON(url, data, GetResults); Or even better. Replace your hardcoded anchor with one which will already contain the lookup url in its href property (which would of course be generated by an url helper): <a id="lookup" href="Url.Action("GetBlah_Name", "Ajax")" class="button"> <span>Lookup</span> </a> and then in a separate javascript file unobtrusively AJAXify it: $(function() { $('#lookup').click(function() { var data = { lname: $('#Surname').val(), fname: $('#FirstName').val() }; $.getJSON(this.href, data, GetResults); return false; }); }); Now how your urls will look like will totally depend on how you setup your routes in the Application_Start method. Your views and javascripts are now totally agnostic and if you decide to change your route patterns you won't need to touch jaavscript or views. A: It seems you want to cal a controller at ~/Ajax. Is it? If yes, you should use this code: $.getJSON(callbackURL + '/Ajax/GetBlah_Name/?lname=' + $('#Surname').val() + '&fname=' + $('#FirstName').val(), null, GetResults) UPDATE: This will work for your Q, but the complete solution is @Darin Dimitrov's answer. I suggest you to use that also. UPDATE2 ~ is a special character that just ASP.NET works with it! So http doesn't understand it. and if you start your url with a word -such as Ajax-, the url will be referenced from where are you now (my english is not good and I can't explain good, see example plz). For example, you are here: http://localhost:2222/SomeController/SomeAction when you create a link in this page, with this href: href="Ajax/SomeAction" that will be rendered as http://localhost:2222/SomeController/Ajax/SomeAction But, when url starts with /, you are referring it to root of site: href="/Ajax/SomeAction" will be: http://localhost:2222/Ajax/SomeAction Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/7511409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check if a port is assigned to any program or added in firewall - C# We have Windows Service which will be installed by installer. We have an option to allow user to provide a port number and select whether the service must start on completion of installation. We are having a check on installer itself for checking whether the port is open/available. TcpClient TcpScan = new TcpClient(); TcpScan.Connect("localhost", portno); if (TcpScan.Connected == true) { TcpScan.Close(); } My problem is if the user selects the option of not to start the service on installation and then we install another instance on the same machine with the same port as used in first one, then if we start both the services then one of the service will not work. So is there any way I can check whether the port provided by user is already there in firewall or is already assigned to some other windows service? (Also assume the service can be in stopped state) A: I think no, because any app could open a port at runtime. You can (for example) use a Mutex to avoid multiple instances of your service on the same port (giving the mutex a name like String.Format(MyMutex_{0},my_port}. And you could/should check if that port is free during service startup and close it gracefully if it's not. A: Finally got the answer by doing some R&D string OP = @"C:\Windows\Temp\ExceptionList.txt"; ProcessStartInfo procStartInfo = null; string command = "netsh advfirewall firewall show rule name=all > " + OP; procStartInfo = new ProcessStartInfo("cmd", "/c " + command); procStartInfo.CreateNoWindow = true; procStartInfo.WindowStyle = ProcessWindowStyle.Hidden; System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo = procStartInfo; proc.Start(); proc.WaitForExit(); if (File.Exists(OP)) { StreamReader SR = new StreamReader(OP); string FileData = SR.ReadToEnd(); SR.Close(); //Logic to read the output and then fetch only records which are enabled and have LocalPort } Output (ExceptionList.txt) file contains data in this format Rule Name: NETTCP --------------------------------------------- Enabled: Yes Direction: In Profiles: Domain Grouping: LocalIP: Any RemoteIP: Any Protocol: TCP LocalPort: 8080 RemotePort: Any Edge traversal: No Action: Allow
{ "language": "en", "url": "https://stackoverflow.com/questions/7511410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Separate Admin and Front in codeigniter What is the best way to separate admin and front-end for a website in codeigniter where as I was to use all libraries, models, helpers etc. in common, but only controllers and Views will be separate. I want a more proper way, up for performance, simplicity, and sharing models and libraries etc. A: You all can find complete solution over here, https://github.com/bhuban/modular Module separation for admin and front-end using HMVC and template separation using template libraries I am using two third party libraries, you can find it in zip file. * *HMVC for modular developed by wiredesignz *Template engine for templating by Phil Sturgeon Just unzip it into your webserver root directory and run localhost/modular for front-end and localhost/modular/admin for back-end application/back-modules, it is for the back-end modules application/front-modules, it is for the front-end modules similarly templates/admin for the back-end templates templates/front for the front-end templates themes/admin for the back-end themes themes/front for the front-end themes Nothing hacked in original code just configured using config.php and index.php A: I highly suggest reading the methods outlined in this article by CI dev Phil Sturgeon: http://philsturgeon.co.uk/blog/2009/07/Create-an-Admin-panel-with-CodeIgniter My advice: Use modules for organizing your project. https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/wiki/Home Create a base controller for the front and/or backend. Something like this: // core/MY_Controller.php /** * Base Controller * */ class MY_Controller extends CI_Controller { // or MX_Controller if you use HMVC, linked above function __construct() { parent::__construct(); // Load shared resources here or in autoload.php } } /** * Back end Controller * */ class Admin_Controller extends MY_Controller { function __construct() { parent::__construct(); // Check login, load back end dependencies } } /** * Default Front-end Controller * */ class Public_Controller extends MY_Controller { function __construct() { parent::__construct(); // Load any front-end only dependencies } } Back end controllers will extend Admin_Controller, and front end controllers will extend Public_Controller. The front end base controller is not really necessary, but there as an example, and can be useful. You can extend MY_Controller instead if you want. Use URI routing where needed, and create separate controllers for your front end and back end. All helpers, classes, models etc. can be shared if both the front and back end controllers live in the same application. A: I use a very simple approach: file folders. Check out the CI User Guide section, Organizing Your Controllers into Sub-folders. I have my public-facing website built as any other would be built with CodeIgniter. Then I have two additional folders, controllers/admin and views/admin. The admin controllers are accessed via http://[hostname]/admin/controller, and behave just as any other controller except they have specific authentication checks. Likewise, the views are simply called with the folder name included: $this->load->view('admin/theview');. I haven't found a reason to do anything more complicated than that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Converting a wire value in Verilog for further processing I'm new to Verilog. I have written code to convert a wire value to an integer: wire [31:0] w1; integer k; always @ (w1) k = w1; Source: converting a wire value to an integer in verilog Now, for the next part I get an ERROR! wire [63:0] w2; // Suppose it contains some value wire [63:0] w3; assign w3[k-1:0] = w2[k-1:0]; // ERROR in this line ERROR : k is not a constant. How do I solve this issue? A: Verilog requires that part selects (code like [msb:lsb] to select part of a vector) be constant. To access a variable-sized group of bits requires something more complicated. Here is one way to do it: wire [63:0] src; wire [6:0] k; wire [127:0] mask = { { 64 { 1'b0 } }, { 64 { 1'b1 } } } << k; wire [63:0] dest; assign dest = mask[127:64] & src; The technique here is to construct a vector of 64 zeros followed by 64 ones, shift that vector by a variable amount, and then use a portion of the vector as a qualifying mask to control which bits are transferred from src to dest. A related concept which does not help in your example but which is worth being aware of: Verilog-2001 introduced the "indexed part-select". An indexed part select specifies a base index and a width. The width is required to be constant but the base index does not need to be constant. The syntax for an indexed part select is vec[base+:width] or vec[base-:width]. A: The part select operators in Verilog 2001 could be useful for what you want to achieve. Basically verilog allows for the starting index to be variable but needs the width of the assignment to be constant. The "+:" operator indicates counting upwards from the index value and vice-versa for "-:". You can do something like, assign w3[k-1 -: 8 ] = w2[k-1 -: 8]; // Where 8 bits is copied downwards Search for "+:" in the below document. http://www.sutherland-hdl.com/papers/2001-Wescon-tutorial_using_Verilog-2001_part1.pdf Word of caution, generally variable part selects is considered as bad verilog.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQLite: How to set ID PK to start from zero instead of starting from 1? Is it possible to set default starting value to zero instead of 1? Currently I'm using FMDB but wondering is it possible at all ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7511433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the primary use case for asynchronous I/O My application is not web based, just need to use sockets to service around 1000 clients. Throughput and latency are of utmost importance to me. Currently using select() from NIO but thinking of moving on to asynchronous IO in NIO.2. * *When should asynchronous I/O be used? *What is the primary use case for asynchronous I/O? A: If you are using Infiniband networks I would suggest looking at the Asynchronous IO. Comparing Java 7 Async NIO with NIO. However if you are using regular ethernet, it is just as likely to slower as faster. The coding is more complicated than using non-blocking IO which is more complicated than using blocking IO. If latency is of utmost importance I suggest you look at using kernel by-pass network adapters like Solarflare. However if a 100 micro-second latency is acceptable to you, it is unlikely you need this. A: Asynchronous IO is very good in situations where you need to scale to handle many concurrent connections. Historically one way of doing this was to dedicate a thread per connection, but this approach has limitations you can read about here. With Asynchronous IO you can easier handle many things with less threads and thus scale better. Depending on the problem it might or might not be the right approach as nothing can beat a single thread when it comes to latency. However, this is a very extreme end and means you care about microseconds. In many cases is a trade-off between latency and throughput/scalability. In any case it comes down to what you want to solve and what your expectations (numbers) need to be. Asynchronous IO is great and many cases and so is synchronous. There might also be other things you might want to consider such as protocol. Multiple clients interested in the same data (streaming) could indicate you want to look at multicast. If traffic is dedicated per client, then that might not be the approach. Not knowing your latency requirements, but assuming they are not in a few microseconds I would definitely look into asychronous IO just reading you have 1000 clients. Asynchronous IO is by no means slow and synchronous/single thread connections might not scale well for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: I want to write a plugin for Excel 2007 in JAVA I want to write a plugin for Excel 2007 in JAVA. Is it possible? Where can I get material to start it? A: Googling "java plugin for excel" returned this http://xll4j.sourceforge.net/ in about 0.18 seconds! A: In programming, I suppose the question should not be Can I do it? Instead it should be: Is there an existing tool that someone else made that I can use to do it?' If none exist, you can always make one! But in this case, it seams XLL4J may work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VS Load Test and 'Total Bytes Sent' Performance Counter? I have a load test for a WCF service, where we are trying out different compression libraries and configurations and we need to measure the total number of mb sent during a test. Is there a performance counter that measure the relative trafic pr. test. If so, how do I add it to my load test - it seems that only a fraction of the performance counters are visible - E.g. under the category "Web Service", i don't see the performance counter "Total Bytes Received" in VS Load test, but I can find it in PerfMon. Thanks A: In the load test expand Counter Sets > Expand applicable > Right Click on Counter Sets > Add Counters You can implement your own custom performance counter like so: using System; using System.Diagnostics; using System.Net.NetworkInformation; namespace PerfCounter { class PerfCounter { private const String categoryName = "Custom category"; private const String counterName = "Total bytes received"; private const String categoryHelp = "A category for custom performance counters"; private const String counterHelp = "Total bytes received on network interface"; private const String lanName = "Local Area Connection"; // change this to match your network connection private const int sampleRateInMillis = 1000; private const int numberofSamples = 200000; private static NetworkInterface lan = null; private static PerformanceCounter perfCounter; private static long initialReceivedBytes; static void Main(string[] args) { setupLAN(); setupCategory(); createCounters(); updatePerfCounters(); } private static void setupCategory() { if (!PerformanceCounterCategory.Exists(categoryName)) { CounterCreationDataCollection counterCreationDataCollection = new CounterCreationDataCollection(); CounterCreationData totalBytesReceived = new CounterCreationData(); totalBytesReceived.CounterType = PerformanceCounterType.NumberOfItems64; totalBytesReceived.CounterName = counterName; counterCreationDataCollection.Add(totalBytesReceived); PerformanceCounterCategory.Create(categoryName, categoryHelp, PerformanceCounterCategoryType.MultiInstance, counterCreationDataCollection); } else Console.WriteLine("Category {0} exists", categoryName); } private static void createCounters() { perfCounter = new PerformanceCounter(categoryName, counterName, false); perfCounter.RawValue = getTotalBytesReceived(); } private static long getTotalBytesReceived() { return lan.GetIPv4Statistics().BytesReceived; } private static void setupLAN() { NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface networkInterface in interfaces) { if (networkInterface.Name.Equals(lanName)) lan = networkInterface; } initialReceivedBytes = lan.GetIPv4Statistics().BytesReceived; } private static void updatePerfCounters() { for (int i = 0; i < numberofSamples; i++) { perfCounter.RawValue = getTotalBytesReceived(); Console.WriteLine("received: {0} bytes", perfCounter.RawValue - initialReceivedBytes); System.Threading.Thread.Sleep(sampleRateInMillis); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: erazor set variable a little question about erazor https://github.com/ciscoheat/erazor i know this framwork is based on Razor template engine. http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx i noticed the api doesn't fit exactly with Razor (ex: @for(a in p) differs from RAZOR) this template system for haxe is very handy... i just don't know how to setup a variable like we do in templo ( :: set mock="tada!":: ) //@scope is mycontroller; @{var mock = scope.getMock()} @if(mock!=null){ //display some html } any tips ? thx A: The following snippet works: import erazor.Template; import neko.Lib; class Main { static function main() { var template = new Template("@{var mock = scope.getMock();} @if (mock != null) { @mock }"); Lib.print(template.execute( { scope : { getMock : function() return "hi" } } )); } } What you missed is that inside a code block all the statements must be correctly closed (missing ;). Also erazor is loosely based on Razor and uses the Haxe syntax for expressions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to manage efficiently ib in xcode for big projects Can we use multiple separate views and integrate/call them on main view within a cocoa project? Currently we are dropping all of our sub views and IB controls into a single view and making changes in IB is becoming unamageble now. When working on IB in xCode, it consumes 2.4 GB of memory. Please suggest a better strategy to organize IB views and controls. A: Yes. Absolutely. There are lots of examples of using several nib or xib files together. I suggest you check out the sample code at developer.apple.com.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use Concat function in the sfunc parameter while making a aggregate function using PostgreSQL I am recently inclined in PostgreSQL and trying to make a ListAggregation function as given here the only difference being that I am trying to use CONCAT instead of TextCat . My function is as under CREATE AGGREGATE ListAggregation( basetype = Text, sfunc = Concat, stype = Text, initcond = '' ); It is throwing error ERROR: function concat(text, text) does not exist ********** Error ********** ERROR: function concat(text, text) does not exist SQL state: 42883 what mistake I am making...please help N.B.~ I have even looked at the example given here Thanks A: Interesting, what are you palanning to do? There is already a string_agg() aggregate function in PostgreSQL 9.0+ ... A: You should create state change function sfunc to implement an aggregate with the signature: sfunc( state, value ) ---> next-state -- sfunc: CREATE OR REPLACE FUNCTION concat(text, text) RETURNS text LANGUAGE SQL AS $$ SELECT $1||$2; $$; -- Aggregate: CREATE AGGREGATE ListAggregation( basetype = text, sfunc = concat, stype = text, initcond = '' ); -- Testing: WITH test(v) AS (VALUES ('AAAA'), ('BBBB'), ('1111'), ('2222') ) SELECT ListAggregation(v) FROM test;
{ "language": "en", "url": "https://stackoverflow.com/questions/7511465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: xml parsing from server with html tags I am new in android development.i send you xml file,it contain some html tag.that is follows- How i parse text,image. XMLFILE- <NewDataSet> <Table><Cat_id>1</Cat_id><Cat_Parentid>0</Cat_Parentid><Cat_Name>News for the day</Cat_Name><Cat_Desc><div style="text-align: center;"><span class="Apple-style-span" style="font-weight: normal; font-size: medium; "></span></div><span class="Apple-style-span" style="color: rgb(105, 105, 105); font-family: Verdana; font-size: 13px; font-weight: normal; "><br><div style="text-align: center;">Yes we are coming at E & I? Are you?</div></span><br><h1 style="font-weight: bold; "><span style="font-family: Verdana; font-size: 14pt; ">News for the day...</span></h1><span style="color: rgb(105, 105, 105); "><span style="font-family: Tahoma; font-size: 10pt; ">Template Mobile Sites for IC: <a href="http://icmobilesite.zapak_vi.net/">http://icmobilesite.zapak_vi.net/</a></span><br><span class="Apple-style-span" style="font-family: Tahoma; font-size: 13px; color: rgb(105, 105, 105); ">Promotional valid till 30 Sept 2011: MOBILE WEBSITE (Base Product Mobile CMS) for JUST $159<br></span></span><br><span style="font-family: Tahoma; font-size: 10pt; color: rgb(105, 105, 105); ">Mobile Template link: </span><a href="http://icmobilesite.zapak_vi.net/"><span class="Apple-style-span" style="font-size: 15px; font-family: Calibri, sans-serif; color: rgb(105, 105, 105); ">http://newsletter.zapak_vi.net/Mobilesite/</span><br></a><span style="font-size: 10pt; font-family: Tahoma; "><span style="font-size: 10pt; "><br><span style="color: rgb(105, 105, 105); ">With the promotion on Business Edge and eFusion still running successful in e market place - $ 499</span><br><span style="color: rgb(105, 105, 105); ">Check out some of the latest site launch on: </span><br><br><span style="color: rgb(105, 105, 105); font-weight: bold; ">http://www.randallcontracting.co.uk/Pages/Default.aspx </span><br><br><span style="color: rgb(105, 105, 105); font-size: 10pt; "><span style="font-weight: bold; ">Category</span>: Building & Construction</span><br></span><br></span><div style="color: rgb(105, 105, 105); text-align: left; "><span style="font-size: 10pt; font-family: Tahoma; ">Description: WELCOME TO RANDALL CONTRACTING Randall Contracting is a family-run contracting SME which has been servicing London and the South East since 1956. Working closely with our Clients and external Design Consultants, we place great emphasis on a safe, positive, practical and common sense approach to our projects. Our delivery methods have resulted in an extensive volume of repeat business from both Private and Public Sectors. Safety and Environmental concerns are a high priority on all our contracts and we continually strive to source innovative working methods and solutions. Our equipment is regularly updated and maintained to ensure minimal environmental impact.</span><br><br></div><span style="color: rgb(105, 105, 105); font-weight: bold; font-family: Tahoma; "><span style="font-size: 10pt; "><br></span></span><br></Cat_Desc><Cat_Active>true</Cat_Active><Cat_SortOrder>1</Cat_SortOrder><langid>1</langid><proCatImage>1bag6.jpg</proCatImage><bigimage>no-img.gif</bigimage></Table> <NewDataSet> END OF FILE A: Use this way public class HTMLData_XHandler extends DefaultHandler { boolean in_root; boolean in_subtag1; boolean in_subtag2; @Override public void startDocument() throws SAXException { super.startDocument(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); if (localName.equals("root")) { in_root = true; } else if (localName.equals("subtag1")) { in_subtag1 = true; } else if (localName.equals("subtag2")) { in_subtag2 = true; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); String data = new String(ch, start, length); if (in_subtag2) { array_list.add(data); } if (in_subtag1) { array_list.add(data); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); if (localName.equals("root")) { in_root = false; } else if (localName.equals("subtag1")) { in_subtag1 = false; } else if (localName.equals("subtag2")) { in_subtag2 = false; } } @Override public void endDocument() throws SAXException { super.endDocument(); } } array_list variable is for storing data from tags. you can choose any kind of variable, as your wish. A: That same thing i done with parsing. XML Handler class- class xmlHandler extends DefaultHandler { private Vector nodes = new Vector(); private Stack tagStack = new Stack(); public void startDocument() throws SAXException { } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // System.out.println("1"); if (qName.equals("clause")) { Noden node = new Noden(); nodes.addElement(node); // System.out.println("2"); } // System.out.println("3"); tagStack.push(qName); } public void characters(char[] ch, int start, int length) throws SAXException { String chars = new String(ch, start, length).trim(); if (chars.length() > 0) { String qName = (String) tagStack.peek(); Noden currentnode = (Noden) nodes.lastElement(); // System.out.println(qName); if (qName.equals("en")) { currentnode.setEn(chars); } else if (qName.equals("alt")) { currentnode.setAlt(chars); } } } public void endElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { tagStack.pop(); } public void endDocument() throws SAXException { StringBuffer result = new StringBuffer(); for (int i = 0; i < nodes.size(); i++) { Noden currentnode = (Noden) nodes.elementAt(i); result.append("En : " + currentnode.getEn() + " Alt : " + currentnode.getAlt() + "\n"); } System.out.println(result.toString()); } class Noden { private String en; private String alt; public Noden() { } public void setEn(String en) { this.en = en; } public void setAlt(String alt) { this.alt = alt; } public String getEn() { return en; } public String getAlt() { return alt; } }; retriving- try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); InputStream is = null; String xml = "your pasable string"; String newXml = xml.substring(xml.indexOf("<translation>"), xml.indexOf("]]")); System.out.println(newXml); is = new ByteArrayInputStream(newXml.getBytes()); InputSource inputSource = new InputSource(is); saxParser.parse(inputSource,new xmlHandler()); } catch(Exception ex) { ex.printStackTrace(); } This will helps you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: ASP.NET4 Charting Only show certain dates on X-axis I'm using ASP.NET to draw some line charts with multiple series. On the x-axis I am plotting the date however I do not have values for weekend dates and therefore it is drawing a straight line from the friday to the monday. I'm wondering is there a way to basically only show dates on the x-axis for where you actually have values? I have tried setting the x-axis data type to string which works except for when I have some missing values during the week. If that happens, it basically messes up my scale with duplicate entries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validation failed in Entity Framework, ASP.NET MVC3 My application using ASP.NET MVC3 with EF4.1, deployed on IIS7. Recently I've meet an error when trying to save an entity to an existing database on the production server, but everything goes well on my development machine. I tried to build deploy package in VS2010 and import that package in IIS7, also, I've tried to upload all the solutions and create an application in IIS7 manually, but both of the 2 sites come to an error when executing a function that saves an entity to the database. Error message is pasted below, but the physical path in error message does not exist in the production server, it's a path in my local development machine. This makes me confused. Has anybody ever seen this before? BTW, I've fully backed up my database and restored it on the production server, so all the databases are same. I'm open to hear any advice. Thanks Cheng Error message: Server Error in '/xxxx' Application. Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.] System.Data.Entity.DbContext.SaveChanges() +212 xxxxx.Models.SetupRepository.CreateApplicationOption(Guid companyId) in D:\xxxx\Models\SetupRepository.cs:59 xxxxx.MvcApplication.MvcApplication_PostAcquireRequestState(Object sender, EventArgs e) > in D:\xxxx\Global.asax.cs:87 System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +148 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
{ "language": "en", "url": "https://stackoverflow.com/questions/7511469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating strongreference from Weakreference Following is a sample code of our application, where we are trying to keep a weak reference of a huge page model object, which takes a lot of memory. Dictionary<int,WeakReference> modelCache; IPageModel ReadPageModel() { IPageModel page; if (!modelCache.ContainsKey(cacheKey) || !modelCache[cacheKey].IsAlive) { model = new PageModel(); modelCache[cacheKey] = new WeakReference(Model); } else { model = modelCache[cacheKey].Target as IPageModel; } return model; } The model that we are returning(in else part) is a reference to a weak object, so it can be null at later times. Is there a way, so that we can create a strong reference to this object, and later when we are done with the object we can make it a weak reference. I came across some examples where weak references are converted to strong but not vice versa. A: Java gc weakreferenced objekts only when they are ONLY weakreferenced. Thus as long as you hold a normal reference to the object java will not gc it and you will not get a null reference. A: Thanks Xeno Lupus, So the reference was strong reference, but before I put the value object got collected.. Now i have modified the code as follows, IPageModel page; if (modelCache.ContainsKey(cacheKey) && modelCache[cacheKey].IsAlive) { model = modelCache[cacheKey].Target as IPageModel; } if(model == null) { model = new PageModel(); modelCache[cacheKey] = new WeakReference(Model); } return model;
{ "language": "en", "url": "https://stackoverflow.com/questions/7511472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Binary string comparison I'm just learning python and the best way to learn a language is to use it, so I thought I'd make a script that compares binary words to determine which ones are grey. If there is one bit that is different then it should flag record which number binary code it is. So by means of example, if N=3 then the binary code is 000, 001, 010, 011, 100, 101, 110, 111 If I chose my first binary code as 010 then the code should return 110, 000, 011 as the results, or preferably the indices 0,3,6 (or 1,4,7). My question is this : What is the best pythonic way to do this, mostly I'm aiming at the fastest code. My reason is that some of you would have a better idea on the optimal way to do this and I could then compare my code to that and this would teach me far more. A: Since this is a binary calculation problem (with a weird input), it's not really the area where you can apply pythonic tools like generators, list comprehensions and itertools. def neighbors(code, N=3): num = int(code, 2) return [num ^ (1 << (N-i-1)) for i in range(N)] If you want the output to be sorted (i.e. 0,3,6 instead of 6,0,3), use: def neighbors_sorted(code, N=3): num = int(code, 2) return sorted(num ^ (1 << i) for i in range(N)) A: I wanted to post my initial attempt as the first answer but the website blocked me for around 8 hrs, and I've only been able to reply now. I've split the code into the more important snippets. This is my attempt so far : I think I should perform the following mods to the code below : 1) Use dicts so that I have 0:000,1:001,... to improve the indexing. 2) Take the comparison string, adapt it to a list of all possible options then compare this to the full binary list e.g. 010 becomes 110,000,011 and this is then is compared to the full binary list. My attempt to create a list of binary numbers is as follows (not using dicts yet) def BinaryNumberList(N=4): Bins=[] for Num in range(2**N): Bin='' for Pow in sorted(range(N),reverse=True): Bin=Bin+str(Num/(2**Pow)) Num=Num-Num/(2**Pow)*2**Pow Bins.append(Bin) return Bins Then run a for loop for comparing each string to the rest (currently not the best one) def GreySets(Bins): for Bin1 in Bins : for Bin2 in Bins : stringXOR(Bin1,Bin2) The string XOR I got from some one elses code on the interwebs and it returns a TrueFalseTrue (I need it to retrun the number of bits that don't match) def stringXOR(a, b): # Error Checking msg = "Strings do not have same length: %d, %d!" assert len(a) == len(b), msg % (len(a), len(b)) cnt = len(a) - 1 # Code result = '' while cnt + 1: result = `(a[cnt] != b[cnt])` + result cnt = cnt - 1 return result
{ "language": "en", "url": "https://stackoverflow.com/questions/7511476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hide a groupbox and also remove the space where it was present in winform In my winform, I have three group boxes, based on selection of the items in a combobox the second group box(at the center) is hidden using groupbox.visible property. The problem is when the second goupbox is hidden, there seems to be an empty space in the area of the hidden group box, I want to move the third group box to the place where second group box is present. Can I use any other control instead of group box? A: You could manually set Location and Size properties of your third groupbox or (I think better) set Dock property of both groupboxes to Top, so when your second gb becomes not visible, the third should scroll up to occupy free space. A: You have a small number of options, assuming you are using just the default VS controls. If you place these group boxes in a flow layout panel, when you make it invisible the layout panel will move other controls into it's previously occupied space. If you dock the group boxes, making one invisible causes the others to occupy the space if the docking dictates. If you cannot use layout mechanisms or controls, your only option is to modify the location or size of neighbouring controls to fill the space manually. I very much advise trying to use the layout containers, or find a container online that handles the positioning for you. Position code buried in the form using potentially lots of "magic" numbers is definitely not maintainable. A: you should solve it by chaning control that you're groupboxes are in. Their position can't be set to constants. The other solution is to change position of third groupbox when you change visibility of the second one. A: A FlowLayoutPanel should work http://msdn.microsoft.com/en-us/library/system.windows.forms.flowlayoutpanel.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7511478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Behaviour in file writing by multiple threads Many threads are writing StringBuffer to same file. StringBuffer contains around 100 lines. What is the output in file if multiple threads write to same file. Is each output from different threads mixup in file or they appear sequentially. A: all of the above plus an exception could be thrown on one or more of the threads Without some sort of synchronisation between the threads the result is non deterministic. A: The data is likely to appear in the order it is written. However, unless you control this, that order is likely to be somewhat random. Using multi-threads is also likely to be much slower, esp for such a small file. Its could be as many times slower as you have threads.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySql Foreign keys: ON DELETE NO ACTION behavour - how to leave info in referenced field? I have two tables, one 'users' and one 'orders', where the order table has a foreign key reference to the user id table. (I'm using email address as user id in this case.) What I want to accomplish is this: * *If the user table id is updated (= email address is changed), this will reflect in the referenced order table user_id field. (This works fine using ON UPDATE CASCADE directive - no problem here!) *If the user is deleted from the user table, the order will remain, KEEPING the referenced user_id. I'm having problem with the second goal: If I use ON DELETE CASCADE on the referenced user id field, the order row is of course deleted. If I use ON DELETE NO ACTION, I get an error when I try to remove the user. (#1451 - Cannot delete or update a parent row: a foreign key constraint fails) If I use ON DELETE SET NULL, I can delete the user row, but the referenced info is set to null so I can't track down who made that order... Is there a way to allow removal of the user from the user table while keeping the referenced user_id information in the orders table? A: Two options: * *Don't actually delete the user, just mark them as deleted by setting a deleted field. or: * *Remove the foreign key constraint. I would recommend the first option. Taking the second option can lead to data inconsistencies. Besides, just having the value of the key without the corresponding data in the other table will not help you much anyway. A: Actually there is another alternative - replace the user table's email address key with an autoincrement INT. Then you could just copy the user attribute (ugh, denormalized) into the order (I guess you could justify it as being the 'email address of the ordering user at the time of order'). Then ON DELETE SET NULL could reset the foreign key INT but not the copied attribute (email address).
{ "language": "en", "url": "https://stackoverflow.com/questions/7511485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: PHP fseek with remote files I want to read remote file from the end but fseek doesn't support remote files. Is there way to make this? A: Write your own streamwrapper. Or copy the whole file locally and fseek on that. A: you should try cURL . it should get the job done. u just need to check if CURL is installed on ur web server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Listening to routed events / commands from a popup I have a control that dynamically creates a popup. The popup contains controls that fire routed events / commands, which I want to react to in the original control. The original control is set as the placement target of the popup. Would you expect the original control to receive bubbled events? I know it's in a different visual tree, but I wondered whether they would be offered to the placement target. From my code it would appear not. Can anyone suggest a way to handle this situation? Responding to events in a different visual tree. I was wondering if there was some control I could write that would sit in the root of the popup and act as a "bridge" into the originating visual tree? Many thanks, A: I have managed to get around this by adding my CommandBinding to the popup's CommandBindings collection instead of my control's. As I do this in code at the point of the popup's creation, I can specify callbacks in my control, even though the binding is in the popup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ext.Button into Ext.List Sencha Touch I am new in Sencha Touch Can I add Ext.Button into a Ext.List if yes then how Thanks Amit Battan A: It's been discussed on the Sencha Forum... http://www.sencha.com/forum/showthread.php?118790-Buttons-%28and-other-widgets%29-in-Ext.List-or-Ext.DataView A: I don't think you can. Maybe it's possible but I'm sure very complicated. Do you need to add the button per list item or per list? If per list item, do you need to add more the one button? A: From the question, as simple as it is, the only way that I have been able to get a button into a list is by creating a titlebar and docked to the top and in that titlebar having a button in it. This can be achieved in a view file. this.add({ xtype: 'titlebar', docked: 'top', title: 'Courses', items:[{ xtype: 'button', align: 'left', iconCls: 'add', iconMask: true, handler: function(){ var panel = Ext.create('UniversityData.view.EntryForm'); panel.showBy(this); } }] }); This would go in your view's config section
{ "language": "en", "url": "https://stackoverflow.com/questions/7511500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My class has some timing issues I have a class that I use to display text on stage, with some number effects. It works pretty well, but when I chain it like this public function onAdd(e:Event) { //stuff addChild(new messager("Welcome.")); addChild(new messager("WASD to move, mouse to shoot.")); addChild(new messager("Kill zombies for XP and collect ammo boxes.",waveOne)); } public function waveOne(){ addChild(new messager("Good luck and have fun.",newWave)); } The text (Good luck and have fun) is not displayed, but newWave is called. The reason why I don't call waveOne in onAdd is so that it doesn't happen too quick - my class just throws the text at the user once every 50 frames (which is intended, for later when you kill enemies and the text needs to catch up). Here is my class (with the effects removed): package { import flash.display.MovieClip; import flash.events.*; import flash.utils.Timer; public class Messager extends MovieClip{ var actualText:String; var callback:Function; var upTo:int = 0; static var waitingFor:int = 0; public function Messager(text:String,callback:Function=null) { this.callback = callback; actualText = text; x = 320 - actualText.length * 6.5; y = 0 - waitingFor * 60; addEventListener(Event.ENTER_FRAME, onEnterFrame); waitingFor++; } public function onEnterFrame(e:Event) { y+= 1; if(y > 60){ waitingFor--; } if(y > 200){ alpha -= 0.03; if(alpha <= 0){ if(callback != null){ callback(); } removeEventListener(Event.ENTER_FRAME, onEntFrm); this.parent.removeChild(this); } } } } It is set to linkage with a movieclip that has a textfield. Thanks for any help. A: y = 0 - waitingFor * 60; Maybe y of the last Mesager is a big negative number? Have you tried to trace waitingFor?
{ "language": "en", "url": "https://stackoverflow.com/questions/7511504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mysterious issue with Google Chrome, BIRT and WebSphere I have a web app which I deploy on Tomcat 6, Jetty 7 and WebSphere 7. It uses BIRT reporting. I use the following browsers for testing: Firefox 6, Google Chrome 14, IE 9. All of these combinations work but one: Chrome with WebSphere. When I try to view a report using this pair, I get a SAXException: unexpected end of file in org.apache.axis.SOAPPart line 696: DeserializationContext dser = new DeserializationContext(is, getMessage().getMessageContext(), getMessage().getMessageType()); dser.getEnvelope().setOwnerDocument(this); // This may throw a SAXException try { dser.parse(); // <-- ERROR } catch (SAXException e) { Exception real = e.getException(); if (real == null) real = e; throw AxisFault.makeFault(real); } The input is an InputStream but it's an WebSphere implementation and I have no idea how I could get at the data. I can see what the browser sends to the server but that looks fine to me (indented for easier reading): <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <Body xmlns="http://schemas.xmlsoap.org/soap/envelope/"> <GetUpdatedObjects xmlns="http://schemas.eclipse.org/birt"> <Operation> <Target> <Id>Document</Id> <Type>Document</Type> </Target> <Operator>GetPage</Operator> <Oprand> <Name>Stichtag</Name> <Value></Value> </Oprand> <Oprand> <Name>__isdisplay__Stichtag</Name> <Value></Value> </Oprand> <Oprand> <Name>__page</Name> <Value>1</Value> </Oprand> <Oprand> <Name>__svg</Name> <Value>false</Value> </Oprand> <Oprand> <Name>__page</Name> <Value>1</Value> </Oprand> <Oprand> <Name>__taskid</Name> <Value>2011-8-21-12-36-37-692</Value> </Oprand> </Operation> </GetUpdatedObjects> </Body> </soap:Envelope> I tried to debug this but the runtime sax parser has no debug information. Any ideas what I could try?
{ "language": "en", "url": "https://stackoverflow.com/questions/7511506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why [] should be set for robotium explicitly? As it said in this QnA some functions in robotium required anyDensity to be set as true in the AndroidManifest.xml file. but it said in the android doc that applications that support android 1.6 and higher, it is true by default. then, why should this be set explicitly? android:anyDensity Indicates whether the application includes resources to accommodate any screen density. For applications that support Android 1.6 (API level 4) and higher, this is "true" by default and you should not set it "false" unless you're absolutely certain that it's necessary for your application to work. The only time it might be necessary to disable this is if your app directly manipulates bitmaps (see the Supporting Multiple Screens document for more information).
{ "language": "en", "url": "https://stackoverflow.com/questions/7511507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL help required for writing a query I have number of records in database of which some are duplicates like 1 test 20-09-2011 2 main 20-09-2011 3 New 20-09-2011 4 test 20-09-2011 5 test 20-09-2011 6 test 20-09-2011 7 main 20-09-2011 8 main 20-09-2011 Now what i want is i get all three distinct records but with maximum id record out of them as below: 3 New 20-09-2011 6 test 20-09-2011 8 main 20-09-2011 Please suggest Thanks all A: select * from table as t1 where t1.id = (select max(t2.id) from table as t2 where t1.name =t2.name) where name is the second attribute of your table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to change the audio play speed with AVAudioPlayer in iPhone? I'm playing a local mp3 file with class 'AVAudioPlayer' on my iOS App. And I want to change the speed when play it. such as I want to play this mp3 file slower. How to achieve it? A: Now it is possible to change the speed of sound. here is my sample code: player = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:path] error:&err]; player.volume = 0.4f; player.enableRate=YES; [player prepareToPlay]; [player setNumberOfLoops:0]; player.rate=2.0f; [player play]; you set "enableRate" to YES and you can change it. see more docs A: That's not possible with AVAudioPlayer. See AVAudioPlayer: How to Change the Playback Speed of Audio? for potential workarounds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lost syslog packets I wrote a program that listens on UDP port 514 for syslog messages and writes any incoming packets to a log file. On one of the servers where this program is deployed, it has suddenly stopped writing to the log file. It is working fine on all other servers. Steps I have taken to diagnose the problem. 1) Wrote a udp packet sender (A) that sends data on udp 514 to that server. The program receives those packets and writes them to file just fine. 2) Ran tcpdump to see if the rig (B) that is supposed to send data to that server was in fact doing so. It was. 3) Ran (A) while tcpdump was running to see if the destination IP address and port were the same as the packets from (B). They were. 4) Stopped the program and wrote a listener that just prints anything received on udp 514 to screen. The listener printed only packets from (A). Are there any network experts around who can think of other diagnostic tests I can perform to find out what's wrong? A: If it stopped writing the log file possibly your code is buggy. If the udp listener does not read data from the socket, the transfer will still be shown by the network sniffer tool. Use a debugger to find out what your program is doing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jaspersoft: Dropdownlist in iReport I am trying to create a parameter which should be a dropdownlist. I need to let the use choose from 3 different values. Is this possible? Or will I have to code one myself in Java? If so, how can this be done? I'm using iReport Designer 4.0.2. Thanks! A: Yes, you can do it with JasperServer. This articles should help you: Cascade Parameter Reports in IReport & Jasper Server JasperServer Guide Adding Report Units from JRXML Files
{ "language": "en", "url": "https://stackoverflow.com/questions/7511516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I use the class field on an ArrayList instance in Java? I have this code, which compiles: new TypeToken<ArrayList<ServerTask>>() {}.getType() Then I have tried ArrayList<ServerTask>.class which does not compile. I am new to Java programming (came from C#) and I have thought that T.class is an exact equivalent of typeof(T) in C#. Apparently there is something really basic that I do not understand, so my question is what is wrong with ArrayList<ServerTask>.class and do I have no choice, but use new TypeToken<ArrayList<ServerTask>>() {}.getType() instead? Is there a shorter (nicer, saner) form? Thanks. A: Unfortunately (?) Java implements generics using Type Erasure. This means that there is no construct to get the generic type, and at runtime your ArrayList actually only stores Objects. To be exact, Generics in Java are a compile-time only construct. They guarantee type-safety at compile time only. EDIT: I just noticed this bit of code - new TypeToken<ArrayList<ServerTask>>() {}.getType() This is a workaround for the limitations of type erasure. Type information is preserved if you extend a generic class with a specific type. For example: public interface List<T> { } public class StringList implements List<String> { // The bytecode of this class contains type information. } In your example, you are trivially extending the class TypeToken, causing the compiler to generate an anonymous inner class that contains the type information. The implementation of TypeToken.getType() will use reflection to give you this type information. EDIT2: For a more detailed explanation, have a look at Reflecting Generics. A: Your first code sample creates an anonymous subclass of TypeToken complete with concrete generic bindings. The type returned will be an instance of Class. But beware, because (new TypeToken<ArrayList<ServerTask>>() {}.getType()).getClass(TypeToken.class) will return false! In your second code sample, you're trying to do something that Java doesn't support because of how generics are implemented with type erasure. There is no class that represents an ArrayList whose generic parameter is bound...from the compiler's point of view an ArrayList is an ArrayList regardless of the generic type, so the expression doesn't compile. It's possible that neither piece of code is going to work out quite right. If you need to be playing around classes with generic parameters, you may want to look into gentyref, which I've found to be very helpful in simplifying the API to ask the kinds of questions you're trying to get answers to. A: About the ".class" construct, it is not an operator nor an instance member, it is actually a way to tell the language "go and find the Class object for this class name before the dot". Is a way of constructing class literals. As specified in the JLE, section 15.8.2, the compiler will complain if you try to use it with a parameterized type (among others). A: The example given by Bringer128 is considered an anti-pattern called pseudo-typedef antipattern.Here is the alternative: class TokenUtil{ public static <T> TypeToken<T> newTypeToken(){ return new TypeToken<T>(); } public static void main(String[] args) { TypeToken<ArrayList<ServerTask>> typeTok = TokenUtil.newTypeToken(); Type type = typeTok.getType(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to create constant space BETWEEN li inline list items I want to use a list for horizontal links. I understand I need to use display: block for the ul and display: inline for the li. There are a number of questions for getting constant width for the li elements, but I want constant space between them, they contain text of different width themselves. Thanks. I think my question was unclear: I am looking to have a fixed width ul with unknown width li elements and want to have constant space between them, not constant width li elements. Is this only achievable with javascript? A: Use the margin css property. If they all have the same margin, then the distances between the content of the adjacent <li>s will be the same. You might want to take a look at the Box Model Edit to address comment below: If you want the gaps between the items to stay the same regardless of the content, margin should do the job. If you want the position of the items to stay the same regardless of the content (and so the gaps between them will change), you need to set the width of the item. A: I'd like to offer my solution to this: http://jsfiddle.net/connectedcat/bZpaG/1/ JQuery excerpt: $(document).ready(function(){ var nav_width = 0; $('nav li').each(function(){ nav_width += $(this).width(); }); var for_each = ($('nav ul').width() - nav_width)/($('nav li').length - 1); $('nav li').each(function(){ $('nav li').css('margin-right', for_each); }); $('nav li:last-child').css('margin-right', 0); }); As far as I have figured out there is no way to do it purely in css, js is required to figure out the distances for the truly fluid layout. One conundrum that still bugs me in relation to this issue is the fact that different browsers render fonts slightly differently (as in a certain word rendered in Safari may take up 48px, while in Firefox - 49px.) I put in some css to account for this, but it results in some stray pixels. If anybody knows how to make it super neat and clean across all platforms - I would appreciate some schooling:)
{ "language": "en", "url": "https://stackoverflow.com/questions/7511518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Application fails to load inconsistently on iPhone 3G I have two iPhone devices: 3G and 3GS. My application always loads successfully on iPhone 3GS but on iPhone 3G it loads like 10% of tries (but it loads). I do not have any exceptions or zombies. Can someone lead me to possible causes or suggestions to how can i find root cause of the problem? A: There are many possibilities. One of them is the "Images". Are you using a lot of images? What are the resolution. Remember: iPhone 4, ipod touch use XX@2x resolution (retina image: 640 x 960 px) iPhone 3 without @2x (smaller resolution: 320 x 480 px)
{ "language": "en", "url": "https://stackoverflow.com/questions/7511519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: database cleaner transaction with cucumber rails I am writing a scenario for signup form. @abc @selenium Scenario:Non registered user signs up Given I am on the sign-up page When I fill in the following: |first_name|Anidhya| |last_name|Ahuja| |email|anidhya@gmail.com| |password|123456| And I press "submit" Then I should see "Registration complete" I want to use database cleaner to roll back the test database after this scenario so that I can use this scenario again and again. For that inside my env.rb file I wrote: begin require 'database_cleaner' require 'database_cleaner/cucumber' DatabaseCleaner.strategy = :transaction Cucumber::Rails::World.use_transactional_fixtures = true rescue NameError raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it." end Before('@abc') do DatabaseCleaner.start end After('@abc') do DatabaseCleaner.clean end Now when I run the scenario , the user gets saved in the database and the database cleaner fails. I dont see any error messages * *Could you please clarify how to use database cleaner for only one scenario.I only want to use cleaner for this scenario. *Also could you please also provide the vital difference between using truncation and transaction.I think truncation clears the whole database but I dont want that. *Is there a better method of doing signup testing than this? A: You can't run transactions with selenium because the test runs on two separate instances of the app AFAIK
{ "language": "en", "url": "https://stackoverflow.com/questions/7511520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: nHibernate: Using entity-name with QueryOver and CreateCriteria I have two hbm.xml mappingfiles. They are identical except for the class table and class entity-name properties. They are supposed to populate the same Entity. They have entity-name= Alpha and Beta, table= PersonAlpha and PersonBeta respectively. I have tryed using both QueryOver and Criteria to populate the entity Person: var person = session.QueryOver<Person>("Alpha").Where(p => p.Firstname == "Donald").SingleOrDefault<Person>(); var person2 = session.CreateCriteria("Beta").Add(Restrictions.Eq("Firstname", "Donald")).UniqueResult<Person>(); As Im ref to the entity-name I thought nHibernate would know which mappingfile to use, but according to Profiler each of the above statements generete SQLs against both the PersonAlpha and PersonBeta tables. Why is this? Im using version 3.2.0 2001 og nHibernate. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7511523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Select all Sheet from an Excel File basically, i am uplaoding a dynamic excel file and i want to select all the sheets containing a data and have it in a dataset. But i dont know how, all I can get is from a static sheet name and only one sheet per select, how can i select all shhet within one excel file and have it in a dataset? thanks. this is what i got so far Dim exConS As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _ excelfile & ";Extended Properties=Excel 8.0;" Dim exCon As New OleDbConnection(exConS) Dim dsExcel As New DataSet() Dim sExcel As String = "SELECT * FROM [SSI-data3$]" Dim daExcel As New OleDbDataAdapter(sExcel, exCon) daExcel.Fill(dsExcel) A: I think you should use Microsoft.Office.Interop.Excel to get worksheet names and then with a foreach you can get them A: I think you can use GetSchema with suitable schema name from the Jet schema set to retrieve the names of tables - in Excel, this includes both named ranges and sheets. You would have to create a UNION query to get every sheet in the one set of data, which would only be suitable if the columns matched.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP zip archive progress bar I've googled for this but didn't find any solution - is there a way to create a progessbar for adding/extracting files to/from zip archive in PHP? Can I get some kind of status message which I can than get with an AJAX request and update the progress bar? Thanks. A: I am trying to do the same thing at the moment; it is mostly* complete (*see issues section below). The basic concept I use is to have 2 files/processes: * *Scheduler (starts task and can be called to get updates) *Task (actually completes the task of zipping) The Scheduler will: * *Create a unique update token and save to cache (APC) *Call the Task page using curl_multi_exec which is asynchronous, passing update_token *Return the token in JSON format OR *Return the contents of the APC under the update_token (in my case this is a simple status array) as JSON The Task will: * *Update the APC with status, using the update token *Do the actual work :) Client-side You'll need some JavaScript to call the Scheduler, get the token in return, then call the Scheduler, passing update_token, to get updates, and then use these returned values to update the HTML. ** Potential pitfalls** Sessions can be a problem. If you have the same session you will notice that your browser (or is this Apache?) waits for the first request in the session to complete before returning others. This is why I store in the APC. Current Issues The problem with the ZipArchive class is that it appears to all the grunt work in the ->close() method, whilst the addFile method appears to take little to no time to complete. As a workaround you can close and then reopen the archive at specific byte or file intervals. This actually slows the process of zipping down a little, but in my case this is acceptable, as the visual progress bar is better than just waiting with no indication of what is happening.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: expat for IronPython 2.7.1 beta 2 I'm trying to get NLTK working with IronPython 2.7.1. The installation works so far, but I tried some sample code and the expat module is missing. Any hint how to get that up and running for IronPython? I found some hints on the web, but they are quite outdated (IronPython 2.0) and are using python projects which seem to be dead. A: The version from the old FePy project (here) should still work, but it's incomplete and might not have all of the capabilities NLTK needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Magento - Move the "terms and conditions" from the last checkout step to the first one How can I move the terms and conditions from the last checkout step to the first one ? I have tried only with the xml files, but I can't continue to the next step in this case. Please help to do that. A: In checkout.xml, move <block type="checkout/agreements" name="checkout.onepage.agreements" as="agreements" template="checkout/onepage/agreements.phtml"/> from <checkout_onepage_review> handle into <checkout_onepage_index>: You have to modify <block type="checkout/onepage_billing" name="checkout.onepage.billing" as="billing" template="checkout/onepage/billing.phtml"/> into <block type="checkout/onepage_billing" name="checkout.onepage.billing" as="billing" template="checkout/onepage/billing.phtml"></block> and put the line inside. In info.phtml (or review.phtml for v1.4.2) cut <?php echo $this->getChildHtml('agreements') ?> and paste that line you've just cut into billing.phtml. A: Long time done this post but those that are still in need: To add to that contributed from @OSdave - as @Bizboss is saying the terms and conditions checkbox doesn't have to be checked to proceed to the next step. To provide a front end solution with least fuss just add required-entry to the class name - e.g. <input type="checkbox" id="agreement-<?php echo $_a->getId()?>" name="agreement[<?php echo $_a->getId()?>]" value="1" title="<?php echo $this->htmlEscape($_a->getCheckboxText()) ?>" class="checkbox required-entry" /> This employs JS validation to prevent it from proceeding to the next stage without being checked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inserting or updating multiple records in database in a multi-threaded way in java I am updating multiple records in database. Now whenever UI sends the list of records to be updated, I have to just update those records in database. I am using JDBC template for that. Earlier Case Earlier what I was whenever I got records from UI, I just do jdbcTemplate.batchUpdate(Query, List<object[]> params) Whenever there was an exception, I used to rollback whole transaction. (Updated : Is batchUpdate multi-threaded or faster than batch update in some way?) Later Case But later as requirement changed whenever there was exception. So, whenever there is some exception, I should know which records failed to update. So I had to sent the records back to UI in case of exception with a reason, why did they failed. so I had to do something similar to this: for(Record record : RecordList) { try{ jdbcTemplate.update(sql, Object[] param) }catch(Exception ex){ record.setReason("Exception : "+ex.getMessage()); continue; } } So am I doing this in right fashion, by using the loop? If yes, can someone suggest me how to make it multi-threaded. Or is there anything wrong in this case. To be true, I was hesitating to use try catch block inside the loop :( . Please correct me, really need to learn a better way because I myself feel, there must be a better way , thanks. A: Your case looks like you need to use validation in java and filter out the valid data alone and send to the data base for updating. BO layer -> filter out the Valid Record. -> Invalid Record should be send back with some validation text. In DAO layer -> batch update your RecordList This will give you the best performance. Never use database insert exception as a validation mechanism. * *Exceptions are costly as the stack trace has to be created *Connection to database is another costly process and will take time to get a connection *Java If-Else will run much faster for same data-base validation A: make all update-operation to a Collection Callable<>, send it to java.util.concurrent.ThreadPoolExecutor. the pool is multithreaded. make Callable: class UpdateTask implements Callable<Exception> { //constructor with jdbctemplate,sql,param goes here. @Override public Exception call() throws Exception { try{ jdbcTemplate.update(sql, Object[] param) }catch(Exception ex){ return ex; } return null; } invoke call: <T> List<Future<T>> java.util.concurrent.ExecutorService.invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException
{ "language": "en", "url": "https://stackoverflow.com/questions/7511541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can we identify the date on which someone liked my page? How can we identity the date on which someone liked my page. is there any way where we can identify the date on which someone liked my page ? A: No. You can't even get a list of people that like your page, so you can't get a date they liked it. The only information you can get is how many people like it. You can view a chart of how many people liked your page over time at Facebook Insights. A: Well no, You can make a graph call to the statuses and feeds of a user with valid access_token to get the id and name of the people who liked the post.. The timestamp can be found for the comments though .. { "id": "257821xxxxxxx", "from": { "name": "Maxxxxxx", "id": "100xxxxxx" }, "message": "incredible ..", "updated_time": "2011-09-15T11:21:15+0000", "likes": { "data": [ { "id": "6xxxxxx6", "name": "Axxxxxxxxxa" } ] }, "comments": { "data": [ { "id": "257xxxxxxxxxxxx904", "from": { "name": "Maxxxxxxxxxxal", "id": "1xxxxxxxxxxxxxx" }, "message": "htxxxxxxxxxxxxxxxxxxxxxxxxxx", "can_remove": true, "created_time": "2011-09-15T11:22:06+0000" } ] } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I want to make a availability button on my registration page Many websites have an "check availability" button. And I want to have this to. But this seems to be only available when using Ajax and Jquery. Is there any way for me to do this using only PHP and Javascript. Because i'm a starting programmer, which does not have the skills to work with Ajax or Jquery. What I want, I have a username field. I typ in a username, and I want to check if the name is available. If the person clicks on the check availability button, I want a pop-up that says "This username is available" or "This username has already been taken". If any knows how to do this in just PHP and Javscript, I would be very obliged to know. A: Using ajax (and jquery) is easier than it seems. on your client-side you have a request like this: $.ajax({ url: 'usernameChecker.php', dataType: 'GET', data: 'username=' + $("#yourUserNameFieldID").val(), success: function(result) { alert(result); } }); Of course you need to include jquery to implement this. jQuery makes it easy to make ajax-calls. On your serverside you can use something like this: <?php if(isset($_GET["username"])) { // check username if(username_is_free) // of course this needs to be a bit different, but you'll get the idea { echo "Username is free!"; } else echo "Username is taken!"; } ?> A: $(document).ready(function(){ // available-button is the ID of the check availability button //checkAvailability.php is the file which gets the username param and checks if its available // user is the id of the input text field where the user enter the username // available-message is the id of a div which displays the availability message. Use this instead of alert $('#available-button').click(function() { $.ajax({ type : 'POST', url : 'checkAvailability.php', data: { username : $('#user').val() }, success : function(data){ $('#available-message').text(data); }, error : function(XMLHttpRequest, textStatus, errorThrown) { alert("Some Error occured. Try again") } }); return false; }); }); A: Use jQuery ajax, that is the best & easy way to do it. Using Ajax send a request to a php page which will take username as parameter (get or post method, you can specify in ajax call) and then on server side search for uniqueness of username in database & return appropriate response. A: Is there any way for me to do this using only PHP and Javascript. Because i'm a starting programmer, which does not have the skills to work with Ajax or Jquery. I think you'll find making an AJAX request in jQuery a lot more simple than writing one in pure javascript. As jQuery is an extension on Javascript, you can use minimal jQuery to make the request to the server, and then deal with the response using pure javascript. Look into using jQuery AJAX: http://api.jquery.com/jQuery.ajax/ $.ajax({ url: "test.html", context: document.body, success: function(){ $(this).addClass("done"); } }); Here you would change the success part to something like: success: function(data){ if (data == 1){ $(".message").html("Available"); } else { $(".message").html("Already Taken"); } } A: I would recommend using jQuery for this task. jQuery (or another Javascript library) will make the task simple to complete compared trying to do it without using one of them. jQuery docs are good and for there are plenty of online tutorials matching what you want to do. You will benefit from putting in the time to learn about the jQuery library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I go about adding testing to a finished rails app? Right so I started a rails app [3.0.9] a while back and didn't include any testing, and now that I'm nearing the end of it, the daunting task looms. I don't actually have testing experience yet. A cardinal sin, I know, but nothing that can be done about it now other than fix it. Luckily in my case, it's a relatively small app with just 4 models, and only a few controller methods per model. The business logic is mostly non-trivial. Where would I start testing here? Should I do cucumber tests and add RSpec to the exceptions? What combination should give me enough coverage to confidently push it to production when the time comes? A: What I generally advise in a case like this (a finished site and no tests) is to write black-box tests first with cucumber. This will make sure you can have very quickly a test-suite that will cover purely the operational side: it will make sure the entire website works (and keeps working) as intended. Only then I would start writing tests (I prefer rspec, but that is a matter of opinion), based on a need. The cucumber tests go through all layers, so everything could be covered. With rspec you can test your models, controllers and views in isolation which is really nice, but will be a lot of work to do afterwards (although for only 4 models ...). A: Rspec is awesome. If you plan to do any UI testing then watir or selenium are very good open source tools. You can use rspec or test::unit for using watir or selenium. A: Adding tests for a small app with just 4 models is not that difficult. Any test is better than nothing. RSpec or Test::Unit will do for the beginning. A: Consider this an opportunity to learn a testing framework that you think you'll like and would use in future projects since the application you have written seems relatively small. I don't know if Heckle would work or if there is something like it, but that could help you check that your tests actually are testing what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to get session from codeigniter with node.js i'm writing application like social network where in my application can show status update and chat . when i search on internet i found node.js for long polling technology and i think i can use that for chat and streaming page in my application. but when i use node.js i have a stack this is a technology i want to my project: 1) i'm using codeigniter for framework and mysql database in address localhost:81/myproject 2) and using node.js in port 127.0.0.1:8080 to chat and streaming page this is code javascript server with node.js name is server.js var sys = require("sys"), http = require("http"), url = require("url"), path = require("path"), fs = require("fs"), events = require("events"); function load_static_file(uri, response) { var filename = path.join(process.cwd(), uri); path.exists(filename, function(exists) { if(!exists) { response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\n"); response.end(); return; } fs.readFile(filename, "binary", function(err, file) { if(err) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(err + "\n"); response.end(); return; } response.writeHead(200); response.write(file, "binary"); response.end(); }); }); } var local_client = http.createClient(81, "localhost"); var local_emitter = new events.EventEmitter(); function get_users() { var request = local_client.request("GET", "/myproject/getUser", {"host": "localhost"}); request.addListener("response", function(response) { var body = ""; response.addListener("data", function(data) { body += data; }); response.addListener("end", function() { var users = JSON.parse(body); if(users.length > 0) { local_emitter.emit("users", users); } }); }); request.end(); } setInterval(get_users, 5000); http.createServer(function(request, response) { var uri = url.parse(request.url).pathname; if(uri === "/stream") { var listener = local_emitter.addListener("users", function(users) { response.writeHead(200, { "Content-Type" : "text/plain" }); response.write(JSON.stringify(users)); response.end(); clearTimeout(timeout); }); var timeout = setTimeout(function() { response.writeHead(200, { "Content-Type" : "text/plain" }); response.write(JSON.stringify([])); response.end(); local_emitter.removeListener(listener); }, 10000); } else { load_static_file(uri, response); } }).listen(8383); sys.puts("Server running at http://localhost:8383/"); now in codeigniter side i making webservices on url http://localhost:81/myproject/getUser with response is json format and i access this with session auhtentication if not is redirect to login page. [{"user_id":"2a20f5b923ffaea7927303449b8e76daee7b9b771316488679","token":"3m5biVJMjkCNDk79pGSo","username":"rakhacs","password":"*******","name_first":"rakha","name_middle":"","name_last":"cs","email_id":"email@gmail.com","picture":"img\/default.png","active":"1","online":"0","created_at":"2011-09-20 11:14:43","access":"2","identifier":"ae70c3b56df19a303a7693cdc265f743af5b0a6e"},{"user_id":"9a6e55977e906873830018d95c31d2bf664c2f211316493932","token":"RoUvvPyVt7bGaFhiMVmj","username":"ferdian","password":"*****","name_first":"willy","name_middle":"","name_last":";f;w","email_id":"email1@gmail.com","picture":"img\/default.png","active":"1","online":"0","created_at":"2011-09-20 11:47:20","access":"2","identifier":"1ccd4193fa6b56b96b3889e59c5205cc531177c9"}] this is the point problem when i execute node server.js i get error like this undefined:0 sysntaxerror:unexpected end of input at object.parse(native) i don't know about that error i think because i using session ? but i'm not sure. when i test using test.js for testing my webservices var http = require("http") var options = { host: 'localhost', port: 81, path: '/myproject/getUser', method: 'GET' }; var req = http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); // write data to request body req.write('data\n'); req.write('data\n'); req.end(); and this is the output problem with request: parse error but when i using another webservice who has been response json format too and not using session that's work i can get the body response..if this problem is session how i can fix this?..this is can make me confused..thanks for your comment A: hard to say but I would primary try to send an object in jSON and not directly an array. i.e. just encapsulate the array into an object: {"data":[…]} This "may" be causing the parse error. Something else, for this purpose, it won't be bad to add the following to your responding PHP method: header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json');
{ "language": "en", "url": "https://stackoverflow.com/questions/7511549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Call function who's name is stored in a variable I have created a small classic asp file that I indend to call form asp.net using the below. I works, but it feels wrong somehow: Booking.BelongsToSite = file_get_contents("http://localhost:82/test2.asp?functionName=RetBTS&param=" + User.ID); protected string file_get_contents(string fileName) { string sContents = string.Empty; if (fileName.ToLower().IndexOf("http:") > -1) { // URL System.Net.WebClient wc = new System.Net.WebClient(); byte[] response = wc.DownloadData(fileName); sContents = System.Text.Encoding.ASCII.GetString(response); } else { // Regular Filename System.IO.StreamReader sr = new System.IO.StreamReader(fileName); sContents = sr.ReadToEnd(); sr.Close(); } return sContents; } Can anyone see any problems with doing this? Also is it possible to do something like the below in Classic ASP / VB script. I can't get it to call a dynamic function name: dim functionName, param, result functionName = request("functionName") param = request("param") result = functionName(param) Also any idea how to parse the parameters. Say if I pass the parameters in the head like "1,2,3,4", how can I pass the into the parenthesis? A: I think you're looking for the Eval function in VBScript. You can use it to call your method in the following way (demo script is vbs in wsh): Dim func, param func = "Hello" param = "everybody" MsgBox(Eval(func & "(""" & param & """)")) Function Hello(name) Hello = "Hello " & name End Function That returns "Hello everybody", as expected. As for your asp.net code: I'm not going to judge whether or not your solution is sensible, I don't know the situation. It can definitely work though. Just two remarks: * *Both WebClient and StreamReader implement IDisposable. Wrap them in a using block. *If you're going to download urls like that, make sure to validate your string, so that you don't go and download bad urls. Same for the function name in your classic asp that you pass in your querystring. Menno A: Try to use GetRef instead of Eval. dim functionName, param, result functionName = request("functionName") param = request("param") result = GetRef(functionName)(param)
{ "language": "en", "url": "https://stackoverflow.com/questions/7511553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I use CSS to style my form components? How does Vaadin use CSS that was written purely for HTML elements (e.g. styling and layout of body, h1, etc elements) and use that exact CSS style in Vaadin? Does one need to make changes on the CSS to map to corresponding Vaadin elements, or can one use that CSS as is? A: You can use the CSS as is, but you'll (naturally) have to tell Vaadin which CSS classes to use by calling myComponent.setStyleName("myStyleClass"); or myComponent.addStyleName("myStyleClass"); The difference between the two is that setStyleName replaces all existing styles with the provided one and addStyleName doesn't replace anything but adds the provided style for the component. You can also modify your CSS to override default Vaadin styles, for example .v-panel .v-panel-content { background: yellow; } would change every Panel's background color to yellow. I recommend that you create a new theme which is based on an existing Vaadin theme. Here's how to: * *Create a directory in the VAADIN/themes/ directory (eg. VAADIN/themes/myTheme). *Create styles.css in your theme directory. *Add @import "../runo/styles.css"; to the beginning of your styles.css (you can replace runo by any other existing theme). *Call setTheme(myTheme); in your Vaadin application class. *If you want to apply application-wide styles, override the Vaadin component CSS definitions in your styles.css. If you don't know the names of the CSS classes, you can use firebug and check the HTML elements' classes. *If you want to create a component-specific style, define it in styles.css and call setStyleName or addStyleName methods. See the CSS entry in the Book of Vaadin here. A: As far as I can tell from looking at the demos, Vaadin just generates HTML, so yes. A: Does one need to make changes on the CSS to map to corresponding Vaadin elements, or can one use that CSS as is? You can use your own CSS styles (just as it is) and it can use for either individual components (as said by "miq*" earlier) or entire page. ` Here is a link for more info: https://vaadin.com/book/-/page/themes.css.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7511560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to check whether 3g is active or not in android i am trying to check whether 3G is active or not in my handset and after that i have to fire an Intent. So plz anybody help me out Thanks in advance:) A: another snippet from an applilcation I've written recently: TelephonyManager telManager; telManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE); int cType = telManager.getNetworkType(); String cTypeString; switch (cType) { case 1: cTypeString = "GPRS"; break; case 2: cTypeString = "EDGE"; break; case 3: cTypeString = "UMTS"; break; case 8: cTypeString = "HSDPA"; break; case 9: cTypeString = "HSUPA"; break; case 10:cTypeString = "HSPA"; break; default:cTypeString = "unknown"; break; } A: Try this stuff, void checkConnectionStatus() { ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if( wifi.isAvailable() ){ Toast.makeText(this, "Wifi" , Toast.LENGTH_LONG).show(); } else if( mobile.isAvailable() ){ Toast.makeText(this, "Mobile 3G " , Toast.LENGTH_LONG).show(); } else {Toast.makeText(this, "No Network " , Toast.LENGTH_LONG).show();} } } A: first you need to check if is wifi or mobile network than just call (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).getNetworkType()); not that you could be on EDGE or GPRS or something so you can also do this if (getSsTelephony().getNetworkType() >= TelephonyManager.NETWORK_TYPE_UMTS) return NETWORK_3G; A: ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo mMobile = connManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (mMobile.isAvailable() == true) { Intent otherActivity = new Intent(); mapActivity.setClass(getBaseContext(), other.class); startActivity(otherActivity); } Don't forget to add the "ACCESS_NETWORK_STATE" permission in the AndroidManifext.xml file! A: This will check if you have internet connection(3G): private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager .getActiveNetworkInfo(); return activeNetworkInfo != null; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: CF app two way communications with server Users in field with PDA's will generate messages and send to the server; users at the server end will generate messages which need to be sent to the PDA. Messages are between the app and server code; not 100% user entered data. Ie, we'll capture some data in a form, add GPS location, time date and such and send that to the server. Server may send us messages like updates to database records used in the PDA app, messages for the user etc. For messages from the PDA to server, that's easy. PDA initiates call to server and passes data. Presently using web services at the server end and "add new web reference" and associated code on the PDA. I'm coming unstuck trying to get messages from the the server to the PDA in a timely fashion. In some instances receiving the message quickly is important. If the server had a message for a particular PDA, it would be great for the PDA to receive that within a few seconds of it being available. So polling once a minute is out; polling once a second will generate a lot of traffic and, maybe draim the PDA battery some ? This post is the same question as mine and suggests http long polling: Windows Mobile 6.0/6.5 - Push Notification I've looked into WCF callbacks and they appear to be exactly what I want however, unavailable for compact framework. This next post isn't for CF but raises issues of service availability: To poll or not to poll (in a web services context) In my context i'll have 500-700 devices wanting to communicate with a small number of web services (between 2-5). That's a lot of long poll requests to keep open. Is sockets the way to go ? Again that's a lot of connections. I've also read about methods using exchange or gmail; i'm really hesitant to go down those paths. Most of the posts i've found here and in google are a few years old; something may have come up since then ? What's the best way to handle 500-700 PDA CF devices wanting near-instant communication from a server, whilst maintaing battery life ? Tall request i'm sure. A: Socket communication seems like the easiest approach. You say you're using webservices for client-server comms, and that is essentially done behind the scenes by the server (webservice) opening a socket and listening for packets arriving, then responding to those packets. You want to take the same approach in reverse, so each client opens a socket on its machine and waits for traffic to arrive. The client will basically need to poll its own socket (which doesnt incur any network traffic). Client will also need to communicate its ip address and socket to the server so that when the server needs to communicate back to the client it has a means of reaching it. The server will then use socket based comms (as opposed to webservices) to send messages out as required. Server can just open a socket, send message, then close socket again. No need to have lots of permanently open sockets. There are potential catches though if the client is roaming around and hopping between networks. If this is the case then its likely that the ip address will be changing (and client will need to open a new socket and pass the new ip address/socket info to the server). It also increases the chances that the server will fail to communicate with the client. Sounds like an interesting project. Good luck! A: Ages ago, the CF team built an application called the "Lunch Launcher" which was based on WCF store-and-forward messaging. David Kline did a nice series on it (here the last one, which has a TOC for all earlier articles). There's an on-demand Webcast on MSDN given by Jim Wilson that gives an outline of store-and-forward and the code from that webcast is available here. This might do what you want, though it got some dependencies (e.g. Exchange) and some inherent limitations (e.g. no built-in delivery confirmation). A: Ok, further looking and I may be closer to what I want; which I think i a form of http long poll anyway. This article here - http://www.codeproject.com/KB/IP/socketsincsharp.aspx - shows how to have a listener on a socket. So I do this on the server side. Client side then opens a socket to the server at this port; sends it's device ID. Server code first checks to see if there is a response for that device. If there is, it responds. If not, it either polls itself or subscribes to some event; then returns when it's got data. I could put in place time out code on the server side if needed. Blocking on the client end i'm not worried about because it's a background thread and no data is the same as blocking at the app level; as to CPU & batter life, not sure. I know what i've written is fairly broad, but is this a strategy worth exploring ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7511566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Backbone.js - navigating to a route after the "click" event on a view My "view" is set up as below. simple. var ItemView = Backbone.View.extend({ tagName : "li", events : { "click" : "display" }, display : function() { //app.navigate('item'); // take me to my route! } }); And I have my router var App = Backbone.Router.extend({ routes: { "" : "index", "item" : "view_item" }, index: function() { alert('hi!'); }, view_item: function() { alert('bye!'); } }); app = new App(); Backbone.history.start(); Now, when I click on ItemView, it should run "display" method and I want the display method to take me to the route I specified in routes "item". Is this possible? I thought "navigate" function will work, but it doesn't. How could I achieve this? A: display : function() { app.navigate('item', true); } You need the second parameter set to true. From the Backbone documentation: navigaterouter.navigate(fragment, [triggerRoute]) Whenever you reach a point in your application that you'd like to save as a URL, call navigate in order to update the URL. If you wish to also call the route function, pass triggerRoute. A: Or you can do it directly from html, if you're using "< a >" tag. example: <a href="#item">Show Itens</a> It also works, I prefer this way when of course is possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: C# using FileOpendialogbox control within my form class I have a weird requirement. I need to use FileOpenDialogBox control within my form. I mean not as other window but as control of a form. I know many applicationss that doing it. How can I do it in C#? A: Try this object I found on the web.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sencha Touch Watermark Is there a method in Sencha Touch to set input watermark like jQuery watermark plugin? I'm using general HTML input text. A: Yes, it's called the placeHolder property of a textfield
{ "language": "en", "url": "https://stackoverflow.com/questions/7511571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP extending with unknown arguments I have an abstract class and child's: abstract class Cubique_Helper_Abstract { abstract public function execute(); } class Cubique_Helper_Doctype extends Cubique_Helper_Abstract{ public function execute($type) {} } As you can see, method execute() is common. But number of arguments can be different in all classes. How can I keep this extending with different arguments of method? It's my current error: Declaration of Cubique_Helper_Doctype::execute() must be compatible with that of Cubique_Helper_Abstract::execute() Thank you i advance. A: you can make method or function with out limited argument. function test(){ $num = func_num_args(); for ($i = 0;$i < $num;$i++) { $arg[$i] = func_get_arg($i); } // process on arguments } A: * *You could remove execute() from the abstract, but you probably do not want to do that. *You could also give it an data object as argument, like this: class MyOptions { public function getType(){} public function getStuff(){} } abstract class Cubique_Helper_Abstract { abstract public function execute(MyOptions $options); } class Cubique_Helper_Doctype extends Cubique_Helper_Abstract{ public function execute(MyOptions $options) { $type = $options->getType(); } } *Or, you could make it depend on values in constructor and leave out the argument: abstract class Cubique_Helper_Abstract { abstract public function execute(); } class Cubique_Helper_Doctype extends Cubique_Helper_Abstract{ public function __construct($type) { // since __construct() is not in abstract, it can be different // from every child class, which let's you handle dependencies $this->type = $type; } public function execute() { // you have $this->type here } } The last alternative is my favorite. This way, you really make sure you have the dependencies and when it's time to execute() you don't have to give it any arguments. I would not use func_get_args() since you lose track of dependencies. Example: class Cubique_Helper_Doctype extends Cubique_Helper_Abstract { public function execute() { $args = func_get_args(); $type = $args[0]; $title = $args[1]; $content = $args[2]; // do something, for example echo $type; // will always echo "" if you miss arguments, but you really want a fatal error } } $d = new Cubique_Helper_Doctype(); $d->execute(); // this is a valid call in php, but it ruins your application. // you **want** it to fail so that you know what's wrong (missing dependencies) A: You could use func_get_arg so that the child class's method signature is the same. A: When the number of arguments is different, you receive the error: Fatal error: Declaration of Cubique_Helper_Doctype::execute() must be compatible with that of Cubique_Helper_Abstract::execute() in C:\wamp\www\tests\41.php on line 16 So your only option is to make the arguement an array and pass in it the actual arguments or make the declaration of execute with no parameters and mamipulate the sent arguments with func_get_args or func_get_arg and func_num_args
{ "language": "en", "url": "https://stackoverflow.com/questions/7511573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difference in creating an instance between VB.NET & C# I am converting some code from VB.NET to C#. In VB.NET, I have this code: Dim ind As Foo.Index Dim ed As Foo.Edit ind = New Foo.Index ed = ind.InFunction() That works. So in C# my code will look like this: Foo.Index ind; Foo.Edit ed; ind = New Foo.Index(); ed = ind.InFunction(); But this doesn't work. I am sure that I did not forget to import namespaces. And now I've been wondering, is there any difference between those two? EDIT: And I finally add ed = New Foo.Edit(); into my C# code, but it also doesn't work. IMHO, I think there is a feature in VB.NET that allows auto initializing in variables (like the comment from Bex below suggests). Is it true? FINAL: Seems I do need to show all the code. But I need to talk directly to you as well (or you just install the software of mine). It makes me really confused. Thank you all. Sorry for this kind of newbie question. A: C-like languages (like C#) require you follow the pattern of [type] [variable name] at a minimum. C#, using the simplest form of initialization, requires you to use the new keyword. A simple C# class definition: class Foo { public Foo() { } } Then, to initialize an instance: Foo myFooIsStrong = new Foo(); A: //instantiation IndexServer.ClientInfo ci = new IndexServer.ClientInfo(); IndexServer.IXServicePortC konst = new IndexServer.IXServicePortC(); IndexServer.IndexServer ix = new IndexServer.IndexServer(); IndexServer.EditInfo ed = new IndexServer.EditInfo(); A: I don't quite understand what you are asking but this may help. VB auto initializes a lot of variables and c# doesn't. So in c# you should initialize your variables. A: The problem is that vb.net let's you import namespace roots, while C# requires you to import the full namespace. Your VB code has a statement like this at the top: Imports MyLibrary This puts the MyLibrary namespace sort of "in scope", such that you can use the type MyLibrary.Foo.Index either through the full name or by simply saying Foo.Index. C# does not allow this. You must either also import MyLibrary.Foo or reference the entire name in your code. A: C# is case sensitive. So the ed = New Foo.Edit(); should be ed = new Foo.Edit(); A: Here's an example using IndexServer; ... IndexServer ix = new IndexServer(); ClientInfo ci = new ClientInfo(); EditInfo ed = ix.checkoutSord(ci, Konstanta.EDIT_INFO.mbSord, Konstanta.LOCK.NO); Without knowing what those classes look like, hard to tell you more. But instantiation is basically the same, just need to change some syntax for declaring variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find the control XPath on Focus in WebBrowser control I had developed a windows application with WebBrowser control, which can interact with windows control using this sample provided http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting.aspx But my need is when user focus an control, that controls XPath need to be send to my windows application For that two main needs are their * *Need to set javascript event to all controls (can it be commonly configured in single control) *that javascript need to find xpath and send Can any one help me in doing this
{ "language": "en", "url": "https://stackoverflow.com/questions/7511587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iPhone : what the best way to integrated iPhone application to other application? I want to reuse iPhone source code application with other application, so in Xcode iPhone does it be able build library .jar file? A: You cannot reuse a whole application, but you can create a static library and have other apps link to it. A: ".jar" is a Java archive format, so no. iPhones don't come with a jvm. You can build libraries though. The best way to recycle your code from one application to the next is to try to write in the most general or abstract way you can, i.e. in such a way as to minimize the dependence on any given project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check if folder is read only in C#.net I am working in asp.net(C#)4.0. Before uploading an image, I want to check that if the folder in which the image has been uploaded is exists or not. If it exists, is it read-only or not and if it is read-only, I want to make it not read-only. How can I do so. Each time when I start my application, the folder is set to read-only. So I want to avoid this problem by checking it all by programmatically. I did like this... SaveFilePath = Server.MapPath("~\\_UploadFiles\\") + FileName; DirectoryInfo oDirectoryInfo = new DirectoryInfo(Server.MapPath("~\\_UploadFiles\\")); if(!oDirectoryInfo.Exists) Directory.CreateDirectory(Server.MapPath("~\\_UploadFiles\\")); else { if (oDirectoryInfo.Attributes.HasFlag(FileAttributes.ReadOnly)) { oDirectoryInfo.Attributes = FileAttributes.Normal; } } if (File.Exists(SaveFilePath)) { File.Delete(SaveFilePath);//Error is thrown from here } This code throws an error from the specified place on code. The folder "_UploadFiles" is read only but still its not going in to the if statement to make FileAttributes.Normal The error is.. Access to the path 'C:\Inetpub\wwwroot\WTExpenditurev01_VSS_UploadFiles\Winter.jpg' is denied. A: use the System.IO.DirectoryInfo class: var di = new DirectoryInfo(folderName); if(di.Exists()) { if (di.Attributes.HasFlag(FileAttributes.ReadOnly)) { //IsReadOnly... } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Want to use c++ or perl to send a file over the internet using OpenSSH and SFTP---Windows Vista both I Want to use c++ or perl to send a file over the internet using OpenSSH and SFTP. Both Computers will be running Windows Vista. The C++ would be a Console Program. How do I accomplish this? Thank You. I A: For a Perl solution check Net::SFTP::Foreign. Though on Windows, nowadays, the Net::SSH2 backend (Net::SFTP::Foreign::Backend::Net_SSH2) is probably a better option than the default OpenSSH one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nullPointerException when passing an arrayList to another function? in the project im working on, i need to take input from the text box and some selected files from the JFileChooser... i wish to pass the arrayList of files to another class where it has to be processed.. but im getting a nullPointerException here... m new to java so really dont know how to work this out... :-/ plz help!! i have included the indexing class as well: import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; //notice javax public class home extends JFrame { JLabel lab=new JLabel("MiniGoogle",JLabel.CENTER); JLabel lab2=new JLabel("Select Files:",JLabel.CENTER); JLabel lab3=new JLabel("Enter Keywords",JLabel.CENTER); JPanel pane = new JPanel(new BorderLayout(0,50)); JButton search = new JButton("Search!"); JTextField kw=new JTextField(25); JButton Browse=new JButton("Browse"); JFileChooser fc= new JFileChooser(); ArrayList files=new ArrayList(); String dest; home() // the frame constructor method { setBounds(100,100,350,350); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container con = this.getContentPane(); // inherit main frame con.add(pane); JPanel s=new JPanel(new FlowLayout()); JPanel r=new JPanel(new FlowLayout()); search.setActionCommand("search"); r.add(lab2); r.add(Browse); r.add(lab3); r.add(kw); pane.add ("North", lab); pane.add ("Center", r); s.add(search); pane.add("South",s); setVisible(true); // display this frame Browse.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { fc = new JFileChooser(); fc.setMultiSelectionEnabled(true); fc.setCurrentDirectory(new java.io.File("C:/Ananya/Files/DSA/project 2/searchfiles")); fc.setDialogTitle(dest); fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fc.setAcceptAllFileFilterUsed(false); if (fc.showOpenDialog(fc) == JFileChooser.APPROVE_OPTION) { files.addAll(Arrays.asList(fc.getSelectedFiles())); } else { System.out.println("No Selection "); } } }); search.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ String text=kw.getText(); if(text.equals("")||files==null) { JOptionPane.showMessageDialog(null,"Empty fields!","Error!",JOptionPane.WARNING_MESSAGE); } else { try{ new Indexing(files,text);/*this is where the exception is thrown*/ }catch(Exception ex) { System.out.println(ex+"home"); } } } }); } public static void main(String args[])throws IOException { new home(); } } this is my indexing class: public class Indexing{ HashMap map=new HashMap(); int n; ArrayList temp; String s; public Indexing(ArrayList files,String kw)throws IOException { for(int i=0;i<2;i++) { temp=new ArrayList(50); BufferedReader br = new BufferedReader(new FileReader((File)files.get(i))); String line = "", str = ""; while ((line = br.readLine()) != null) { str += line + " "; } StringTokenizer st = new StringTokenizer(str); while (st.hasMoreTokens()) { temp=new ArrayList(50); s = st.nextToken(); s.trim(); s.toLowerCase(); char ch=s.charAt(s.length()-1); if(!(Character.isLetterOrDigit(ch))) s=s.substring(0,s.length()-1); if(map.get(s)==null) { temp.add(files.get(i)); map.put(s,temp); } else if(!(((ArrayList)map.get(s)).contains(files.get(i)))) { ((ArrayList)map.get(s)).add(files.get(i)); } } } ArrayList result=(ArrayList)map.get(kw); new SearchResults(result,kw); //line 43 } } this is the SearchResults class: import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.util.*; public class SearchResults { JFrame jtfMainFrame; JLabel msg; JPanel p; JPanel s; File fl; JButton buttons[]; JLabel files[]; public SearchResults(ArrayList results,String kw) { jtfMainFrame = new JFrame(kw+" - MiniGoogle Search"); jtfMainFrame.setSize(50, 50); p=new JPanel(new BorderLayout(0,60)); msg=new JLabel(("Results for "+kw+":"),JLabel.CENTER); p.add("North",msg); s=new JPanel(new FlowLayout()); int l=results.size(); //line 22 for(int i=0;i<l;i++) { fl=(File)results.get(i); files[i].setText((i+1)+"."+ fl); buttons[i]=new JButton("Go!"); s.add(files[i]); s.add(buttons[i]); buttons[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String[] commands = {"cmd", "/c",fl.getAbsolutePath()}; try{Runtime.getRuntime().exec(commands);}catch(Exception ex) { System.out.println(ex); } } }); } p.add("Center",s); p.add("South",msg); jtfMainFrame.setBounds(100,100,350,350); jtfMainFrame.setVisible(true); } public static void main(String[] args) { // Set the look and feel to Java Swing Look try { UIManager.setLookAndFeel(UIManager .getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { System.out.println(e); } } } this is the exception trace: java.lang.NullPointerException at SearchResults.<init>(SearchResults.java:22) at Indexing.<init>(Indexing.java:46) at home$2.actionPerformed(home.java:75) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236) at java.awt.Component.processMouseEvent(Component.java:6041) at javax.swing.JComponent.processMouseEvent(JComponent.java:3265) at java.awt.Component.processEvent(Component.java:5806) at java.awt.Container.processEvent(Container.java:2058) at java.awt.Component.dispatchEventImpl(Component.java:4413) at java.awt.Container.dispatchEventImpl(Container.java:2116) at java.awt.Component.dispatchEvent(Component.java:4243) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916) at java.awt.Container.dispatchEventImpl(Container.java:2102) at java.awt.Window.dispatchEventImpl(Window.java:2440) at java.awt.Component.dispatchEvent(Component.java:4243) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183) A: I'm pretty sure that the NPE occurs here in this line: files.addAll(Arrays.asList(fc.getSelectedFiles())); Check that fc.getSelectedFiles() does not return null. A: It seems the exception occurs at this line: fc.setDialogTitle(dest); assign a value to dest first: dest = "The Title!"; A: There seems to be a mistake in the mapping in class Indexing. In line 42 you fetch an ArrayList based on a key word kw. However the Map doesn't contain such a key word and returns null. SearchResult tries to call the size() method on that list and rightfully throws a NullPointerException. We can't really fix your problem but that is the cause. Somewhere you need to either fix your mapping logic or add additional null checks. Whatever is appropriate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why math.Ceiling (double a) not return int directly? Possible Duplicate: Why doesn't Math.Round/Floor/Ceiling return long or int? msdn defined this method:Returns the smallest integer greater than or equal to the specified double-precision floating-point number. but in fact,it is public static double Ceiling ( double a ) why not return int directly? what does microsoft think of ? A: It's because the range of a double (±5.0 × 10−324 to ±1.7 × 10308) is much greater than the range of an int (-2,147,483,648 to 2,147,483,647). If the return type were int many possible inputs would fail. For example Math.Ceiling might be forced to throw an OverflowException in a checked context, or it might even return an incorrect result in an unchecked context. This is undesirable behaviour. Also some special values such as NaN and PositiveInfinity can be returned by this method. This is only possible if the return type is double. If you believe that the result will fit into an int, you can add an explicit cast: int result = (int)Math.Ceiling(a);
{ "language": "en", "url": "https://stackoverflow.com/questions/7511597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Does the quantifier {0} make sense in some scenarios? Example: /(?:Foo){0}bar/ I saw something like this in another answer. At first I thought "what should that be", but then, "OK could make sense, kind of a negative look behind", so that Foo is not allowed before bar, but this is not working. You can see this here on Regexr: It matches only bar but it matches also the bar in Foobar. When I add an anchor for the start of the row: /^(?:Foo){0}bar/ it behaves like I expect. It matches only the bar and not the bar in Foobar. But that's exactly the same behaviour as if I used only /bar/ or /^bar/. Is the quantifier {0} only a useless side effect, or is there really a useful behaviour for that? A: An explicit repetition count of zero can be useful in automatically generated regular expressions. You avoid coding a special case for zero repetitions this way. A: In traditional regular expressions, /x{0}/ (language = { xn : x = 0}) would mean "match exactly 0 of x", which is the same thing as // (language = { Λ }). Since the two are equivalent, you should be able to remove any /x{0}/ you find lying around. But PCREs and other extensions to regular expressions can get quite byzantine. I would not be surprised if /x{0}/ did something in Perl. I would be disgusted, but not surprised. I think it's probably some artifact of a program that automatically generates regular expressions but doesn't simplify them. Which is a shame, since it's so easy to write programs that simplify regular expressions. A: I can't think of a single good reason to use x{0}. But I can think of several why it should be avoided: * *It's useless since it always matches. *It slows the regex engine down (unless the regex is precompiled). *It's probably a sign of misunderstanding by the regex author. I'm willing to bet that someone who writes (?:foo){0} is trying to say "make sure that foo doesn't match here", which of course fails because the empty string can always be matched, whether foo is there or not. That's what negative lookaround assertions are for. (?<!foo)bar etc. A: There are good uses of {0}. It allows you to define groups that you don't intend to capture at the moment. This can be useful in some cases: * *The best one - use of the group in recursive regular expressions (or other weird constructs). Perl, for example, has (?(DEFINE) ) for the same use. A quick example - in PHP, this will match barFoo (working example): preg_match("/(?:(Foo)){0}bar(?1)/", "barFoo", $matches); *Adding a failed captured group (named or numbered) to the result matches. *Keeping the indices of all groups intact in case the pattern was refactored. Less good uses, as Peter suggested are useful in: * *Generated patterns. *Readability - Patterns with certain duplication, where {0} and {1} may lead thinking in the right direction. (OK, not the best point) These are all rare cases, and in most patterns it is a mistake.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: PHP SQL Server Connection to Local During my internship, I'm working on a Tracking system that is based on PHP and MSSQL. The company is writing software for transport companies, also uses SQL Server databases. The next thing that I'm going to do is to get datas from those companies SQL Servers. But those SQL Servers are located in those companies local machines. Now, there's a problem that not all companies have static ip's. I'm really confused about the system, how should it go? How should the mechanism be? I may use MSSQL connection and ODBC connection (DSNless). A: These companies have domains right? They should create a domain-link for you to use so that you can use that url to access the sql-database. They can't expect you to build something on ip while they have a dynamic one ;-).
{ "language": "en", "url": "https://stackoverflow.com/questions/7511601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android onCreate confusion Every example I find for any code makes use of onCreate(). For many of the classes I am writing for a program, I had to pass in the initial Activity as the classes required access to what is currently on display (EditText, Button, etc). I had attempted to make each class extend Activity but this typically resulted in run-time exceptions and failures. Currently, each class that requires input from the related View must make use of "parentactivity".findViewByID(...).getData(). Is this the proper way to request data from a View? Should I create respective View objects (EditText, Button, etc) and attach those to the loaded views, then request data from there? On what I perceive to be a related issue, I had attempted to create a RelativeRadioGroup of ToggleButtons (ToggleButtons in a RelativeLayout in a RadioGroup), only to find that the android:onClick attribute for them is not calling the available method. I have the method in the primary startup class (as well as a few other classes so as to pass the data to where it is needed). While I determined it is unlikely to call the method where the data is required (where the method was originally ONLY located), I do not understand why it is not called in the main class. A: With regards to the radiobutton, did you add the listener? As for passing data from views I've taken two approaches. If I have used a stock View in the Activity I get the data and then pass only the data to where I need it. Or if its a Custom View I've added my own getData() like method to conveniently get the data in the format I need it. Don't pass your Activity around just so you can access its View's data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get the PHP Uploads directory? I have uploaded a file using HTML / PHP and following is the print_r() of the $_FILES['file'] array: Array ( [name] => Chrysanthemum.jpg [type] => application/octet-stream [tmp_name] => G:\xampp\tmp\php82DB.tmp [error] => 0 [size] => 879394 ) As you can see above, the temp file is stored in the tmp_name directory. I need to get that directory path using PHP. How do I get it ? Tried using sys_get_temp_dir() but this is what it returns me. I do NOT want to get the directory from the array or from the file upload data. I want to dynamically get the php file uploads directory using a function. C:\Users\admin\AppData\Local\Temp A: $tmp_dir = ini_get('upload_tmp_dir') ? ini_get('upload_tmp_dir') : sys_get_temp_dir(); A: Php file upload temporary directory is a php config variable located on php.ini file. You can get the variable config value by using ini_get function. $path = ini_get('upload_tmp_dir'); // your code here A: $upload_dir = ini_get('upload_tmp_dir');
{ "language": "en", "url": "https://stackoverflow.com/questions/7511610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Playing Videos using MPMoviePlayer Now I am here with new question related to MPMoviePlayer. I am having a table view that lists the videos on one side of ipad, on other side - I play the video selected in list. These happens in same view. Now switching to different videos works fine. Now when I am editing the video using UIVideoEditorController, I am replacing the current video file in documents folder and then play the video again. But then my player stops working... I think the issue is that player within the UIVideoEditorController is not released properly. I released the editor but still I am there only.. NOTHING WORKS AGAIN :( Please help me asap -(void)playVideoWithIndex:(NSNumber *)index1 { int index = [index1 intValue]; indexVideo = [index1 intValue]; if(index > [SourceArray count]){ NSLog(@"dg"); return; } if (mp) { [mp stop]; [mp.view removeFromSuperview]; [mp release]; mp=nil; } // NSArray *sourcePaths=[[NSArray alloc] initWithArray:[[NSBundle mainBundle] pathsForResourcesOfType:@"mov" inDirectory:nil]]; videoDtls *v =[SourceArray objectAtIndex:index]; lbl_date.text=v.iVideoDate; lbl_Title.text=v.iVideoTitle; lbl_description.text=v.iVideoDesc; lblDesc.text = @"Description"; lable_title.text = v.iVideoTitle; NSString *documentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; NSString *mainImageFolderPath=[documentFolderPath stringByAppendingPathComponent:@"Videos"]; NSString *urlStr = [mainImageFolderPath stringByAppendingPathComponent:v.iVideoPath]; self.vpath = urlStr; NSLog(@"asdsd %@",urlStr); NSURL *url = [NSURL fileURLWithPath:urlStr]; mp = [[MPMoviePlayerController alloc] initWithContentURL:url]; if ([mp respondsToSelector:@selector(loadState)]) { // Set movie player layout //[mp setControlStyle:MPMovieControlStyleFullscreen]; //[mp setFullscreen:YES]; // May help to reduce latency [mp prepareToPlay]; mp.useApplicationAudioSession = NO; // mp.controlStyle = MPMovieControlStyleDefault; // mp.useApplicationAudioSession = YES; // Register that the load state changed (movie is ready) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerLoadStateChanged:) name:MPMoviePlayerLoadStateDidChangeNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerEnterFullScreen:) name:MPMoviePlayerDidEnterFullscreenNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerExitFullScreen:) name:MPMoviePlayerWillExitFullscreenNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil]; [[mp view] setFrame:CGRectMake(0, 0, 480, 320)]; // Add movie player as subview [playerView addSubview:[mp view]]; mp.initialPlaybackTime = -1.0; } else { // Register to receive a notification when the movie is in memory and ready to play. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePreloadDidFinish:) name:MPMoviePlayerContentPreloadDidFinishNotification object:nil]; } // Register to receive a notification when the movie has finished playing. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil]; } This method is called when a video is played from table view.. - (void)videoEditorController:(UIVideoEditorController *)editor didSaveEditedVideoToPath:(NSString *)editedVideoPath { CFShow(editedVideoPath); NSFileManager *fileManager = [[NSFileManager alloc] init]; NSError *error = nil; NSString *path = self.vpath; NSLog(@"PATH %@", self.vpath); if([fileManager removeItemAtPath:path error:&error] != YES){ NSLog(@"ERROR 1 : %@",[error localizedDescription]); } else{ // can do save here. the data has *not* yet been saved to the photo album if ([fileManager copyItemAtPath:editedVideoPath toPath:path error:&error] != YES) NSLog(@"Can't move file with error: %@", [error localizedDescription]); } [popOver dismissPopoverAnimated:YES]; [self dismissMoviePlayerViewControllerAnimated]; [editor release]; [self performSelector:@selector(playVideoWithIndex:) withObject:[NSNumber numberWithInt:indexVideo] afterDelay:0.2]; } This method is called when editor returns successfully. After This my video does not play A: Finally I solved issue by using UIVideoEditorController in another view controller and then delaying playing video for fraction of second. May this happened because I was trying to play a video that was being replaced.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Adding views or windows to MainWindow I'm stumbling over some basic concepts, that I cannot grasp. I hope, somebody can clear some things up for me, as I've found no resource, that would explain that. OR maybe, it's in the bright open and I just don't see it. Understood so far: The MainWindow holds the menu and is therefore more or less essential. The info.plist holds the nib, that's loaded on appstart. Not understood so far: I am trying a single window application. I can do everything in the appDelegate (works fine so far) and I can have an additional controller, to whcih I can connect UIElements from the MainWindow to (works although fine so far). BUT: What I'd really like to do, is have a MainWIndow, that only has the menu, and a separate controller and nib (possibly even more than one of both later on), that are loaded and added subsequently. My questions: * *Use NSWindowController or NSViewController? And why? (I'd use NSViewController) *What, where and how to instantiate (presumably in the didFinishLaunching of the appDelegate?) *How to add window or view to the one and only main-window instead of having a second, independent window (I'm not yet up for multiDocumentApps) Thanx a lot, any thoughts appreciated! A: Not understood so far: I am trying a single window application. I can do everything in the appDelegate (works fine so far) and I can have an additional controller, to whcih I can connect UIElements from the MainWindow to (works although fine so far). BUT: What I'd really like to do, is have a MainWIndow, that only has the menu, and a separate controller and nib (possibly even more than one of both later on), that are loaded and added subsequently. For the sake of clarity, MainWindow is a nib file so I’ll refer to it as MainWindow.nib. It is the standard nib file name specified in the application’s Info.plist file as the nib file to be loaded when the application starts. By default, Xcode creates a MainWindow.nib file that contains both the main menu and the main window. You’re free to delete the window from MainWindow.nib file and have another nib file to hold that window. Let’s call this other nib file MyWindow.nib. Use NSWindowController or NSViewController? And why? (I'd tend to viewController) Since you’ll have a separate nib file to hold a window, you’ll use NSWindowController. Create a subclass of NSWindowController, e.g. MyWindowController, which will be responsible for controlling the window stored in MyWindow.nib. This subclass will have outlets pointing to the user-interface elements in that window, and potentially other objects you define in MyWindow.nib. When doing this, it’s important that you do the following in MyWindow.nib: * *Set the file’s owner to be of type MyWindowController; *Connect the window outlet in file’s owner to the window object. NSViewController is used to manage a view, normally loaded from a nib file, and it doesn’t apply to windows. You can repeat this — window in a .nib file, subclass of NSWindowController to manage that window — for as many windows as needed. What, where and how to instantiate (presumably in the didFinishLaunching of the appDelegate?) Since you want a single window in your application, one option is for your application delegate to hold a reference (instance variable, declared property) to the single window controller that manages that window. Then, in -applicationDidFinishLaunching:, instantiate said controller. For example: // MyAppDelegate.h @class MyWindowController; @interface MyAppDelegate : NSObject <NSApplicationDelegate> @property (retain) MyWindowController *myWindowController; @end and: // MyAppDelegate.m #import "MyAppDelegate.h" #import "MyWindowController.h" @implementation MyAppDelegate @synthesize myWindowController; - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { self.myWindowController = [[[MyWindowController alloc] initWithWindowNibName:@"MyWindow"] autorelease]; [self.myWindowController showWindow:self]; } … @end If you want more windows, it’s just a matter of declaring instance variables/properties to hold their corresponding controllers and instantiate the controllers like above. How to add window or view to the one and only main-window instead of having a second, independent window (I'm not yet up for multiDocumentApps) Are you sure you want to add a window to the main window? If so, that’d be called an attached window. You can use the mechanism above (place the window in its own nib file, have a subclass of NSWindowController to manage it, have your original MyWindowController hold a reference (instance variable, declared property) to the attached window controller, and instantiate it/load the attached window nib file when appropriate) and then use -[NSWindow - addChildWindow:ordered:] to attach the secondary window to the main window. For example, considering MyWindowController has a declared property secondaryWindowController, in MyWindowController.m: - (void)someAction:(id)sender { // If the secondary window hasn't been loaded yet, load it and add its // window as a window attached to the main window if (self.secondaryWindowController == nil) { self.secondaryWindowController = [[[MySecondaryWindowController alloc] initWithWindowNibName:@"MySecondaryWindow"] autorelease]; [[self window] addChildWindow:self.secondaryWindowController.window ordered:NSWindowAbove]; } } If you want to add a view to the main window, the easiest way is to do so in the nib file directly. If you need/want to do it programatically, you need to have a reference to the view and then add it to the main window’s content view, e.g.: [self.window.contentView addSubView:someView]; You can create someView programmatically or load it from a separate nib file. In the latter case, the procedure is much like what was described above but instead of using a subclass of NSWindowController you’d use a subclass of NSViewController. For example, in MyWindowController.m: - (void)anotherAction:(id)sender { // If the view hasn't been loaded yet, load it and add it // as a subview of the main window's content view if (self.someViewController == nil) { self.someViewController = [[[MyViewController alloc] initWithNibName:@"MyView" bundle:nil] autorelease]; // You'll probably want to set the view's frame, e.g. // [self.someViewController.view setFrame:...]; [self.window.contentView addSubview:self.someViewController.view]; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Facebook posting status containing html I am posting status using Facebook C# SDK. It works fine but I when my post contains some html it doesn't work. Basically it contains anchor tag and my site's link. How can I resolve this error? A: This isnt an error, this is intended. You cant send HTML in a post status, regular URL's will be parsed as anchor tags though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I make this generic I have a bunch of ViewModel classes, Q001ViewModel, Q002ViewModel, ..., QnnnViewModel. These all inherit from VMBase. I also have a set of Subs ShowQnnn, ShowQnnn, ..., ShowQnnn. An example is: Private Sub ShowQ001() Dim workspace As Q001ViewModel = _ CType(Me.Workspaces.FirstOrDefault(Function(vm) vm.GetType() Is GetType(Q001ViewModel)), Q001ViewModel) If workspace Is Nothing Then workspace = New Q001ViewModel(_dbc) Me.Workspaces.Add(workspace) End If Me.SetActiveWorkspace(workspace) End Sub Workspaces is an ObservableCollection of VMBase. The ShowQnnn procedures are used to display a ViewModel. The point is that a new QnnnViewModel will be added to the workspaces collection only if one of that type does not already exist. Is there a way to turn then ShowQnnn procedures into one generic version? A: Sorry but I don't know VB.Net syntax enough regarding generics (feel free to edit my answer with the VB.Net version), so i'll answer in C#. If the constructors take different arguments the solution would look like : void ShowQxxx<T>(Func<T> constructor) where T : VMBase { var workspace = (T)(Workspaces.FirstOrDefault(vm => vm is T); if (workspace == null) { workspace = constructor(); Workspaces.Add(workspace) } SetActiveWorkspace(workspace) } ... ShowQxxx(() => new Q001ViewModel(_dbc)); Otherwise you could simplify even more using reflection : void ShowQxxx<T>() where T : VMBase { var workspace = (T)(Workspaces.FirstOrDefault(vm => vm is T); if (workspace == null) { var ctor = typeof(T).GetConstructor(new [] { typeof(MyDataBaseType) }); workspace = (T)(ctor.Invoke(_dbc)); Workspaces.Add(workspace) } SetActiveWorkspace(workspace) } ... ShowQxxx<Q001ViewModel>(); A: Here is the VB version Private Sub ShowQxxx(Of T As VMBase)(constructor As Func(Of T)) Dim workspace As T = _ CType(Me.Workspaces.FirstOrDefault(Function(vm) vm.GetType() Is GetType(T)), T) If workspace Is Nothing Then workspace = constructor() Me.Workspaces.Add(workspace) End If Me.SetActiveWorkspace(workspace) End Sub .... ShowQxxx(Function() New Q001ViewModel(_dbc))
{ "language": "en", "url": "https://stackoverflow.com/questions/7511630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flex Charts Custom AxisRenderer Grouping I have to group the horizontal columns in all kind of flex charts. Expected result is shown below. On top, i want to display the grouping of the horizontal axis. Please let me know if this can be achievable in flex charts? Appreciate your help on this. Thanks, Raghu.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mvvm and Mef and Item control template I have the following case on my WPF app : I have a main user control with its MainViewModel which binded to the control datacontext . Inside the main control , I have an item control which item source is binded to List . the item control has a user control as its template which draw the users details , each template as we know has User as its Datacontext . My question : How I can use the Main control datacontext (MainViewModel) in the template user control . I tried to use mef to import MainViewModel but the problem its exported with creation policy "NonShared" so the import will bring new instances of the MainViewModel and not the one of the Main control . Thanks in advance ... A: If you are trying to use MEF, you could always compose the existing value with a unique name, e.g.: MainViewModel vm = DataContext; container.ComposeExportedValue("SharedViewModel", vm); That way, you can always provide an import for it in your user control: [Import("SharedViewModel")] public MainViewModel ViewModel { get; set; } Where ComposeExportedValue is an extension method belonging to the AttributedModelServices type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GWT RequestFactory Hibernate unnecessary call find method in locator Using RequestFactory I gets data to View, then in other transaction someone else updating this object to version 1 (My view has still version 0). Next I update some values and push changes by RequestFactory to DAO Layer. The problem is when changed object is transferted to Service Layer: the Locator calls find method and gets newest version of object (changed by someone else). So when we gets to update method in DAO layer object is merged with version1 and changes from both transaction! In this situation in normal case Hibernate should throw exception because object should has other version value (Optimistic Lock)? Locator: @Component public class TaskItemLocator extends Locator<TaskItem, Long> { @Autowired private TaskItemDao taskItemDao; @Override public TaskItem find(Class<? extends TaskItem> aClass, Long id) { return taskItemDao.findTaskItem(id); } } DAO: @Override @Transactional(propagation = Propagation.REQUIRED) public void updateTaskItems(List<TaskItem> taskItemToUpdate) { for (TaskItem ti : taskItemToUpdate) { getHibernateTemplate().update(ti); } } When I simulate this situation without calling find in RequestFactory everything works ok. The exception is thrown when other transaction changes my object. But how to gets this behavior in RequestFactory? Besides befor every update RequestFactory call find method so select to DB is performed. Next go to DAO layer and hibernate calls exacly the same select query because he checks object version. So one select is duplicated unnecessery, for every updated object!!! A: RequestFactory sends only diffs (i.e. what you changed on the object, on the client-side), so it needs to apply those diffs to an object on the server-side before calling your service method, and that's why it needs to find the object by its ID. Also, when you reference an object without modifying it (e.g. you set a property object A to reference object B, object B isn't modified), the same find() method is used; and in this case you probably don't want an optimistic lock error (i.e. baking optimistic lock check into the find() isn't possible). Optimistic locking is hard to do well, because you then have to handle conflicts (and users don't want to read "someone changed the thing while you were modifying it, so I'm gonna trash your changes and start you over fresh from the newest version"). See http://code.google.com/p/google-web-toolkit/issues/detail?id=6046 about optimistic locking and RequestFactory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RadioButtons generation? I am working on scripts that would generate a list of radiobuttons. The user would have to choose one of the answer, and one cell is filled with the result. The number of radiobuttons in not known at the beginning, and depends onthe number of contacts in a group of gmail contacts. My question is pretty simple, how can I display as much radiobuttons as needed ? I tried to put them in a loop, but it appears that nothing is loaded but my submit button. function test(){ var mydoc = SpreadsheetApp.getActiveSpreadsheet(); var app = UiApp.createApplication().setTitle('Choose your contact'); //to use radios you will need a form var form = app.createFormPanel().setId('form').setEncoding('multipart/form-data'); //Retrieving contacts in first speadsheet tag var sheet = mydoc.getSheets()[0];//select first sheet var tagName = sheet.getRange("G4").getValue();//where the tag is placed var length = count_contacts_in_tag(tagName) //initiates grid var formContent = app.createGrid().resize(length + 1,1); form.add(formContent); var group = ContactsApp.getContactGroup(tagName); var contacts = group.getContacts(); **// TODO: My problem is here!** for (var i in length) { var myRadio1 = app.createRadioButton("radio", "one").setFormValue('one'); formContent.setWidget(i, 0, myRadio1); } formContent.setWidget(length, 0, app.createSubmitButton('Submit!')); //submit button app.add(form); mydoc.show(app); } Any hint would be grately appreciated ! Thanks by advance A: The answer is pretty straghtfoward, as long as you know where to search for the information. THe Google Scripts are a subset of JavaScript. My problem was simply coming from the structure of my loop. It should be : for (var i=0; i C U . . .
{ "language": "en", "url": "https://stackoverflow.com/questions/7511646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what's the difference between methods dictionary and dictionaryWithCapacity? what's the difference between [NSMutableDictionary dictionary] and [NSMutableDictionary dictionaryWithCapacity:10]? which one is better? A: dictionaryWithCapacity is better if you know how many elements you are going to put in at the start. This means it can immediately allocate the required amount of space for your items. It does not prevent you from adding more. It just means that if you exceed the allocated amount, it will have to allocate more, which may be more resource intensive. On the flipside, if you don't know how many items you need, and you allocate too much space, you're not being memory efficient which is very important in mobile devices. I don't have any benchmarks, but I don't believe the different is terribly huge, so I wouldn't be too fussed. A: dictionaryWithCapacity will come back to bite you when you end up putting too much in there, or wasting space if you don't put enough in there. I would always use dictionary unless I was hitting specific memory or performance problems and dictionary appeared to be the cause of them. Otherwise it's just unnecessary complexity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PHP date_default_timezone_set() and time() Does date_default_timezone_set() function affect the value of time()? Or does it just affect the date() function? A: time() is timezone independent. See this comment on PHP's time() documentation page: The function time() returns always timestamp that is timezone independent (=UTC).
{ "language": "en", "url": "https://stackoverflow.com/questions/7511653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }