text
stringlengths
8
267k
meta
dict
Q: Problem casting to an interface in flex I am using interfaces for module communication like in adobe flex documentation. When I have a ModuleLoader in mxml, everything works great. <mx:TabNavigator id="testNav" height="100%" width="100%"> <s:ModuleLoader id="firstTab" label="ONE" width="100%" url="path/to/module/Mod1.swf"/> <s:ModuleLoader id="secondTab" label="TWO" width="100%" url="path/to/module/Mod2.swf"/> </mx:TabNavigator> and i have this code var someChild:* = firstTab.child as ISomeModule; ISomeModule is the interface. But when I have a ModuleLoader in actionscript in another file, when I do the same thing, someChild becomes null when cast to ISomeModule var myLoader:ModuleLoader=new ModuleLoader(); myLoader.percentHeight=50; myLoader.percentWidth=50; myLoader.loadModule(moduleURL + "?attr=value&attr2=" + parentDocument.attr2); and in another function, I have var childMod:* = myLoader.child as ISomeModule; myLoader.child is not null but when cast to ISomeModule, it becomes null. Does anyone have an idea about how to solve this? thanks A: 2 things: * *You need the same ApplicationDomain for cross-module class sharing (you should also enable optimizing in your Module compilation): <s:ModuleLoader url="someURL" applicationDomain="{ApplicationDomain.currentDomain}" /> *If I remember correctly, it should be firstChild.content and not firstChild.child for the actual module itself. A: This post is quite some years old but currently I ran into a similar issue by creating ModuleLoader dynamically with AS3. The above hint to set the ApplicationDomain saved my day... thanks! private function createModule():void { _moduleLoader = new ModuleLoader; _moduleLoader.applicationDomain = ApplicationDomain.currentDomain; _moduleLoader.addEventListener(ModuleEvent.READY, onModuleReady); _moduleLoader.url = "path/to/your/module/MyModule.swf"; _moduleLoader.loadModule(); } private function onModuleReady(event:ModuleEvent):void { // iMyModule is null if ApplicationDomain is not set var iMyModule:* = event.currentTarget.child as IMyModule; } Thanks, Olaf
{ "language": "en", "url": "https://stackoverflow.com/questions/7516686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How (if) is it possible to retrieve via YouTube API Video of a specific size(big one)? Is it possible to retrieve and specify size of YouTube video? Normally API gives me videos in small resolution 360p. But I need way bigger 1080p would be my weapon of choice. Do you know if it's possible to get this size? Thanks for help in advance! A: There are multiple APIs, so it depends on which you are using. But the embed API has a javascript method to set the quality: setPlaybackQuality(hd1080); Read more about the embed-API here: http://code.google.com/apis/youtube/youtube_player_demo.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7516687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What jar/dex file provides the real implementation of the Android.jar I ran into some interesting problem after compiling the Android SDK source. I tried to disassemble the resulting android.jar, but found that most methods contained in that jar file are just a stub that does nothing more than throwing a runtime exception, for example: public void startActivityForResult(android.content.Intent, int); Code: 0: new #2; //class java/lang/RuntimeException 3: dup 4: ldc #3; //String Stub! 6: invokespecial #4; //Method java/lang/ RuntimeException."<init>":(Ljava/lang/String;)V 9: athrow I can understand there might be no need for Android.jar to contain the real implementations of Android Framework, given it only serves as a compile-time library for 3rd party apps. But my question is: what is the Jar or Dex file(s) that provides the real implementation of android.jar? I assume it should also be generated when compiling the SDK, am I right? Thanks! LL
{ "language": "en", "url": "https://stackoverflow.com/questions/7516688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MVC3 Optional Model Property I have a dropdownlist which I would like to be optional, however, the ModelState.IsValid check is trying to validate the property. Is there a way to tell it the property is optional? Here is my code: <h2>New Version</h2> @using (Html.BeginForm()) { <div>Version Number: @Html.TextBoxFor(m => m.Number)</div> <div>Enabled: @Html.CheckBoxFor(m => m.IsActive)</div> <div></div> <div> Template (optional): @Html.DropDownListFor(m => m.TemplateVersionId, new SelectList(Model.CurrentVersions, "VersionId", "Number"), "-- Select Template --") </div> <input type="submit" value="Save" /> @Html.ActionLink("Cancel", "Index"); } and my ViewModel: public class AddVersionViewModel { public double Number { get; set; } public bool IsActive { get; set; } public int TemplateVersionId { get; set; } public ICollection<Version> CurrentVersions { get; set; } } I want the TemplateVersionId to be optional. A: Change it to an int? to make it nullable. A: When you create Nullable items it becomes optional in forms public class AddVersionViewModel { public double Number { get; set; } public bool IsActive { get; set; } public int? TemplateVersionId { get; set; } public ICollection<Version> CurrentVersions { get; set; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Object Tags and Asp I have a master page that gets all its images from a table on a database, and I am trying to incorporate flash, for banners, but I can't quite seem to figure it out. Right now there is a: <asp:image id="headerimg" runat="server"> and that generates the appropriate img tag needed to show an image in html. Now I would like to know if there is any way where I can generate an object tag if a .swf file is present and populate the tag with width height and data and also not show the img tag. Update__ I now have made a usercontrol that will create the object tag, but can someone please tell me if it is looking like I am doing it right.. IDataReader dr = DB.GetRS("SELECT HeaderGraphic,HeaderAlign, fWidth, fHeight, Flash FROM Store where CustomerID='" + Session["Customer"].ToString() + "'"); if(dr["Flash"] == 1) { HtmlGenericControl obj = new HtmlGenericControl("object"); obj.Attributes["width"] = dr["fWidth"]; obj.Attributes["height"] = dr["fHeight"]; obj.Attributes["data"] = dr["HeaderGraphic"]; this.Controls.Add(obj); } else { HtmlGenericControl image = new HtmlGenericControl("img"); img.Attributes["src"] = dr["HeaderGraphic"]; img.Attributes["align"] = dr["HeaderAlign"]; this.Controls.Add(image); } is this continuing to look right? and is there anything I am missing? Thanks. A: Why not create a user control that generates the required <OBJECT /> html to display the swf file and then you can dynamically load these if there are swf file present? A: is this looking right? and how do I get this into the html? Yes it looks right. You can add it into your page this way: this.Controls.Add(obj); Hope it helps! Hanlet EDIT: I could recommend you to look into Generic Handlers and see if you can somehow use it. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7516698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to reference a page with parameters Wicket I need to send Wicket links (through mail, for example) which references instances in the system. For example, the mail could contain: From: ...@... To: ...@... Subject: Order Pending ... txt... Click here to go: http://I.dont.care.the.style.of.the.linkPage.OrderDetailPage?orderId=1001 ... txt... I have two constructor of this OrderDetailPage public class OrderDetailPage extends BasePage { public OrderDetailPage(PageParameters parameters){ this(OrderRepository.getById(parameters.getAsInteger("orderId")), null); } public OrderDetailPage(Order order, WebPage back) { super(new CompoundPropertyModel<Order>(order)); //Renders the page for the order received. //back is the page we came from. Null hides link. ... } ... } I don't know how to send the links, because, I can't create a Bookmarkable Link because it looks for the default constructor... and of course, I don't have one. What I'm doing for another page is: final PageParameters pars = new PageParameters(); pars.add("orderId", "1001"); BookmarkablePageLink<Void> link = new BookmarkablePageLink<Void>("alink", OrderDetailPage.class, pars); link.add(new Label("id", "1001")); add(link); Markup: <li><a href="#" wicket:id="alink"><span wicket:id="id"/></a></li> The generated URL is http://localhost:8080/wicket/bookmarkable/packagePath.OrderDetailPage?orderId=1001 Which is OK, but Still, doesn't call the "parameters" constructor. FIX: I fix this, but I know the solution is NOT OK. public OrderDetailPage() { this(WicketApplication.orderRepository.get(Integer .parseInt(RequestCycle.get().getRequest() .getRequestParameters().getParameterValue("orderId").toString())), null); } EDIT: I read something about "mounting" the URL, could this work? How? A: The BookMarkablePageLink has 2 constructors: one for connecting to the default constructor of the linked page, and one with an extra parameter to supply the link with PageParameters, which will call the constructor with the PageParameters. You create the link like so: PageParameters pars = new PageParameters(); pars.add("id", 12345); add(new BookmarkablePageLink("id", MyPage.class, pars); This also works with the setResponsePage method: PageParameters pars = new PageParameters(); pars.add("id", 12345); setResponsePage(MyPage.class, pars);
{ "language": "en", "url": "https://stackoverflow.com/questions/7516705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Warning Received memory warning. Level=2 iPhone my application crashes showing Received memory warning. Level=2. Complete warning is warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.5 (8L1)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found). Please help It is working fine in iphone simulator but not on actually divice A: Isn't is just a memory problem ? The "RAM" of iPad and iPhone is really limited, if you use too much of it, the system will send level 1 warning and level 2 warning. If you still use too much memory after that, it will kill your application. You don't encounter the problem on the simulator because your computer have much more memory. If you want to simulate such memory warning to see how your code behave in such a situation. Use this code : // Do as if there has been a memory warning in the simulator + (void)simulateMemoryWarningInSimulator { #if TARGET_IPHONE_SIMULATOR #ifdef DEBUG CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), (CFStringRef)@"UISimulatedMemoryWarningNotification", NULL, NULL, true); #endif #endif } A: Try adding this Framework in your xcode project - libxml.dylib Yes and if it looks like a memory issue, run your app on a device coupled with Instruments. It should show you what exactly is causing the memory issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: OpenCV: compute Rotation Matrix for stereoRectify I want to compute the rotation and translation matrices to use for stereoRectify in open CV. The rectified images look twisted and totally incorrect (Like completely twisted cone at the center of the image going both directions) I have the rotation and translation matrices of both cameras.... Also, this is a smilar post but it is not helping: Finding Rotation matrices between two cameras for "Stereorectify" I am sharing my code below... // Create interinsic parameters matrix given the translation and rotation matrecis Mat CreateExternsicParamsMat(Mat R, Mat T) { Mat ext1(4,4,T.type()); Mat ext2(4,4,T.type()); for(int i=0; i<3;i++) for(int j=0;j<3; j++) ext1.at<double>(i,j) = R.at<double>(i,j); for(int i=0; i<3;i++) ext1.at<double>(i,3) = T.at<double>(i,0); ext1.at<double>(3,3) = 1; ext1.at<double>(3,2) = 0; ext1.at<double>(3,1) = 0; ext1.at<double>(3,0) = 0; return ext1; } Mat ext1 = CreateExternsicParamsMat(R1,T1); Mat ext2 = CreateExternsicParamsMat(R2,T2); Mat ext1inv; invert(ext1,ext1inv); Mat ext = ext1inv*ext2; for(int i=0; i<3;i++) for(int j=0;j<3; j++) R.at<double>(i,j) = ext.at<double>(i,j); for(int i=0; i<3;i++) T.at<double>(i,0)=ext.at<double>(i,3); stereoRectify( M1, D1, M2, D2, img_size, R, T, R1, R2, P1, P2, Q);
{ "language": "en", "url": "https://stackoverflow.com/questions/7516716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL JOIN help. Outputting table.rowName * 3 based on a Linking table I have a linking table with all the ID's of the tables linked. My JOIN isn't working, though : $strSql="SELECT clients.clientName, projects.projectName, projectTemplates.projectTempName FROM projectTempList JOIN clients ON projectTempList.clientID = clients.clientID JOIN projects ON projectTempList.projectID = projects.projectID JOIN projectTemplates ON projectTempList.projectTemplateID = projectTemplates.projectTempID WHERE projectTempList.projectCostID = $intProjectCostId"; Structure in my linking table is: projectTempList -> projectID, clientID, projectTemplateID, projectCostID I need to select the clientName, projectName, projectTempName from clients, projects, and projectTemplates. This is based on having a linked table with the respective ID's in a table called projectTempList. I have the costID in a variable. EDITJOIN clients ON projectTempList.clientID = clients.clientID needed to be clients.projectclientID. Many thanks for your help. A: A few things: * *Output echo $strSql; and see if it is what you expect. Test it against MySQL directly (i.e. PHPMyAdmin) *Ensure you are not returning any errors with echo mysql_error(); *You mentioned having clientID, but your WHERE clause uses projectCostID *Be mindful of SQL Injection, i.e. properly escape $intProjectCostId with something like " . (int)$intProjectCostId
{ "language": "en", "url": "https://stackoverflow.com/questions/7516724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Set find member vs. using find on list Since the items in a Standard Library set container are sorted, will using the find member on the set, in general, perform faster than using the find algorithm on the same items in a sorted list? Since the list is linear and the set is often implemented using a sorted tree, it seems as though the set-find should be faster. A: With a linked list, even a sorted one, finding an element is O(n). A set can be searched in O(log n). Therefore yes, finding an element in a set is asymptotically faster. A sorted array/vector can be searched in O(log n) by using binary search. Unfortunately, since a linked list doesn't support random access, the same method can't be used to search a sorted linked list in O(log n). A: It's actually in the standard: std::set::find() has complexity O(log n), where n is the number of elements in the set. std::find() on the other hand is linear in the length of the search range. If your generic search range happens to be sorted and has random access (e.g. a sorted vector), then you can use std::lower_bound() to find an element (or rather a position) efficiently. Note that std::set comes with its own member-lower_bound(), which works the same way. Having an insertion position may be useful even in a set, because insert() with a correct hint has complexity O(1). A: You can generally expect a find operation to be faster on a Set than on a List, since lists are linear access (O(n)), while sets may have near-constant access for HashSets (O(1)), or logarithmic access for TreeSets (O(log n)). A: set::find has a complexity of O(log(n)), while std::find has a complexity of O(n). This means that std::set::find() is asymptotically faster than std::find(std::list), but that doesn't mean it is faster for any particular data set, or for any particular search. A: I found this article helpful on the topic. http://lafstern.org/matt/col1.pdf You could reconsider your requirements for just a "list" vs. a "set". According to that article, if your program consists primarily of a bunch of insertions at the start, and then after that, only comparisons to what you have stored, then you are better off with adding everything to a vector, using std::sort (vector.begin(), vector.end()) once, and then using lower_bound. In my particular application, I load from a text file a list of names when the program starts up, and then during program execution I determine if a user is in that list. If they are, I do something, otherwise, I do nothing. In other words, I had a single discrete insertion phase, then I sorted, then after that I used std::binary_search (vector.begin(), vector.end(), std::string username) to determine whether the user is in the list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Parse img from RSS description tag with SAX Looking around i have found many tutorials about rss and img parsing from the inside of the description tag. My problem is that the app i m developing is homework for my college and i can only use SAX and not jSON as in the most examples. My RSS is working fine,but i cant load images.. So,my answers are two: 1)How to parse image from the description tag and 2)How to load it in the RSS activity. A: Try android.util.Xml . And take a look here how to use it http://www.ibm.com/developerworks/opensource/library/x-android/index.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7516736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: renaming my files from .htm to .php screws up the character encoding..? I was given the job to work in the SEO of a website that is entirely html and javascript. First thing I see, they have hardcoded the headers and the footers(which I want to edit) on every page. I decided that I want to change all the .htm files to .php in order to take advantage of the php include function and to include the header and the footer as a separate file into every page(yes I know that I could've modify the .htaccess file to treat .htm files as .php but there is a couple of more reasons I wanted .php). After the change, the special characters on the website started showing as question marks on black background or simply as a normal question mark. When I open the .php files from the cPanel of my host, i see at the top of the editor that encoding is UTF-8 so I don't understand what the problem is. What I do to fix this problem is some kind of "magic" that I hate and it doesn't always work from the first time - copy the code in the whole file, change the encoding to us-ascii, save(at this point the file becomes empty o.O), CLOSE, open back up, paste the code back, tell the editor to open it as utf-8(it creates a new file...), paste the code back in. Then the special characters(like cyrilic, etc.) are displayed properly. I don't want to do this for as many pages are on the website plus I want to understand the proper way to do it. Anyone can provide any help? A: The files encoding must match the charset declared by the HTTP header and the meta tags of your HTML files. Do you have something like this in your HTML: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> When you inspect the HTTP headers with Firebug (or anything else) do you see something like this (watch for "Content-Type"): Response Headers Date Thu, 22 Sep 2011 14:53:26 GMT Server Apache mod_fcgid/2.3.6 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 Expires Thu, 19 Nov 1981 08:52:00 GMT Cache-Control private, max-age=10800, pre-check=10800 Content-Language EN Last-Modified Fri, 22 Jul 2011 13:22:29 GMT Content-Type text/html; charset=UTF-8 When you open the file in your editor and you check it's charset, is it the same as above? Make sur that if you use UTF-8, no BOM are added to your files (at least for PHP files). I guess your editor messed thing up... Can you provide the URL to an actual page? It could help us to tell what's is exactly going on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In App Purchase How to avoid the purchasing of items which I already bought through INApp billing from android market.. That is the purchase should be avoided second time Thanks, Raj A: There are 2 types for items: Managed and unmanaged. If you choose Managed you can't charge twice for the same item. Read here for more info: http://developer.android.com/guide/market/billing/billing_admin.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7516740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting the HTML source from a WPF-WebBrowser-Control using IPersistStreamInit I am trying to get the HTML source of a webpage that has been loaded into a WPF WebBrowser control. The only way to do this seems to be casting the instance of WebBrowser.Document to IPersistStreamInit (which I will have to define myself, as it is a COM interface) and call the IPersistStreamInit.Save method, passing an implementation of an IStream (again, a COM interface), which will persist the document to the stream. Well, sort of: I am always getting the first 4 kilobytes of the stream, not the entire document and I don't know why. Here's the code of IPersistStreamInit: using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Security; namespace PayPal.SkyNet.BpiTool.Interop { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), SuppressUnmanagedCodeSecurity, Guid("7FD52380-4E07-101B-AE2D-08002B2EC713")] public interface IPersistStreamInit { void GetClassID(out Guid pClassID); [PreserveSig] int IsDirty(); void Load([In, MarshalAs(UnmanagedType.Interface)] IStream pstm); void Save([In, MarshalAs(UnmanagedType.Interface)] IStream pstm, [In, MarshalAs(UnmanagedType.Bool)] bool fClearDirty); void GetSizeMax([Out, MarshalAs(UnmanagedType.LPArray)] long pcbSize); void InitNew(); } } Here's the code of the IStream-Implementation: using System; using System.IO; using System.Runtime.InteropServices.ComTypes; namespace PayPal.SkyNet.BpiTool.Interop { public class ComStream : IStream { private Stream _stream; public ComStream(Stream stream) { this._stream = stream; } public void Commit(int grfCommitFlags) { } public void CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten) { } public void LockRegion(long libOffset, long cb, int dwLockType) { } public void Read(byte[] pv, int cb, IntPtr pcbRead) { this._stream.Read(pv, (int)this._stream.Position, cb); } public void Revert() { } public void SetSize(long libNewSize) { this._stream.SetLength(libNewSize); } public void Stat(out System.Runtime.InteropServices.ComTypes.STATSTG pstatstg, int grfStatFlag) { pstatstg = new System.Runtime.InteropServices.ComTypes.STATSTG(); } public void UnlockRegion(long libOffset, long cb, int dwLockType) { } public void Write(byte[] pv, int cb, IntPtr pcbWritten) { this._stream.Write(pv, 0, cb); } public void Clone(out IStream outputStream) { outputStream = null; } public void Seek(long dlibMove, int dwOrigin, IntPtr plibNewPosition) { this._stream.Seek(dlibMove, (SeekOrigin)dwOrigin); } } } Now I have a class to wrap it all up. As I don't want to redistribute the mshtml-interop-assembly I chose late-binding - and as late binding is easier in VB I did it in VB. Here's the code: Option Strict Off Option Explicit Off Imports System.IO Public Class HtmlDocumentWrapper : Implements IDisposable Private htmlDoc As Object Public Sub New(ByVal htmlDoc As Object) Me.htmlDoc = htmlDoc End Sub Public Property Document As Object Get Return Me.htmlDoc End Get Set(value As Object) Me.htmlDoc = Nothing Me.htmlDoc = value End Set End Property Public ReadOnly Property DocumentStream As Stream Get Dim str As Stream = Nothing Dim psi As IPersistStreamInit = CType(Me.htmlDoc, IPersistStreamInit) If psi IsNot Nothing Then str = New MemoryStream Dim cStream As New ComStream(str) psi.Save(cStream, False) str.Position = 0 End If Return str End Get End Property End Class Now I should be able to use all this: private void Browser_Navigated(object sender, NavigationEventArgs e) { HtmlDocumentWrapper doc = new HtmlDocumentWrapper(); doc.Document = Browser.Document; using (StreamReader sr = new StreamReader(doc.DocumentStream)) { using (StreamWriter sw = new StreamWriter("test.txt")) { //BOOM! Only 4kb of HTML source sw.WriteLine(sr.ReadToEnd()); sw.Flush(); } } } Anybody knows, why I don't get the entire HTML souce? Any help is greatly appreciated. Regards Arne A: Move your code from Browser.Navigated to Browser.LoadCompleted as Sheng Jiang correctly notes above and it works A: This is just a guess: The stream does not have a known length, since it may still be downloading. You'll need to read it until it says EOF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I decode html coded characters in an NSString? I am writing an app with both english and french support. The app requests information from a server and the server response uses JSON. I am using the JSONKit library to parse the response but the strings its parsing from the french responses look like this: Membres &#8211;&#201;conomisez 5% sur les services et jusqu&#8217;&#224; 15% sur d&#8217;autres produits How do I decode the special characters? so that I get this: Membres –Économisez 5% sur les services et jusqu’à 15% sur d’autres produits I looked at the API for NSString and tried some of the instance methods but I don't know much about character encodings and I ended up getting some weird results. So if you can also provide a brief explanation on character encodings I'd really appreciate it. Thanks in advance A: This solution worked well for me if you're still using Objective C code. - (NSString *)decodeHtmlStringValue { NSData *encodedString = [self dataUsingEncoding:NSUTF8StringEncoding]; NSAttributedString *htmlString = [[NSAttributedString alloc] initWithData:encodedString options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil]; return [htmlString string]; } If your using swift https://stackoverflow.com/questions/25607247/how-do-i-decode-html-entities-in-swift A: Check out these NSString categories A: NSString stringByReplacingPercentEscapesUsingEncoding with the correct string encoding should do the magic. [yourString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; might be a good candidate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Solution Configuration but not Platform in VS2010 Toolbar I'm running VS2010 premium. One of my teammates has both the solution configuration drop-down (Debug, Release) AND the platform (Win32, x64) combo-boxes in his toolbar. I don't. For a reference, I'm hoping to see: Instead, I only see the first combo-box. What do I need to configure to make the second one appear? A: I had the same issue, here is how I got the menu back * *On the menubar go to View → Toolbars → Customize... *Click on the "Commands" tab *Select the "Toolbar" radio button and find "Standard" in the drop down list *Click the "Add Command..." button *Select the "Build" category *Find and select the "Solution Platforms" command and click "OK" *Move your new command to a comfortable place on your toolbar using "Move Up" and "Move Down" *Enjoy not having to dig through Solution Properties to change the platform A: in my case the toolbar was not showing. the above answer helped me find a simpler solution VIEW > Toolbars > ✓ Standard
{ "language": "en", "url": "https://stackoverflow.com/questions/7516755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "62" }
Q: In C# how do I reference the port number configured in app.exe.config? In our server, we configure the port in app.config as follows: <configuration> <system.runtime.remoting> <application> <channels> <channel ref="tcp" port="1234" /> </channels> </application> </system.runtime.remoting> </configuration> We then proceed to configure the server with the following C# code: RemotingConfiguration.Configure(string.Format("{0}{1}", appFolder, "app.exe.config"), false); How do I reference the port number after it has been configured short of parsing the file by hand? A: Looks like it is possible after all. After calling RemotingConfiguration.Configure(string, bool), I run the following method: private string GetPortAsString() { // Parsing System.Runtime.Remoting.Channels.IChannel[] channels = System.Runtime.Remoting.Channels.ChannelServices.RegisteredChannels; foreach (System.Runtime.Remoting.Channels.IChannel c in channels) { System.Runtime.Remoting.Channels.Tcp.TcpChannel tcp = c as System.Runtime.Remoting.Channels.Tcp.TcpChannel; if (tcp != null) { System.Runtime.Remoting.Channels.ChannelDataStore store = tcp.ChannelData as System.Runtime.Remoting.Channels.ChannelDataStore; if (store != null) { foreach (string s in store.ChannelUris) { Uri uri = new Uri(s); return uri.Port.ToString(); // There should only be one, and regardless the port should be the same even if there are others in this list. } } } } return string.Empty; } This gives me the TcpChannel info I need, which allows me to grab the ChannelUri and get the port. GRAIT SUCCESS! A: You can only configure through code or configuration, you can't do both. This means you can't access the configured details via code, (without passing the xml file yourself). A: I've just taken a look at the ConfigurationManager to help get the values you need...unfortunately it doesnt look like there is a sectionGroup for system.runtime.remoting: ie, this call fails: var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var sectionGroup = cfg.GetSectionGroup("system.runtime.remoting"); So it doesn't appear to me you can use anything existing in the framework to extract it nicely. I'm unsure why this sectionGroup doesnt exist in-code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: set UITableView image I am trying to load locally stored images in a background thread and set them as UITableViewCell images. I keep getting an exception and don't really know how to approach it. Here is my code: - (void)loadImageInBackground:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *path = [[tableImages objectAtIndex:indexPath.section]objectAtIndex:indexPath.row]; UIImage *img = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:path ofType:@"png"]]; [self performSelectorOnMainThread:@selector(assignImageToImageView:) withObject:img waitUntilDone:YES]; [img release]; [pool release]; } - (void) assignImageToImageView:(UIImage *)img { UITableViewCell *cell = (UITableViewCell *)[self.tableView viewWithTag:0]; ((UIImageView *)cell.imageView).image = img; } Anyone have any ideas? Thanks to all! A: As is mention in your error you are trying to set image to object of class UITableView. It is impossible. In your code it is error here: UITableViewCell *cell = (UITableViewCell *)[self.tableView viewWithTag:0]; By default all views has default view tag set to 0. When your are calling that method to your tableView it returns you first UIView with tag == 0. I think you didn't change default tag of your UITableView *tableView so that method returns you tableView and not UITableViewCell. In this case, you need to choose right way to access appropriate UITableViewCell *cell;.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: After pausing the gstreamer pipeline and make changes nothing was applied when get back to playing state? The code below is to stream mpeg4 video (using v4l2src element of the following capabilities: width=640, height=480, frame rate=30/1) over a network using a updsink element and the capabilities values should change to (width=352, height=288, frame rate=15/1) after pressing "1" on the keyboard. I tried to do this by pausing the pipeline after the "1" is pressed and then re-setting the caps to the new values and then get the pipeline into playing state again but this did not work for me. I get the caps values printed before pausing the pipeline and after the changes made and I can see that the changes to the caps were done but not applied when the pipeline is brought to playing state again () please help....... you can playback this stream by typing into a new terminal the following command just before running the code below: gst-launch udpsrc multicast-group=127.0.0.1 port=8999 ! mpeg4videoparse ! ffdec_mpeg4 ! ffmpegcolorspace ! autovideosink ====================== #include <gst/gst.h> #include <glib.h> #include <stdio.h> #include <glib-object.h> static gboolean bus_call (GstBus *bus, GstMessage *msg, gpointer data) { GMainLoop *loop = (GMainLoop *) data; switch (GST_MESSAGE_TYPE (msg)) { case GST_MESSAGE_EOS: g_print ("End of stream\n"); g_main_loop_quit (loop); break; case GST_MESSAGE_ERROR: { gchar *debug; GError *error; gst_message_parse_error (msg, &error, &debug); g_free (debug); g_printerr ("Error: %s\n", error->message); g_error_free (error); g_main_loop_quit (loop); break; } default: break; } return TRUE; } int main (int argc, char *argv[]) { GMainLoop *loop; GstElement *pipeline, *source, *filter, *vrate, *encoder, *conv, *sink; GstBus *bus; GstCaps *filtercaps; gint width, height, num, denom; const GstStructure *str; /* Initialisation */ gst_init (&argc, &argv); loop = g_main_loop_new (NULL, FALSE); /* Check input arguments */ if (argc != 2) { g_printerr ("Usage: %s <Ogg/Vorbis filename>\n", argv[0]); return -1; } /* Create gstreamer elements */ pipeline = gst_pipeline_new ("video-player"); source = gst_element_factory_make ("v4l2src", "file-source"); vrate = gst_element_factory_make ("videorate", "video-rate"); filter = gst_element_factory_make ("capsfilter", "filter"); conv = gst_element_factory_make ("ffmpegcolorspace","converter"); encoder = gst_element_factory_make ("ffenc_mpeg4","mpeg-decoder"); sink = gst_element_factory_make ("udpsink","audio-output"); if (!pipeline || !source || !filter || !vrate || !conv || !encoder || !sink) { g_printerr ("One element could not be created. Exiting.\n"); return -1; } /* Set up the pipeline */ /* we set the input filename to the source element */ filtercaps = gst_caps_new_simple ("video/x-raw-yuv", "width", G_TYPE_INT, 640, "height", G_TYPE_INT, 480, "framerate", GST_TYPE_FRACTION, 30, 1, NULL); g_object_set (G_OBJECT (filter), "caps", filtercaps, NULL); gst_caps_unref (filtercaps); g_object_set (G_OBJECT (encoder), "bitrate" , 384 , NULL); g_object_set (G_OBJECT (sink), "host" , argv[1] , NULL); g_object_set (G_OBJECT (sink), "port" , 8999 , NULL); g_object_set (G_OBJECT (sink), "async" , FALSE , NULL); /* we add a message handler */ bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); gst_bus_add_watch (bus, bus_call, loop); gst_object_unref (bus); /* we add all elements into the pipeline */ /* file-source | ogg-demuxer | vorbis-decoder | converter | alsa-output */ gst_bin_add_many (GST_BIN (pipeline), source, vrate, filter, conv, encoder, sink, NULL); /* we link the elements together */ /* file-source -> ogg-demuxer ~> vorbis-decoder -> converter -> alsa-output */ gst_element_link_many (source, vrate, filter, conv, encoder, sink, NULL); /* Set the pipeline to "playing" state*/ g_print ("Now playing: \n"); gst_element_set_state (pipeline, GST_STATE_PLAYING); /* Print out the frame size and rate */ str = gst_caps_get_structure (filtercaps, 0); if (!gst_structure_get_int (str, "width", &width) || !gst_structure_get_int (str, "height", &height) || !gst_structure_get_fraction (str, "framerate", &num, &denom)) g_print ("No width/height available\n"); g_print ("The video size of this set of capabilities is %dx%d and the frame rate is %d/%d\n", width, height, num, denom); /* Pausing the streame */ int in; if (scanf ("%d", &in) == 1){ g_print ("Now pausing: \n"); gst_element_set_state (pipeline, GST_STATE_PAUSED ); g_assert (GST_STATE (pipeline) == GST_STATE_PAUSED); g_assert (GST_STATE (source) == GST_STATE_PAUSED); g_assert (GST_STATE (filter) == GST_STATE_PAUSED); g_assert (GST_STATE (vrate) == GST_STATE_PAUSED); g_assert (GST_STATE (encoder) == GST_STATE_PAUSED); g_assert (GST_STATE (conv) == GST_STATE_PAUSED); g_assert (GST_STATE (sink) == GST_STATE_PAUSED); /* apply the alterations to the caps now */ gst_caps_set_simple (filtercaps, "width", G_TYPE_INT, 352, "height", G_TYPE_INT, 288, "framerate", GST_TYPE_FRACTION, 15, 1, NULL); /* Print out the frame size and rate after alteration*/ str = gst_caps_get_structure (filtercaps, 0); if (!gst_structure_get_int (str, "width", &width) || !gst_structure_get_int (str, "height", &height) || !gst_structure_get_fraction (str, "framerate", &num, &denom)) g_print ("No width/height available\n"); g_print ("The video size of this set of capabilities is %dx%d and the frame rate is %d/%d\n", width, height, num, denom); /* set back to playing */ gst_element_set_state (pipeline, GST_STATE_PLAYING); g_assert (GST_STATE (pipeline) == GST_STATE_PLAYING); g_assert (GST_STATE (source) == GST_STATE_PLAYING); g_assert (GST_STATE (filter) == GST_STATE_PLAYING); g_assert (GST_STATE (vrate) == GST_STATE_PLAYING); g_assert (GST_STATE (encoder) == GST_STATE_PLAYING); g_assert (GST_STATE (conv) == GST_STATE_PLAYING); g_assert (GST_STATE (sink) == GST_STATE_PLAYING); } /* Iterate */ g_print ("Running...\n"); g_main_loop_run (loop); /* Out of the main loop, clean up nicely */ g_print ("Returned, stopping playback\n"); gst_element_set_state (pipeline, GST_STATE_NULL); g_print ("Deleting pipeline\n"); gst_object_unref (GST_OBJECT (pipeline)); return 0; } Cheers. Ibra A: you miss the function of g_object_set(G_OBJECT(filter), "caps", filtercaps, NULL);
{ "language": "en", "url": "https://stackoverflow.com/questions/7516766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to authorise user from the forum's main page? I'm trying to implement a simple blog, which contains topics models/Topic.cs public class Topic { public int ID {get; set;} [StringLength(50)] [RequiredAttribute(ErrorMessage = "*")] public string Title {get; set;} [StringLength(1024)] [RequiredAttribute(ErrorMessage = "*")] public string Body { get; set; } public int CommentsCount { get; set; } public DateTime TimeLastUpdated { get; set; } public int AuthorID { get; set; } public virtual List<Comment> commentsList { get; set; } } Main Page looks like a list of topics. Controllers/HomeController.cs public class HomeController : Controller private ContentStorage db = new ContentStorage(); public ViewResult Index() { // Topics = DbSet<Topic> Topics { get; set; } return View(db.Topics.ToList()); } [HttpPost] public void LogIn(string login, string password) { int i; i = 10; } } Main page's view is very simple. Views/Home/Index @model IEnumerable<MvcSimpleBlog.Models.Topic> ... <table width="95%" height="86" border="0"> <tr> <td width="45%" valign = "bottom" >Login:</td> <td width="45%" valign = "bottom" >Password:</td> <td width="10%"></td> </tr> <tr> <td width="45%"><p> <input type="text" name="login" /> </p></td> <td width="45%"><p><input type="password" name="password" /></p></td> <td width="10%" align = "left"> @using (Html.BeginForm("LogIn", "Home")) { <input type = "submit" value = "Enter" /> } </td> </tr> <tr> <td width="45%" valign = "top" >@Html.ActionLink("Register", "Register", "Account")</td> </tr> </table> How could i pass the values from edit boxes in the View to the HomeController method? The method "LogIn" was supposed to receive data from the view, call the "Account" controller, passing user's login and password to it. An "Account" controller shoud validate this user and redirect browser to the main page with topics. But i can't access login and password edit boxes in the view... and i really don't know what should i do, and is my model correct A: Those input fields should be inside your Html.BeginForm if you want their values to be posted to the server when the form is submitted. Currently you only have a single submit button inside your form. So: @using (Html.BeginForm("LogIn", "Home")) { <table width="95%" height="86" border="0"> <tr> <td width="45%" valign="bottom">Login:</td> <td width="45%" valign="bottom">Password:</td> <td width="10%"></td> </tr> <tr> <td width="45%"> <p> <input type="text" name="login" /> </p> </td> <td width="45%"> <p> <input type="password" name="password" /> </p> </td> <td width="10%" align="left"> <input type="submit" value="Enter" /> </td> </tr> <tr> <td width="45%" valign="top"> @Html.ActionLink("Register", "Register", "Account") </td> </tr> </table> } Now your LogIn controller action could receive the 2 values as action parameters like so: [HttpPost] public ActionResult LogIn(string login, string password) { ... perform authentication }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: replacing a custom tag's value with a string in php I want to read a html file and replace what ever is inside mytag. so in html file we have something like this : <div> <h3><mytag>_THIS_DAY</mytag></h3> <div> [LOGIN] </div> </div> and then in php file , i need to read the file and replace the values inside tags. str_replace() ? how to get the value inside those tags in php and then how to replace them with something like a string ? A: str_replace() uses regular expressions, which (as noted elsewhere on this site) are usually insufficient for parsing HTML. You should use an HTML parser to retrieve and/or replace the required values. A: Warning: You shouldn't parse XHTML with regexp That said, you can still do it: preg_replace("~(?<=<mytag>)[^>]+(?=</mytag>)~", "independance day", $yourHtml); Quick explanation: * *[^>]+ We look for a string of 1+ char and without > *(?<=<mytag>) This string must be after <mytag> (positive lookahead) *(?=</mytag>) This string must be folowed by </mytag> (positive lookbehind) Live example A: * *take a look in the php-manual fpr preg_replace. with a regex you can perform a simple replacement *if you want to something more complex, you can parse your html. you can use for example the simple_html_dom-contribution: http://simplehtmldom.sourceforge.net/
{ "language": "en", "url": "https://stackoverflow.com/questions/7516770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mysql get things after certain date So, I have a database table holding tickets. One of the fields is "availableUntil". when I make the database call to get tickets, I want to be able to exclude those tickets who's date has already been passed relative to the current date. Anyone know of a way to do this? A: SELECT blablabla... WHERE availableUntil >= CURRENT_TIMESTAMP A: SELECT [what_you_want] FROM your_base WHERE availableUntil > CURRENT_DATE();
{ "language": "en", "url": "https://stackoverflow.com/questions/7516774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Delphi 32 to Delphi XE2 (64 bit) conversion I'm looking at migrating a Delphi 2007 business applications to 64 Bit using Delphi XE2. I wanted to know if there are any guidelines which will help to developers or companies, who are considering migration of there Delphi applications to 64 bit with Delphi XE2. Any help in this regard will be highly appreciated. A: Addtionally to the answer of David you can check the documentation of Embarcadero about this topic * *Delphi 64-bit compiler Sneak preview (Video) *Converting 32-bit Delphi Applications to 64-bit Windows *64-bit Cross-Platform Application Development for Windows *64-bit Windows "Hello World" Cross-Platform Application A: Here is my advice. * *First of all port the application to 32 bit Unicode. *Then, port to 64 bit. I would expect step 1 to be harder than step 2. For step 1 there is Marco Cantù's Unicode whitepaper. I'm not aware of anything similar yet for 64 bit. I strongly urge you to keep these two porting tasks separate. Smaller independent tasks are always easier than one bigger combined task. Regarding the 64 bit port I can think of the following issues to deal with: * *All 3rd party libraries need updating. *All inline assembler will need attention. *Access to Windows API functions need looking at. A common idion is to pass Integer(MyObject). That needs to be replaced with NativeInt(MyObject). Other than that I don't think there is much to be concerned about. The Unicode port is likely to be far more problematic. Barry Kelly's answer here puts some more flesh on this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: awk between 2 timestamps New to awk I am trying to print only the lines from a logfile with the first field between these 2 values: awk '{print $0($1 > 1300000000) && ($1 < 1305000000)}' Log2.log and...its not right. A: awk '1300000000 < $1 && $1 < 1305000000' Log2.log Style :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7516781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Authentication fails silently in Symfony2 I'm having trouble getting authentication to work but it only appears to happen in very specific circumstances. Authentication is done via a third party API so I've written my own user provider class and inside that class is some code that syncs data between the API and Symfony, as part of that syncing process it determines which roles the user should have. After doing this it sets up the relationships between the roles and user via a ManyToMany relationship. The getRoles() method in my User object gets the role objects out of the database and turns it into an array of strings, the role names come from my database and all start with ROLE_. If I login with an account that should have no extra roles it works fine, but if I login to an account that should have roles I just get sent back to the login screen with no error message. I've checked the log and saw these entries: security.INFO: User "test105@example.com" has been authenticated successfully [] [] event.DEBUG: Notified event "security.interactive_login" to listener "Pogo\MyBundle\Listener\LoginListener::onSecurityInteractivelogin". [] [] event.DEBUG: Listener "Symfony\Component\Security\Http\Firewall::onKernelRequest" stopped propagation of the event "kernel.request". [] [] event.DEBUG: Listener "Symfony\Bundle\FrameworkBundle\EventListener\RouterListener" was not called for event "kernel.request". [] [] event.DEBUG: Listener "Symfony\Bundle\AsseticBundle\EventListener\RequestListener" was not called for event "kernel.request". [] [] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\Security\Http\Firewall\ContextListener::onKernelResponse". [] [] security.DEBUG: Write SecurityContext in the session [] [] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse". [] [] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bundle\SecurityBundle\EventListener\ResponseListener::onKernelResponse". [] [] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bridge\Monolog\Handler\FirePHPHandler::onKernelResponse". [] [] event.DEBUG: Notified event "kernel.response" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\CacheListener::onKernelResponse". [] [] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse". [] [] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener::onKernelResponse". [] [] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\RouterListener::onEarlyKernelRequest". [] [] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest". [] [] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest". [] [] security.INFO: Populated SecurityContext with an anonymous Token [] [] event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\Security\Http\Firewall\ExceptionListener::onKernelException". [] [] security.DEBUG: Access denied (user is not fully authenticated); redirecting to authentication entry point [] [] security.DEBUG: Calling Authentication entry point [] [] I don't understand how it can be authenticated at top, then as soon as it checks the firewall it finds itself with an anonymous token which is why it presumably sends me back to the login screen. My firewall / access_control settings are: firewalls: public: pattern: /.* anonymous: true tessitura_login: login_path: /account/login check_path: /secure/login_check logout: path: /secure/logout target: / access_control: - { path: ^/secure/.*, role: ROLE_USER } - { path: ^/admin.*, role: ROLE_ADMIN } - { path: ^/account/login/?, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: /.*, role: IS_AUTHENTICATED_ANONYMOUSLY } Any help with this would be massively appreciated, I've spent a few hours on this now and am completely stumped. A: Got this silent fail issue when was using phone number as username and didn't specified username property in refreshUser() method, which should be: public function refreshUser(UserInterface $customer) { $class = get_class($customer); if( !$this->supportsClass($class) ) { throw new UnsupportedUserException("Instances of \"{$class}\" are not supported"); } return $this->loadUserByUsername($customer->getPhoneNumber()); // <-- This is it! } I think I'm not the only one who missed it, might help. A: A broken session storage caused this for me. I was using PdoSessionHandler and disappointingly it gave no clear error or log message. A: I've experienced the same. When my users logs in I check what role he has with a couple of statements like this: if(true === $this->get('security.context')->isGranted('ROLE_MANAGER')){ //return redirect } if(true === $this->get('security.context')->isGranted('ROLE_USER')){ //return redirect } //throw error Time to time some users get an error thrown in their face. I imagine that it is because of the same reason. The user is somehow authenticated but haven't got their role. I can't reproduce the problem my self. I have just heard error reports from my users. A: I've experienced the same. And for me it was because the /tmp partition was full so the session can be store on server side and avter redirect to the nex A: I just experienced the same issue when logging in to my system where sessions are configured to be stored in memcache but memcached was not running. As said above unfortunately it gave no better error message. Hope that helps someone to save some time ;-) A: I had the same issue with the user login i have used the sonata admin bundle and i was also using the database session with PdoSessionHandler session.handler.pdo: class: Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler arguments: ["@pdo", %pdo.db_options%] First issue i got when i create a group with lot of roles/permissions the data truncated in the field so i alter my roles field with longtext and changed the ROW_FORMAT=COMPRESSED ALTER TABLE `fos_group` CHANGE `roles` `roles` LONGTEXT NOT NULL COMMENT '(DC2Type:array)'; ALTER TABLE `fos_group` ENGINE=INNODB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8; It does the job and save all the roles/permissions into the field as complete serialized string.But user was unable to login with no error message then i have review the logs generated by symfony in app/logs dir it has user has been authenticated successfully and then redirect to dashboard but from dashboard the logs generated as access denied (user is not fully authenticated) the reason was the session data is truncated in the session table so i alter my session table as well and this does the job ALTER TABLE `session` CHANGE `session_value` `session_value` LONGTEXT NOT NULL; ALTER TABLE `session` ENGINE=INNODB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8; I have also updated my.ini file and changed the file format to Barracuda by default file format is antelop [mysqld] innodb_file_per_table innodb_file_format = Barracuda
{ "language": "en", "url": "https://stackoverflow.com/questions/7516787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: http post request not sending parameters in Blackberry 5.0 I've been working on a BlackBerry post request, and the request is getting sent, but the parameters don't seem to be. Here is my code: HttpConnection httpConnection = (HttpConnection) Connector.open(url); httpConnection.setRequestMethod(HttpConnection.POST); httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false); encPostData.append("time", "1314144000"); System.out.println("url: " + httpConnection.getURL()); byte[] postData = encPostData.toString().getBytes("UTF-8"); System.out.println("post data: " + encPostData.toString()); httpConnection.setRequestProperty("Content-length", String.valueOf(postData.length)); System.out.println("url: " + httpConnection.getURL()); System.out.println("message:" + httpConnection.getResponseMessage()); OutputStream os = httpConnection.openOutputStream(); os.write(postData); os.flush(); os.close(); The response I get from the server(which we set up) is that we didn't send a time stamp. Is there something wrong with my encPostData.append("time", "1314144000"); code? A: Your call to getResponseMessage() before writing the post data is forcing a response before anything has been written on the connection. System.out.println("message:" + httpConnection.getResponseMessage()); Move that to the end, after the output stream data has been written, and I think it will work better for you. A: Make the http connection in read write mode.Might be that is the problem making http connection without mode link HttpConnection connection = (HttpConnection) Connector.open("url", Connector.READ_WRITE); See below link for making http connection. blackberry server connection problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7516789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Open mail in Outlook, through URL. Using Exchange Webservice I'm trying to get a intranet page to open an mailitem in the Outlook client. We are using Exchange Webservices(EWS), and communicating with an Exchange 2007 server. What we have done so far, is to be able to read top 5 mailitems from an inbox, and displaying these on a webpage. What we would like to do is to get the list of mailitems to link directly into Outlook. This means that when the user clicks a link to an email, Outlook should open, and open the specific mailitem. We have registered the outlook protocol, and we have general links will open the Outlook client. By general links i mean outlook:inbox will open Outlook and open the inbox, and outlook:calendar will open Outlook and open the calendar. From each mailitem, ive tried to call outlook:itemidtype.id, but this doesn't work. Anyone got a clue on how to open the mailitem? A: Haven't tried this myself, but Outlook uses the MAPI EntryId to locate an item. You can retrieve this value using an extended property. http://msdn.microsoft.com/en-us/library/bb446027.aspx A: Microsoft documents the /f switch for command line access to a message, but helpfully fails to provide a real world example I can't get /f to work, and think it is broken. Anyone have an example of this, instead of MS useless doc of "/f msgfilename"
{ "language": "en", "url": "https://stackoverflow.com/questions/7516792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP Array special value Solution Possible Duplicate: PHP compare HTML characters array Solution I got a value stored in $arrNew[4], I want to check if the value currently stored in $arrNew[4] is equal to another value. The problem is, the value in arrNew[4] isn't there most of the times, so i want it as a string so i can use it on other parts. example $string = "text" I want "text". The same goes with $arrNew[4] But if I echo $arrNew[4] out I get "vrij &nbsp &nbsp " It isn't the same as in $arrNew[4] because I can't do $forNew == "vrij &nbsp &nbsp " it doesn't equal TRUE but $forNew == $arrNew[4] does. So how should I get the value stored in $arrNew[4] to a string, without it being changed. (probably cause of special characters?) How should I do this ? Any help is appreciated :) foreach ($arrNew as $forNew) { $forCount = $forCount + 1 ; if($forNew == $arrNew[4]) { echo "Vrij: ".$arrOld[$forCount] ; } } A: The problem is, the value in arrNew[4] isn't there most of the times, You should explain why. so i want it as a string so i can use it on other parts. Why do you think that not having it as a string will not allow you to use it elseehere, please explain. But if I echo $arrNew[4] out I get "vrij &nbsp &nbsp " Echoing a variable and getting &nbsp in the browser is sure there is an important piece of information that you don't display, please show it (sounds like something related html specialchar). It isn't the same as in $arrNew[4] because I can't do $forNew == "vrij &nbsp &nbsp " it doesn't equal TRUE but $forNew == $arrNew[4] It seems that apart from php you have some work to do on expressing your self, describing and presenting a problem in an understoodable way. So how should I get the value stored in $arrNew[4] to a string, without it being changed. Just undo whatever you did on storage, I suspect it doesn't get a value assigned in a trvial way but insted through an html specialchar function. Finally take serious consideration on writing good question, put your self in others position.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: memcache alongwith PHPCassa I am using PHPCassa to get values out of my cassandra instance where my result array looks something like : Array ( [1576_AF_ACTS_A300_2011-09-12] => 150 [1576_AF_ACTS_A300_2011-09-13] => 1565 [1576_AF_ACTS_A300_2011-09-14] => 1515 [1576_AF_ACTS_A300_2011-09-15] => 1519 [1562_AF_ACTS_A300_2011-09-12] => 1510 [1561_AF_ACTS_A300_2011-09-13] => 15189 [1563_AF_ACTS_A300_2011-09-14] => 15189 [1568_AF_ACTS_A300_2011-09-15] => 15125 [121_AF_ACTS_A300_2011-09-16] => 15123 [1580_AF_ACTS_A300_2011-09-12] => 15127 [1580_AF_ACTS_A300_2011-09-15] => 15189 [1580_AF_ACTS_A300_2011-09-17] => 15158 ) Now, I want to store my result in memcache . What unique memcache key should I frame for this ? What I have got at my disposal is an endless array of keys which I frame based on some input parameters from a UI form. How can I save this information alongwith a unique memcache key? A: I would recommend avoiding memcache in favor of Cassandra's row cache: http://www.datastax.com/docs/0.8/configuration/storage_configuration#rows-cached This gives you a simpler architecture that avoids the cache coherence problems you get from a two-layer system.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails App incremental ticket number for different accounts I have a multi-tenant Rails app that creates support tickets. The tickets are supposed to have incremetal ticket numbers. I can't use the ID column, because since the app will be used by different accounts, they will find odd ticket numbers. For example, if Account 1 creates two tickets, they get Ticket #1 and Ticket #2. Account 2 creates one ticket, he gets Ticket #3. (That would be odd because he's supposed to get Ticket #1, because it's the first ticket he creates under his account). So, I'm supposed to add a ticket_number column to the tickets table. Now, how would you go about incrementing the numbers automatically and being separated from other accounts? A: class Ticket after_create :increment_tickets def increment_ticket Account.increment_counter(:ticket_number, self.account_id) end end A: The solution should be that your customer table (you have to have one, for to be multi-tenant) should be expanded by the following migration: class AddCounter < ActiveRecord:Migration def self.up add_column :accounts, :ticket_counter, :integer add_column :tickets, :ticket_number, :integer end end Every time, you create a ticket for the customer, you have to increment the ticket number. See the post of @fl00r. The creation of the Ticket should go like that (code from a controller of mine): class TicketController def create #Here comes your addition: params[:ticket][:ticket_number]= Account.find(session[:account_id]).ticket_counter # Here comes the rest @article = Ticket.new(params[:ticket]) ... end end The context here is: * *You have to know which is the current account (see session[:account_id], if you have other stores for the current account, use that). *The ticket is created with the ticket_counter in the params[:ticket] hash. *After the creation, the counter in the account is incremented (see the answer of @fl00r).
{ "language": "en", "url": "https://stackoverflow.com/questions/7516798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL & PHP Get Num of Records for Each Type I have a MySQL database table which holds 6 types of records I need to get the total number of records for each of the types and then create a variable for each one of the results so for example wt = 3 spv = 33 shw = 78 and so on.. I have written this code $tquery = "SELECT equipment, COUNT(id) AS num FROM contract GROUP BY equipment"; $tresult = mysql_query($tquery) or die(mysql_error()); while($trow = mysql_fetch_array($tresult)){ echo "There are ". $trow['COUNT(id)'] ." ". $trow['equipment'] ." items."; echo "<br />"; } The reason for needing a variable for each type is that I need to work out a percentage value to show this data in a chart, I have written this code and it works fine as long as I have the correct data from the table. Any help would be awesome thanks A: Firstly, where you're referencing $trow['COUNT(id)'], this is incorrect; it should be coming back to you with the name num (as defined in your SQL query), so you should actually be using $trow['num']. Now to store your totals: Create an array to contain your totals. Lets call it $total. Define it as an empty array outside the while loop: $total = array(); Then inside the loop, assign a new element for the $total array containing the equipment type as the key, and the count as the value: $total[$trow['equipment']] = $trow['num']; When the loop is finished, you should then have an array containing all the totals, which you can perform calculations on. PHP provides you with the array_sum() and count() functions (among plenty of other handy functions) which should be enough to get you started with working out averages and percentages. hope that helps. A: Try something like : $tquery = "SELECT equipment, COUNT(id) AS num FROM contract GROUP BY equipment"; $tresult = mysql_query($tquery) or die(mysql_error()); while ($tabl = mysql_fetch_array($tresult)){ echo "There are " . $tabl['num'] . " of " . $tabl['equipment'] . ".<br />"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaScript Bookmarklet to open new Window and transmit params of origin Page I have a perfectly working bookmarklet to grab the Document-Title and the URL of the current Website and place it into the URL of the new loaded Page (Code below) … now I wonder how to let this domain.com/bookmarklet?… open in a new small window (600x600px), so that I still see the old website from where I grabed the title and url in the background and have the new page (domain.com/bookmarklet?…) in the foreground. javascript:location.href='http://domain.com/bookmarklet?url='+encodeURIComponent(location.href)+';title='+encodeURIComponent(document.title) How can I achieve that? A: Use window.open(...) instead of setting location.href = .... A: you need to use window.open() for that javascript:window.open ("http://domain.com/bookmarklet?.......","MyBookmarklet");
{ "language": "en", "url": "https://stackoverflow.com/questions/7516801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Debugging with multiple library versions in intellij We have a large maven project and not all of the projects specify the same version of various libraries, largely because these libraries haven't changed in some time. This causes problems with debugging because IntelliJ frequently selects the older version when it's the newer that's being used at runtime. Aside from fixing the poms, how can we get IntelliJ to resolve to the sources for the correct version of the library. A: There is no way to do it except configuring your project dependencies correctly (to use the same library version in all the modules).
{ "language": "en", "url": "https://stackoverflow.com/questions/7516802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Perlin noise for motion? I'm successfully using Perlin noise to generate terrain, clouds and a few other nifty things. However, I'm now trying to animate a group of flying insects (specifically fireflies), and it was suggested to me to use Perlin noise for this, as well. However, I'm not really sure how to go about this. The first thing that occurred to me was, given a noise map like so: * *Assign each firefly a random initial location, velocity and angular acceleration. *On frame, advance the fly's position following its direction vector. *Read the noise map at the new location, and use it to adjust the angular acceleration, causing the fly to "turn" towards lighter pixels. *Adjust angular acceleration again by proximity of other flies to avoid having them cluster around local maximums. However, this doesn't cover cases where flies reach the edge of the map, or cases where they might wind up just orbiting a single point. The second case might not be a big deal, but I'm unsure of a reliable way to have them turn to avoid collisions with the map edge. Suggestions? Tutorials or papers (in English, please)? A: Here is a very good source for 2D perlin noise. You can follow the exact same principles, but instead of creating a 2D grid of gradients, you can create a 1D array of gradients. You can use this to create your noise for a particular axis. Simply follow this recipe, and you can create similar perlin noise functions for each of your other axes too! Combine these motions, and you should have some good looking noise on your hands. (You could also use these noise functions as random accellerations or velocities. Since the Perlin noise function is globally monotonous, your flies won't rocket off to crazy distances.) http://webstaff.itn.liu.se/~stegu/TNM022-2005/perlinnoiselinks/perlin-noise-math-faq.html If you're curious about other types of motion, I would suggest Brownian Motion. That is the same sort of motion that dust particles exhibit when they are floating around your room. This article gets into some more interesting math at the end, but if you're at all familliar with Matlab, the first few sets of instructions should be pretty easy to understand. If not, just google the funcitons, and find their native equivalents for your environment (or create them yourself!) This will be a little more realistic, and much quicker to calculate than perlin noise http://lben.epfl.ch/files/content/sites/lben/files/users/179705/Simulating%20Brownian%20Motion.pdf Happy flying! A: Maybe you're looking for boids? Wikipedia page It doesn't feature Perlin noise in the original concept, maybe you could use the noise to generate attractors or repulsors, as you're trying to do with the 'fly to lighter' behavior. PS: the page linked above features a related link to Firefly algorithm, maybe you'll be interested in that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7516810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How can I round up a figure in Java? Hello I am new to android. I want to calculate amount in my application. If amount is 35.60 I want to display 36.00 .& if amount is 35.4 I want to display 35.00. How can i do this? Please help me. A: You just need to use the Math.round() method: Math.round(35.6) returns 36 and Math.round(35.4) returns 35 as you require. A: A pretty standard way of doing that, if you don't know about any rounding function, is to add 0.5 and convert to int, like so: int rounded = (int)(value + 0.5) A: For flexibility in rounding, consider using BigDecimal like below: BigDecimal foo = new BigDecimal(2432.77112).setScale(2, BigDecimal.ROUND_HALF_UP); double myNativeDouble = foo.doubleValue(); There are other rounding methods available to choose from, check the javadocs for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to reroute a Jersey JSP template response to an InputStream? All, I am using Java/Jersey 1.9 to create a web service that generates XML. I'm generating XML using a JSP template (explicitly via the Viewable class). Is there any way to reroute the JSP results to a local InputStream for further processing? At the moment I'm actually calling my own XML web service as an http loopback (localhost) from a different method. Thanks for any insights, Ian @GET @Path("kml") @Produces("application/vnd.google-earth.kml+xml") public Viewable getKml( @QueryParam("lat") double lat, @QueryParam("lon") double lon, @QueryParam("alt") double alt) { overflights = new SatelliteOverflightModel( context, new SatelliteOverflightModel.Params(lat, lon, alt) ).getOverflights(); return new Viewable("kml", this); } @GET @Path("kmz") @Produces("application/vnd.google-earth.kmz") public InputStream getKmz(@Context UriInfo uriInfo, @QueryParam("lat") double lat, @QueryParam("lon") double lon, @QueryParam("alt") double alt) throws IOException { Client client = Client.create(); WebResource webr = client.resource(uriInfo.getBaseUri()+"overflights/kml"); InputStream result = webr.queryParams(uriInfo.getQueryParameters()).get(InputStream.class); // Do something with result; e.g., add to ZIP archive and return return result; } A: You can consider using a ContainerResponseFilter for this instead of a resource - see e.g. the Gzip filter Jersey provides. The difference would be that your filter would depend on Accept and Content-Type headers instead of Accept-Encoding and Content-Encoding headers (like the gzip filter does). If you insist on using the resource, you can inject Providers interface on your resource, find the right MessageBodyWritter and call the write method on it: @GET @Path("kmz") @Produces("application/vnd.google-earth.kmz") public InputStream getKmz(@Context UriInfo uriInfo, @QueryParam("lat") double lat, @QueryParam("lon") double lon, @QueryParam("alt") double alt, @Context Providers providers, @Context HttpHeaders headers) throws IOException { Viewable v = getKml(lat, lon, alt); MessageBodyWriter<Viewable> w = providers.getMessageBodyWriter(Viewable.class, Viewable.class, new Annotation[0], "application/xml"); OutputStream os = //create the stream you want to write the viewable to (ByteArrayOutputStream?) InputStream result = //create the stream you want to return try { w.writeTo(v, v.getClass(), v.getClass(), new Annotation[0], headers, os); // Do something with result; e.g., add to ZIP archive and return } catch (IOException e) { // handle } return result; } DISCLAIMER: This is off the top of my head - untested :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7516819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Return identity value from an insert in a generalized way in C# I'd like to be able to get the identity value back after calling an insert statement. I can do this now and it works fine with SQL server by adding SET @RETURN_VALUE = SCOPE_IDENTITY() and using an out parameter. The problem is that this would only work with SQL server and I need to support Oracle and SQLite as well. Now I know could write separate code for each but is there a generic way to do this in .NET? Java for example has a getGeneratedKeys method which can be called after the insert, returning a result set of generated column names and values. Any similar construct in .NET? TIA A: Unfortunately each DBMS has its own specific way of retrieving the last inserted identity value, so you have to write specific code for each DBMS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ScaleToFit Layout Quandry I'm try learn to more about the Android layout system; this is a learning experience for me. I'm currently trying to create a layout which basically amounts to two linear layouts: A fill_parent vertical, with an inner fill_width horizontal, so that I have an ImageView banner [in the outer], then seven ImageButton columns filling the width of the view [in the inner]. My issue comes, as I need the ImageButton's content to proportionally fill the entire button view [the columns], but respect the ImageButton boundaries, so that if either a small or big image is the source, it will be centered in the ImageButton, filling both it's vertical and horizontal dimensions, and be centered. -I have no control over the source images. I thought that CenterCrop would do it, but nada for me... ImageView.ScaleType CENTER_CROP Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). Any related thoughts on what I have; ignore the outer outer layout please: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:id="@+id/linearLayout2" android:layout_height="fill_parent" android:orientation="vertical" android:layout_width="fill_parent" android:background="@color/special_grey" android:layout_margin="0dp"> <ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_margin="10dp" android:src="@drawable/banner_logo" /> <LinearLayout android:id="@+id/linearLayout1" android:layout_margin="5dp" android:layout_gravity="center" android:layout_width="fill_parent" android:layout_height="250dp" android:baselineAligned="true"> <ImageButton android:minWidth="20dp" android:adjustViewBounds="true" android:layout_margin="0dp" android:src="@drawable/sample_0" android:maxWidth="100dp" android:id="@+id/imageButton1" android:layout_weight="1" android:scaleType="centerCrop" android:cropToPadding="true" android:layout_gravity="center" android:layout_width="0dp" android:padding="0dp" android:layout_height="250dp" /> <ImageButton android:minWidth="20dp" android:adjustViewBounds="true" android:layout_margin="0dp" android:src="@drawable/sample_1" android:maxWidth="100dp" android:id="@+id/imageButton2" android:layout_weight="1" android:cropToPadding="true" android:layout_width="0dp" android:padding="0dp" android:layout_height="250dp" android:scaleType="centerCrop" android:scrollbarAlwaysDrawHorizontalTrack="false" android:scrollbarAlwaysDrawVerticalTrack="false" android:layout_gravity="fill"/> <ImageButton android:minWidth="20dp" android:adjustViewBounds="true" android:layout_margin="0dp" android:src="@drawable/sample_2" android:maxWidth="100dp" android:id="@+id/imageButton3" android:layout_weight="1" android:cropToPadding="true" android:layout_gravity="center" android:layout_width="0dp" android:padding="0dp" android:layout_height="250dp" /> <ImageButton android:minWidth="20dp" android:adjustViewBounds="true" android:layout_margin="0dp" android:src="@drawable/sample_3" android:maxWidth="100dp" android:id="@+id/imageButton4" android:layout_weight="1" android:cropToPadding="true" android:layout_gravity="center" android:layout_width="0dp" android:padding="0dp" android:layout_height="250dp" /> <ImageButton android:minWidth="20dp" android:adjustViewBounds="true" android:layout_margin="0dp" android:src="@drawable/sample_4" android:maxWidth="100dp" android:id="@+id/imageButton5" android:layout_weight="1" android:cropToPadding="true" android:layout_gravity="center" android:layout_width="0dp" android:padding="0dp" android:layout_height="250dp" /> <ImageButton android:minWidth="20dp" android:adjustViewBounds="true" android:layout_margin="0dp" android:src="@drawable/sample_5" android:maxWidth="100dp" android:id="@+id/imageButton6" android:layout_weight="1" android:cropToPadding="true" android:layout_gravity="center" android:layout_width="0dp" android:padding="0dp" android:layout_height="250dp" /> </LinearLayout> </LinearLayout> </LinearLayout> A: My comments are only small suggestions as I'm not really sure what you want to achieve with this layout or how it should look like eventually, maybe you could elaborate a little bit or add a small image for a better understanding. I think your linearLayout1 is missing an orientation, but this shouldn't be critical as it should default to vertical (I think). Couldn't you put the Image of your ImageView as a backgroundImage for your linearLayout2? Then you could skip the ImageView. Then I would put most of the ImageButton attributes into a styles-definition. This allows you to change settings much easier and cleans up your code ([Android Developers: Applying Styles and Themes])1 As I have said before, maybe you could elaborate a little bit more about how it should look like, then it will be easier to help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: javascript or jquery fileSize I was looking all over the web how i can get the file size on the client side so i found a few examples the first example was $(this)[0].files[0].fileSize but unfortunately it does not working in ie so i found this example function getSize(){ var myFSO = new ActiveXObject("Scripting.FileSystemObject"); var filepath = document.upload.file.value; var thefile = myFSO.getFile(filepath); var size = thefile.size; alert(size + " bytes"); } which is suppose to work in ie but i heard it has security problems and i don't know if it work in all browsers.. so , i need to know what i can use in javascript client side to get the file size.. e.g : file from input type file thank you for helping. A: JavaScript cannot access any information about local files. This is done deliberately for security reasons. ActiveXObject("Scripting.FileSystemObject"); is an IE-only construct and will not work across browsers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Number representation by Excel I'm building a VBA program on Excel 2007 inputing long string of numbers (UPC). Now, the program usually works fine, but sometimes the number string seems to be converted to scientific notation and I want to avoid this, since I then VLook them up. So, I'd like to treat a textbox input as an exact string. No scientific notation, no number interpretation. On a related side, this one really gets weird. I have two exact UPC : both yield the same value (as far as I or any text editor can tell), yet one of the value gives a successful Vlookup, the other does not. Anybody has suggestions on this one? Thanks for your time. A: Long strings that look like numbers can be a pain in Excel. If you're not doing any math on the "number", it should really be treated as text. As you've discovered, when you want to force Excel to treat something as a string, precede it with an apostrophe. There are a couple of common problems with VLOOKUP. The one you found, extra whitespace, can be avoided by using a formula such as =VLOOKUP(TRIM(A1),B1:C:100,2,FALSE) The TRIM function will remove those extraneous spaces. The other common problem with VLOOKUP is that one argument is a string and the other is a number. I run into this one a lot with imported data. You can use the TEXT function to do the VLOOKUP without having to change the raw data =VLOOKUP(TEXT(A1,"00000"),B1:C100,2,FALSE) will convert A1 to a five digit string before it tries to look it up in column B. And, of course, if your data is a real mess, you may need =VLOOKUP(TEXT(TRIM(A1),"00000"),B1:C100,2,FALSE)
{ "language": "en", "url": "https://stackoverflow.com/questions/7516837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to send GPS positions to my phone (with eclipse) to test a GPS application without exit from home? I need to send GPS positions to my phone (with eclipse) to test a GPS application without exit from home? thanks A: the ddms can do that with the emulator, i THINK it will work with a real phone
{ "language": "en", "url": "https://stackoverflow.com/questions/7516850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to call a method in its onSubmit event? I try to implement file uploader script from this Github project and I need to set some additional params from the form before submitting the upload. According to the documentation it's being set like that: uploader.setParams({ anotherParam: 'value' }); How can I set these parameters in the onSubmit event? Something like: var uploader = new qq.FileUploader({ onSubmit: function() { // <- I want to set the params here } }); I tried self.setParams() and this.setParams() but no luck. I'm not that advanced in javascript so I would be thankful for any help. A: You can use the same code you posted. "uploader" will exist when onSubmit is called var uploader = new qq.FileUploader({ onSubmit: function() { uploader.setParams({ anotherParam: 'value' }); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7516852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: html form value before and value after I wondered if this was possible: It looks like this: <tr> <td> Full Name: </td> <td> <input type='text' class="inputbox" name='fullname' value='<?php echo $fullname; ?>'> </td> </tr> But I wanted to get rid of the <td>Full Name</td> and instead of that in the input box itself: value="Full Name". But the function value='<?php echo $fullname; ?> would echo the typed in full name of the person if he did not enter all fields. My form is made in that way; if someone fills in the form, but leaves one field out, it will echo "please fill in all fields" under the form. But it would be annoying if he had to enter all the information over again! That's where value="<?php echo $fullname; ?> comes in. It will echo the information the user had typed. So I need a value that shows "Full Name" normally but after a user put in his full name:"John Smith" but not all fields, he would get the "enter all fields" and the "Full Name" Would change in "John Smith". At this moment he will get "John Smith" if he did not enter all fields, but i wan't the field too show "Full Name" before the user entered "John Smith" And NOT show "Full Name" again. So in other words I need two values, one that shows normally, and after submit is presses it will echo $fullname. I hope you guys understand what I mean. Greetz A: I think what you are looking for are placeholders... <input type='text' class="inputbox" name='fullname' placeholder="Your name..." /> Please note placeholders are not supported by older browsers. A: Maybe you like the placeholder? If the input-field has no value, it will show the placeholder, else it will show the value. Another option is working with an if-condition: <input name="textfield" type="text" value="<?php echo (isset($_POST["textField"]) ? $_POST["textField"] : "Full name")?> /> A: <input type='text' class="inputbox" name='fullname' value='<?php echo isset($fullname) ? $fullname : 'Full Name:' ?>'>
{ "language": "en", "url": "https://stackoverflow.com/questions/7516854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sharing an object throughout an app I am currently developing an application for the iPhone. The appdelegate shows a splash-screen while I'm caching data (e.g. NSDictionary) for use in a certain view. What is the best way to call this data from the view I need it in? I don't think passing it along as a variable from view to view until it reaches the view is a correct way to do this. App Delegate (with Splashscreen that should cache the data to NSDictionary) | View A | SubView | Final View (here I want to use the cached data) Thanks :-) A: If the NSDictionary that you're caching the data in is an ivar of your App Delegate you can access it from anywhere in your app using the following lines: myAppDelegate *delegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate]; NSDictionary *myData = [delegate cachedData]; Hope that answers your question. A: If you have an object that will never be released throughout the entire life of the app, and really want it to be accessible from absolutely anywhere in the app (say, so that a simple debug NSLog from absolutely anywhere in the code can print it's state), then that's what global variables are for. Just assign a global variable with a reference to the object. If you don't mind generating nearly equivalent but microscopically slower and larger code, then assign it to an instance variable in the app delegate with a suitable getter. Note that using global variables is a violation of encapsulation that won't be very scalable, maintainable or suitable for unit testing, but is perfectly suitable for a small app which is not much larger than most objects would encapsulate anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I validate whether a URL location exists or not? We're hosting SSIS reports on our servers and we are storing their paths in a sql server table. From .Net, I want to be able to make sure the path entered is correct. This should return "true" because there's a report there, for example: http://server/Reports/Pages/Viewer.aspx?%2fShopFloor%2fProduction+by+Turn&rs:Command=Render This should return false. http://I am an invalid location/I am laughing at you/now I'm UEEing I was looking at WebRequests, but I don't know if that's the route I should be taking. Any help would be appreciated. Thanks! A: You can try making a HEAD request to validate that the resource exists. With a HEAD request, you would only need the HTTP Code (200 = Success, 404 = Not Found) without consuming resources or excess memory to download the entire resource. Take a look at HttpWebRequest class for performing the actual request. A: Do a http HEAD request to the URL, which should just fetch headers. This way you dont need to download the entire page if it exists. from the returned headers(if there are any) you should be able to determine if its a correct URL or not. A: I'm unsure of the exact layout of your network, but if the .net application has visibility to the location the reports are stored, you could use File.Exists(). Otherwise, mellamokb and red-X have the right idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rounding % Labels on bar chart in ggplot2 q1 <- qplot(factor(Q1), data=survey, geom="histogram", fill=factor(Q1), ylim=c(0,300)) options(digits=2) q1 + geom_bar(colour="black") + stat_bin(aes(label=..count..), vjust=-2, geom="text", position="identity") + stat_bin(geom="text", aes(label=paste(..count../sum(..count..)*100,"%"), vjust=-0.75)) + labs(x="Question # 1:\n 0 = Didn't respond, 1 = Not at all familiar, 5 = Very familiar") + opts(title="Histogram of Question # 1:\nHow familiar are you with the term 'Biobased Products'?", legend.position = "none", plot.title = theme_text(size = 16, , vjust = 1, face = "bold"), axis.title.x =theme_text(size=14), axis.text.x=theme_text(size=12), axis.title.y=theme_text(size=14, angle=90), axis.text.y=theme_text(size=12)) As you can see I'm getting way more digits than what is needed, I was hoping the options(digits=2) would do it but I guess not. Any ideas? A: Actually you are very close to there. Here is a minimal example: df <- data.frame(x = factor(sample(5, 99, T))) ggplot(df, aes(x)) + stat_bin(aes(label = paste(sprintf("%.02f", ..count../sum(..count..)*100), "%")), geom="text") also, format, round, prettyNum, etc, is available. UPDATED: Thanks to @Tommy 's comment, here si a more simple form: ggplot(df, aes(x)) + stat_bin(aes(label = sprintf("%.02f %%", ..count../sum(..count..)*100)), geom="text")
{ "language": "en", "url": "https://stackoverflow.com/questions/7516861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Trying to use curl to do a GET, value being sent is allows null I'm trying to use curl to do a simple GET with one parameter called redirect_uri. The php file that gets called prints out a empty string for $_GET["redirect_uri"] it shows red= and it seems like nothing is being sent. code to do the get //Get code from login and display it $ch = curl_init(); $url = 'http://www.besttechsolutions.biz/projects/facebook/testget.php'; //set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_GET,1); curl_setopt($ch,CURLOPT_GETFIELDS,"redirect_uri=my return url"); //execute post print "new reply 2 <br>"; $result = curl_exec($ch); print $result; // print "<br> <br>"; // print $fields_string; die("hello"); the testget.php file <?php print "red-"; print $_GET["redirect_uri"]; ?> A: This is how I usually do get requests, hopefully it will help you: // create curl resource $ch = curl_init(); //return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Follow redirects curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Set maximum redirects curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // Allow a max of 5 seconds. curl_setopt($ch, CURLOPT_TIMEOUT, 5); // set url if( count($params) > 0 ) { $query = http_build_query($params); curl_setopt($ch, CURLOPT_URL, "$url?$query"); } else { curl_setopt($ch, CURLOPT_URL, $url); } // $output contains the output string $output = curl_exec($ch); // Check for errors and such. $info = curl_getinfo($ch); $errno = curl_errno($ch); if( $output === false || $errno != 0 ) { // Do error checking } else if($info['http_code'] != 200) { // Got a non-200 error code. // Do more error checking } // close curl resource to free up system resources curl_close($ch); return $output; In this code, the $params could be an array where the key is the name, and the value is the value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to tell if object is in an NSAutoreleasePool I would like to know how many times an object has been autoreleased. I've used objective c long enough that it's generally straight forward to know whether an object has been autoreleased or not, however I constantly see questions dealing with memory and retain counts. At some point an answer always ends, "You can't trust the retainCount of an object" - which I agree with, BUT if you could determine how many times an object has been autoreleased, then you actually could trust the retainCount if you added a category like: @interface NSObject (NSObject_MemoryDebugging) - (NSUInteger) autoReleaseCount; - (NSUInteger) retainCountWithAutoRelease; @end @implementation] /** Determine how many times this object has been marked for autorelease **/ - (NSUInteger) autoReleaseCount; { // ??? not sure how to figure this out. return 0; } - (NSUInteger) retainCountWithAutoRelease { NSUInteger retainCount = [self retainCount]; NSUInteger autoReleaseCount = [self getAutoReleaseCount]; // ??? return retainCount - autoReleaseCount; } @end There would still be an exception for immutable types as those typically increase the retain count during a copy, so you still can't trust retainCount on those. What I am NOT proposing I am not seeking this answer to use retainCount in production code. However, I can see this as being valuable for someone debugging memory issues. I imagine some people will HATE this question since programmers should not care about how many times an object has been autoreleased. Coding should be all about balancing allocs, retain, copy, new with release, end of story. However, the point of this is to help out people banging their heads. [NSObject retainCount] burns a lot of people, and an answer to this question would be pretty cool. I'm certain there's a way to determine how many times an object has been autoreleased. I just don't know what it is, hence the question. See similar question: Objects inside NSAutoreleasePool in objective-c. Edit Thank you everyone for your answers. You may find this interesting => Ariel pointed out that GNUStep's implementation of Cocoa and specifically it's NSAutoReleasePool has this method: +(NSUInteger)autoreleaseCountForObject:(id)anObject. This method is slow, and only returns the autorelease count from NSAutoReleasePools on the callers thread. Still... It's interesting that its there. The docs cite that it is really only useful for debugging. This is really what I was hoping to find (or find possible) in the Cocoa framework somehow. I agree with the answers given that even if it were possible to get the autorelease count that better tools exist (Zombies, Leaks, static analyzer). A: First, you'd have to deal with multiple autorelease pools and an object being autoreleased more than once, possibly in multiple pools. Second, it's not (just) NSAutoreleasePool that's making -retainCount untrustworthy. The problem is that all sorts of objects, both yours and Apple's, retain things for all sorts of reasons, most unbeknownst to you. Even accounting for autorelease, your objects will often not have the retain count you expect, because behind the scenes, something's observing it or placing it in a dictionary temporarily, etc. The best ways to debug memory issues are the Leaks instrument, NSZombie, and the static analyzer. A: No, there isn’t a public API to determine whether an object has been autoreleased. Even if this were publicly available, your -retainCountWithAutoRelease method would have some problems: * *An object can be placed multiple times in the same autorelease pool so you’d need an autorelease count for a single autorelease pool instead of a flag indicating whether an object has been autoreleased; *An object can be placed in multiple autorelease pools due to multithreading, so you’d need an autorelease count spanning multiple autorelease pools; *Due to multithreading, you’d need to synchronise your code with Cocoa’s handling of retain counts and autorelease pools, and the internal locking used by Cocoa is not visible to applications. A: NSAutoreleasePool does have an +(void)showPools method that I was previously completely unaware of. This could be useful. Also see Is there a way to inspect an NSAutoreleasePool's objects?. On that thread, KennyTM said (in a comment): Well, since the content is printed to stderr, you could reopen the stream and parse from it to get all the pointers For reference, I used class-dump against the Foundation framework to see it's NSAutoreleasePool details and it had the following: @interface NSAutoreleasePool : NSObject { void *_token; void *_reserved3; void *_reserved2; void *_reserved; } + (void)addObject:(id)arg1; + (id)allocWithZone:(struct _NSZone *)arg1; + (void)showPools; + (void)releaseAllPools; + (unsigned int)autoreleasedObjectCount; + (unsigned int)topAutoreleasePoolCount; + (BOOL)autoreleasePoolExists; + (void)enableRelease:(BOOL)arg1; + (void)enableFreedObjectCheck:(BOOL)arg1; + (unsigned int)poolCountHighWaterMark; + (void)setPoolCountHighWaterMark:(unsigned int)arg1; + (unsigned int)poolCountHighWaterResolution; + (void)setPoolCountHighWaterResolution:(unsigned int)arg1; + (unsigned int)totalAutoreleasedObjects; + (void)resetTotalAutoreleasedObjects; - (id)init; - (void)drain; - (oneway void)release; - (id)initWithCapacity:(unsigned int)arg1; - (void)addObject:(id)arg1; - (id)retain; - (unsigned int)retainCount; - (id)autorelease; - (void)dealloc; @end I've added this as an answer as it seemed more of an answer than more detail on the question I asked. A: Sounds like you'll need to override -(id)autorelease; method as the work of adding object to NSAutoreleasePool done there.Something like that: -(id)autorelease{ _isAutoreleased = YES; //some BOOL member initialized to NO and returned on -(BOOL)isAutoreleased; [NSAutoreleasePool addObject:self]; return self; } Also take a look at this link
{ "language": "en", "url": "https://stackoverflow.com/questions/7516864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: file processing (for file with more than one fields) and problems associated with it here is a code i wrote to create the symtab of a sic/xe .asm file.... #include<iostream> #include<fstream> #include<iomanip> #include"aviasm.h" using namespace std; void aviasm::crsymtab() { ofstream outs("symtab.txt",ios::out);//creating the symtab ofstream outi("intermfile.txt",ios::out);//creating the intermediate file ifstream in("asmfile.txt",ios::in);//opening the asmfile which i have already written in.seekg(0,ios::beg); char c; string str[3]; string subset; long locctr=0; int i=0; while((c=in.get())!=EOF) { in.putback(c); while((c=in.get())!='\n') { in.putback(c); //putting back the first encountered letter in>>str[i++]; //the asm file has three or less fields in every row } if(str[0].size()!=0 && str[1].size()!=0 && str[2].size()!=0)//if all 3 are there { if(str[1]=="start") { outi<<hex<<locctr; outs<<str[1]<<" "<<locctr<<"\n"; outs<<resetiosflags(ios::hex); outi<<" "<<str[0]<<" "<<str[1]<<" "<<str[2]<<"\n"; locctr=stol(str[2],0,16); }//str[1]=start }//end of all the three fields } in.close(); outi.close(); outs.close(); }//end of crsymtab .....here is a sample sic/xe .asm file.....note that in the above code i have not included the entire coded because the problem occurs even if i comment out the entire portion of the code except the above...the problem that occurs is whenever i run the code: * *A message box with: 'Unhandled exception at 0x00ba7046 in aviasm.exe: 0xC0000005: Access violation writing location 0xcccccccc.' appears and my program enters debugging mode...also a file named iosfwd(std::char_traits<char>) appears with an arrow at the line _Left=_Right; of the following function: static void __CLRCALL_OR_CDECL assign(_Elem& _Left, const _Elem& _Right) { // assign an element _Left = _Right; } *Also, I output a few words to the console at the start and end of the block str[1]="start" to check whether this function was working...although both lines were working and I am also sure that input is being successfully taken by the program from the asm file(I have checked this),no lines are being output to intermfile and symtab...plz help?? A: You should run your program inside a debugger. If you are using Windows, then MSVC provides a debug environment. If you are using Linux, compile your program with -g, and run the gdb debugger: gdb ./myprog. You would immediately discover that on this line: in>>str[i++]; //the asm file has three or less fields in every row i has a value of 4, which exceeds the size of the str array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jibx-maven-plugin 1.2.3 schema-codegen goal value ignored I am trying to use jibx-maven plugin 1.2.3 for generating Java Source Code from a Schema file. Following is the plugin config in my pom.xml <build> <plugins> <!-- To use the JiBX Maven Plugin in your project you have to add it to the plugins section of your POM. --> <plugin> <groupId>org.jibx</groupId> <artifactId>jibx-maven-plugin</artifactId> <version>1.2.3</version> <executions> <execution> <goals> <goal>schema-codegen</goal> </goals> <configuration> <schemaLocation>src/main/resources</schemaLocation> <options> <package>com.poc.jibx</package> </options> </configuration> </execution> </executions> </plugin> </plugins> </build> When I try to run the goal using command: mvn jibx:schema-codegen I get the following output [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building jibx-sample 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- jibx-maven-plugin:1.2.3:schema-codegen (default-cli) @ jibx-sample --- [INFO] Generating Java sources in target/generated-sources from schemas available in src/main/config... Loaded and validated 0 specified schema(s) Total classes in model: 0 [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.691s [INFO] Finished at: Thu Sep 22 20:11:33 IST 2011 [INFO] Final Memory: 6M/71M [INFO] ------------------------------------------------------------------------ As can be seen in the output the default schema location is being searched for i.e. src/main/config instead of my the configured location src/main/resources. I came across the following JIRA which says the the above plugin config is appropriate and should work prefectly. http://jira.codehaus.org/browse/JIBX-450 However it is not working in my case.Am I missing anything else for making this work? Thanks, Jignesh A: The issue is resolved and I am posting the solution here so that it can help others, if they face this issue: The correct pom.xml should look like below <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.poc.jibx</groupId> <artifactId>jibx-sample</artifactId> <version>0.0.1-SNAPSHOT</version> <name>jibx-sample</name> <build> <plugins> <plugin> <groupId>org.jibx</groupId> <artifactId>jibx-maven-plugin</artifactId> <version>1.2.3</version> <configuration> <schemaLocation>src/main/conf</schemaLocation> <includeSchemas> <includeSchema><YOUR_SCHEMA_FILE_NAME>.xsd</includeSchema> </includeSchemas> <options> <package>com.poc.jibx</package> </options> <schemaBindingDirectory>src/main/java</schemaBindingDirectory> </configuration> <executions> <execution> <id>generate-java-code-from-schema</id> <goals> <goal>schema-codegen</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> In my first post the plugin section shows the configuration section inside the execution element while in the above code it is outside executions The code snippet I used earlier I took from the sample usage example shown at http://jibx.sourceforge.net/maven-jibx-plugin/schema-codegen.html under section Generate Java Sources from Schemas and Compile Binding Java Sources from XSD Schemas Here is below a sample usage: which I suppose is wrong and needs rectification. The correct code snippet is available under section Generate Java Sources from Schemas Java Sources from XSD Schemas Here is a sample plugin section: Thanks, Jignesh A: Jignesh, Actually, your first pom should have worked fine. khmarbaise is correct, it is considered good practice to place your schema definitions in the /src/main/config directory and make sure they have an .xsd extension. Here is a corrected project file. I am using your schema location. Note the OSGi bundle packaging. This will work fine for non-OSGi projects, and your project is ready to go when you start using OSGi. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.poc.jibx</groupId> <artifactId>test</artifactId> <version>0.0.1</version> <packaging>bundle</packaging> <build> <plugins> <plugin> <groupId>org.jibx</groupId> <artifactId>jibx-maven-plugin</artifactId> <version>1.2.3</version> <executions> <execution> <id>generate-java-code-from-schema</id> <goals> <goal>schema-codegen</goal> </goals> <configuration> <schemaLocation>src/main/resources</schemaLocation> <options> <package>com.poc.jibx</package> </options> </configuration> </execution> <execution> <id>compile-binding</id> <goals> <goal>bind</goal> </goals> <configuration> <schemaBindingDirectory>target/generated-sources</schemaBindingDirectory> <includes> <include>binding.xml</include> </includes> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Include-Resource>META-INF/binding.xml=${basedir}/target/generated-sources/binding.xml</Include-Resource> <Export-Package>com.poc.jibx.*;version=${project.version}</Export-Package> </instructions> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.jibx</groupId> <artifactId>jibx-run</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.jibx</groupId> <artifactId>jibx-extras</artifactId> <version>1.2.3</version> </dependency> </dependencies> </project> Good luck! Don jibx-maven-plugin project contributor
{ "language": "en", "url": "https://stackoverflow.com/questions/7516872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: smarty - how to use variables in code? This is part of my smarty code: {if $cat=="3_0" or $cat=="3_15" or $cat=="3_16" or $cat=="3_17"} How can I setup my code to use variable for characters (numbers) 15, 16, 17...? For example I would like have short code like that: {if $cat=="3_0" or $cat=="3_"+ any two characters} A: I think that you can do something like: {if $cat|substr:0:2 eq "3_"} or {if $cat|truncate:2 eq "3_"} http://www.smarty.net/docsv2/en/language.modifiers.tpl Let me know ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7516873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: textarea that was using plain text with option of markdown or textile filter now needs images My clients can enter text into textarea and have the option to use the markdown or textile filters for each textarea. With some models (articles, newsletter, etc) they can upload images to associate with the model, which are displayed in a column next to the text of the text. This worked fine for a while, but they have now told me that the want the ability to put the images INSIDE the text a specific positions. What is the best way to go about this? I suppose I may have to use a wysiwyg for this, but would rather not. And how would this work for images which are not yet on the server, etc? A: There are different directions you could go to: * *Follow the path of Confluence, which released in their new version 4.0 a rewritten WYSIWYG editor, that stores as source XHTML, not any more wiki markup. * *Leads to an update of all pages when migrating. *Was pretty difficult to implement. I do not know if they use any more the TinyMCE editor of previous versions. *Follow the format of markdown how to include images in your source format. So by typing: This is my text. !image.png! The inline image shows ..., you will have a format that is understandable. * *You have to expand the interpretation, so that the !<filename>! will be mapped that is stored locally anyway. *You have to add clear-up dialogs for the images that are yet not known, so doing bulk uploads ... *You may provide a drag area on your view, that then shows the filename and gives examples how to include that inside the text area. *Go for something in between, by allowing users to drag images inside the editor. There are plugins written in Javascript that allow you to do that, e.g. UI Draggable for jquery * *I have no idea how to integrate that image inside the text editor. Overlay? So the second one is the easiest, and the user knows how to do it. If they only decide that this is the solution they want to have :-) A: I think I'm going to use a combination of #2 above, and the Liquid templating engine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Map View v/s Web View? I am confused between webview and mapview, which is better?? in terms of flexibility, overlays, usage, load-speed, zoom levels etc etc A: MapView is the native built-in class for doing Map related stuff. WebView is a native element for the browser. It has a javascript to Java bridge, so you can call Java methods in your native Android application from the JavaScript page. For my personal experience: * *WebView is less flexible, kinda sluggish for UI interaction. *MapView has better optimizations and has richer content. *MapView has definitely better caching. *MapView loads faster (imo) *The MapView api's make life much easier. Zooming/handling etc is great. Though if you are good at JavaScript and the V3 you should go for WebView. It all boils down to the feature set (WebView has a larger feature set, or so I've heard) that you want to use, your project duration (MapView is faster and easier to code for) A: Those 2 classes are completely different. The WebView class is there to show a webpage, the MapView class is there to intergrate Google Maps into your application. So depending on what you want to achieve you can pick one. Since your tags say Google and Maps you should use the MapView, see also the Google Map View tutorial on the Android Developers site. -- for future questions please provide some more information in your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difference between Apache rules to block libwww-perl I want to know the difference between these rules and which is most effective to block libwww-perl with the file .htaccess SetEnvIfNoCase User-Agent "libwww-perl" bad_bot Order Deny,Allow Deny from env=bad_bot or RewriteCond %{HTTP_USER_AGENT} libwww-perl.* RewriteRule .* – [F,L] Thank you! A: Functionally, I think they are much the same, with some minor pros and cons. However the former is probably more portable, since you won't have worry about mod_rewrite being installed on the server should you move the site at some point in the future. Naturally, if you have other mod_rewrite rules this won't make much difference to you. You also have a wildcard set up in the mod_rewrite rule, that isn't present in SetEnvIfNoCase. I understand this is possible to do this there also, and it might be wise to do so, since you can then catch different libwww versions. I'm sure you know libwww-perl can send an arbitrary user agent string, so neither will stop the determined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Remove particular content (›) from last a tag in a div I have a list with breadcrumbs that is generated like this: <div class="breadcrumps"><a href="#">Link1</a>&#8250;<a href="#">Link2</a>&#8250;<a href="#">Link3</a>&#8250;</div> How can I remove the '›' after the last a tag? Currently I have this code which doesn't work...:( $(document).ready(function () { $('.breadcrumps'); $(this).find('a:last-child').remove('&#8250;'); }); thanks in advance! A: Here is one way to do it: http://jsfiddle.net/jXBte/ <div class="breadcrumps"> <a href="#">Link1</a><span>&#8250;</span> <a href="#">Link2</a><span>&#8250;</span> <a href="#">Link3</a><span>&#8250;</span> </div> and the js: $(document).ready(function () { $('.breadcrumps').find('span:last-child').remove(); }); A: $(document).ready(function() { $('.breadcrumps').html(function(index, oldHtml) { $(this).html(oldHtml.substring(0, oldHtml.length - 1)); }); }); Just beware that the DOM elements are being replaced, so old bindings might be lost. For example, The following won't work: $(document).ready(function() { $('a').click(function() { alert('Clicked'); }); $('.breadcrumps').html(function(index, oldHtml) { $(this).html(oldHtml.substring(0, oldHtml.length - 1)); }); }); But this will: $(document).ready(function() { $('.breadcrumps').html(function(index, oldHtml) { $(this).html(oldHtml.substring(0, oldHtml.length - 1)); $('a').click(function() { alert('Clicked'); }); }); }); A: Use substr: $('.breadcrumps').text(function(x,i){return i.substr(0,i.length-1);}); http://jsfiddle.net/XxDfY/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7516880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Label for File input in firefox When I add a label the a form input, I can normally click the label and it will refer me to the appropriate input (see below). <label for="input">Label</label><input type="text" id="input"/> However, when I try to accomplish the same with a file input, the click on the label gets ignored. Is this a bug? A "feature"? And is there any way to still accomplish this? jsFiddle testcase: here A: The label's prescribed behavior differs between HTML specifications. More precisely, this is probably a bug in FF (rather than an extra feature in the others), because this behavior should usually be included according to the HTML 4 spec: When a LABEL element receives focus, it passes the focus on to its associated control. See the section below on access keys for examples. The current HTML spec is more nuanced, but does indicate the possibility that it do nothing (this is the expected behavior in iOS).
{ "language": "en", "url": "https://stackoverflow.com/questions/7516882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Check if app available on Android Market Given an Android application's id/package name, how can I check programatically if the application is available on the Android Market? For example: com.rovio.angrybirds is available, where as com.random.app.ibuilt is not I am planning on having this check be performed either from an Android application or from a Java Servlet. Thank you, PS: I took a look at http://code.google.com/p/android-market-api/ , but I was wondering if there was any simpler way to checking A: You could try to open the details page for the app - https://market.android.com/details?id=com.rovio.angrybirds. If the app doesn't exist, you get this: It's perhaps not ideal, but you should be able to parse the returned HTML to determine that the app doesn't exist. A: Given an Android application's id/package name, how can I check programatically if the application is available on the Android Market? There is no documented and supported means to do this. A: While the html parsing solution by @RivieeaKid works, I found that this might be a more durable and correct solution. Please make sure to use the 'https' prefix (not plain 'http') to avoid redirects. /** * Checks if an app with the specified package name is available on Google Play. * Must be invoked from a separate thread in Android. * * @param packageName the name of package, e.g. "com.domain.random_app" * @return {@code true} if available, {@code false} otherwise * @throws IOException if a network exception occurs */ private boolean availableOnGooglePlay(final String packageName) throws IOException { final URL url = new URL("https://play.google.com/store/apps/details?id=" + packageName); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.connect(); final int responseCode = httpURLConnection.getResponseCode(); Log.d(TAG, "responseCode for " + packageName + ": " + responseCode); if(responseCode == HttpURLConnection.HTTP_OK) // code 200 { return true; } else // this will be HttpURLConnection.HTTP_NOT_FOUND or code 404 if the package is not found { return false; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: bash: Inverse (ie. NOT) shell wildcard expansion? Is there a way of handling invers bash v4 shell expansion, ie. treat all files NOT like a wildcard? I need to rm all files that are not of the format 'Folder-???' in this case and was wondering if there is a shorter (ie. built-in) way then doing a for file in * do [[ $i =~ \Folder-...\ ]] && rm '$i' done loop. (the example doesn't work, btw...) Just out of bash learning curiosity... A: @Dimitre has the right answer for bash. A portable solution is to use case: for file in *; do case "$file" in Folder-???) : ;; *) do stuff here ;; esac done Another bash solution is to use the pattern matching operator inside [[ ... ]] (documentation) for file in *; do if [[ "$file" != Folder-??? ]]; then do stuff here fi done A: In case you are ok with find, you can invert find's predicates with -not. As in find -not -name 'Folder-???' -delete (note this matches recursively among other differences to shell glob matching, but I assume you know find well enough) A: shopt -s extglob rm -- !(Folder-???)
{ "language": "en", "url": "https://stackoverflow.com/questions/7516888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Storing in String Possible Duplicate: What's the most elegant way to concatenate a list of values with delimiter in Java? I have 3 different words listed in property file in 3 different lines. QWERT POLICE MATTER I want to read that property file and store those 3 words in String, not in aarylist separated by whitespace. The output should look like this String str = { QWERT POLICE MATTER} Now I used the follwoing code and getting the output without white space in between the words: String str = {QWERTPOLICEMATTER}. What should I do to the code to get the string result with words separated by whitespace. FileInputStream in = new FileInputStream("abc.properties"); pro.load(in); Enumeration em = pro.keys(); StringBuffer stringBuffer = new StringBuffer(); while (em.hasMoreElements()){ String str = (String)em.nextElement(); search = (stringBuffer.append(pro.get(str)).toString()); A: Try: search = (stringBuffer.append(" ").append(pro.get(str)).toString()); A: Just append a blank space in your loop. See the extra append below: while (em.hasMoreElements()){ String str = (String)em.nextElement(); search = (stringBuffer.append(pro.get(str)).toString()); if(em.hasNext()){ stringBuffer.append(" ") } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to have a menu across top with links left aligned and right aligned this may seem simple. I have a menu across the top of the page currently right aligned. I want one link to be to the left of the page. How do it? <div id="toptop"> <ul id="bottomnavlistl"> <li class="a"> <a href="@Url.Content("~/Account/EditDetails/")">LOGIN</a> <a href="@Url.Content("~/Account/LogOff/")">LOGOUT</a> </li> <li class="first"><a href="@Url.Content("~")">HOME</a></li> css ul#bottomnavlistl li { display: inline; padding: 10px 0px 5px 0px; border-right: 1px dotted #8A8575; float:right; } A: Use float:left http://htmldog.com/reference/cssproperties/float/ A: Your css should have somthing like .a{float:left;} .first{float:right} A demo here
{ "language": "en", "url": "https://stackoverflow.com/questions/7516890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flash - prompt user to remember camera and mic settings I request my user from mic and camera setting on my website with Flash, but the remember checkbox does not show, so every time my user logs in he's requested once again for permissions, how can I make the checkbox show to avoid this? A: Call Security.showSettings(SecurityPanel.PRIVACY) before trying to access the camera. Camera Class LiveDocs A: var _mic:Microphone; _mic = Microphone.getMicrophone(<index>); if(_mic.muted){ Security.showSettings(SecurityPanel.PRIVACY); } You can use "muted" property of the microphone instance. You do not need to listen the StatusEvent.STATUS. With the code block above, you can ask for permission only once.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: LINQ - SQL Display data in html table I would like to perform a select statement using a DataContext from the code behind page and then display the results in an HTML table. Best ways to do this? A: The best way to do this as always depends. One of the fastest and easiest way would be to directly bind the data to a DataGrid. A: If you really need to create html table you can use a literal in frontend and add the literal text from back end eg <asp:Literal ID="ltrUser" runat="server"></asp:Literal> In backend code if (!IsPostBack) { var data = datasource; ltrUser.Text = "<table><tr><td>"; ltrUser.Text += "<h1>"+ data.name + "</h1>"; ltrUser.Text += "</td></tr></table>"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I check if an element is in overflow area? i have a div with a with of 300px. this DIV contains different Icons and if there are too many Icons then they are not visible due to overflow:hidden How may i programatically check if an icon is visible or is in overflow area? A: I couldn't find anything exactly like that so I wrote a quick library function. Element.addMethods({ isClipped: function(element, recursive){ element = $(element); var parent = element.up(); if ((element === document.body) || !parent) return true; var eLeft = element.offsetLeft, eRight = eLeft+element.getWidth(), eTop = element.offsetTop, eBottom = eTop+element.getHeight(); var pWidth = $R(parent.scrollLeft, parent.getWidth()+parent.scrollLeft), pHeight = $R(parent.scrollTop, parent.getHeight()+parent.scrollTop); if (!pWidth.include(eLeft) || !pWidth.include(eRight) || !pHeight.include(eTop) || !pHeight.include(eBottom)) { return true; } if (recursive) return parent.isClipped(true); return false; } }); It's not elegant (I did say "quick") but it allows you to use isClipped() on any element. You can see a jsfiddle test here. It tests if any part of an element (excluding borders) is part of the overflow. You could do something similar to test for elements that are entirely outside the containing client area. A: http://elvingrodriguez.com/overflowed/ It's a jQuery plugin that tells you if an element is overflowed. A: If a node's scrollWidth/Height is higher than it's offsetWidth/Height, then something will be (partially) hidden. It's then a matter of determining which area is hidden through simple math (adding up icon widths, calculating the scroll offset and then eventually checking if an icon is within that visible area).
{ "language": "en", "url": "https://stackoverflow.com/questions/7516905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Are lambdas constructors for delegate types? I've discovered that Rhino Mocks' AssertWasCalled fails when I use lambdas as parameters to the method being asserted. TEST : _mockDoer.AssertWasCalled(x => x.Print(y => Console.WriteLine("hi"))); CODE INSIDE SYSTEM UNDER TEST : _doer.Print(y => Console.WriteLine("hi"))); This has made me think of lambdas as, effectively, constructors for delegate types. Am I missing anything important when I think of lambdas as constructors for delegate types? A: Well, they're not really "constructors" in any of the normal uses of the word "constructor". They're expressions which can be converted to delegate types or expression tree types - the latter being essential when it comes to out-of-process LINQ. If you're really asking whether it's expected that using two "equivalent" lambda expressions can create unequal delegate instances: yes, it is. IIRC, the C# language specification even calls out that that's the case. However, using the same lambda expression more than once won't always create different instances: using System; class Test { static void Main(string[] args) { Action[] actions = new Action[2]; for (int i = 0; i < 2; i++) { actions[i] = () => Console.WriteLine("Hello"); } Console.WriteLine(actions[0] == actions[1]); } } On my box, that actually prints True - actions[0] and actions[1] have the exact same value - they refer to the same instance. Indeed, we can go further: using System; class Test { static void Main(string[] args) { object x = CreateAction(); object y = CreateAction(); Console.WriteLine(x == y); } static Action CreateAction() { return () => Console.WriteLine("Hello"); } } Again, this prints True. It's not guaranteed to, but here the compiler has actually created a static field to cache the delegate the first time it's required - because it doesn't capture any variables etc. Basically this is a compiler implementation detail which you should not rely on. A: Just to expand on Jon's (excellent, as always) answer: in current implementations of C#, if "the same" lambda appears in two different source code locations then the two lambdas are never realized into equal delegates. However, we reserve the right to in the future detect this situation and unify them. Whether the converse holds or not is also implementation-dependent. If two delegates are created from a lambda at a particular source code position, the delegates might or might not have equality. There are some scenarios where it is impossible for the delegates to have equality (because they are closed over different instances of local variables, for example). In situations where it is possible for them to have equality, most of the time they do, but there are a few cases where we could perform this optimization and do not, just because the compiler is not yet sophisticated enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Count number of occurrences of a specific regex on multiple files I am trying to write up a bash script to count the number of times a specific pattern matches on a list of files. I've googled for solutions but I've only found solutions for single files. I know I can use egrep -o PATTERN file, but how do I generalize to a list of files and out the sum at the end? EDIT: Adding the script I am trying to write: #! /bin/bash egrep -o -c "\s*assert.*;" $1 | awk -F: '{sum+=$2} END{print sum}' Running egrep directly on the command line works fine, but within a bash script it doesn't. Do I have to specially protect the RegEx? A: You could use grep -c to count the matches within each file, and then use awk at the end to sum up the counts, e.g.: grep -c PATTERN * | awk -F: '{sum+=$2} END{print sum}' A: grep -o <pattern> file1 [file2 .. | *] | uniq -c If you want the total only: grep -o <pattern> file1 [file2 .. | *] | wc -l Edit: The sort seems unnecessary. A: The accepted answer has a problem in that grep will count as 1 even though the PATTERN may appear more than once on a line. Besides, one command does the job awk 'BEGIN{RS="\0777";FS="PATTERN"} { print NF-1 } ' file
{ "language": "en", "url": "https://stackoverflow.com/questions/7516913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why this java regex is not working as I want? These are two type of string I can get in input: String mex1 = "/ABCD/YY YYYYY SPA QWE XXXXX XXXXX SPA - 02342990153*XXXXX XXXX SPA ABCD LEGALI"; String mex2 = "/ABCD/YY YYYYY SPA QWE XXXXX XXXXX SPA - 02342990153*XXXXX XXXX SPA ABCD LEGALI/ORDERS/9865432342990160"; Which fall in two possible cases, with */some_word/some_number* and without it I have written this regex which is giving a result I don't understand: String mex=//<one of two input cases as already explained> Pattern p = Pattern.compile("(/ABCD/)(.+ )(/\\w+/\\d+)?"); Matcher m = p.matcher(mex); if(m.find()) { System.out.println(m.group(1)); System.out.println(m.group(2)); // this the group I would like to retrieve... } And the result is: mex2 /ABCD/ YY YYYYY SPA QWE XXXXX XXXXX SPA - 02342990153*XXXXX XXXX SPA ABCD LEGALI mex1 /ABCD/ YY YYYYY SPA QWE XXXXX XXXXX SPA - 02342990153*XXXXX XXXX SPA ABCD which is not what I expected in particular with mex2, where the string I want to retrieve get truncated. Also, why after including the boundaries results in match find = false ? Pattern p = Pattern.compile("^(/ABCD/)(.+ )(/\\w+/\\d+)?$"); thanks A: There are two issues with your regex: * *The (.+ ) requires a space at the end of the group. *The .+ is a greedy match so it matches the remainder of the string. Try the following regex: /ABCD/(.+?)(/\\w+/\\d+)?$ A: Try this one (/ABCD/)([^\/]+(/\\w+/\\d+)?) The [^\/] will capture anything but /
{ "language": "en", "url": "https://stackoverflow.com/questions/7516916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Installshield : How to preserve files after uninstallation I am using installshield 11 to create Basic MSI Project. My requirment is, when i unstall the project, i want to preserve certain files.( I don't want these Certain files to be removed when unstallation takes place ). Morover, these files are not a part of the component, but they are created(copied) during installation process by using copyfile (script) command from specific location. -Dev A: Use Disable(LOGGING)....Enable(LOGGING). Using CopyFile() in-between these methods will prevent uninstall removing the files A: Windows installer removes only those files and folders which it installs. That is each file present in it's database in File table and Folder table. It do not remove any file which does not have entry in File table, similar for folder. Also, If folder is not empty then that folder does not get deleted during uninstall. If your installing some files using Copyfile script ( may be using any custom action) then those files will not be removed during uninstall. A: Thanks Balachandra for your response, But i have below observation which might help. Files which i want to preserve is created by CopyFile, and target dir which i mention in the copyfile command does not exist. So CopyFile creates the folder and copy the file to that folder. So obviosly we will not have this folder entry in the dir table of installsheild But this approach does not help, uninstallation is removing all copied files from this folder. -Dev A: Thanks, Alerter, I've been fighting this one for 2 days. We install an example configuration file and create a copy of it (on first installation). We needed to preserve the configuration file if the customer changed it, but the file was always getting deleted on uninstall. Disabling the LOGGING around the CopyFile command was exactly the solution for this situation. Dev, I know this is an old post, but you should accept this as the correct answer. Hopefully this phrase will help others find this solution easier through the search engines: Installshield file created with CopyFile is always deleted during uninstall
{ "language": "en", "url": "https://stackoverflow.com/questions/7516922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Temp record Insertion technique I am using sql server 2008. I have to insert records in temporary table using multiple select statements like below. Insert into #temp Select a From TableA Insert into #temp Select a From TableB Insert into #temp Select a From TableC Insert into #temp Select a From TableD OR Insert Into #temp Select A From ( Select A from TableA Union Select B From TableB Union Select B From TableC )K Please advice which approach should be best or any other and Why? A: The two techniques you present are not interchangeable. The UNION operation will remove duplicate values while the individual INSERT operations will not. To get identical results, you'd need to use UNION ALL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a Table with a column of type BLOB in a DBAdapter I have a global DBAdapter and also for each Table one. In my global DB-Adapter I added the type "BLOB" to the column. But i don't get what i have to change in my DBAdapter for the specific Table. What I need to change there that it also works with the BLOB type. So here you go: Global DBAdapter: package de.retowaelchli.filterit.database; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import de.retowaelchli.filterit.database.ADFilterDBAdapter; public class DBAdapter { public static final String DATABASE_NAME = "filterit"; public static final int DATABASE_VERSION = 1; public static final String CREATE_TABLE_ADFILTER = "create table adfilter (_id integer primary key autoincrement, " + ADFilterDBAdapter.NAME+"," + ADFilterDBAdapter.KEYWORD+"," + ADFilterDBAdapter.CACHE + ");"; private static final String CREATE_TABLE_SFILTER = "create table sfilter (_id integer primary key autoincrement, " +SFilterDBAdapter.NAME+"," +SFilterDBAdapter.KEYWORD+"," +SFilterDBAdapter.SMILEY+ ");"; private static final String CREATE_TABLE_ADMESSAGES = "create table admessages (_id integer primary key autoincrement, " +MessagesDBAdapter.PHONENUMBER+"," +MessagesDBAdapter.MESSAGE+ ");"; //HERE I CHANGED IT TO BLOB! private static final String CREATE_TABLE_SMILEY = " create table smiley (_id integer primary key autoincrement, " +SmileyDBAdapter.SOURCE+" BLOB ," +SmileyDBAdapter.INFO+ ");"; private final Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; /** * Constructor * @param ctx */ public DBAdapter(Context ctx) { this.context = ctx; } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_ADFILTER); db.execSQL(CREATE_TABLE_SFILTER); db.execSQL(CREATE_TABLE_ADMESSAGES); db.execSQL(CREATE_TABLE_SMILEY); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Adding any table mods to this guy here } } /** * open the db * @return this * @throws SQLException * return type: DBAdapter */ public DBAdapter open() throws SQLException { this.DBHelper = new DatabaseHelper(this.context); this.db = this.DBHelper.getWritableDatabase(); return this; } /** * close the db * return type: void */ public void close() { this.DBHelper.close(); } } This is my DBAdapter of this Table: package de.retowaelchli.filterit.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class SmileyDBAdapter { public static final String ROW_ID = "_id"; public static final String SOURCE = "source"; public static final String INFO = "info"; private static final String DATABASE_TABLE = "admessages"; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; private final Context mCtx; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DBAdapter.DATABASE_NAME, null, DBAdapter.DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } /** * Constructor - takes the context to allow the database to be * opened/created * * @param ctx * the Context within which to work */ public SmileyDBAdapter(Context ctx) { this.mCtx = ctx; } public SmileyDBAdapter open() throws SQLException { this.mDbHelper = new DatabaseHelper(this.mCtx); this.mDb = this.mDbHelper.getWritableDatabase(); return this; } /** * close return type: void */ public void close() { this.mDbHelper.close(); } public long createSmiley(String source, String info ){ ContentValues initialValues = new ContentValues(); initialValues.put(SOURCE, source); initialValues.put(INFO, info); return this.mDb.insert(DATABASE_TABLE, null, initialValues); } public boolean deleteSmiley(long rowId) { return this.mDb.delete(DATABASE_TABLE, ROW_ID + "=" + rowId, null) > 0; //$NON-NLS-1$ } public Cursor getAllSmileys() { return this.mDb.query(DATABASE_TABLE, new String[] { ROW_ID, SOURCE, INFO }, null, null, null, null, null); } public Cursor getSmiley(long rowId) throws SQLException { Cursor mCursor = this.mDb.query(true, DATABASE_TABLE, new String[] { ROW_ID, SOURCE, INFO }, ROW_ID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } public boolean updateSmiley(long rowId, String source, String info, String cache){ ContentValues args = new ContentValues(); args.put(SOURCE, source); args.put(INFO, info); return this.mDb.update(DATABASE_TABLE, args, ROW_ID + "=" + rowId, null) >0; } } What I need to change in my SmileyDBAdapter to bring it working. That it supports the type BLOB. Im really frustrated after trying this for serval hours -.- Thx in Advance for your Answer Best Regards safari A: Check this Code for Inserting the Image from the Web link and store in the Database as BLOB and shown in ImageView . Java Code : CategoryDetails.Java public class CategoryDetails extends Activity { public NotesDbAdapter mDbHelper; ByteArrayBuffer baf ; private Cursor mNotesCursor; ImageView img; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mDbHelper = new NotesDbAdapter(this); mDbHelper.open(); new Task_like_flag().execute(); img=(ImageView)findViewById(R.id.ImageView01); } public Bitmap convertBlobToBitmap(byte[] blobByteArray) { Bitmap tempBitmap=null; if(blobByteArray!=null) tempBitmap = BitmapFactory.decodeByteArray(blobByteArray, 0, blobByteArray.length); return tempBitmap; } public class Task_like_flag extends AsyncTask<String, Void, Void> { private final ProgressDialog dialog = new ProgressDialog(CategoryDetails.this); JSONObject object_feed; // can use UI thread here protected void onPreExecute() { this.dialog.setMessage("Loading..."); this.dialog.setCancelable(false); this.dialog.show(); } @Override protected Void doInBackground(String... params) { URL url = null; try { url = new URL("http://www.theblacksheeponline.com/uploaded/Quick_images/681314276069brewehas.jpg"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //http://example.com/image.jpg //open the connection URLConnection ucon = null; try { ucon = url.openConnection(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //buffer the download InputStream is = null; try { is = ucon.getInputStream(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BufferedInputStream bis = new BufferedInputStream(is,128); baf = new ByteArrayBuffer(128); //get the bytes one by one int current = 0; try { while ((current = bis.read()) != -1) { baf.append((byte) current); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mDbHelper.createNote(baf.toByteArray()); return null; } @Override protected void onPostExecute(Void result) { byte[] imageByteArray; Bitmap theImage = null; try{ mNotesCursor = mDbHelper.fetchAllNotes(); startManagingCursor(mNotesCursor); if (mNotesCursor.moveToFirst()) { do { imageByteArray = mNotesCursor.getBlob(mNotesCursor.getColumnIndex(NotesDbAdapter.KEY_IMAGE)); ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByteArray); theImage= BitmapFactory.decodeStream(imageStream); } while (mNotesCursor.moveToNext()); } }catch(Exception e){ Log.v("Excep", ""+e); } img.setImageBitmap(theImage); if (this.dialog.isShowing()) { this.dialog.dismiss(); } } } } NotesDbAdapter.Class public class NotesDbAdapter { public static final String KEY_CATEGORY = "category"; public static final String KEY_DATE = "notes_date"; public static final String KEY_DESC = "item_desc"; public static final String KEY_PRIZE = "item_prize"; public static final String KEY_MODE = "mode"; public static final String KEY_MONTH = "month"; public static final String KEY_IMAGE = "img"; public static final String KEY_ROWID = "_id"; private static final String TAG = "NotesDbAdapter"; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; /** * Database creation sql statement */ private static final String DATABASE_CREATE = "create table notes (_id integer primary key autoincrement, " + "img BLOB not null);"; private static final String DATABASE_NAME = "data"; private static final String DATABASE_TABLE = "notes"; private static final int DATABASE_VERSION = 2; private final Context mCtx; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS notes"); onCreate(db); } } /** * Constructor - takes the context to allow the database to be * opened/created * * @param ctx the Context within which to work */ public NotesDbAdapter(Context ctx) { this.mCtx = ctx; } /** * Open the notes database. If it cannot be opened, try to create a new * instance of the database. If it cannot be created, throw an exception to * signal the failure * * @return this (self reference, allowing this to be chained in an * initialization call) * @throws SQLException if the database could be neither opened or created */ public NotesDbAdapter open() throws SQLException { mDbHelper = new DatabaseHelper(mCtx); mDb = mDbHelper.getWritableDatabase(); return this; } public void close() { mDbHelper.close(); } /** * Create a new note using the title and body provided. If the note is * successfully created return the new rowId for that note, otherwise return * a -1 to indicate failure. * * @param title the title of the note * @param body the body of the note * @return rowId or -1 if failed */ public long createNote(byte[] img) { byte yes[]=img; ContentValues initialValues = new ContentValues(); initialValues.put(KEY_IMAGE, yes); Log.v("row", ""+mDb.insert(DATABASE_TABLE, null, initialValues)); return mDb.insert(DATABASE_TABLE, null, initialValues); } /** * Return a Cursor over the list of all notes in the database * * @return Cursor over all notes */ public Cursor fetchAllNotes() { return mDb.query(DATABASE_TABLE, null, null, null, null, null, null); } } Main.xml : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon"/> </LinearLayout>
{ "language": "en", "url": "https://stackoverflow.com/questions/7516933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Reporting Software for .net application I have done lots of research and have had a look at crystal report, windward reports and Telerik, but they are not what I am looking for. I need reporting software that will integrate with a .net web application that runs on several servers but doesn't require an additional application running on the machine and doesn't require any additional license fees. It must have SQL integration, Export to word and Excel, have report parameter filtering and have charting capabilities. It would also be good if it could have dashboard view, ability for users of application to build their own reports similar to the SQL reporting model, timed report outputs the ability to send reports via email and integrate with Visual Studio 2010. so many reporting tools out there I haven't got a clue which to use I thank you in advance A: Check out ActiveReports.NET from DataDynamics. It covers all your needs. A: The free ReportViewer control ticks a lot of your boxes (in "local mode") I doubt you'll get all features for free: with the ReportViewer control you can do some of the missing features yourself. For example sending emails via the .net SMTP classes and using quartz.net for scheduling. "You get what you pay for" etc
{ "language": "en", "url": "https://stackoverflow.com/questions/7516936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to read Mifare classic Nfc tag? Could anyone explain the procedure of reading the NFC tag. I have gone through this link. http://mifareclassicdetectiononandroid.blogspot.com/2011/04/reading-mifare-classic-1k-from-android.html And Nfc Demo link also. There are two different procedures to read the tag. Do i need to go into blocks and sectors level to read my Mifare classic 1k tag? A: Yes, unless you are using Ndef. If you are storing Ndef data on your tag, you can connect to it as a Ndef type tag, and then just pass Ndef messages back and forth, the phone will handle all the block and sector reads for you. But if you are storing data that is not Ndef, then you have to read and write individual blocks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EF4 How to create query with dynamic select and where statement I am trying to create a some kind of dynamic loader for my models where I can specify which properties I need, the main purpose of it is to create a REST API which provides dynamic information as JSON for individual models. The API would be accessed by e.g. /api/model?id=581D1393-3436-4146-A397-E47CF5419453&fields=foo,bar,baz For this purpose I used the Dynamic LINQ like described in ScottGu's Blog, the problem is that I need to do queries over multiple tables with joins and load data from different tables, which I can't do in this case, as far I know. Now I use ObjectQuery<DbDataRecord> approach with Entity SQL where I can create a query however I want, but in this case I lose compiler validation and it is harder to refactor. My question is, is there a there a best practice scenario for this kind of problem? And is it may be simpler to achieve with some other ORM? Greetings Russlan A. A: Actually I think you can do it, though you think you can't. I am saying this because of the laze loading. using(var someContext = new SomeContextEntities()) { var data = someContext.Entity; foreach(var kvp in queries) { switch(kvp.Key) { case "q1": var val = kvp[kvp.Key]; data = data.Where(q => q.q1 == val); break; case "q2": var val2 = kvp[kvp.Key]; data = data.Where(q => q.q2 == val2); break; case "q3": var val3 = kvp[kvp.Key]; data = data.Where(q => q.q1.q3 == val3); ... } } return data.ToList(); } If you look at the generated script or result set, you will get what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: parsing using DOM Element Suppose I have some html and I want to parse something from it. In my html I know A, and want to know what is in C . I start getting all td elements, but what to do next ? I need to check something like " if this td has A as value then check what is written in third td after this. But how can I write it ? $some_code = (' .... <tr><td>A</td><td>...</td><td>c</td></tr> ..... '); $doc->loadHTML($some_code); $just_td = $doc->getElementsByTagName('td'); foreach ($just_td as $t) { some code.... } A: With XPath: /html/body//tr/td[text()="A"]/following-sibling::td[3] will find the third sibling of a td element with text content of A that is a child of a tr element anywhere below the html body element.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How should I Encode my Twitter Key? I have my consumer and secret key. I know I have to encode the secret key when it is included in my app. What is the best way to go around doing this? A: The first solution could be to use obfuscation (search for ProGuard for Android, there are a lot of resources about it) and the next one could be to add extra security decoding all of your strings using one way encryption (algorithms like AES does are useful). Of course the best option is to avoid adding this kind of keys and moving to the server side, adding the code to be used in the Android client. This solution not always can be applied, of course, but did you asked yourself if it's really needed the key in your client device? If you move your Twitter key to a server that does all the job related with the Twitter service (publish, get the timeline, etc), you won't need to add it to the app, you only will need to communicate securely your clients with your server. I know, that this solution only could apply if you have a really powerful service (lot of effort to do it) and you are able to sign to your server with secure methods (SSL, etc).
{ "language": "en", "url": "https://stackoverflow.com/questions/7516949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there Any way to imitate Lion's Launchpad? I have been struggling to imitate Launchpad. At the beginning I thought about making NSWindow bgcolor transparent: //make NSWindow's bgcolor transparent [window setOpaque:NO]; [window setBackgroundColor:[NSColor clearColor]]; But now I realized it's way more ideal to * *capture wallpaper *blur it and make it bg-image for NSWindow or a view Rather than hiding all the opened windows and menubar, which was the first idea I had have come with (Still not sure with better, if you had any better idea...). * *Capture & blur wallpaper used by a user *Make it background image for nswindow or a view *Fade-in to fullscreen view *Click somewhere blank or press ESC to fade-out Are those possible to achieve without using private APIs? Sorry if it's not clear my poor English. Simply I'm trying to imitate Launchpad-styled full screen. Thanks for any advice. A: To get an image of the desktop background, use: NSURL *imageURL = [[NSWorkspace sharedWorkspace] desktopImageuRLForScreen:[NSScreen mainScreen] NSImage *theDekstopImage = [[NSImage alloc] initWithContentsOfURL:imageURL]; You can blur the image using CIFilter. Here's a Apple doc describing how to apply filters. And then you can load that image into a color and set that as the background color for the window. Additionally, set the window to have no style mask (no close buttons, title frame, etc.), cover the screen, and be in front of everything except the dock: [yourWindow setBackgroundColor:[NSColor colorWithPatternImage:theDesktopImage]]; [yourWindow setStyleMask:NSBorderlessWindowMask]; [yourWindow setLevel:kCGDockWindowLevel - 1]; [yourWindow setFrame:[[NSScreen mainScreen] frame] display:YES]; To have the window fade in, you can use NSWindow's animator proxy. (Replace 1.0 with 0.0 to make it fade out.) [[yourWindow animator] setAlphaValue:1.0]; Of course you could customize that a bit more with things like CoreAnimation, but this should work just fine. To handle background clicking, I suggest making a subclass of NSView where you -orderOut: your window on -mouseDown:. Then put an instance of that subclass that spans the entire frame of your window. Also, NSViews sometimes don't respond to key events, so you can add an event listener to detect any time the escape key is pressed while your app is active: [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:(NSEvent *ev)^ { if([ev keyCode] == 0x53) { [yourWindow orderOut:self]; } return ev; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php: looping thru results from mysql query to increment counter (associative array) I'm retrieving data from a MySQL db and creating reports from it. I need to get counts when certain conditions are met, and since db queries are rather expensive (and I will have a lot of traffic), I'm looping thru the results from a single query in order to increment a counter. It seems like it's working (the counter is incrementing) and the results are somewhat close, but the counters are not correct. At the moment, there are 411 records in the table, but I'm getting numbers like 934 from a ['total'] counter and 927 for ['males'], and that definitely can't be right. However, I get 4 from ['females'], which is correct… I'm pretty sure it was working last night, but now it's not—I'm quite baffled. (there are still just 411 records) $surveydata = mysql_query("SELECT `age`,`e_part`,`gender` FROM $db_surveydata;") or die(mysql_error()); $rowcount = mysql_num_rows($surveydata); $age=array('18+'=>0,'<18'=>0,'total'=>0); $e_part=array('yes'=>0,'no'=>0,'total'=>0); $genders=array('male'=>0,'female'=>0,'trans'=>0,'don\'t know'=>0,'total'=>0); while ($responses = mysql_fetch_assoc($surveydata)) { foreach ($responses as $response){ switch ($response){ case $responses['age']: if ($responses['age'] > 18) {$age['18+']++;$age['total']++;} // i tried putting the ['total'] incrementer in the if/else // just in case, but same result else {$age['<18']++;$age['total']++;} break; case $responses['e_part']: if ($responses['e_part']) {$e_part['yes']++;} else {$e_part['no']++;} $e_part['total']++; break; case $responses['gender']: switch ($responses['gender']){ case 1:$genders['male']++;break; case 2:$genders['female']++;break; case 3:$genders['trans']++;break; case 9:$genders['don\'t know']++;break; default:break; } $genders['total']++; break; default:break; } // end switch } //end for } // end while thanks! A: this is the problem: foreach ($responses as $response){ switch ($response){ case $responses['age']: switch $responses looks for match foreach ($responses as $k=>$v){ switch ($k){ case 'age': if ($v > 18) .... A: mysql_fetch_assoc() retrieves a single row from the table. You then loop over that row, processing each individual field. Then the long set of if() checks to determine which field you're on. That entire structure could be changed to: while($response = mysql_fetch_assoc($surveydata)) { if ($responses['age'] > 18) { $age['18+']++; } else { $age['<18']++; $age['total']++;} if ($responses['e_part']) { $e_part['yes']++; } else { $e_part['no']++; } $e_part['total']++; switch ($responses['gender']){ case 1:$genders['male']++;break; case 2:$genders['female']++;break; case 3:$genders['trans']++;break; case 9:$genders['don\'t know']++;break; default:break; } $genders['total']++; } A: There's no need for the switch ($response); you can't really switch on an array like that. And even if you could, the 'values' you get wouldn't make any sense -- i'm thinking if it works at all, the value you're switching on would be either 'Array' or the length of the array. (I forget how PHP handles arrays-as-scalars.) You'll want something like this... $total = 0; while ($response = mysql_fetch_assoc($surveydata)) { if (isset($response['age'])) { ++$age[($response['age'] < 18) ? '<18' : '18+']; ++$age['total']; } if (isset($response['e_part'])) { ++$e_part[($responses['e_part']) ? 'yes' : 'no']; ++$e_part['total']; } if (isset($response['gender'])) { switch ($response['gender']) { case 1: ++$genders['male']; break; case 2: ++$genders['female']; break; case 3: ++$genders['trans']; break; case 9: ++$genders["don't know"]; break; } ++$genders['total']; } ++$total; } The benefit of the if (isset(...)) is that if 'age', 'e_part', or 'gender' is null, the corresponding code to count it won't get activated. It does about the same thing as your code, minus the embarrassing loop -- and minus the counting of the field even though it is null, because every row will have the same fields.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you use the net functions effectively in Go? For example, having basic packet protocol, like: [packetType int][packetId int][data []byte] And making a client and server doing simple things with it (egx, chatting.) A: Here's a client and server with sloppy panic error-handling. They have some limitations: * *The server only handles one client connection at a time. You could fix this by using goroutines. *Packets always contain 100-byte payloads. You could fix this by putting a length in the packet somewhere and not using encoding/binary for the entire struct, but I've kept it simple. Here's the server: package main import ( "encoding/binary" "fmt" "net" ) type packet struct { // Field names must be capitalized for encoding/binary. // It's also important to use explicitly sized types. // int32 rather than int, etc. Type int32 Id int32 // This must be an array rather than a slice. Data [100]byte } func main() { // set up a listener on port 2000 l, err := net.Listen("tcp", ":2000") if err != nil { panic(err.String()) } for { // start listening for a connection conn, err := l.Accept() if err != nil { panic(err.String()) } handleClient(conn) } } func handleClient(conn net.Conn) { defer conn.Close() // a client has connected; now wait for a packet var msg packet binary.Read(conn, binary.BigEndian, &msg) fmt.Printf("Received a packet: %s\n", msg.Data) // send the response response := packet{Type: 1, Id: 1} copy(response.Data[:], "Hello, client") binary.Write(conn, binary.BigEndian, &response) } Here's the client. It sends one packet with packet type 0, id 0, and the contents "Hello, server". Then it waits for a response, prints it, and exits. package main import ( "encoding/binary" "fmt" "net" ) type packet struct { Type int32 Id int32 Data [100]byte } func main() { // connect to localhost on port 2000 conn, err := net.Dial("tcp", ":2000") if err != nil { panic(err.String()) } defer conn.Close() // send a packet msg := packet{} copy(msg.Data[:], "Hello, server") err = binary.Write(conn, binary.BigEndian, &msg) if err != nil { panic(err.String()) } // receive the response var response packet err = binary.Read(conn, binary.BigEndian, &response) if err != nil { panic(err.String()) } fmt.Printf("Response: %s\n", response.Data) } A: Check out Jan Newmarch's "Network programming with Go".
{ "language": "en", "url": "https://stackoverflow.com/questions/7516958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascript: How can I remove appended child row (tr)? I am using JS to append array data to a table. I am trying to add a button that removes the appended data, and puts its own data in instead. I can get the data to be added, but I cant get the data removed. I have tried these with no luck - .children().last().remove(); & .removeChild() ; I have a fiddle but I cant get the original data remove when new added (button now works! -thanks) - http://jsfiddle.net/2waZ2/37/ What code do I add so when the new line from the array is added the old data is removed? Code to append on load: var row = document.createElement('tr'); row.innerHTML = displayArrayAsTable(QR4, 24, 25); document.getElementById('mytable').appendChild( row ) ; Button code to add data: function addNewRow() { var row = document.createElement('tr'); row.innerHTML = displayArrayAsTable(QR4L, 24, 25); document.getElementById('mytable').appendChild( row ) ; } A: http://jsfiddle.net/2waZ2/47/ Removing the 1st child row: var table = document.getElementById('mytable'); table.removeChild(table.children[1]) A: I have updated the fiddle and it works fine now. You can use something like this before adding the new row: var last = document.getElementById('mytable').lastChild ; document.getElementById('mytable').removeChild(last); A: A trivial answer with jQuery: http://jsfiddle.net/guard/2waZ2/48/
{ "language": "en", "url": "https://stackoverflow.com/questions/7516965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Swing, how to apply KeyListener on no specific component Generally we apply the Key Listener on specific components like text field, password fields, etc. But I would like to generalize this listener behavior to be applicable to all. A: Swing was designed to be used with Key Bindings which might do what you want. I would start by checking out Key Bindings. Don't forget to read the Swing tutorial for complete information. If that doesn't help then see Global Event Listeners for a couple of suggestions. A: All swing components are a JComponent. You may use all of then as a JComponent: @Override public void keyTyped(KeyEvent e) { JComponent component = (JComponent) e.getSource(); // TODO Implements your action } You can see that this is a limited approach. You also may work according to the class of your source: @Override public void keyTyped(KeyEvent e) { Object source = (JComponent) e.getSource(); if (source instanceof JTextField) { // TODO Implment action for JTextField } else if (source instanceof JTextArea) { // TODO Implment action for JTextArea } } Depending on your needs you may use the Reflections API to do this...
{ "language": "en", "url": "https://stackoverflow.com/questions/7516971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can't fetch data with Ruby and Basecamp API My code: require 'rubygems' require 'basecamp' basecamp = Basecamp.establish_connection!('example.basecamphq.com', 'example', '123456', true) projects = Basecamp::Project.find(:all) projects.inspect It gives: /Users/kir/.rvm/gems/ruby-1.8.7-p352@project/gems/activeresource-3.1.0/lib/active_resource/base.rb:922:in `instantiate_collection': undefined method `collect!' for #<Hash:0x105faa450> (NoMethodError) from /Users/kir/.rvm/gems/ruby-1.8.7-p352@project/gems/activeresource-3.1.0/lib/active_resource/base.rb:894:in `find_every' from /Users/kir/.rvm/gems/ruby-1.8.7-p352@project/gems/activeresource-3.1.0/lib/active_resource/base.rb:806:in `find' from bs.rb:4 What's wrong with my code? A: There were some problems with the basecamp wrapper gem and rails >= 3.1.x. The "undefined method `collect!'" error was one of them. I pushed some fixes and bumped the gem version to 0.0.7 which should solve that and other problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Perl period vs comma operator Why does print "$str is " , ispalindrome($str) ? "" : " not" , " a palindrome\n" print "madam is a palindrome", but print "$str is " . ispalindrome($str) ? "" : " not" . " a palindrome\n" prints ""? A: The conditional operator (? :) has higher precedence than the comma, but lower than the period. Thus, the first line is parsed as: print("$str is " , (ispalindrome($str) ? "" : " not"), " a palindrome\n") while the second is parsed as: print(("$str is " . ispalindrome($str)) ? "" : (" not" . " a palindrome\n"))
{ "language": "en", "url": "https://stackoverflow.com/questions/7516978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Retrieving irq number of a NIC I need to retrieve an interrupt number of interface by its' name as appears in ifconfig. Is there some standard API to do it? A: The interrupt number lives in sysfs. Look for the file /sys/class/net/[ethname]/device/irq. For example: more /sys/class/net/*/device/irq :::::::::::::: /sys/class/net/eth0/device/irq :::::::::::::: 30 :::::::::::::: /sys/class/net/eth1/device/irq :::::::::::::: 29 A: /sys/class/net/[ethname]/device/irq should legacy irq number, device may not be using legacy irq, it may be using msix. check $ ls /sys/class/net/eth0/device/msi_irqs/ or $ grep eth0 /proc/interrupts
{ "language": "en", "url": "https://stackoverflow.com/questions/7516984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: dot notation and accessing instance variable So I was reading some other thread about using dot notation to access an instance variable and a definition was the following: By self.myVariable you are accessing the instance variable myVariable and by myVariable you are accessing the local variable. They're not the same thing. This seems to be very confusing to me, especially coming from a java background. Can someone explain to me clearly what he means by local variable here? Is this the same thing as using this in java? If it is the same then in java if say you have: private int myVariable; int testFunction(int m) { myVariable = 3; } This would access myVariable instance variable as there is no local variable defined in the method. A: Self.myVariable does not access the instance variable (most of the time there won't be a difference, there exceptions like when you have a custom setter). Instead it accesses the getter of the property. It is equivalent to: [self myVariable]; If you want to access an instance variable directly you can use just: myVariable; If you want to access the instance variable of another object you can do: otherObject->myVariable; Although as Caleb says below in the comments, this is frowned upon. A: from what i know though the dot notation is just the new way of accessing things. prior it would have been [self myVariable] where as now you can do self.myVariable. the major differences between objective c and java (at least for this question) is how values or objects are passed in this call OBJECTIVE C (look at the messaging section) JAVA "By self.myVariable you are accessing the instance variable myVariable and by myVariable you are accessing the local variable. They're not the same thing." this makes sense although i think its phrased weird this is what they are saying self.myVariable - instance variable of a class (happens to be self) myVariable - local variable foo.myVariable - instance variable of class foo also remember "local" is the same as scope so int x; //local variable to the class with a scope of the whole class method foo{ int x; //local variable to the method with a scope of the method } A: Hm…. I'm not too sure what the definition is talking about, but a local variable is definitely a variable defined inside a method. If you are the class that has the instance variable is accessing the instance variable, you should just go ahead and call it directly just by it's instance variable name. However, if there's a local variable defined in the method, then it would get the local variable instead of your instance variable. So for example @interface Class : NSObject { int instanceVariable; } @end @implementation Class -(id)init { if (self = [super init]) { //You can access your instance variable like this instanceVariable = 1; } } @end By the way, to use the dot syntax, you must implement an accessor method or use the @property and @synthesize. @interface Class : NSObject { int instanceVariable; } @property int instanceVariable; @end @implementation Class @synthesize instanceVariable; -(id)init { … } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/7516985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I access flash messages in zend framework, in IE? I'm using this in my layout file $flash_messages = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger')->getMessages(); It works correctly in all browsers, except IE. The array is empty in IE. I confirmed that the messages are being set correctly, and are accessed correctly in other browsers. It is just not working in IE. Edit: I think I spoke too soon. The messages are not even getting set, and this is the line I am using (though this line gets executed) $this->_helper->FlashMessenger('my message here...'); A: Hmm wierd, first time of my life i hear that something that is server side behaves differently in different browsers.. * *It could be a session problem, check your IE accepts all cookies. *It could be a css problem, check that your message isn't just hidden by incompatible css rules And i believe it's : Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger')->setMessage('my message'); A: Flash messages are just like sessions but with lifetime of 1 hop only . i.e first request will store the data , in second request you can access the data but in third you will get empty data . I think in IE you are jumping to third request or missing the first request itself (the time to store data) .
{ "language": "en", "url": "https://stackoverflow.com/questions/7516989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I get a ratio from a selection in sql? I will revise the question with an appropriate name once I'm certain how to communicate what I want. I have a table called batch_log where people start and stop the work on a batch. Each entry looks like this: "id";"batch_id";"userid";"start_time";"end_time";"time_elapsed" "99980";"cd9e4c9e-d8bb-4983-64f4-4e777b451b93";"phastie";"2011-09-22 08:54:34";"2011-09-22 10:07:07";"01:12:33" What I really want to do is for a particular person select how long they have tracked compared to the total time for that batch so that I can give them credit for that much of the estimated time. Is there a way to do this in sql? EDIT[Ended up doing the following:] SELECT user_time_by_batch.batch_id, userid, user_time_by_batch / total_time_by_batch FROM ( SELECT SUM(time_elapsed) user_time_by_batch, userid, batch_id FROM batch_log Where start_time between "2011-08-01" and now() and end_time is not null and time_elapsed BETWEEN "00:00:00" AND "10:00:00" and batch_id not in ("-1", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9", "-10", "-11", "-12", "-13") GROUP BY batch_id, userid ) user_time_by_batch INNER JOIN ( SELECT SUM(time_elapsed) total_time_by_batch, batch_id FROM batch_log Where start_time between "2011-08-01" and now() and end_time is not null and time_elapsed BETWEEN "00:00:00" AND "10:00:00" and batch_id not in ("-1", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9", "-10", "-11", "-12", "-13") GROUP BY batch_id ) total_time_by_batch ON user_time_by_batch.batch_id = total_time_by_batch.batch_id A: This should give you what you need SELECT user_id, user_time_by_batch / total_time_by_batch FROM ( SELECT SUM(time_elapsed) user_time_by_batch, user_id, batch_id FROM batch_log GROUP BY batch_id, user_id ) user_time_by_batch INNER JOIN ( SELECT SUM(time_elapsed) total_time_by_batch, batch_id FROM batch_log GROUP BY batch_id ) total_time_by_batch ON user_time_by_batch.batch_id = total_time_by_batch.batch_id A: select batch_id, userid, SUM(end_time - start_time) AS total_user_contribution FROM batch_log GROUP BY batch_id, userid will get you the individual user contributions on a per-batch basis. To get the total time for a batch, you could either sum up the individual contributions as you retrieve the data from the above query, or run a separate query to calculate the sum there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Calling SLNode find() method I am working on an assignment for school where a SinglyLinkedList class is provided and we are supposed to create a program that makes calls to this class to add, delete, find, and display items in a list. I have implemented the add, delete and display methods just fine, but I can't figure out how to call the find method. Any help would be great. Here is the method from the SinglyLinked Class which I need to implement: private SLNode<E> find( E target ) { SLNode<E> cursor = head.getSuccessor(); while ( cursor != tail ) { if ( cursor.getElement().equals( target ) ) { return cursor; // success } else { cursor = cursor.getSuccessor(); } } return null; // failure } Here is what I have...I've included the implementations of the other methods as well: public static void addPet() { Scanner keyboard = new Scanner(System.in); System.out.print("\nPlease enter your pet's name and what type of \n animal it is(i.e. \"Mickey, Mouse\"): \n"); petType = keyboard.nextLine(); pet.add(petType, 0); System.out.printf("%s was added to the list.\n\n", petType); } public static void displayPets() { int i; for(i=0; i<pet.getLength(); i++) { System.out.printf("\n%d.\t%s",i+1, pet.getElementAt(i)); } System.out.print("\n\n"); } public static void deletePet() { int i; int j; int k; String a; for(i=0; i<pet.getLength(); i++) { System.out.printf("\t%d. %s\n",i+1, pet.getElementAt(i)); } System.out.println(); System.out.printf("\nPlease enter the number of the item to delete: \n"); Scanner input = new Scanner(System.in); j = input.nextInt(); System.out.printf("%s was deleted from the list.\n\n", pet.getElementAt(j-1)); pet.remove(j-1); } public static void findPet() { String keyword; Scanner keyboard = new Scanner(System.in); System.out.print("Please enter a search term: "); keyword = keyboard.nextLine(); //.find(keyword); } I'm sure I will kick myself because it's simpler than I'm making it, but I'm really just stuck. A: Your list apparently contains pets, represented by some pet type (which looks like a String). So find expects a similar pet type you added in addPet. And returns an SLNode containing the found pet, if there is one. Since you haven't posted SLNode, I can't tell how to get the element contained in it, but calling getElement() on it looks like a safe bet :-) So you need to check the value returned by find, for nullness. If it's not null, you can e.g. get the element contained in it and print it. I suppose this should be enough for you to write the code; if it's not clear, please comment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change CSS value when page has loaded on all EXCEPT first instance I have the following piece of code do change the value of a division once the page has loaded but I was wondering if it would be possible to amend it to change the value of all of the divisions with that class with the exception of the first one. jQuery('#accordion div.pane').css('display', 'none'); A: Simply use the :gt selector to select all but the first: jQuery('#accordion div.pane:gt(0)').css('display', 'none'); or the less concise "notty firsty": jQuery('#accordion div.pane:not(:first)').css('display', 'none'); and why not use hide instead of setting the style: jQuery('#accordion div.pane:gt(0)').hide(); For better performance (and a concise solution), you might consider using JavaScript's Array.slice, which works on jQuery objects since they are arrayish: jQuery('div').slice(1).hide(); A: jQuery('#accordion div.pane').not(':first').css('display', 'none'); A: You could give your first element a distinguishing ID or class, and use the jQuery not selector: http://api.jquery.com/not-selector
{ "language": "en", "url": "https://stackoverflow.com/questions/7517008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android - connecting to Wifi without security regulations (no WEP/WPA/WPA2) I tried to establish a connection to an unsecured Access point, but it always creates a new profile with WPA2. ap_ssid = "\"AP_SSID\""; wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(true); } config = new WifiConfiguration(); config.SSID = ap_ssid; config.status = WifiConfiguration.Status.ENABLED; int netID = wifiManager.addNetwork(config); wifiManager.enableNetwork(netID, true); A: config.allowedKeyManagement.set(KeyMgmt.NONE);
{ "language": "en", "url": "https://stackoverflow.com/questions/7517015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sonar - how to create sub projects with sonnar-runner I have a Java project which consists of a couple of modules. I am using Sonar to statically analyse my code. Currently I am using sonar-runner to analyse each of the modules, and they appear as different Projects in the main page of Sonar. I would like to see the main project name on the main page, and, once I will click on it, and than on "Components" - to see all of it's modules as sub-projects - just like it appears here: http://nemo.sonarsource.org/components/index/308832 A: No it's not possible with Java runner. Only Maven plugin and Ant task support project structures with modules. Note that the modules of C# projects are automatically created from the VisualStudio solution file, even if the Java runner is used. A: Do you project use Maven ?If it is the case it should work fine if you have a pom.xml for each module and one for your parent module.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to access Assembly Information in Asp.Net How do you access the Assembly Information in Asp.Net (Title, Description, Company, etc.)? Do you have to use reflection? A: You're just talking about web.config? <configuration> <system.web> <compilation> <assemblies> <add assembly="<AssemblyName>, Version=<Version>, Culture=<Culture>, PublicKeyToken=<PublicKeyToken>"/> </assemblies> </compilation> </system.web> </configuration> In code-behind, you might do this: Imports System.Web.Configuration ... WebConfigurationManager.GetSection("sectionyouwant") Here's an example from msdn: http://msdn.microsoft.com/en-us/library/system.web.configuration.webconfigurationmanager.aspx A: To read the information in the assembly level attributes (eg. AssemblyCopyrightAttribute) you will need to use reflection. However with a little helper it is quite easy: public static T GetAttribute<T>(this Assembly asm) where T : Attribute { if (asm == null) { throw new ArgumentNullException("asm"); } var attrs = asm.GetCustomAttributes(typeof(T), false); if (attrs.Length != 1) { throw new ApplicationException( String.Format("Found {0} instances of {1} in {2}. Expected 1", attrs.Length, typeof(T).Name, asm.FullName)); } return (T)(attrs[0]); } and thus given a type, TargetType, from that assembly: string copyright = typeof(TargetType).Assembly.GetAttribute<AssemblyCopyrightAttribute>().Copyright;
{ "language": "en", "url": "https://stackoverflow.com/questions/7517017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check if parameter is NULL within WHERE clause I´m having trouble with a Stored Procedure that takes about forever to execute. It is quite large and I can understand that I´ll take some time but this one continues for almost 20 minutes. After some debugging and researching I noticed that replacing this part of the WHERE clause; ((p_DrumNo IS NULL) OR T_ORDER.ORDER_ID IN (SELECT ORDER_ID FROM ORDERDELIVERY)) made a HUGE difference. So the Procedure works just fine as long as p_DrumNo is NULL or I modify the above to not check if p_DrumNo is NULL; (T_ORDER.ORDER_ID IN (SELECT ORDER_ID FROM ORDERDELIVERY)) The goal with this WHERE clause is to filter the result set on p_DrumNo if it´s passed in to the Stored Procedure. The WHERE clause then continues with further conditions but this specific one halts the query. ORDERDELIVERY is just a ~temporary table containing ORDER_IDs related to the parameter p_DrumNo. How can this simple IS NULL-check cause such big impact? It´s probably related to the use of OR together with the subquery but I don´t understand why as the subquery itself works just fine. Thanks in advance! UPDATE [2011-09-23 10:13] I´ve broken down the problem into this small query that show the same behaviour; Example A SQL query SELECT * FROM T_ORDER WHERE ('290427' IS NULL OR ORDER_ID IN (SELECT ORDER_ID FROM T_ORDER WHERE ORDERNO LIKE '290427%') ); Execution plan OPERATION OBJECT_NAME OPTIONS COST ------------------------------------------------------------ SELECT STATEMENT 97 FILTER TABLE ACCESS T_ORDER FULL 95 TABLE ACCESS T_ORDER BY INDEX ROWID 2 INDEX PK_ORDER UNIQUE SCAN 1 Example B SQL query SELECT * FROM T_ORDER WHERE ( ORDER_ID IN (SELECT ORDER_ID FROM T_ORDER WHERE ORDERNO LIKE '290427%') ); Execution plan OPERATION OBJECT_NAME OPTIONS COST ------------------------------------------------------------ SELECT STATEMENT 4 NESTED LOOPS 4 TABLE ACCESS T_ORDER BY INDEX ROWID 3 INDEX IX_T_ORDER_ORDERNO RANGE SCAN 2 TABLE ACCESS T_ORDER BY INDEX ROWID 1 INDEX PK_ORDER UNIQUE SCAN 0 As you all can see the first query (example A) makes a full table scan. Any ideas on how I can avoid this? A: Instead of evaluating your procedure's parameter state in the SQL statement itself, move that evaulation to the containing PL/SQL block so it's executed only once before the ideal SQL statement is submitted. For example: CREATE OR REPLACE PROCEDURE my_sp (p_DrumNo VARCHAR2) IS BEGIN IF p_DrumNo IS NULL THEN SELECT ... INTO ... -- Assumed FROM ... WHERE my_column = p_DrumNo; ELSE SELECT ... INTO ... -- Assumed FROM ... WHERE ORDER_ID IN (SELECT ORDER_ID FROM ORDERDELIVERY); END; END; I've also had some success in tuning SQL statements with an OR by breaking the statement into two mutually exclusive statements with a UNION ALL: SELECT ... FROM ... WHERE p_DrumNo IS NULL AND ORDER_ID IN (SELECT ORDER_ID FROM ORDERDELIVERY) UNION ALL SELECT ... FROM ... WHERE p_DrumNo IS NOT NULL AND my_column = p_DrumNo; A: You came across such an issue due to the fact your index doesn't work if you include OR to your query. To get the same info I'd rather do this to make the index work (basing on updated query): SELECT * FROM T_ORDER WHERE '290427' IS NULL UNION ALL SELECT * FROM T_ORDER WHERE ORDER_ID IN (SELECT ORDER_ID FROM T_ORDER WHERE ORDERNO LIKE '290427%')); It will return the same result since 290427 seem to be a variable and it tends to be null or not null at the particular moment. But also you can try using dynamic sql inside you stored procedure for such purposes: %begin_of_the_procedure% query_ := 'SELECT * FROM T_ORDER WHERE 1=1'; if var_ is not null then query_ := query_||' AND ORDER_ID IN (SELECT ORDER_ID FROM T_ORDER WHERE ORDERNO LIKE '''||to_char(var_)||'%'')'; end if; open cursor_ query_; %fetching cursor loop% %end_of_the_procedure% And I wanted to say that I don't see sence of that IN, it'd be quite the same: SELECT * FROM T_ORDER WHERE ('290427' IS NULL OR ORDERNO LIKE '290427%');
{ "language": "en", "url": "https://stackoverflow.com/questions/7517018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is there a more efficient way to get this flat data into a dictionary? I have the following code: public class Alert { public string Alias { get; set; } public int ServiceHours { get; set; } public int TotalHoursDone { get; set; } public int UserId { get; set; } public int VehicleId { get; set; } } private static readonly List<Alert> AlertsToDo = new List<Alert>(); public void SomeFunction() { // creates a dictionary of user ids as the key with their alerts // (sorted by alias) as the value. // Just one loop needed and no awkward state logic. var alertsGrouped = AlertsToDo.Select(a => a.UserId) .Distinct() .ToDictionary(userId => userId, userId => AlertsToDo.Where(a => a.UserId == userId) .OrderBy(a => a.Alias) .ToList()); } So, I have a list of Alert objects. My LINQ query outputs a Dictionary the key of which is the UserId and the value of which is a List of Alerts for that UserId sorted by Alias. I'm happy enough with the ingenuity of this query but am wondering if there's an easier way to do it? Specifically, I'm having to use a second query for every key to create the value List. Asking purely out of interest as this is fast enough for the job in hand. A: There's a shorter approach that is more readable, using the Enumerable.GroupBy method. For a small amount of data you most likely won't see a difference, whereas a large amount of data would change the performance. Your query first gets the distinct values, then filters items on UserId. The grouping cuts down on those steps upfront. To know for sure you would need to profile. Here's the query using grouping: var query = AlertsToDo.GroupBy(a => a.UserId) .ToDictionary(g => g.Key, g => g.OrderBy(a => a.Alias).ToList()); A: Sorry about the delay, but as promised here are some test results. The code I tested with: public partial class Form1 : Form { public Form1() { InitializeComponent(); } public class Alert { public string Alias { get; set; } public int ServiceHours { get; set; } public int TotalHoursDone { get; set; } public int UserId { get; set; } public int VehicleId { get; set; } } private static readonly List<Alert> AlertsToDo = new List<Alert>(); private void button1_Click(object sender, EventArgs e) { var rng = new Random(); var watch = new System.Diagnostics.Stopwatch(); watch.Start(); for (int i = 0; i < 1000000; i++) { int random = rng.Next(); AlertsToDo.Add(new Alert { Alias = random.ToString(), UserId = random }); } Console.WriteLine(@"Random generation: {0}", watch.ElapsedMilliseconds); watch = new System.Diagnostics.Stopwatch(); watch.Start(); var alertsGrouped = AlertsToDo.Select(a => a.UserId) .Distinct() .ToDictionary(userId => userId, userId => AlertsToDo.Where(a => a.UserId == userId) .OrderBy(a => a.Alias) .ToList()); watch.Stop(); Console.WriteLine(@"Mine: {0}", watch.ElapsedMilliseconds); Console.WriteLine(alertsGrouped.Count); watch = new System.Diagnostics.Stopwatch(); watch.Start(); alertsGrouped = AlertsToDo.GroupBy(a => a.UserId) .ToDictionary(g => g.Key, g => g.OrderBy(a => a.Alias).ToList()); watch.Stop(); Console.WriteLine(@"Ahmad's: {0}", watch.ElapsedMilliseconds); Console.WriteLine(alertsGrouped.Count); } } And the output: Random generation: 769 Mine: 32164861 (over 8 hours) 999798 Ahmad's: 4133 999798 Unsurprisingly the GroupBy is quicker as my version performs a subquery, but just look at how much quicker! So the winner is: Ahmad, obviously.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How Come when I sampling profile a program and it actually runs faster than not profiling? I use DotTrace 4.5 performance time in release mode: 2400000000 Basic: 00:00:08.8051103 2400000000 Five: 00:00:09.1561338 2400000000 Overload: 00:00:16.3740938 2400000000 IListtoFive: 00:00:15.5841445 time when profiling in release mode. 2400000000 Basic: 00:00:01.0048224 2400000000 Five: 00:00:03.5416982 2400000000 Overload: 00:00:11.8009959 2400000000 IListtoFive: 00:00:11.2568770 My code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace testLineIndex { class Program { static long Five(int s0, int s1, int s2, int s3, int s4) { return s4 + 100 * s3 + 10000 * s2 + 1000000 * s1 + 100000000 * s0; } static long Overload(IList<int> line) { return Five(line[0], line[1], line[2], line[3], line[4]); } static long IListtoFive(IList<int> line) { return line[0]+100* line[1]+10000* line[2]+1000000* line[3]+100000000*line[4]; } static void Main(string[] args) { Stopwatch watch = new Stopwatch(); long testSize = 400000000; //List<int> myList = new List<int> { 1, 2, 3, 4, 5 }; int[] myList = new int[] { 1, 2, 3, 4, 5 }; long checksum = 0; watch.Start(); for (long i = 0; i < testSize; i++) { long ret = Five(1,2,3,4,5); checksum += ret % 9; } watch.Stop(); Console.WriteLine(checksum); Console.WriteLine("Basic: {0}", watch.Elapsed); checksum = 0; watch.Restart(); for (long i = 0; i < testSize; i++) { long ret = Five(myList[0], myList[1], myList[2], myList[3], myList[4]); checksum += ret % 9; } watch.Stop(); Console.WriteLine(checksum); Console.WriteLine("Five: {0}",watch.Elapsed); checksum = 0; watch.Restart(); for (long i = 0; i < testSize; i++) { long ret = Overload(myList); checksum += ret % 9; } watch.Stop(); Console.WriteLine(checksum); Console.WriteLine("Overload: {0}", watch.Elapsed); checksum = 0; watch.Restart(); for (long i = 0; i < testSize; i++) { long ret = IListtoFive(myList); checksum += ret % 9; } watch.Stop(); Console.WriteLine(checksum); Console.WriteLine("IListtoFive: {0}", watch.Elapsed); Console.ReadKey(); } } } A: My suspicion is the debugger. Even if you are running it in release mode, running it from VS attaches the debugger, which would slow it down considerably.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Finding the least-used permutation I need to distribute a set of data evenly over time based on historical data such that each digit appears an equal (or close to equal) number of times in each position over time. The problem is, given a list of orderings used in the past, that look like this (but could have any number of elements): 1,2,5,3,4 4,1,5,2,3 1,3,5,2,4 4,1,2,3,5 2,4,1,3,5 5,1,4,3,2 1,5,3,2,4 5,1,3,2,4 3,2,5,4,1 4,3,1,5,2 how can I find an ordering of the values that is the least used and will lead to a "more balanced" set of orderings. The obvious answer is I could group by and count them and pick the least used one, but the problem is the least used permutation may not have ever been used, for example here, the ordering "1,2,3,4,5" is a candidate for least used because it doesn't appear at all. The simple answer seems to be to identify which position "1" appears in the least frequent and set that position to "1" and so on for each digit. I suspect that works, but I feel like there's a more elegant solution that I haven't considered potentially with cross joins so that all possible combinations are included. any ideas? A: What you have here is a histogram leveling problem. Consider the problem from this perspective: you have a set of N histograms that represent the frequency of occurrence of the value N values over a discrete range {1..N}. What you want to do is to add a new set of values to your population of data that shifts the all histograms closer to being level. Given the nature of your problem, we know that each value will, overall, appear the same number of times as every other value. One way to do so, is to find which values N has the lowest frequency of occurence in any position - and assign it that position. Next, in the remaining histograms, find the next value with the lowest frequency of occurence in any position, and assign that value to that position. Continue repeating this process until all values have been assigned a unique position. This gives you your next set of values. You can now iteratively repeat this operation to continue generating new value sets that will attempt to re-balance the distribution of values with each iteration. If you maintain the histograms as you distribute values, this becomes a relatively efficient operation (you don't have to constantly re-scan the data set). Keep in mind, however, that for any sufficiently small population of values, you will always be "out of balance" to some degree. There's no way around this. A: I presume that you have a way to generate a random permutation (e.g. Most efficient way to randomly "sort" (Shuffle) a list of integers in C#). Given that, one suggestion to generate a single new ordering is as follows: 1) Generate two random permuations 2) Keep whichever one of them would even out the imbalance the most. One measure of balance would be to think of the list of all of the counts of digit frequencies at each position as a vector, which, in the case of perfect balance, would have each element the same. The imbalance would then be the length of the vector you get by subtracting off that perfect vector. By choosing between two random permutations you will pick a permutation from a distribution whose mean vector points in a direction opposite to the current imbalance, so you should tend to correct it while still producing a random-ish sequence of permutations. A: If the total number of combinations is small enough there's an approach I used on a similar problem long ago: Maintain a pool of choices that is periodically replenished. In your example you have 120 possible permutations. Make an array of 120 elements, assign each an initial value of say 5. When you need a random value you pick from this pool, the number in the bin being the weight given to that bin. (At the start the bins sum to 600. Pick a random from 1 to 600, subtract bins from it until <= 0. The bin you just subtracted is your result.) When an entry is picked decrement that bin by one. Once you've made 120 draws from the pile add 1 to every bin. Obviously this becomes impractical if the total number of possibilities is too high.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Check whether a directory exists or not using JavaScript How to check whether a directory or folder exists or not using javascript or jquery? A: You can't. If Javascript had access to the file system (either client or server), it would be a security hole. A: Do you mean Javascript running in the browser and checking a directory in the user's machine? If so, you'll have a very hard time doing this, as the browser is isolated from the computer's file system for security reasons. It can't be done. Good thing too -- if it could be done, there would be any number of malicious hackers using it to find out what software you've got installed, etc. (occasionally the hackers to manage to find a way through the sandbox and do manage to get at the file system, but these holes generally get closed by the browser vendors very quickly) A: JavaScript cannot access the local filesystem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to optimize this sql delete statement I have 3 tables, the first one, table1, has as primary key the id column, the second table (table2) has a column table1_id that refer as foreign key to the table1.id, the third table (table3) has, as table2, a column table1_id that refer as foreign key to table1.id. I have to delete from table1 all the rows where table1.id is not in table2.table1_id and not in table3.table1_id now i am using this query: DELETE FROM table1 WHERE table1.id IN (SELECT table1.id FROM (table2 RIGHT OUTER JOIN table1 ON table2.table1_id = table1.id) LEFT OUTER JOIN table3 ON table3.table1_id = table1.id WHERE table2.table1_id IS NULL AND table3.table1_id IS NULL); but it is very slow, it takes a lot of time, there are some better approach to this delete statement? If this can help i can assume that table2 has more data that table3. The database i am using is Apache Derby. Thanks for the help. A: Assuming you got the obvious covered (indices created for table1.id, table2.table1_id and table3.table1_id), you don't need to perform full outer joins just to test if a key is in another table, you can use subqueries and exists() -- or not exists() in your case. And since you're only testing for existence, you can use the following pattern: where not exists ( select top 1 1 from... where... ) A: DELETE table1 FROM table1 LEFT JOIN table2 ON table1.id = table2.table1_id LEFT JOIN table3 ON table1.id = table3.table1_id WHERE table2.table1_id IS NULL AND table3.table1_id IS NULL A: DELETE from table1 WHERE table1_id NOT IN (SELECT table1_id FROM table2) AND table1_id NOT IN (SELECT table1_id FROM table3) A: Do you know how many rows you are deleting? I agree with @Blindy, that not exists would probably be better in your case if Derby supports it (I don't know Derby so I can't say for sure). However, if there are a lot of records being deleted, you might want to do this in batches. Deleting a 10,000,000 records is going to take a long time no matter how efficent the query is. Deleting them in a loop that does 1000 at a time is often better for the database as it won't take a table lock and lock out users while the whole process is done. Again I don't know Derby, so I don't know if this is true of Derby, but it certainly would help a large delete in most databases I am familiar with.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Graphing data, website views what platform to use I have been tasked with producing a analytic tool for some of the data which we get in about the activities the company i work for has with its clients. Last week i made a mock up view of one possible graph using some PHP and the Flot Jquery graphing tool. Unfortunatly I dont think I am going to be able to use flot for what i need in the long term as to make the graph i needed work I had to hack 8 divs one of top of the other otherwise i just got a flat line... So now i am looking at technologies to work with for this tool. One of the senior members here recommends using Django for the framework and do the graphs using reportlabs or matplotlib I have spent the last couple of days looking for decent tutorials on how to produce graphs using report labs or matplotlib and using django to display them, unfortunately i havent been able to find much which is of any use. the 2 examples i found on the django site werent terriably useful and most examples give you something like: drawing = Drawing() data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99', 'Apr-99','May-99','Jun-99','Jul-99','Aug-99'] drawing.add(bc) but how do you then intergrate that with django`s views? this was my attempt which produced a blank screen... def chartTest(request): import mycharts drawing = Drawing() d = mycharts.testChart(drawing) binaryStuff = d.asString('gif') return HttpResponse(binaryStuff,'image/gif') I did manage to make matplotlib produce a graph but it had a grey background which for life of me I couldn't work out how to make it go away and found it hard looking on Google for any information about why it is like that. I am a little bit stuck atm, so if anyone has any ideas on where I can find helpful advice on learning these tools that would be most awesome. thanks A: Have a look at Google Charts Tools http://code.google.com/apis/chart/ A: Also have a look at jqPlot http://www.jqplot.com/ - it uses jQuery - a javascript library. I usually pass all my data down into the template, and the charts/graphs are rendered in the client's browser. A: Also check out d3.js. Beautiful plots that are natively HTML5, and great for interaction too. http://mbostock.github.com/d3/
{ "language": "en", "url": "https://stackoverflow.com/questions/7517055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the Prof. method to layout the install file in Linux user@ubuntu:~/Downloads$ tree mongodb-linux-i686-2.0.0 mongodb-linux-i686-2.0.0 |-- bin | |-- bsondump | |-- mongo | |-- mongod | |-- mongodump | |-- mongoexport | |-- mongofiles | |-- mongoimport | |-- mongorestore | |-- mongos | |-- mongosniff | |-- mongostat | `-- mongotop |-- GNU-AGPL-3.0 |-- README `-- THIRD-PARTY-NOTICES I need to install MongoDB and above is the expanded folder structure of the MongoDB. Question: Where should I store the folder mongodb-linux-i686-2.0.0? Or Should I copy all files under mongodb-linux-i686-2.0.0/bin to /user/bin/? I just want to do it in a professional way since I will install more and more application on my machine. A: It is quite common to install third-party software in /usr/local or (less common) in /opt (for example, both Mathematica and Matlab install their binaries in /usr/local. /usr/local is, according to the FHS, the "tertiary hierarchy for local data, specific to this host". Installing your software here ensures that its files will not be overwritten by system updates. So, you should copy mongodb-linux-i686-2.0.0 in /usr/local and you should add /usr/local/mongodb-linux-i686-2.0.0/bin to the PATH environment variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding, removing and updating tags for comments in web page I'm building a commenting feature for a web page where all comments can have any number of tags (not HTML tags, but tags like here in SO, duplicates not allowed) and those tags can be updated by anybody. Let's say some comment contains tags [tag1, tag2, tag3] and someone adds one tag, tag4, removes tag2. Now how do I check that which old tag was not in the new set of tags, and what tags were possibly added? I have table comments, which contains id and comment columns (among others, not related to this problem) and comment_tags table, which have id, tag and comment_id columns. I could get all old tags to given comment, then loop through that array and with each tag, check that was that included in the new set of tags. If not, delete that tag. And then loop through the new set of tags, check with each new tag that is it included in the old set of tags. If not, add that tag to comment_tags table. Somehow that just sounds too slow and I'm guessing that there is some better way to do that. So this was my initial thought: $db = new Database(); $purifier = new HTMLPurifier(); $existing_tags = $db -> get_comment_tags($_POST['comment_id']); $new_tags = $purifier -> purify($_POST['tags']); $new_tags = explode(" ", $new_tags); $new_tags = array_unique($new_tags); /* Delete tags that were not included in the new set of tags */ foreach ($existing_tags as $tags => $tag) { if (!in_array($tag['tag'], $new_tags)) { $db -> delete_comment_tag($existing_tags[$tags]['id']); } } /* Since get_comment_tags returns array which contains arrays, let's strip unnecessary info */ $filtered_existing_tags = array(); foreach ($existing_tags as $key => $value) { $filtered_existing_tags[] = $value['tag']; } /* Add tags that were not included in the old set of tags */ foreach ($new_tags as $key => $value) { if (!in_array($value, $filtered_existing_tags)) { $db -> add_comment_tag($_POST['comment_id'], $value); } } A: I usually would just run two SQL queries to accomplish that, both on the posts_tags table: one to delete all tags currently linked to the post, and another one to insert all currently valid tags.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding Index on every foreign key - Pros and Cons? We have an SQL Server 2008 R2 database that is attached to our web application. Data is added each day, but MANY reports are run against it. As such the data is being read much more often than it is being written to. The reports are running slow, and adding the 'suggested indexes' has helped, but I think just adding every foreign key will help the most overall. Are there any downside? We already run a full maintenance on a Saturday (rebuilds indexes etc). so that's not a problem. OR, would it be best to only add indexes for all Fkeys on all tables with OVER X Rows, where x is 1000? Any help appreciated! PS, the biggest table has only 570288 rows in, the next biggest 273255. 188 tables in all, but only 32 of them have more than 1000 rows! A: The ones with less than 1000 rows probaly won't benefit much from the index especially if both the parent and child tables are small. SQL Server is likely to to a full table scan no matter what. In that case you are probaly just adding over head on insert by adding the index. Most of the time, large table should have indexes on FK fields unless they will rarely be used in a join due to denormalization. In your case I would probably put the indexes on for the large tables (or ones you expect to get large) and leave them be on a the small tables and see if performance improves. Then if you still have some slow running queries, look at them on an individual basis.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }