text
stringlengths
8
267k
meta
dict
Q: In Javascript, is it not recommended to use ==, and how to use ===? Possible Duplicate: Javascript === vs == : Does it matter which “equal” operator I use? In Douglas Crockford's book Javascript: The Good Parts, it is recommended to not use == at all, due to hard to memorized rules. Do advanced or seasoned Javascript programmers really not use == or !=? If so, then I guess we will be using === and !==, but then how do we use them effectively? Is the most common case comparing a string with number, so we can always do if (Number(s) == 3) { ... } // s is a string Can Number(s) work in most browsers? And what are the other common cases to use with ===? A: The problem with == is that it uses type-coercion which can have unexpected results. You nearly always want === or !==. You can explicitly change the types as appropriate. In your example it would be easier to write "3" as a string instead of converting the string to a number. A: Never say never, but indeed, in most cases it is best to use the more strict === and !== operators, because they compare the value as well as the type. Comparing '68' to 68 is not a problem, if it matches, it is probably what you meant. The big risk in not doing so lies especially in 'empty values'. Empty strings may be evaluated as false, as may 0 and 0.0. To prevent hard to find errors, it is best to do a strict type comparison as well. If you want something to be true or false, it should be true or false and not any other value. Even in cases where these other types would be allowed, it may be better to explicitly convert it to the type you're comparing with, just for the sake of readability, maintanability and clarity. You are in that case making clear that you know the value can be of another type and that it is allowed so. With just using the less strict operator, no one can tell if you just forgot or made a deliberate choice. So yes, I'd say it's a best practise to always use the strict operators, although there will always be exceptions. A: === is 'exactly equal to' where == is not exact. For example, '' == false // true 0 == false // true false == false // true '' === false // false 0 === false // false false === false // true == will return true for 'falsy' or 'truthy' values. Read this for more information. A lot of developers will use ===. It does not hurt to use === solely. But in some cases === is not necessary. Crockford suggests a lot of things in his book. Some people follow his word to the T. Others, myself included, take it all with a grain of salt. He has some good points, but a lot of it is preference. You should make sure you know exactly what == and === do. And with that information you can decide how to use them, and when. A: == operator compares two operands values and returns a Boolean value. === This is the strict equal operator and only returns true if both the operands are equal and of the same type. Example: (2 == '2') //return true (2 === '2') //return false
{ "language": "en", "url": "https://stackoverflow.com/questions/7627491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using pycurl to get next page google results I have written code to search something on google using pycurl. I would like to be able to use pycurl to do this but all help is greatly appreciated. I am looking for the ability to search a term and then "click the next page button" or "click the indexed numbers at the bottom" using pycurl so I can get more then just the first 10 web results. Thanks in advance. A: There are multiple ways to do this. if your base url is http://www.google.co.uk/search?hl=en&q=YOUR_QUERY_STRING you can add &num=100 to the end of your url to get first 100 results. or if you can add &start=N, where N is a multiple of 10, and resend the webrequest to get the next page or you just use XPATH to parse the webpage and get the url of the next page on the search results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: StructureMap: Multithreaded env. No default instance defined for PluginFamily I'm dealing with structuremap error for quite a while. The error is: StructureMap.StructureMapException: StructureMap Exception Code: 202 No Default Instance defined for PluginFamily SomeNamespace.ISomeInterface, SomeNamespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Our project is fully multithreaded and StructureMap can be called several times per second with different profile name each time. StructureMap setting is done when application starts. I use the StructureMap.Configuration.DSL.Registry: var registry = new Container(...some parameters settings...); StructureMap.ObjectFactory.Configure(x => x.IncludeRegistry(registry)); And Container is: class Container : StructureMap.Configuration.DSL.Registry { public Container(...Some settings parameters...) { For<IConnG>().Use<DG>() .Ctor<string>("user").Is(some parameter) .Ctor<string>("pass").Is(some parameter) .Ctor<string>("site").Is(some parameter) .Ctor<string>("DateFormat").Is(some parameter); For<IRPG>().Use<RPG>(); Scan(asm => { asm.TheCallingAssembly(); asm.Include(type => type.IsAbstract == false && type.IsSubclassOf(typeof(BaseC))); asm.With(new RegistrationConvention()); }); var actionName = (enumA)Enum.Parse(typeof(enumA), some parameter); switch (actionName) { case enumA.ActionA: Profile(enumA.ActionA.ToString(), (pe) => { pe.For...; pe.For...; pe.For...; pe.For<IXXX>().Use<DefaultXXX>(); **pe.For<IAction<SomeNamespace.SearchParams, SomeNamespace.SearchParams>>().Use<DefaultSearchParams>();** pe.For...; }); break; case enumA.ActionB: Profile(enumA.ActionB.ToString(), (pe) => { pe.For...; pe.For...; pe.For...; pe.For<IXXX>().Use<DefaultXXX>(); **pe.For<IAction<SomeNamespace.SearchParams, SomeNamespace.SearchParams>>().Use<DefaultSearchParams>();** pe.For...; }); break; case enumA.ActionC: Profile(enumA.ActionC.ToString(), (pe) => { pe.For...; pe.For...; pe.For...; pe.For<IXXX>().Use<DefaultXXX>(); **pe.For<IAction<SomeNamespace.SearchParams, SomeNamespace.SearchParams>>().Use<XXXSearchParams>();** pe.For...; }); break; case enumA.ActionD: Profile(enumA.ActionD.ToString(), (pe) => { pe.For...; pe.For...; pe.For...; pe.For<IXXX>().Use<DefaultXXX>(); **pe.For<IAction<SomeNamespace.SearchParams, SomeNamespace.SearchParams>>().Use<DefaultSearchParams>();** pe.For...; }); break; } } } The RegistrationConvention is: public class RegistrationConvention : StructureMap.Graph.IRegistrationConvention { #region IRegistrationConvention Members public void Process(Type type, StructureMap.Configuration.DSL.Registry registry) { var interfaces = new List<Type> { type.GetInterface("IInfo`1"), type.GetInterface("IBook`1"), type.GetInterface("IConf`1"), type.GetInterface("IClxP`1"), type.GetInterface("ICanc`1"), type.GetInterface("IConf2`1"), type.GetInterface("IMaxP`1"), type.GetInterface("IAction`1") }; interfaces .ForEach(contractType => { if (contractType != null) { registry.For(contractType).Use(type); } }); } #endregion } I'm calling StructureMap in code like that: var container = StructureMap.ObjectFactory.Container; container.SetDefaultsToProfile(Some profile name); var adaptor = container.GetInstance<IAction<SomeNamespace.SearchParams, SomeNamespace.SearchParams>>(); This code is called by many threads, and I'm getting this error not all the times, but quite a lot. When printing out WhatDoIHave() it indicates it has it. I'll be glad to have any suggestion/correction. Thanks in advance. A: It was hard to solve, but finally I got there! The problem was I misused StructureMap: StructureMap, as far as I correctly grasped the intention of using it, is intended to dynamicaly load settings once, when application loads. In our project, we're switching profiles many times per seconds and trying to retrieve an instance based on that profile. We got many exceptions like it doesn't recognize the default instance although WhatDoIHave() showed the opposite. The problem was exactly that - calling the Container from many threads and switching profiles upon each request. So, for a reminder, when application starts, for each profile I added its settings to the only one Container: var registry = new OurRegistry(settings parameters..., profileName); StructureMap.ObjectFactory.Configure(x => x.IncludeRegistry(registry)); And in many places in code, I used to call StructureMap like that: var container = StructureMap.ObjectFactory.Container; container.SetDefaultsToProfile(profileName); var adaptor = container.GetInstance<ISomeInterface<ConcreteType>>(); This code was used parallel and each thread used another profile. So, as a fix I created a Container per profile! var registry = new OurRegistry(settings parameters..., profileName); var container = new StructureMap.Container(registry); And I stored each container in our code, not on StructureMap as before, so each profile-prone thread is using it's own profiled Container. That's even faster then before because you don't have to switch profiles so much, only once! And no more #$@!@ 202 exception :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to create a web service that receives and sends xml based on xsd files? I need to create a .NET web service that accepts xml, uses this to query a database, and then returns xml. I have been given xsd files for the request and response. Could someone point me in the right direction for where I start from or an example? I haven't used WCF before so would prefer to use a simple asmx file to do this. I know how to get the data from the database, so it's the xml and web service bits where I'm lost. I've tried googling this for a while but don't know where to start. Thanks. A: The problem you have is that asmx and WCF are both code-first web service technologies. What this means is that you generally start with classes and the web service stack takes care of exposing your types as XML across the wire. You are starting with a schema, which is not code. So if you want to use asmx/wcf you need to model your schema in code. You can do this by inferring a class structure from your schema using xsd.exe (or svcutil.exe for WCF). Alternatively you can model your classes by hand based on the schema definition. Once you have your classes then you can add declarative attributes to the code (See http://msdn.microsoft.com/en-us/library/83y7df3e.aspx for asmx, DataContract and DataMember for WCF). These attributes control: * *how an incoming stream of XML is deserialized to a type when a service request is received, and *how instances of your response types get serialized to XML when passed out of your service The problem with this approach is that getting your XML to validate against your XSD schemas will be a little bit hit and miss, as you cannot rely 100% on class inference from XSD, and additionally you may miss some fine detail if you are modelling it by hand. Whichever way you do it you need to make sure that your request and response class instances cleanly serialize into XML which will validate against the XSD schemas you have been given. Also look at a framework called WSCF-Blue which allows you to do contract-first web service design: http://wscfblue.codeplex.com/ Good luck, if you need any more detail about this please let me know via a comment. A: From what I can understand, you need to build a webservice, which will accept XML as input, do some processing and spit out XML. I assume you have a basic understanding of XML but dont know anything about XSD. In very simple terms, XSD is a document which is used to validate a XML file. Think of it a rule book for how XML file should be structed, you can read more about XSD from W3schools. Dont worry about the XSD to much right now. Get a few sample XML documents, which you need to accept as input and output. Build a console application to parse the sample XML file and get the results from the database. Then use the results to build the output XML by looking at the output sample XML. Once you have that completed, then you can use the .NET classes to validate your input and output XML from the XSD you have. You can look at this answer to see how validation is done. Once that is done, you can create your web service to return the XML as string. Hope this help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the relationship between XNA and XNA for Windows Phone? What is the relationship between XNA and XNA for Windows Phone? Is that latter a true subset of the former like the .NET Client Profile? Mostly a subset (like Silverlight vs Silverlight for Windows Phone)? Or is it simply a similar API like WPF vs Silverlight? A: They're identical in terms of the XNA API, and both are developed using the same download, typically XNA + C# + Visual Studio. There are differences in what each platform supports though. For XNA in general I'd always consult Shawn Hargreaves blog first, and this article is most relevant: http://blogs.msdn.com/b/shawnhar/archive/2010/03/10/xna-game-studio-on-windows-phone.aspx The biggest differences vs Xbox 360/Windows are display resolution, input methods available, and the fact that Windows Phone 7 doesn't support programmable shaders (so you can't write your own velvet/Fresnel shader for WP7, but you can for Windows and the 360). Performance also varies: on Windows XNA performs well without much effort as it runs on the full .NET Framework. On the 360 and WP7, it runs on the .NET Compact Framework, so whilst you get the full XNA API you only have access to a subset of the full .NET Framework (though in a typical game you won't miss much of it) plus its garbage collection is shocking so depending on your game you may really have to watch memory allocation. A: According to the following MSDN page, it's a subset of full XNA: http://msdn.microsoft.com/en-us/library/gg490768.aspx If you're considering writing XNA games for Windows 8, you may want to hold fire, as it's none too clear if XNA is still a long-term strategy for Microsoft (at least, if their comments at the recent BUILD conference are anything to go by): http://www.rabidlion.com/2011/09/opinion-why-xna-isnt-dead-yet.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7627508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript for google image ripping broke with update I grabbed a few small scripts and threw them together to take google's new image layout and turn back into the old one, then take the images and replace them with the full size versions. Worked great until about last week. Not sure what changed on the server side. (function() { // Get list of all anchor tags that have an href attribute containing the start and stop key strings. var fullImgUrls = selectNodes(document, document.body, "//a[contains(@href,'/imgres?imgurl\x3d')][contains(@href,'\x26imgrefurl=')]"); //clear existing markup var imgContent = document.getElementById('ImgContent'); imgContent.innerHTML = ""; for(var x=1; x<=fullImgUrls.length; x++) { //reverse X to show images in correct order using .insertBefore imgContent.nextSibling var reversedX = (fullImgUrls.length) - x; // get url using regexp var fullUrl = fullImgUrls[reversedX].href.match( /\/imgres\?imgurl\=(.*?)\&imgrefurl\=(.*?)\&usg/ ); // if url was fetched, create img with fullUrl src if(fullUrl) { newLink = document.createElement('a'); imgContent.parentNode.insertBefore(newLink , imgContent.nextSibling); newLink.href = unescape(fullUrl[2]); newElement = document.createElement('img'); newLink.appendChild(newElement); newElement.src = decodeURI(fullUrl[1]); newElement.border = 0; newElement.title = fullUrl[2]; } } function selectNodes(document, context, xpath) { var nodes = document.evaluate(xpath, context, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); var result = []; for (var x=0; x<nodes.snapshotLength; x++) { result.push(nodes.snapshotItem(x)); } return result; } })(); A: Google changed the 'ImgContent' id for the image table holder to something slightly more obscure. A quick change had everything working again. I made a simple problem complicated by looking past the easy stuff. Thanks to darvids0n for the enabling, he ultimately pointed out what I was missing. A: the script is not going to work as said by bobby . try this grease monkey script from user script repository. rip Google image search :- http://userscripts.org/scripts/show/111342
{ "language": "en", "url": "https://stackoverflow.com/questions/7627509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to retrieve HTML from silverlight Webbrowser control out of frames i need to get the html of a frame inside the silverlight webbrowser control. i've looked at the following questions How to retrieve HTML from Webbrowser control out of frames in .net (c#) accessing Frames rendered in webbrowser control in C#.net but they offer solution for WPF. how to do the same in silverlight webbrowser control? A: I dont think this will be possible, since If you host content in an , all the regular security rules for iframes apply. from http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser(v=vs.95).aspx and if i understand this line correctly, this means, you wont be able to access any content from within the iFrame.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jqGrid multiselect - limit the selection of the row only using the checkbox Good morning, I'm working on a jqGrid that have the multiselection active. I need to limit the selection of the row only using the multisel box, not by clicking everywhere on the row. Thats's because I need to do some action by clicking links on some cells and I won't alter the active multiselection. I tried to set the multiboxonly property, but it's not what I need. I didn't find anything else to customize this function of the grid. A: I would like to suggest easier solution: beforeSelectRow: function(rowid, e) { return $(e.target).is('input[type=checkbox]'); }, A: When multiselect is set to true, clicking anywhere on a row selects that row; when multiboxonly is also set to true, the multiselection is done only when the checkbox is clicked. So the answer would be: multiboxonly: true A: You can control on which click the row will be selected with respect of your custom beforeSelectRow event handler. If the handler return true, the row will be selected. If you return false the row will be not selected. The second parameter of beforeSelectRow is event object, e.target is the DOM element which was clicked. You can get the cell (<td>) in which the click done with $(e.target).closest('td'). Then you can use $.jgrid.getCellIndex to get the index of the cell insido of the row. The index in the colModel should point to the 'cb' column which contain the checkboxes. So the code could be the following: beforeSelectRow: function (rowid, e) { var $myGrid = $(this), i = $.jgrid.getCellIndex($(e.target).closest('td')[0]), cm = $myGrid.jqGrid('getGridParam', 'colModel'); return (cm[i].name === 'cb'); } The corresponding demo you can see here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Show Views when Editing Edittext in Landscape Mode? I have been searching for a solution to this for a long time and would be very grateful for your help- I have an EditText with a TextView next to it, which shows line numbers. Normally when editing an EditText in landscape mode only the EditText is displayed. Is it possible to display the TextView whilst the user is editing the EditText in landscape mode as well as the EditText? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7627515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where is the .JS file in this code? And why are they calling it this way? Where is the JS file and is this Async the fastest way to call JS? I guess they then have PHP calls in the .JS for updating the Ad stats?? The code: <script type="text/javascript"> (function(){ var acc = "acc_230d269_pub"; var st = "nocss"; var or = "h"; var e = document.getElementsByTagName("script")[0]; var d = document.createElement("script"); d.src = ('https:' == document.location.protocol ?'https://' : 'http://')+"engine.influads.com/show/"+or+"/"+st+"/"+acc; d.type = "text/javascript"; d.async = true; d.defer = true; e.parentNode.insertBefore(d,e); })(); </script> A: It inserts the script tag with a dynamically constructed file name and puts it in the document before the first script tag. The advantage of this approach is that it will run only when the document is loaded, so it will not block the document loading. This way, the user will experience no (or less) delay. It's a good practise to do this for analytical tools and such, because they don't add functionality for the user and you just want to track their actions. It doesn't matter if you miss one or two of those measurements. A: I've made your code more readable: 1 <script type="text/javascript"> 2 (function () { 3 var acc = "acc_230d269_pub"; 4 var st = "nocss"; 5 var or = "h"; 6 var e = document.getElementsByTagName("script")[0]; 7 var d = document.createElement("script"); 8 d.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 9 "engine.influads.com/show/" + or + "/" + st + "/" + acc; 10 d.type = "text/javascript"; 11 d.async = true; 12 d.defer = true; 13 e.parentNode.insertBefore(d, e); 14 })(); 15 </script> * *2,14 An anonymous function wrapper is created, so that variables cannot be access from outside the function ("scope") *3   acc looks like the identifier of the advertiser *4,5 st = "nocss" and or = "h" looks like settings to adjust the appearance *7,10-12 A <script> tag is created. async = Loading the script will not block the execution of the document. defer=true prevents the script from not being executed (can be omitted) *6,13 The newly created script tag is inserted before (13) the first script tag in the document (6,13) *8,9 The URL is constructed:If the current page is transmitted over a secure connection, the injected script will also be transferred over the HTTPS protocol. The extension of the requested file is omitted. This file could be served using the application/javascript MIME type by server configuration. A: There are a couple of ways to include js code into html, one is put the code directly into the tag, just like what you wondered about the code you posted, the other method is to use the following syntax: <script type="text/javascript" src="path/to/external_file.js"></script> As a side note, the code you posted uses a technique that prevents js name spacing conflicts by putting the code in the (function() ...)(); block, which I find to be a very good practice. Regarding the question about using async in tag, you might want to take a look at this: http://davidwalsh.name/html5-async A: Most of that code is for loading the JavaScript code asynchronously, in a way that works in different browsers. An explanation of how it works is here: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/ Loading asynchronously means that the browser doesn't wait for it to finish. So the ad won't load faster, but the rest of the page will. If you piece together the string, you'll find that the JavaScript file they're loading is: http://engine.influads.com/show/h/nocss/acc_230d269_pub A: The benefits I see are: * *Asynchronous loading that would help in faster rendering of the UI *The selective http or https used for the location of the js source following the protocol that current page is loaded with I am wondering why the js source would not end with a .js extension though
{ "language": "en", "url": "https://stackoverflow.com/questions/7627519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Passing a struct with a byte array inside to a interop-ed method I have a situation where I have to pass a struct to a C method (declared as extern in my C# file). This struct however is quite complicated. I already used successfully the approach with AllocHGlobal, but I would like to understand if is possible to make it works in this way, by only passing a reference to the struct. [StructLayout(LayoutKind.Sequential)] struct lgLcdBitmapHeader { public Formats Format; } [StructLayout(LayoutKind.Explicit)] struct lgLcdBitmap { [FieldOffset(0)] public lgLcdBitmapHeader hdr; [FieldOffset(0)] public lgLcdBitmap160x43x1 bmp_mono; [FieldOffset(0)] public lgLcdBitmapQVGAx32 bmp_qvga32; } [StructLayout(LayoutKind.Sequential)] struct lgLcdBitmap160x43x1 : IDisposable { /// <summary> /// Format = LGLCD_BMP_FORMAT_160x43x1 /// </summary> public lgLcdBitmapHeader hdr; /// <summary> /// byte array of size LGLCD_BMP_WIDTH * LGLCD_BMP_HEIGHT, use AllocHGlobal to make code safe /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)BWBitmapSizes.Size)] internal byte[] pixels; } [StructLayout(LayoutKind.Sequential)] struct lgLcdBitmapQVGAx32 : IDisposable { /// <summary> /// Format = LGLCD_BMP_FORMAT_160x43x1 /// </summary> public lgLcdBitmapHeader hdr; /// <summary> /// byte array of size LGLCD_QVGA_BMP_WIDTH * LGLCD_QVGA_BMP_HEIGHT * LGLCD_QVGA_BMP_BPP, use AllocHGlobal to make code safe /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)QVGABitmapSizes.Size)] internal byte[] pixels; } The biggest problem is that I have to wrap everything in a union (the lgLcdBitmap struct). Actually C# is complaning because there is an object at offset 0 that is not correctly aligned or overlaps another object. I think that the problem is connected with the fact that my byte array doesn't have a real size (only the one declared with SizeConst). Because I don't want to use fixed (it forces me to use unsafe code), I would like to understand how can I solve this. The only idea that I can think about is declaring Size (inside StructLayout) to allow C# understand what size is my struct, but I'm not sure it will works. The method I have to call is this one: public extern static uint lgLcdUpdateBitmap([In] int device, [In] ref lgLcdBitmap bitmap, [In] Priorities priority); Any suggestion on how make everything works? A: If you don't need the union as such in managed code, don't make it a union. Declare two structs and two overloads of your p/invoke function. A: Since you don't want to use fixed, your byte arrays are best declared as IntPtr, allocated with AllocHGlobal and filled with data using Marshal.Copy. There's no way to get the P/invoke marshaller to do what you need using MarshalAs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I change directory (cd) with Ganymed SSH API? I must be missing something here, but how do I call something like "cd /root/some/dir/" with Ganymed SSH API? * *I created a Connection object *In the first session created, I called "cd /root/some/dir" *In the second session created, I called "ls ." or "./myApp" That didnt work, because ganymed probably starts each session with its own directory So do I need to perform both commands on the same session? something like: session.getStdin().write("cd /root/somedir \n".getBytes()); session.getStdin().write("ls . ".getBytes()); Is that the correct way?? if so, why do we need Session.execCommand? A: After doing some research, the only good solution I managed to find is calling the "cd" command within the same code as the "ls" command, like this session.execCommand("cd /root/somedir ; ls ."); The semicolon will separate the two commands as in any bash code. In this way, you can query the session's result [session.getExitStatus()] of both the cd and ls commands, which is much better then writing the two commands to session.getStdIn() (after writing to stdin, you kinda loose all the ability to check for exit status...) Hope this will help the rest Eyal A: According to the Ganymed FAQ (http://www.ganymed.ethz.ch/ssh2/FAQ.html), you are not allowed to send more than one command per Session object you generate. This is how SSH-2 apparently wants you to handle it. Your two options are to either combine the two commands like session.execCommand("cd /root/somedir ; ls ."); However this wont always work and it get very ugly if you have more than a couple commands. The other way to do this is to open an interactive shell session and write the commands to standard in. This could look something like this: Session sess = conn.openSession(); sess.requestDumbPTY(); sess.startShell(); OutputStream os = sess.getStdin(); os.write("cd /root/somedir\n".getBytes()); os.write("ls -1\n".getBytes()); os.write("exit\n".getBytes()); InputStream stdout = new StreamGobbler(sess.getStdout()); BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); //TODO Note the use of the final exit command. Since this is being treated like a terminal window, if you do not exit from the program any loop you have reading the output of the server will never terminate because the server will be expecting more input A: OK, I took a quick look on the Ganymed javadoc and although I did not try it myself I assume that you should use method execCommand() of session instead of writing into the STDIN. I am pretty sure that session is connected to remote shell and therefore handles the shell state including current directory, environment variables etc. So, just do the following: session.execCommand("cd /root/somedir \n".getBytes()); session.execCommand("ls . ".getBytes()); I hope this will work for you. Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OnChecked event on radiogroup in listview fired multiple times I have created an application containing radiogroup in each row of listview. The problem is that when i scroll the listview, the selection of the radiogroup changes as the oncheckedevent for the radiogroup fires multiple times. Here's my getView function : @Override public View getView(final int position, View convertView, ViewGroup parent) { View row = convertView; WeatherHolder holder = null; if(row == null) { LayoutInflater inflater = ((Activity)context).getLayoutInflater(); row = inflater.inflate(layoutResourceId, parent, false); holder = new WeatherHolder(); holder.imgIcon = (ImageView)row.findViewById(R.id.icon); holder.txtTitle = (TextView)row.findViewById(R.id.toptext); holder.rdgCategory = (RadioGroup)row.findViewById(R.id.radiogroup); RadioGroup.OnCheckedChangeListener rdGrpCheckedListener = new RadioGroup.OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub // setCategoryinList(position, checkedId); switch (checkedId){ case R.id.option1: Log.i("WeatherAdapter","Data set index : " + position + " category : 1"); data.get(position).setCategory(1); break; case R.id.option2: Log.i("WeatherAdapter","Data set index : " + position + " category : 2"); data.get(position).setCategory(2); break; default: Log.i("WeatherAdapter","Data set index : " + position + " category : 0"); data.get(position).setCategory(0); break; } } }; holder.rdgCategory.setOnCheckedChangeListener(rdGrpCheckedListener); row.setTag(holder); } else { holder = (WeatherHolder)row.getTag(); } Weather weather = data.get(position); holder.txtTitle.setText(weather.getAppName()); holder.imgIcon.setImageDrawable(weather.getIcon()); int objCategory = weather.category; Log.i("WeatherAdapter","Data get name : " + weather.getAppName() + " index : " + position + " category : " + objCategory); switch (objCategory) { case option1: holder.rdgCategory.check(R.id.option1); break; case option2: holder.rdgCategory.check(R.id.option2); break; default: holder.rdgCategory.check(R.id.none); break; } return row; } And below is the trace that i get in the logcat when i scroll the listview : 10-02 21:31:29.844: INFO/WeatherAdapter(28361): Data get name : ProgressBar index : 11 category : 0 10-02 21:31:53.399: INFO/WeatherAdapter(28361): Data set index : 10 category : 1 10-02 21:31:53.399: INFO/WeatherAdapter(28361): Data set index : 10 category : 0 10-02 21:31:53.399: INFO/WeatherAdapter(28361): Data set index : 10 category : 0 Any help appreciated. A: I had already answered it in previous answer. So you can have a look at this answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Django - Iterate through postdata from ModelMultipleChoiceField I am creating a form which will allow a user to send an email to multiple people (students). I have used ModelMultipleChoiceField to create checkboxes for each user, however I'm not sure how to deal with the data that gets posted. Here's my view so far: if request.method == 'POST': subject = request.POST['subject'] message = request.POST['message'] email = EmailMessage(subject, message, '[email protected]', recipient_addresses) email.send() else: students = Student.objects.exclude(email='') form = StudentListForm(students=students) The form just posts the ID numbers of the selected recipients. Do I have to filter Student objects like this: Student.objects.filter(pk__in=request.POST['students']) Or is there a 'better' way? Any advice would be appreciated. Thanks A: You're missing most of the point of using a form, which is to rely on it for validation and data conversion, as well as simply showing fields in HTML. if request.method == 'POST': form = StudentListForm(data=request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] recipients = form.cleaned_data['recipients'] recipient_addresses = [r.email for r in recipients] email = ... Basically, you should always access form.cleaned_data instead of request.POST.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to include DLLs to published application? In my solution I reference DLLs file from Libs folder. When I publishe application they don't copy to published folder. Is there anyway to make them to be copied too? A: You should put your DLLs in the Bin folder. The publisher will copy that folder. A: In addition to Slaks I would say, in order to have DLL in bin or Set CopyLocal property if linked reference to True. Or Use postbuild event to achieve the same.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find sub list inside a list in python I have a list of numbers l = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 1, 0, 0, 0, 0] [0, 0, 2, 1, 1, 2, 0, 0, 0, 0] [0, 0, 2, 1, 1, 2, 2, 0, 0, 1] [0, 0, 1, 2, 2, 0, 1, 0, 0, 2] [1, 0, 1, 1, 1, 2, 1, 0, 2, 1]] For example , i have to search a pattern '2,1,1,2' , as we can see that is present in row 6 and 7 . in order to find that sequence i tried converting each list into str and tried to search the pattern , but for some reason the code isnt working. import re for i in l: if re.search('2,1,1,2' , str(i).strip('[').strip(']')): print " pattern found" am i missing something in here ? A: Converting your list in string is really not a good idea. How about something like this: def getsubidx(x, y): l1, l2 = len(x), len(y) for i in range(l1): if x[i:i+l2] == y: return i A: I suggest you to use the Knuth-Morris-Pratt algorithm. I suppose you are implicitly assuming that your pattern is present in the list just one time, or you are just interested in knowing if it's in or not. If you want the list of each first element which starts the sequence, then you can use KMP. Think about it as a sort of string.find() for lists. I hope this will help. A: l = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 2, 1, 1, 2, 0, 0, 0, 0], [0, 0, 2, 1, 1, 2, 2, 0, 0, 1], [0, 0, 1, 2, 2, 0, 1, 0, 0, 2], [1, 0, 1, 1, 1, 2, 1, 0, 2, 1]] import re for i in l: if re.search('2, 1, 1, 2' , str(i).strip('[').strip(']')): print " pattern found" str(list) will return the string with spaces between the elements... You should look for '2, 1, 1, 2' instead of 2,1,1,2 A: Here is the same idea, without regex data = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 2, 1, 1, 2, 0, 0, 0, 0], [0, 0, 2, 1, 1, 2, 2, 0, 0, 1], [0, 0, 1, 2, 2, 0, 1, 0, 0, 2], [1, 0, 1, 1, 1, 2, 1, 0, 2, 1], ] pattern = '2112' for item in data: line = '' for number in item: line += str(number) if pattern in line: print 'pattern found: %s' % item
{ "language": "en", "url": "https://stackoverflow.com/questions/7627548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using Multiple Detail Views with Split View Controller As you know, a UISplitViewController has one root controller and one detail view controller only, but I want to use another detail view controller. When I select the list items from the root controller (popover controller), the selection should fire different detail views -- i.e., row1 fires detail view1, row2 fires detail view2 and a button item fires detail view3, etc. How can I achieve this? A: That project from Apple is from 2012 and doesn't use storyboards. If you are looking for a non-storyboarded solution, it will work fine but in Xcode 6 you should be taking advantage of the new Show Detail segue in storyboards. Here's a quick example project that shows how to use multiple detail view controllers on the same split view by using the Show Detail segue from the Master View Controller. A: There's a project from Apple that covers exactly what you need. MultipleDetailViews This sample shows how you can use UISplitViewController to manage multiple detail views. The application uses a split view controller with a table view controller as the root view controller. When you make a selection in the table view, a new view controller is created and set as the split view controller's second view controller. The root view controller defines a protocol (SubstitutableDetailViewController) that detail view controllers must adopt. The protocol specifies methods to hide and show the bar button item controlling the popover. A: In Swift override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let storyBoard = UIStoryboard(name: "Main", bundle: nil) let imageGalleryVC = storyBoard.instantiateViewController(withIdentifier: "ImageGallerySID") as! ImageGalleryViewController splitViewController?.showDetailViewController(imageGalleryVC, sender: nil) } A: I know this is a late post as this was asked 6 years ago and active last year. But there is a way to have multiple detail views for a split view controller. By embedding each detail controller into its own navigation controller and linking from the master view to each using the 'show detail' segue, you are able to achieve this result of switching between views by using an identifier associated and then from the master view function 'didSelectRowAt' selecting a row is where you can select which detail view you wish to see. if indexPath.row == 0 { performSegue(withIdentifier: "secondView", sender: self) } if indexPath.row == 1 { performSegue(withIdentifier: "thirdView", sender: self) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: about android invalidation? Now, I have a Framelayout, it includes two views. when I call the top view's invalidate() method, I found the another view's onDraw() also be called. I suppose the another view's onDraw() should not be called, Is there a way to stop the onDraw be called? Is there someone tell the reason why onDraw() be called? A: You could try adding willNotDraw="true" (see here) to your view, but I'm not sure it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DockPanelSuite .Can I hide/Disable x and down arrow + tab header Really like the free Dockpanelsuite.New to it and was wondering if possible. I would like to hide the x and down arrow + tabheader Is this possible? Thanks A: The close button can be hidden on a per-DockContent basis via the CloseButtonVisible property of the DockContent. Currently the window list button cannot be hidden as easily. I have logged a new feature request for this option: https://github.com/dockpanelsuite/dockpanelsuite/issues/29 A: Hide the close button using CloseButtonVisible property for the DockContent. content.CloseButtonVisible = false;
{ "language": "en", "url": "https://stackoverflow.com/questions/7627554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: haltonset: understanding skip and leap If i read the doc of how to construct a Halton quasi-random point set and it mentions that it's possible to 'skip' the first values and then retain the 'leap' values. Don't understand what the 'skip' and 'leap' really mean. Have tried the following: >> p = haltonset(1,'Skip',50,'Leap',10); d = haltonset(1,'Skip',51,'Leap',9); >> p(2:10), d(1:9) ans = 0.7344 0.0703 0.7891 0.4766 0.5859 0.1797 0.9922 0.3164 0.6602 ans = 0.7969 0.7344 0.8828 0.5391 0.8516 0.6484 0.9609 0.6172 0.7539 >> p(2:10) == d(1:9) ans = 0 0 0 0 0 0 0 0 0 Thought that it might be that that this would save 10 values to p and 9 to d. Also thought that d would have the same values as p. But this was not the case. I then tested if the 'leap' would be the same as a normal way to make a vector - ex: (1:leap:10) >> p = haltonset(1,'Skip',50,'Leap',1); d = haltonset(1,'Skip',50,'Leap',2); >> p(1:2:10)==d(1:5) ans = 1 0 0 0 0 >> p = haltonset(1,'Skip',0,'Leap',1); d = haltonset(1,'Skip',0,'Leap',2); >> p(1:2:10)==d(1:5) ans = 1 0 0 0 0 but this seemed not to be the case.. Can anybody give a plain English explanation of how to interpreted the 'skip' and 'leap' variables. A: I find the following description to be very clear [quoting this documentation page]: Imagine a simple 1-D sequence that produces the integers from 1 to 10. This is the basic sequence and the first three points are [1,2,3]: Now look at how Scramble, Leap, and Skip work together: * *Scramble: Scrambling shuffles the points in one of several different ways. In this example, assume a scramble turns the sequence into 1,3,5,7,9,2,4,6,8,10. The first three points are now [1,3,5]: * *Skip: A Skip value specifies the number of initial points to ignore. In this example, set the Skip value to 2. The sequence is now 5,7,9,2,4,6,8,10 and the first three points are [5,7,9]: * *Leap: A Leap value specifies the number of points to ignore for each one you take. Continuing the example with the Skip set to 2, if you set the Leap to 1, the sequence uses every other point. In this example, the sequence is now 5,9,4,8 and the first three points are [5,9,4]: EDIT: Let me show with an example: %# create 1D sequences (x: picked, .: ignored) p00 = haltonset(1,'Skip',0,'Leap',0); %# xxxxxxxxxxxxxxx p50 = haltonset(1,'Skip',5,'Leap',0); %# .....xxxxxxxxxx p02 = haltonset(1,'Skip',0,'Leap',2); %# x..x..x..x..x.. p52 = haltonset(1,'Skip',5,'Leap',2); %# .....x..x..x..x %# each pair of these are equal [p50(1:10) p00(6:15)] %# skip vs. noskip [p02(1:5) p00(1:3:13)] %# leap vs. noleap [p52(1:4) p00(6:3:15)] %# skip+leap vs. noskip+noleap In general: skip = 50; leap = 10; p00 = haltonset(1,'Skip',0,'Leap',0); p = haltonset(1,'Skip',skip,'Leap',leap); num = 9; [p(1:num) p00(skip+1:leap+1:num*leap+num-leap+skip)]
{ "language": "en", "url": "https://stackoverflow.com/questions/7627560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Yii Retrieve and store in a variable a renderPartial file I have a php file under protected/views/directory_controller_name with formatting like that <p> <?php echo $model->title;?> </p> ... I display the file with classic method in the controller : $this->render('filename',array('model'=>$model)); But know, I need to send an email with the same template/layout so I want to store the render of the file in an variable like $msgHTML = $this->renderInternal('_items', array('model'=>$model)); But it doesn't work! How can I get render view from a file and store in a variable? Is it possible? I don't want to use: $msgHTML = '<p>'.$model->title.'</p>' ... Because the file is very long and I don't want to duplicate code!!! A: $msgHTML = $this->renderInternal('_items', array('model'=>$model), true); http://www.yiiframework.com/doc/api/1.1/CBaseController#renderInternal-detail A: I might be missing something, but can't you just use regular render() with the return argument set to true? Then you can just use a view 'name' instead of knowing the path. (And unless my trusty stack trace logger is broken, renderFile and renderInternal take the same fully qualified path argument. At least I can see renderPartial() passing the full path to my view file to renderFile.) A: Don't use the renderInternal method, use renderPartial instead. Render internal is low level method and should not be used in such context. To catch the output just set the $return parameter to true: <?php $output = $this->renderPartial('_subView', $dataArray, true); ?> A: you can do this with these ways 1) if you want to get the output with header and footer (i.e ) full layout then do this //add true in the last parameter if you want a return of the output $htmloutput=$this->render('_pdfoutput',array('data'=>'nothing'),true); 2) similarly if you don't want to get the layout files just use renderpartial in the same way $htmloutput=$this->renderpartial('_pdfoutput',array('data'=>'nothing'),true); you will get the html of files in the variable . use this anywhere
{ "language": "en", "url": "https://stackoverflow.com/questions/7627562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: three axis graph in R I have a question regarding generating a graph in R in a three dimension. Suppose, i have the following data in a csv format file; CPU_Usage Power_Consumption(Watt) Bandwidth 50 59 20MB Now i want to represent this on xyz axis where the x-axis represents cpu,y represents power & z represents bandwidth. Then i would want these values to be joined together (by a line) on the three axis graph to form a triangle.There is just a single row in this data. I would appreciate if someone could help me out! A: You can accomplish this with scatterplot3d (among others): library(scatterplot3d) #first draw the lines of the triangle #using type="l" Since we are drawing a #shape, include the first point twice to #close the polygon q <- scatterplot3d(c(50, 0, 0, 50), c(0, 59, 0, 0), c(0, 0, 20, 0), xlim=c(0, 60), ylim=c(0, 60), zlim=c(0, 60), type="l", xlab="CPU Usage", ylab="Power Consumption", zlab="Bandwidth", box=FALSE) #now add the points. scatterplot3d creates a list, #one element of which is a function that operates #on the existing chart, q, adding points: q$points3d(c(50, 0, 0), c(0, 59, 0), c(0, 0, 20)) Of course, if you need to do more than one of these, you can pull the points from your data instead of hard-coding them. I thought hard-coding would make this a bit more readable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to loop through :eq for an unknown range using jquery? How to loop through a jquery each loop using filter :eq for an unknown range? for example, I would like to loop through the following: $("#list li:eq("+ i +")").each(function(i) { i++; }); This code does not work A: $("#list li:eq("+ i +")").each(function(i) { i++; }); The above code has two obvious flaws: * *you're trying to use i before you assign it a value, and *$('#list li:eq(' + i + ')') will only ever return one result (the li that's equal to whatever value i holds. To iterate through the li elements, simply use: $('#list li').each(function(i) { // do whatever you like in here. }); If you need to work only on elements that are equal to a particular value of i: $('#list li').each(function(i) { if (i == 3){ // for example... // do whatever you like in here. } }); Or simply: $('#list li').eq(3) If you have specific requirements then please add those to the question, so that we can better help you with this. A: If you want a counter to use for each item, the each method provides that as the first argument passed.. $("#list li").each(function(idx) { // idx will be different for each li element processed.. }); idx will hold the counter (the index) of the currently processed li element from the matching set.. A: Actually .filter() can be used with a jQuery collection/array-thing. Also if you don’t need what jQuery’s .each() does for you, a simple loop might be better. Here’s an example of how to group stuff using .filter(). Likely not the smartest way to do it: var things = $('.things'), group_size = 3, grouped, index; for (index = 0; index < things.length; index+=group_size) { grouped = things.filter( function(j) { return j >= index && j < index + group_size; }); console.log( grouped ); } You can play with that here : http://codepen.io/gabssnake/pen/ADBwp If you really need .eq(), you can still use it with simple structures: var things = $('.things'), index; // mess with index, use in conjunction with eq for (index = 0; index < things.length; index++) { things.eq( Math.pow(index,2) ).css({ 'color' : 'crimson' }) } See it here : http://codepen.io/gabssnake/pen/hjrIa
{ "language": "en", "url": "https://stackoverflow.com/questions/7627569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Watching function call Is there a way to trace all calls to a certain function? The purpose is to plug-in a debug function when "listening" to a function call. For example, I will say "listen to all calls to mysqli_query()", so I can send the function name (and perhaps the arguments) to a debug/log function. A: There is no built-in way to intercept calls to arbitrary functions for logging. However, the xdebug debugging suite may be able to help you with its execution trace functionality. You'll be able to log both function calls and the arguments involved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery messing with my form Quotes I have a form that uses .delegate to apply input validation to the form however, it appears any form with quotes just disappears.. No errors, the quote just disappears. Anyone know why this is happening? The only work around is to output the default value in the textbox as & #34; otherwise, the quotes will not appear in the textbox, even if it is actually in the value (view source). The input type="text" also uses CSS3 styling, not sure if this has anything to do with it.. Basically, input type="text" value="quotes""" or value="quotes"" will only display 'quotes' in the rendered html, while the source has the correct value in it. It's only doing this on textboxes being targeted by the .delegate code, which is applying "blur" "focus" on the text boxes, and the function is just adding classes and checking if val() = "".. the actual value in the textbox isn't being passed in the .delegate function. The only time the textboxes which are in the delegate code: if ($(this).val()=="") if ($("#divid").val()=="") A: You have to escape the quotes: Either use &quot; (NOT to be used to mark attributes). When your string is constructed using ", the attribute markers should be escaped using \". Examples: * *"<input type=&quot;text&quot;>" wrong, cannot use &quot; to mark attributes *"<input type="text">" wrong, the inner quotes has to be escaped *"<input type=\"text\">" OK, properly escaped. *"<input value=\"&quot;\">" OK, properly escaped. Parsed to an input field with a value of a quotation mark ("). EDIT To clarify: <input type="text" value="quotes"""> within a single quote (`) OR HTML source are interpreted in this way: * *Detected <input start tag. *Found an attribute called type. *The type attribute has a value (=) *The first non-whitespace character after the = character is a quote". Searching for the first occurence of a quote after this quote.. *End quote found, the value of type is type. *Found another attribute: value *The attribute defines a value, because a = is found. *The first non-whitespace character is a quote. Search for the next quote after this quote. *Quote mark found, the value of the value attribute is quotes. *Looking for the next attribute... *Found an unexpected "". Ignored. *Found close tag, the final parsed element is: <input type="text" value="quotes">. When your JavaScript string is defined using double quotation marks,", the previously used substring will cause a JavaScript error: "<input type="text. The JS interpreter found an unexpected character after the closing quote: t.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Unable to maintain uniform scale when resizing window, OpenGL + Java = JOGL I'm using JOGL (Java OpenGL wrapper) for the first time and I have an issue I can't figure out, I'm not sure if this is related to JOGL or OpenGL in general. I render on a GLCanvas inside a JPanel inside a JForm (the whole point of the program is to mix OpenGL and SWING). As of now I'm drawing simple 2D (ortho) triangles (they'll be tiles), I would like them to scale according to the size of the viewport (panel?). I achieved scaling but for some reason the image is stretched, as if scale ratio was not the same on the X component and the Y component, when I resize the window. I.e. they should maintain the same square ratio, but they get stretched instead. As you can see in the code, I use the same zoom factor for X and Y. I don't understand if the error is in my OpenGL code or in my SWING-JOGL code. Can anyone point me in the right direction? An image is better than a thousands words: Here's some code: The OpenGL code class Graphics { /** * The default ratio between the screen size and the tile size, before zoom is applied */ final static float DEFAULT_TILE_TO_SCREEN = 0.5f; /** * The parent engine */ protected Engine myEngine; Graphics(Engine e) { myEngine = e; } /** * Sets up viewport * @param gl2 * @param width * @param height */ void setup( GL2 gl2, int width, int height ) { gl2.glMatrixMode( GL2.GL_PROJECTION ); gl2.glLoadIdentity(); // coordinate system origin at lower left with width and height same as the window GLU glu = new GLU(); glu.gluOrtho2D( 0.0f, width, 0.0f, height ); gl2.glMatrixMode( GL2.GL_MODELVIEW ); gl2.glLoadIdentity(); gl2.glViewport( 0, 0, width, height ); } /** * Renders viewport * @param gl2 * @param width * @param height */ void render( GL2 gl2, int width, int height ) { final float zoomFactor = DEFAULT_TILE_TO_SCREEN * myEngine.myZoomLevel; final float zoom = Math.max(height * zoomFactor, width * zoomFactor); gl2.glClear( GL.GL_COLOR_BUFFER_BIT ); // draw a triangle filling the window gl2.glLoadIdentity(); gl2.glScalef(zoom, zoom, 1); gl2.glBegin( GL.GL_TRIANGLES ); for(int x = 0; x < myEngine.myWorldTiles.maxTileX; ++x) { for(int y = 0; y < myEngine.myWorldTiles.maxTileY; ++y) { gl2.glColor3f( 1, 0, 0 ); gl2.glVertex2f( x + 0.f, y + 0.f ); gl2.glVertex2f( x + 1.f, y + 0.f ); gl2.glVertex2f( x + 1.f, y + 1.f ); gl2.glColor3f( 0, 0, 1 ); gl2.glVertex2f( x + 0.f, y + 0.f ); gl2.glVertex2f( x + 1.f, y + 1.f ); gl2.glVertex2f( x + 0.f, y + 1.f ); } } gl2.glEnd(); } } The SWING integration code public class Engine { /** * The internal rendering canvas */ private GLCanvas myCanvas; /** * The graphics used for rendering */ private Graphics myGraphics; /** * The zoom level of the graphics */ float myZoomLevel = 1; /** * The world map */ TileList myWorldTiles; /** * The currently centered tile */ Point myCenteredTile; public Engine(TileList worldTile) { myWorldTiles = worldTile; GLProfile glprofile = GLProfile.getDefault(); GLCapabilities glcapabilities = new GLCapabilities( glprofile ); myCanvas = new GLCanvas( glcapabilities ); myGraphics = new Graphics(this); myCanvas.addGLEventListener( new GLEventListener() { @Override public void reshape( GLAutoDrawable glautodrawable, int x, int y, int width, int height ) { } @Override public void init( GLAutoDrawable glautodrawable ) { myGraphics.setup( glautodrawable.getGL().getGL2(), glautodrawable.getWidth(), glautodrawable.getHeight() ); } @Override public void dispose( GLAutoDrawable glautodrawable ) { } @Override public void display( GLAutoDrawable glautodrawable ) { myGraphics.render( glautodrawable.getGL().getGL2(), glautodrawable.getWidth(), glautodrawable.getHeight() ); } }); } /** * Sets the zoom level for the screen * @param zoom */ public void setZoomLevel(float zoom) { myZoomLevel = zoom; } /** * Gets the 3D canvas, should be placed in user-defined form/window/panel */ public java.awt.Component getCanvas() { return myCanvas; } /** * Centers the screen on the given tile * @param p */ public void centerOnTile(Point p) { myCenteredTile = p; } } Also in the JFrame init code contentPanel.add(myWorld.myEngine.getCanvas(), BorderLayout.CENTER); A: You have to setup the projection matrix each time the window resizes. I haven't used JOGL before but I think you should do it in that reshape method in the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to improve rendering performance with multiple equal and heavy movieclips? I have 25 kind of heavy movieclips on the screen. They show many bitmaps, each one of in one of their frames. The problem is that the application gets unusable when they are on screen. And even after removing them the app keeps slow. Using Adobe Air 2.0, compiled by Flash CS5. A: There literally thousands of optimization tricks for Flash, but one that usually helps when dealing with large (or complex) Sprites or MovieClips is the cacheAsBitmap property: my_mc.cacheAsBitmap = true; And since you are using Adobe Air, you can also have access to the cacheAsBitmapMatrix property, for further optimization (badly needed on mobile devices!): my_mc.cacheAsBitmapMatrix= my_mc.transform.concatenatedMatrix; my_mc.cacheAsBitmap = true; //also this! Check out this Republic of Code tutorial about when/why better use them. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7627579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: server listens to multiple ports c I need to example to a program for an single thread server that listen to multiple ports in c (linux red-hut) ? should if use one socket? A: You can't bind to multiple ports, thus you can't listen either. You need to use one socket per port. It shouldn't be hard to do so. Simply bind(2) multiple sockets, listen(2) on each of them and add them into a select(2) loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pyodbc connection error when trying to connect to DB on localhost I have a local DB on my machine called 'Test' which contains a table called 'Tags'. I am able to access this DB and query from this table through SQL Server management studio 2008. However, when using pyodbc I keep running into problems. Using this: conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost:1433;DATABASE=Test') yields the error: pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]Invalid connection. (14) (SQLDriverConnectW); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Invalid Instance()). (14)') (with or without specifying the port) Trying an alternative connection string: conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost\Test,1433') yields no error, but then: cur = conn.cursor() cur.execute("SELECT * FROM Tags") yields the error: pyodbc.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'Tags'. (208) (SQLExecDirectW)") Why could this be? A: I tried changing your query to SELECT * FROM Test.dbo.Tags and it worked. A: I don't see any authentication attributes in your connection strings. Try this (I'm using Windows authentication): conn = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}', server = 'localhost', database = 'Test') cursor = conn.cursor() # assuming that Tags table is in dbo schema cursor.execute("SELECT * FROM dbo.Tags") A: For me, apart from maintaining the connection details (user, server, driver, correct table name etc.), I took these steps: * *Checked the ODBC version here (Windows 10) -> *(search for) ODBC -> *Select 32/64 bit version -> *Drivers -> *Verify that the ODBC driver version is present there. If it is not, use this link to download the relevant driver: here Reference Link: here A: conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost:1433;DATABASE=Test') This connection lack of instance name and the port shouldn't be writen like this. my connection is this: cn=pyodbc.connect('DRIVER={SQL Server};SERVER=localhost\SQLEXPRESS;PORT=1433;DATABASE=ybdb;UID=sa;PWD=*****') enter image description here A: Try replacing 'localhost' with either '(local)' or '.'. This solution fixed the problem for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to set the size of DataGridView VB.net Program http://www.repairstatus.org/program.png The DataGridView fetches the data from a MySQL server but it does not fill the entire box in size. Ideally I would like to manually set the table size to fit the box at least width-wise because the rest will fill up once the database is populated more. A: Set the property AutoSizeColumnsMode to be Fill. That'll ensure your columns stretch to 100% within your DataGridView. The columns will stretch/shrink when you resize your grid (if your grid is anchored to your form). A: Look at the Fill Weights for the Columns. Specifically, change the AutoSizeMode to Fill. If trying to expand more than one column, adjust the FillWeight percentage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CodeIgniter 2: How to extend CI_Controller multiple times? I have successfully extended the CI_Controller class by creating a MY_Controller.php which I have placed in the application/core directory. core/My_Controller.php looks something like this: class MY_Controller extends CI_Controller { function __construct() { parent::__construct(); } } Then when I create normal controllers they look something like this: class Home extends MY_Controller { function __construct() { parent::__construct(); } function index() { $this->load->view('home'); } } I'm creating a admin back end and I want to have a different base class for controllers to extend instead of My_Controller. This is so I can have common methods for the admin controllers (i.e. authentication_check etc.) What I can't work out is how I create another controller that extends CI_Controller. The goal is for admin controllers to extend a different base class than the front-end controllers. The admin base controller would look like this: class MY_Admin_Controller extends CI_Controller { function __construct() { parent::__construct(); } } An normal controller for admin pages: class Admin_home extends MY_Admin_Controller { function __construct() { parent::__construct(); } function index() { $this->load->view('admin_home'); } } The problem is that to extend the CI_Controller class you must name your controller file PREFIX_Controller.php and place it in the core/ directory. But I want two controller classes and they can't have the same filename. A: This is pretty easy. Do the following: * *Go to the following directory: your_ci_app/application/core/ and create a php file called MY_Controller.php (this file will be where your top parent classes will reside) *Open this the file you just created and add your multiple classes, like so: class Admin_Parent extends CI_Controller { public function __construct() { parent::__construct(); } public function test() { var_dump("from Admin_Parent"); } } class User_Parent extends CI_Controller { public function __construct() { parent::__construct(); } public function test(){ var_dump("from User_Parent"); } } *Create your children controllers under this directory your_ci_app/application/controllers/ . I will call it adminchild.php *Open adminchild.php and create your controller code, make sure to extend the name of the parent class, like so: class Adminchild extends Admin_Parent { function __construct() { parent::__construct(); } function test() { parent::test(); } } A: You just put both in the same file, I have a project that is exactly the same as this. We just have both the admin and normal extended controller in the MY_Controller.php file, works fine. The main reason for the MY_Controller or other extended files is so that CodeIgniter auto initiates them when you load the base file (whether library, helper, etc.), you can have many classes in these files. Edit: You don't even need to call them MY_Admin_Controller or MY_Controller, we have Admin_Controller and User_Controller and Ajax_Controller in the MY_Controller File A: What you're doing is correct. You just need all of these files in the application/core directory. Here's a post by Phil Sturgeon regarding just this: http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY http://philsturgeon.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY/ The trick is to use the __autoload() function - which Phil describes in his post. A: if you want to extend another class instead of CI_controller you must include the target class. for example include 'auth.php'; class test extends Auth A: All files in the folder application/core MY is subclass CI MY have 2 subclasses Public and Dashboard class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); echo "This is " . __CLASS__ . "<br />"; } } Public class Public_Controller extends My_Controller { public function __construct() { parent::__construct(); echo "This is " . __CLASS__ . "<br />"; } } Dashboard have 2 subclasses, Admin and User class Dashboard_Controller extends My_Controller { public function __construct() { parent::__construct(); echo "This is " . __CLASS__ . "<br />"; } } Admin class Admin_Controller extends Dashboard_Controller { public function __construct() { parent::__construct(); echo "This is " . __CLASS__ . "<br />"; } } User class User_Controller extends Dashboard_Controller { public function __construct() { parent::__construct(); echo "This is " . __CLASS__ . "<br />"; } } in config/config.php /* load class in core folder */ function my_load($class) { if (strpos($class, 'CI_') !== 0) { if (is_readable(APPPATH . 'core' . DIRECTORY_SEPARATOR . $class . '.php' )) { require_once (APPPATH . 'core' . DIRECTORY_SEPARATOR . $class . '.php'); } } } spl_autoload_register('my_load'); in controller/Home.php //class Home extends MY_Controller { //class Home extends Dashboard_Controller { class Home extends Admin_Controller { public function index() { echo "This is " . __CLASS__ . "<br />"; //$this->load->view('home'); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Uploadify with NodeJS | Post parameters not being sent I'm building my latest app using nodeJS and need to be able to upload multiple files. I have chosen to use Uploadify flash based file uploader. Unfortunately the 'scriptData' vars don't seem to be being sent. Usual method of retrieval of POST vars in node looks like var postDataValue = req.body.postDataKey; but with Uploadify the req.body object is empty. Hope someone can help with this. A: I had to send the parameters via query string in the end. Must be something to do with NodeJS. A: It's not Node.js. req.body is not part of node. It's built into BodyParser and provided by Connect. Mainly used in Express. See http://senchalabs.github.com/connect/middleware-bodyParser.html If you don't use it, the req.body object should be empty.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I change the column type (xtype) of a grid using Sencha Designer? I'm using Sencha's Ext Designer to create their Cars example, but I can't find the correct property to change the Price column so that it renders like a number. The code behind it refers to an xtype, but this property is unavailable in the designer. There is also no way to edit the code in the designer tool. How do I change the xtype of a column through the designer? A: I'm using Ext Designer Version: 1.2.2 Build: 48. Right Click on the column in the grid, mouse over the Transform menu item and choose the type you need. I see the following choices: * *Ext.grid.column.Column *Ext.grid.column.Action *Ext.grid.column.Date *Ext.grid.column.Number *Ext.grid.column.Template
{ "language": "en", "url": "https://stackoverflow.com/questions/7627597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Template specialization with polymorphism I'm wanting to invoke a specialized templated function by using a pointer to it's base type. I'm not sure if this possible so I'm open to suggestions and/or alternatives. Here is an example of my situation: class CBase {}; class CDerivedClass : public CBase {}; template<class T> int func<T>(T &x) { ... }; template<> int func<CDerivedClass>(CDerivedClass &x) { ... }; I have another function that manages a list of CBase pointers and then calls the func() function. void doStuff() { CBase *foo[10] = { ...... }; for (int i = 0; i < 10; ++i) func(*foo[i]); } Is there a way to get the derived type, so that func(CDerivedClass &) is called? A: What about Template Subclassing? This idiom allows you to use compile-time polymorphism in C++. The cost of it is higher verbosity (such as specifying the whole class hierarchy up to the current class). In your case: template <typename TSpec> class Klass {}; template <typename TSpec> struct SpecTag {}; template <typename TSpec> class Klass<SpecTag<TSpec> > {}; template <typename TSpec> int func(Klass<TSpec> &x) { ... }; template <typename TSpec> int func(Klass<SpecTag<TSpec> > &x) { ... }; A: Alternative solution : from your example, it's obvious that you just should to use a virtual method in CBase, so you just have to define a virtual function in CBase and an overriding function in the derived class. A: The "Visitor" pattern comes to the rescue in this case. It enables polymorphic behavior in an algorithm implemented outside the class. Some support code is required inside the class, but new algorithms can later be added, existing algorithms modified, etc., without affecting the class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to run some code as an object is being destroyed? In C# I know that my objects are garbage collected when they go out of scope and there are no more pointers/references to it. Is there a way to run some custom code when this garbage collection occurs? A: Yes, it's called a finalizer. http://msdn.microsoft.com/en-us/library/wxad3cah.aspx Much of the C# documentation confusingly uses the term "destructor". Although the C++ naming for a destructor is used in C# for a finalizer, the semantics are totally different. If you consistently use the word finalizer, there won't be any confusion. A: Yes. You can define a finalizer for your class: class Lava { ~Lava() // Finalizer -- runs when object is collected { // TODO: Clean up molten rock } } A: You can use the Finalizer/Destructor (~) method. MSDN - Object.Finalize A: There is no equivalent of a destructor in C# - the best you can do is add a finalizer (which has destructor syntax) which is then scheduled for execution on a dedicated finalizer thread when the GC would have normally collected your object - this does cause additional overhead though and keeps your object instance alive longer than it should have been. Consider the use case carefully.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: env->FindClass("java.lang.Math"); env->FindClass("java.lang.Math"); fails. Why? gcc -I/System/Library/Frameworks/JavaVM.framework/Headers test.cpp -framework JavaVM -o test && ./test http://developer.apple.com/library/mac/#samplecode/simpleJavaLauncher/Listings/utils_h.html#//apple_ref/doc/uid/DTS10000688-utils_h-DontLinkElementID_7 http://developer.apple.com/library/mac/#technotes/tn2147/_index.html #include <jni.h> #include <stdlib.h> int main() { printf("START.\n"); JavaVM* jvm = NULL; JNIEnv *env; JavaVMInitArgs vm_args; JNI_GetDefaultJavaVMInitArgs(&vm_args); vm_args.version = JNI_VERSION_1_6; vm_args.nOptions = 0; int ret = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); if(ret < 0) { printf("Unable to Launch JVM\n"); return 1; } jclass mathClass = env->FindClass("java.lang.Math"); if (mathClass == NULL) { printf("Unable to find java.lang.Math\n"); return 1; } jmethodID cosMethod = env->GetStaticMethodID(mathClass, "cos", "(D)D"); if (cosMethod == NULL) { printf("Unable to find java.lang.Math.cos()\n"); return 1; } printf("call\n"); jdouble jIn = 0.1; jdouble jOut = env->CallStaticIntMethod(mathClass, cosMethod, jIn); printf("jOut: %f", jOut); printf("DestroyJavaVM.\n"); jvm->DestroyJavaVM(); printf("END.\n"); return 0; } A: You should be calling: jclass mathClass = env->FindClass("java/lang/Math"); From the documentation: name: fully-qualified class name (that is, a package name, delimited by “/”, followed by the class name). If the name begins with “[“ (the array signature character), it returns an array class. A: Try: env->FindClass("java/lang/Math")
{ "language": "en", "url": "https://stackoverflow.com/questions/7627601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AVAudioPlayer Notification issue So I'm almost done with my app and I've hit a wall and cannot get around this final problem. I basically have 2 view's. A main page and the game play screen. On the first play the game works fine, but when i leave the main screen and then return to the game screen all the sounds are duplicating and firing the the playerItemDidReachEnd early (because I'm guessing there are 2 instances of it, but it cannot seem to get the player to stop this. Here is the basic code causing this. Any help would go a long way, thanks. I'm not sure if my issue is i'm creating multiple instances of View2 in View1 or if I'm creating multiple player objects in view2 thus duplicating the notification. I know there is a lot going on in my - (void)playerItemDidReachEnd:(NSNotification *)notification, but it works fine on the first load of the page, its only when I click "go back to view1" and then go back in to View2 that the issue happens. View1ViewController.h ---------------------- #import "(i know here are arrows here, but can't make them show)UIKit/UIKit.h> #import "ApplicationViewController.h" @interface MonsterSpellViewController : UIViewController { } -(IBAction)showView1; View2ViewController.m ---------------------- -(IBAction)showView2{ ApplicationViewController *view2 = [[ApplicationViewController alloc]initWithNibName:@"ApplicationViewController" bundle:nil]; view2.modalTransitionStyle = UIModalTransitionStyleCoverVertical; [self presentModalViewController:view2 animated:YES]; } View2ViewController.h ------------------------ #import "(i know here are arrows here, but can't make them show)UIKit/UIKit.h> #import "(i know here are arrows here, but can't make them show)AVFoundation/AVFoundation.h> @class AVAudioPlayer; @interface ApplicationViewController : UIViewController{ AVAudioPlayer *avPlayer; } View2ViewController.m ------------------------- #import "View2ViewController.h" @synthesize avPlayer; -(AVAudioPlayer *)avPlayer { if(!avPlayer) avPlayer = [[AVAudioPlayer alloc]init]; return avPlayer; } -(void) viewDidLoad { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:avPlayer]; } -(IBAction)playSoundTest { NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/monster3.mp3", [[NSBundle mainBundle] resourcePath]]]; self.avPlayer = [AVPlayer playerWithURL:url]; [self.avPlayer play]; } - (void)playerItemDidReachEnd:(NSNotification *)notification { //[player seekToTime:kCMTimeZero]; if (playEscape == YES) { [self btnEscapeSound]; playEscape = NO; } if ((startButton.hidden == NO) && (letterCount != -1) && (playFinal == YES)) { [self btnFinalSound]; playFinal = NO; playEscape = YES; } NSLog(@"Player Check accessed"); if (letterCount == 3) { if (Winner == letterCount) { //moveNextSound = YES; if (intLoopCount < 104) { if (intLoopCount<104) { [self btnStartOver:intLoopCount]; playFinal = NO; //intLoopCount++; } if (intLoopCount==104) { startButton.hidden=NO; playFinal = YES; } } } } if (letterCount == 4) { if (Winner == letterCount) { //moveNextSound = YES; if (intLoopCount < 105) { [self btnStartOver:intLoopCount]; //intLoopCount++; if (intLoopCount==105) { startButton.hidden=NO; playFinal = YES; } } } } } } -(IBAction)goBack:(id)sender{ [self dismissModalViewControllerAnimated:YES]; } A: Try adding [view2 release]; after [self presentModalViewController:view2 animated:YES];
{ "language": "en", "url": "https://stackoverflow.com/questions/7627615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GD+PHP: Exception to see if imagefail fails? imagetruecolortopalette($dst_image,true,$colorcount); imagepalettecopy($dst_image,$src_image); $transparentcolor = imagecolortransparent($src_image); imagefill($dst_image,0,0,$transparentcolor); imagecolortransparent($dst_image,$transparentcolor); So I want something like: if imagefill fails unlink exit with error else continue with imagefill Or: if imagefill takes more than X seconds unlink exit with error else continue with imagefill Any ideas? Please help. A: I ended up switching over to imagemagick. -Two times faster. -Uses less memory. -No more errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Products catalogue: filter by parameters I need to make the filter products by features. So, products model: <pre style='color:#000000;background:#ffffff;'><span style='color:#800000; font-weight:bold; '>class</span> Product<span style='color:#808030; '>(</span>models<span style='color:#808030; '>.</span>Model<span style='color:#808030; '>)</span><span style='color:#808030; '>:</span> name <span style='color:#808030; '>=</span> models<span style='color:#808030; '>.</span>CharField<span style='color:#808030; '>(</span>max_length<span style='color:#808030; '>=</span><span style='color:#008c00; '>255</span><span style='color:#808030; '>,</span> unique<span style='color:#808030; '>=</span><span style='color:#e34adc; '>True</span>'<span style='color:#808030; '>)</span> And feature models: <pre style='color:#000000;background:#ffffff;'><span style='color:#800000; font-weight:bold; '>class</span> Value<span style='color:#808030; '>(</span>models<span style='color:#808030; '>.</span>Model<span style='color:#808030; '>)</span><span style='color:#808030; '>:</span> value <span style='color:#808030; '>=</span> models<span style='color:#808030; '>.</span>CharField<span style='color:#808030; '>(</span>max_length<span style='color:#808030; '>=</span><span style='color:#008c00; '>50</span><span style='color:#808030; '>)</span> <span style='color:#800000; font-weight:bold; '>class</span> FeatureName<span style='color:#808030; '>(</span>models<span style='color:#808030; '>.</span>Model<span style='color:#808030; '>)</span><span style='color:#808030; '>:</span> name <span style='color:#808030; '>=</span> models<span style='color:#808030; '>.</span>CharField<span style='color:#808030; '>(</span>max_length<span style='color:#808030; '>=</span><span style='color:#008c00; '>50</span><span style='color:#808030; '>)</span> <span style='color:#800000; font-weight:bold; '>class</span> Feature<span style='color:#808030; '>(</span>models<span style='color:#808030; '>.</span>Model<span style='color:#808030; '>)</span><span style='color:#808030; '>:</span> name <span style='color:#808030; '>=</span> models<span style='color:#808030; '>.</span>ForeignKey<span style='color:#808030; '>(</span>FeatureName<span style='color:#808030; '>)</span> value <span style='color:#808030; '>=</span> models<span style='color:#808030; '>.</span>ForeignKey<span style='color:#808030; '>(</span>Value<span style='color:#808030; '>)</span> item <span style='color:#808030; '>=</span> models<span style='color:#808030; '>.</span>ForeignKey<span style='color:#808030; '>(</span>Product<span style='color:#808030; '>)</span> To mark up a template form of filtering I need to get all the possible names of the characteristics and values ​​of this characteristic. Like this: Color: Red, White, Blue Size: 1, 2, 3 I hope somebody understood me, tell me how to do clever to realize a functional. Thanks:) A: Start with listing all Features for given product: product = Product.objects.get(pk=given_pk) features = product.feature_set.all().select_related() Now group your features directly in Python. features_dict = {} for feature in features: values = features_dict.get(feature.name.name, []) features_dict[feature.name.name] = values + [feature.value.value] That will give you dict linking all name to it's existing values.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting value array on input:chechbox Why in following PHP code output var_dump for checkbox($service_un) in offset[1] is empty? this variable($service_un) get values checkbox_un in following HTML code that are as array but not know why in output var_dump on offset[1] values input:name="checkbox_un[1][]" are empty. how can fix it? array(2) { [0] = > array(2) { [0] = > string(7)"Minibar" [1] = > string(12)"Teahouse" }[1] = > array(2) { [0] = > string(0)"" [1] = > string(0)"" } } Codes: <input type="text" name="name_un[]" value="jack"> <input type="checkbox" name="checkbox_un[0][]" value="Minibar"> <input type="checkbox" name="checkbox_un[0][]" value="Teahouse"> <input type="text" name="name_un[]" value="jim"> <input type="checkbox" name="checkbox_un[1][]" value="Television"> <input type="checkbox" name="checkbox_un[1][]" value="Foreign"> <?php $name_un = $this->input->post('name_un'); $service_un = $this->input->post('checkbox_un'); var_dump($service_un); // This output ?> A: Checkbox values are only set (to the value in the HTML input tag), if the checkbox has been selected (the checkmark was set). As long as it doesn't, the offset will not be set. Try it for yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to Adjust the second div I have two Div http://jsfiddle.net/KuX3G/ future |--- futureBorderL | |--- futureBorderR The futureBorderR Div is not up to the line, which is the right one. Plz suggest. Thanks!!! A: add float:left for #futureBorderL Demo: http://jsfiddle.net/KuX3G/2/ A: if i understand you correctly, you are trying to have two divs side by side <div style="float:left; width: 150px;">Left</div> <div style="margin-left: 150px;">Right</div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7627624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What purpose does overflow: hidden; serve? I have a web page with a header area in the middle. Elements are then part of the header. Can someone explain what overflow: hidden; does here. I don't understand why I need it or what it does. #hdr_mdl { margin: 0 auto; overflow: hidden; width: 980px; z-index: 10; height: 50px; } A: When overflow: hidden is added to the container element, it hides its children that don’t fit in the container. Example: .overflowhidden { background: green; width: 10rem; height: 10rem; overflow: hidden; } <div class="overflowhidden"> This container has the style overflow:hidden. Text that does not fit becomes hidden. This is a very long sentence of text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text even more text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text this is the end of the sentence. </div> A: overflow:hidden prevents scrollbars from showing up, even when they're necessary. Explanation of your CSS: * *margin: 0 auto horizontally aligns the element at the center *overflow:hidden prevents scrollbars from appearing *width:980px sets the width of the element to be 980px. *z-index:10 causes the element to stay on top of elements without a defined z-index, *or- elements with a z-index below 10, or elements with a z-index of 10, but defined in before the current element *heigh:50px - a height of 50px. A: If the content in #hdrPmdl was to spill over 50px it will not allow the browser to insert scrollbars into the DIV. If the DIV doesnt contain dynamic content and the size will always remain static then it is probably not needed as the content will no be > 50px A: overflow specifies what a browser should do, when content is bigger than block dimensions. overflow:hidden means 'hide it and preserve initial block dimensions'. A: if you use overflow hidden for a particular content than the overflow is clipped for this content, and the rest of the content will be invisible. for clear the matter visit w3school http://www.w3schools.com/cssref/pr_pos_overflow.asp A: Explanation of the overflow property: CSS overflow Property Interactive example of the overflow property: Play it
{ "language": "en", "url": "https://stackoverflow.com/questions/7627625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Socket.io not sending a message to all connected sockets I'm trying out node.js and socket.io. I wan't to use to remove a ping function I have to get updates from my server. Here is an example code of what I'm doing: var app = require('http').createServer(), io = require('socket.io').listen(app), cp = require('child_process'); app.listen(8080); //I check a global value for all the connected users from the php command line var t = setInterval(function(){ cp.exec('/usr/bin/php /Users/crear/Projects/MandaFree/symfony api:getRemainingMessages', function(err, stdout){ if (err) { io.sockets.emit('error', 'An error ocurred while running child process.'); } else { io.sockets.emit('change', stdout); } console.log('Remaining messages: ' + stdout); }); }, 3000); var remaining = io.of('/getRemainingMessages') .on('connection', function(socket){ socket.on('disconnect', function(){}); }); The Issue here, is that when I call io.sockets.emit() the debug console tells me it is doing something, but it looks like it is not getting to the clients. Because they are doing nothing. I use to have one interval for every connected client, and when I used socket.emit() it did worked. But it is not the optimal solution. UPDATE: Here is my client side code. var remaining = io.connect('http://127.0.0.1:8080/getRemainingMessages'); remaining.on('change', function(data){ console.log('Remaining messages: ' + data ); $('#count').html(data); }); remaining.on('error', function(error){ console.log(error); }); A: Had a very similar issue couple of days back and looks like socket.io had some changes in the API. I have never worked with symfony and am hoping the issues are the same. I have a working demo of socket.io sending and receiving a message - uploaded to https://github.com/parj/node-websocket-demo as a reference Essentially two changes * *On Server side - changed socket.on to socket.sockets.on var socket = io.listen(server); socket.sockets.on('connection', function(client) *On Client side - URL and port not required as it is autodetected. var socket = io.connect(); This has been tested using Express 2.5.2 and Socket.io 0.8.7 I have amalgamated your server code with mine, would you be able to try this on the server and my client javascript and client html just to see if it is working? var socket = io.listen(server); socket.sockets.on('connection', function(client){ var connected = true; client.on('message', function(m){ sys.log('Message received: '+m); }); client.on('disconnect', function(){ connected = false; }); var t = setInterval(function(){ if (!connected) { return; } cp.exec('/usr/bin/php /Users/crear/Projects/MandaFree/symfony api:getRemainingMessages', function(err, stdout){ if (err) { client.send('error : An error ocurred while running child process.'); } else { client.send('change : ' + stdout); } console.log('Remaining messages: ' + stdout); }); }, 3000); t(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7627626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: GPS Specific questions for Service application I am working on a simple application that I need to be run as a service and report gps position every 3 minutes. I already have a working example based on the tutorial, but still have the followin doubts. * *The starting of the service GPS1.Start(5*60*1000, 0) Says first parameter is time lapse, and 2nd parameter is distance difference, How is determined, based on prior position ? *If I want to do what I stated before and I am scheduling / starting service every 3 minutes, this means I will need to ask a GPS1.Start(0,0) to get latest fix? what would be the gain to use the parameters? *I trying in a NexusOne and the Time object comes with local time, I have to do this to make it UTC but this is a tweak to the code. Is this a standard or could It change based on Phone model ? hora=DateTime.Date(Location1.Time + 6*DateTime.TicksPerHour) thanks A: If you are only interested in a single fix each time then you should pass 0, 0. These values affect the frequency of subsequent events. You can find the time zone with the code posted here: GetTimeZone
{ "language": "en", "url": "https://stackoverflow.com/questions/7627633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to filter out duplicate requests in UIWebView I am writing an iPhone app that integrates with Foursquare via OAuth. I am able to log in, obtain an access token, and use the API endpoints. I do the log in with a UIWebView. The problem is that for every tap on the web view (Login, Allow, etc.), two identical requests are made. So when I dismiss the web view after obtaining an access token, the web view's didFailLoadWithError: message fires, presumably for the second (duplicate) request. This is causing crashes and unwanted behavior. Is there any way I can prevent the duplicate requests from happening or can I 'filter' them out? A: fa solution for filtering out: You can set the delegate-property of UIWebView to nil before dismissing it. self.myWebView.delegate = nil; self.myWebView = nil; //retain-property edit: but this will not really prevent the UIWebView to send the second request over the wire. This will only end up with not being notified twice. You have to discover why the second request is sent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why Would Slickgrid Ajax/Infinite Scroll Produce Intermittent Blank Rows? In scrolling through a remote data source, SlickGrid works correctly, but often adds a series of empty rows. For instance: Good Good Good Empty Empty Empty Good Good Good Good It seems like, in the process of loading the data, in creates these empty rows, then uses subsequent rows, rather than the empty ones it has created, to render populated rows. I've looked everywhere and come up short. Can anybody think of something that would cause this behavior? Thanks in advance. A: There is a bug in the ensureData(from, to) method in the slickgrid RemoteModel example but I don't remember exactly what. I corrected it and some more to make more efficient use of the back-end database. Here is the code: /** Ensures data range is loaded, loading if necessary. */ function ensureData(from, to) { // Reduce range to only unloaded data by eliminating already loaded data at the extremes // or data which is already being loaded by a pending request if (from < 0) {from = 0;} while (data[from] !== undefined && from < to) {from++;} while (data[to] !== undefined && from < to) {to--;} // no need to load anything if (data[from] !== undefined) { return; } // A request for data must be made: increase range if below optimal request size // to decrease number of requests to the database var size = to - from + 1; if (size < optimalRequestRangeSize) { // expand range in both directions to make it equal to the optimal size var expansion = Math.round((optimalRequestRangeSize - size) / 2); from -= expansion; to += expansion; // if range expansion results in 'from' being less than 0, // make it to 0 and transfer its value to 'to' to keep the range size if (from < 0) { to -= from; from = 0; } // Slide range up or down if data is already loaded or being loaded at the top or bottom... if (data[from] !== undefined) { while (data[from] !== undefined) { from++; to++; } } else if (data[to] !== undefined) { while (data[to] !== undefined && from > 0) { from--; to--; } } } // After adding look-ahead and look-behind, reduce range again to only unloaded // data by eliminating already loaded data at the extremes while (data[from] !== undefined && from < to) {from++;} while (data[to] !== undefined && from < to) {to--;} // clear any pending request if ( request !== null) clearTimeout( request); // launch request to server with a delay of 100ms to cater with quick scrolling down request = setTimeout(function() { requests++; // set records in range to null; null indicates a 'requested but not available yet' for (var i = from; i <= to; i++) { if (!data[i]) { data[i] = null; } } // notify grid (to show loading message) and load through ajax onDataLoading.notify({from: from, to: to}); $.ajax({ url: url, global: false, cache: true, type: "GET", data: { from: from, to: to, sortColumn: sortColumn, sortDirection: sortDirection }, dataType: "xml", success: function(response, textStatus, jqXHR) { if (requests > 0) requests--; onSuccess(response, textStatus, jqXHR) }, error: function(jqXHR, textStatus, errorThrown) { if (requests > 0) requests--; if (textStatus !== "abort") { onDataLoadingError.notify({ from: from, to: to, pendingRequests:requests, textStatus: textStatus, errorThrown: errorThrown }); } } }); }, 100); } Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems with Scala constructors and enums I have the following class definition in Scala: class AppendErrorMessageCommand private(var m_type: Byte) { def this() = this(0x00) def this(errorType: ErrorType) = this(getErrorTypeValue(errorType)) private def getErrorTypeValue(errorType: ErrorType) = { if(errorType == USER_OFFLINE) 0x01 else if(errorType == PM_TO_SELF) 0x02 0x00 } } ErrorType is the following enum: object ErrorType extends Enumeration { type ErrorType = Value val USER_OFFLINE, PM_TO_SELF = Value } I think something is wrong with the constructor definitions in the class. My IDE (which is the Scala IDE for Eclipse) tells me it cannot find getErrorTypeValue. It also tells me that the overloaded constructor is has alternatives. One being the byte and the other the enum. Don't take these error messages of the IDE seriously though. They might be wrong, as this often happens with the IDE. But nonetheless, when the IDE tells me something is wrong, it usually is wrong. So, what is the problem with my class/constructor definitions? A: In this case the IDE is perfectly correct and agrees with the scala command line compiler. Your constructor takes a Byte, so you need to provide it with one (0x00 is an Int), you need to import ErrorType._ and you need to move getErrorTypeValue to the companion object and declare it to return a Byte (the inferred type is an Int): object ErrorType extends Enumeration { type ErrorType = Value val USER_OFFLINE, PM_TO_SELF = Value } import ErrorType._ object AppendErrorMessageCommand { private def getErrorTypeValue(errorType: ErrorType): Byte = { if(errorType == USER_OFFLINE) 0x01 else if(errorType == PM_TO_SELF) 0x02 0x00 } } class AppendErrorMessageCommand private(var m_type: Byte) { def this() = this(0x00.toByte) def this(errorType: ErrorType) = this(AppendErrorMessageCommand.getErrorTypeValue(errorType)) } Another, better way is to avoid having multiple constructors and use a factory method: object AppendErrorMessageCommand { def apply() = new AppendErrorMessageCommand(0x00) def apply(b: Byte) = new AppendErrorMessageCommand(b) def apply(errorType: ErrorType) = new AppendErrorMessageCommand(AppendErrorMessageCommand.getErrorTypeValue(errorType)) private def getErrorTypeValue(errorType: ErrorType): Byte = { if(errorType == USER_OFFLINE) 0x01 else if(errorType == PM_TO_SELF) 0x02 0x00 } } class AppendErrorMessageCommand private(var m_type: Byte) { } See the answers to How can I call a method in auxiliary constructor? A: 0x00 etc are Int literals that happen to be in hexadecimal. getErrorTypeValue returns an Int so this(getErrorTypeValue(errorType)) refers to a constructor taking an Int, which doesn't exist. If you want to type your number literals as Byte, use 0x01: Byte, or specify the return type of your method private def getErrorTypeValue(errorType: ErrorType): Byte = { to use an implicit cast. A: The problem is you can't call getErrorTypeValue when delegating the constructor 'cause the object isn't created yet. I think.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Where to store fixed NSString variables in Cocoa Application? I have different classes, that have NSString fixed variables (like @"/Users/user/media", or xml commands). I think to store everything in class is a bad design. What is the best place to store fixed NSStrings? Might something like preferences file? P.S. I'm new in Cocoa, please describe it with details, how I can store, and read that values. Thanks. A: They are many ways, but I like to do this in my class implementation files: NSString *const ABConstantStringname = @"name"; Where AB is the name spacing you're using (if you are using one), and ConstantStringName is some meaningful name for the constant. Then later, you can just use the ABNameIdentifier variable whenever you like. You don't release it. A: Depends on the scope - if you want to just une in implementation you can just put in .m, but if you want to expose publically to the consumers of the class (outside your .m implementation) you need to also extern it. In header: #import <Cocoa/Cocoa.h> extern NSString* const BNRTableBgColorKey; extern NSString* const BNREmptyDocKey; @interface PreferenceController : NSWindowController { ... In implementation: - (id)init { NSLog(@"init"); NSString * const BNRTableBgColorKey = @"TableBackgroundColor"; NSString * const BNREmptyDocKey = @"EmptyDocumentFlag";
{ "language": "en", "url": "https://stackoverflow.com/questions/7627662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert to DateTime from string containing decimal and comma millisecond separators Given the following 2 strings notice the ".185" and ",185" * *2011-09-15 17:05:37,185 *2011-09-15 17:05:37.185 Reading from a file (not in my control) and I can see they have dates in both formats. I need to create a function that cater for both scenarios. Is the '.' and ',' a culture specific? Any suggestion for such a function? This below is not working as I don't get a date. class Program { static void Main(string[] args) { string date1="2011-09-15 17:05:37.185"; string date2="2011-09-15 17:05:37,185"; const string format1 = "dd/MM/yyyy HH:mm:ss.ff"; const string format2 = "dd/MM/yyyy HH:mm:ss,ff"; DateTime resultDate1; DateTime resultDate2; DateTime.TryParseExact(date1, format1, CultureInfo.InvariantCulture, DateTimeStyles.None, out resultDate1); DateTime.TryParseExact(date2, format2, CultureInfo.InvariantCulture, DateTimeStyles.None, out resultDate2); Console.WriteLine(resultDate1.ToString()); Console.WriteLine(resultDate2.ToString()); Console.Read(); } } A: Is the . and , a culture specific? Yes. In Europe, a comma is often used instead of a period as the decimal separator. Any suggestion for a solution? Yes. My first thought is that the DateTime.ParseExact()/DateTime.TryParseExact() functions have an overload that allows an array of formats to test. You could include both the en-US variant and the en-GB variant. Except that I don't think this will work, as you still only get to include a single culture specifier. So instead, I recommend calling .Replace() before passing the string to ParseExact function to change any commas that might be in the string to periods. In your updated example code, your format string just doesn't match your example dates. You should use this: yyyy-MM-dd HH:mm:ss.fff A: You should use DateTime.ParseExact or .TryParseExact as suggested in Hans Passant's comment. DateTime d1; string[] formats = new [] { "yyyy-MM-dd HH:mm:ss.fff", "yyyy-MM-dd HH:mm:ss,fff" }; DateTime.TryParseExact(s1, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out d1); You should also specify CultureInfo.InvariantCulture, as otherwise the ParseExact method may use a culture-specific date separator (in place of /, e.g. "." in Germany) or time separator (in place of ":").
{ "language": "en", "url": "https://stackoverflow.com/questions/7627663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Django queryset custom properties I have user profile like class UserProfile(models.Model): completed_tasks = models.ManyToManyField(Tasks) then task model class Tasks(models.Model): <...fields...> Then I want to filter some task and have a queryset property "completed" that marks if task objects is in user completed_tasks. Example t = Tasks.objects.filter(...).order_by(...) t[0].completed # False t[1].completed # True Any ideas how can I do that? A: Tricky question: in your model task completion depends on user having it in his collection, which makes the logic ambiguous. Is the task completed if any user completed it? Maybe all users need to complete it? Or maybe answer depends on user asking? Try making your models more defined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I'm trying to make a CSS and Javascript menu with current class I want to build an app made in javascript, PHP, and CSS, but I'm stuck in a dumb place. I want to make a menu to load links in an iframe called "zero". And it works, now I want to make it so that when you clik on a link the background of the link goes blue, and when you click on another, the background goes back to white and that link goes blue, and so on. The dificult part is that I have all the links like this: index.php?act=page_name, so they are actualy the same page, diferent portions of it, loaded in another iframe. and I have a Javascript to do it : function grafice() { document.getElementById("grafice").setAttribute("class", "current"); window.open('index.php?act=grafice_comenzi','zero'); } where "current" is like this : #menucase ul.vert-one li a.current,ul.vert-one li a.current:hover { background:#80BFFF; color:#333333; border-top:solid 1px #0099FF; border-bottom:solid 1px #0099FF; } How do I go next, I want when I click another link, something in Javascript to tell the previous link to go white again. here's a link to my page so far : http://www.guku.byethost31.com/temp/ can anyone help me please ? A: I'd to do this : Once a link is clicked, change it's background color to blue , while you change the background color of the rest of the links in the page to white. (elementName.style.background:....) Another and less suggested option is creating an hidden input field, which in it you store the id of the link you clicked on. After clicking on another link, you can retrieve the id that's stored in the hidden field and change it's background color to white. Good luck with this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone iOS 4 UIButton toggle highlighted state on and off I got a UIButton with style "Info Dark" set up in interface builder in my iPhone 4 app. One of the properties of the button is "Highlighted", which displays a white highlight around the button. I would like to toggle this white highlight on and off, indicating if the button function is active or not. The button is linked for "Touch up inside" event in the interface builder with this callback: infoButton.highlighted = !infoButton.highlighted; After the first touch, the highlight disappears and does not toggle as I expect it to. What else do I need to do to make the highlight toggle and display the state of the button? Thank you! Update: When loaded from the interface builder, the button stays highlighted, even as the view appears/disappears. What causes this to happen is the "shows touch on highlight" interface builder property. If I assign the code above to another button, the info button highlights on and off as expected. However, the touches of the info button itself interfere with the above code, causing the button to lose the "touch" highlight Update 2: I added another info button, directly below the first info button, in the interface builder and made it glow permanently. To create the appearance of the toggle, I hide and unhide the glowInfoButton below the real one. This works as expected: infoButton.highlighted = NO; glowInfoButton.highlighted = YES; glowInfoButton.enabled = NO; glowInfoButton.hidden = YES; - (IBAction)toggleInfoMode:(id)sender { // infoButton.selected = !infoButton.selected; glowInfoButton.hidden = !glowInfoButton.hidden; } A: The Highlighted image is what displays when the UIButton is being pressed, and is controlled within the UIButton itself. You're looking for the Selected property. You can set a Selected Image in IB, and then put a infoButton.selected = !infoButton.isSelected; in your TouchUpInside callback. A: The highlighted property doesn't work like that, buttons aren't toggles. It's just to know if the button is being pressed, if I'm correct. If you want to implement that functionality, I recommend you subclass UIButton or UIControl. A: Perhaps what you really want is infoButton.enabled = NO; This will dim the button and disable touches when set to no, allow normal operation when set to YES. or in your case: infoButton.enabled = !infoButton.isEnabled; to toggle the availability of same. If you put this in your touchupinside event, of course it will work only the first time. After that is disabled and does not receive touch events. You would put it in another method that decides whether or not the button should be enabled. If you truly want it to change each time it is pressed then you probably should use a switch or you may look at the -imageForState, -setTitle:forState and/or -setTitleColor:forState methods. If you want to toggle the appearance each time it is touched, you could change these. A: Now that I see what you really were after I would advise subclass UIButton and check for a call to an event then toggle highlight state accordingly. You can do this without adding the dummy button. in a custom button class implementation file place the following code, or similar: #import "HighlightedButton.h" @implementation HighlightedButton BOOL currentHighlightState; -(void)toggleHighlight:(id)sender { self.highlighted = currentHighlightState; } -(void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event { //get the string indicating the action called NSString *actionString = NSStringFromSelector(action); //get the string for the action that you want to check for NSString *touchUpInsideMethodName = [[self actionsForTarget:target forControlEvent:UIControlEventTouchUpInside] lastObject]; if ([touchUpInsideMethodName isEqualToString:actionString]){ //toggle variable currentHighlightState = !currentHighlightState; //allow the call to pass through [super sendAction:action to:target forEvent:event]; //toggle the property after a delay (to make sure the event has processed) [self performSelector:@selector(toggleHighlight:) withObject:nil afterDelay:.2]; } else { //not an event we are interested in, allow it pass through with no additional action [super sendAction:action to:target forEvent:event]; } } @end That was a quick run at a proper solution, there is a flicker on toggle that you may not like. I am sure if you play around with some changes that can be corrected. I tried it and actually like it for your stated case. A: The highlighted state of a UIButton is simply setting the button's alpha to 0.5f. So if you set the button to not change on highlight, then just toggle the alpha between 0.1 and 0.5. For example: - (void)buttonPressed:(id)sender { if((((UIButton*)sender).alpha) != 1.0f){ [((UIButton*)sender) setAlpha:1.0f]; } else { [((UIButton*)sender) setAlpha:0.5f]; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL query for selecting distinct field and then ordering by date I would like to sort a table by date. I have multiple records for the same artist name but they have different dates e.g. ARTIST:DATE Gerd:2011-09-28 Gerd:2011-09-01 Simon:2011-07-01 Simon:2011-10-02 Franco:2011-01-10 Franco:2011-09-15 Franco:2011-07-01 Des:2011-09-05 How can I extract the distinct username and show the most recent date that they had a record created on? I would also like to only show names that have more than 2 records so in this case the results I want are Simon:2011-10-02 Gerd:2011-09-28 Franco:2011-09-15 (I would like these to be sorted in date order) Thanks! A: Try this: SELECT Artist, MAX(Date) AS MaxDate FROM Artists GROUP BY Artist HAVING COUNT(Artist) > 2 ORDER BY MaxDate DESC Your question explicitly states "more than 2", but your example data illustrates >= 2. In any case, you can adjust the HAVING if/as you require: HAVING COUNT(Artist) >=2
{ "language": "en", "url": "https://stackoverflow.com/questions/7627670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Upload file security >> Restricting names and extensions not enough? (can not rename, or move files) "The most important safeguard is to keep uploaded files where they cannot be directly accessed by the users via a direct URL. This can be done either by storing uploaded files outside of the web root or configuring the web server to deny access to the uploads directory. Another important security measure is to use system-generated file names instead of the names supplied by users when storing files on the file system. This will prevent local file inclusion attacks and also make any kind of file name manipulation by the user impossible" I understand this, however - I am providing options for Wordpress users to upload files to their image directory, so I can not do either of these afaik. The files need to go into the images directory, and be named a name of their choosing. Here is what I am doing so far: 1) Only allowing files with names with one extension, and the extension must be from a trusted list. 2) Only allowing alphanumeric, spaces and underscores in the first part of the name and less than 30 chars. 3) Not allowing files with the name .htaccess to be uploaded 4) Only allowing admin access to the upload and using wp nonces 5) Checking mime type 6) Checking file size Some questions I have are: If I deny uploading any file named '.htaccess' and am denying any file with .php extension, shouldn't this prevent someone from upolading an image file with .php code embedded? I understand that I can use php to copy images without malicious code, however I am planning to allow the upload of .ttf files and .css files as well. I could scan those files with php for script question marks, etc. Is this advisable? If so what would I search for beyond this? If I am only allowing admins access and am using nonces and the above methodology, how secure is my code and are their other things that I should be doing? Any help is greatly appreciated! A: I thought I would bump this - having a hard time finding much feedback here. If you do a thorough scrubbing of file names, and only whitelist image, text and css files, what kind of security does that buy you. Currently, I am uploading as a random name in a directory, scrubbing the name, one extension, whitelisted and re-saving in a public image directory. And only allowing access by wp admins. A: You should disable PHP execution in the images directory. That would prevent a lot of the potential problems you've considered without having to worry about having missed some tricky filename construction. Add php_flag engine off to the apache configuration for that directory. Unless you really need them for some reason, you should also disable .htaccess files, at least in the images directory. Everything you can do in a .htaccess file can be done in an apache configuration file outside of any directory that might be writeable by the web server. See the AllowOverride directive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Universal application has black iPad screen I've just finished my app for iPhone and it is working fine. I now want to make the app universal but am getting a black screen when running it on the iPad simulator. Here is what I have done so far: * *When electing to make universal, I allowed xCode to create my "-iPad" version of my main nib; Therefore, I have MainWindow.xib for iPhone and MainWindow-iPad.xib for iPad. I have checked my plist file and have confirmed that both entries are present *Have double checked each UI component in the new iPad version to make sure all connections are made identically to the iPhone version. I also double check that the classes are correct *I have made sure that the "visible at launch" and "full screen at launch" options are selected *I read somewhere that removing the "-" worked for someone and have tried renaming my nib and plist entries I am assuming that my app would then load the proper nib. Obviously I'm either wrong or have some configuration not right On the other hand, if I need to make some change in my didFinishLoadingWithOptions to force they selection between my nibs - well I must admit I don't know how to accomplish this either. Thanks! A: If the app doesn't crash, than it means it can find the black screen. Truncating the cache is done in Product -> Clean and also what you could try is "Reset" on the iOS simulator. Further more, what you could check is if the "view" is linked correctly in your nib. (see image). A: OK, after much trial and error, I have gotten this to work; Although, I'm not quite sure which exact steps solved the problem, I have a sneaking feeling it was some of the settings I had for the versioning of the app. I created a new test app for iPhone and then converted it to iPad. Of course this worked unlike my app. I then compared everything I could think of between the apps. I changed the supported version from 3.1 to 4.0 on the Target -> Summary tab. I then check my build settings and changed everything in there to 4.0 as well. Finally, for each .xib file I set the deployment to "Project SDK Version (iOS 4.3) and the Development to "Interface Builder 3.1" because that is what my test app was set to. To be honest, I don't even recall altering these or do I really even know if this has an impact all I know is that I did change them as described. Did a project clean, reset the simulator and now it is working. I'm wondering if it was the 3.1 was too early for the iPad... Anyway thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My OnClickListener is not firing Can someone please help me? I have been searching for hours and I cannot find a solution. Why won't my onclicklistener not work? It works for the first time but will not work for the doLogin method. Why? @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final FileUtils file = new FileUtils(); final String patientDetails = FileUtils.readFile("/TextFiles/patientDetails.txt"); if(patientDetails.equalsIgnoreCase("register")){ setContentView(R.layout.main); //Toast t = Toast.makeText(getBaseContext(), patientDetails, Toast.LENGTH_SHORT); //t.show(); ImageButton submit = (ImageButton) findViewById(R.id.btn_submit); submit.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String patientId1 = ((EditText) findViewById(R.id.patientId1)).getText().toString().trim(); String patientId2 = ((EditText) findViewById(R.id.patientId2)).getText().toString().trim(); String patientPassword1 = ((EditText) findViewById(R.id.patientPassword1)).getText().toString().trim(); String patientPassword2 = ((EditText) findViewById(R.id.patientPassword2)).getText().toString().trim(); if((patientId1.equals(patientId2))||(patientPassword1.equals(patientPassword2))){ //save to file String result = file.writeFile1(patientId1+","+patientPassword1+",01:02:03:04:05"); if(result.equalsIgnoreCase("fail")){ Toast t = Toast.makeText(view.getContext(), "Patient details not saved, please try again.", Toast.LENGTH_SHORT); t.show(); }else{ Toast t = Toast.makeText(view.getContext(), "Please login to use the application.", Toast.LENGTH_SHORT); t.show(); } doLogin(); //Intent myIntent = new Intent(view.getContext(), Activity2.class); //startActivityForResult(myIntent, 0); }else{ Toast t = Toast.makeText(view.getContext(), "Please reenter your login details.", Toast.LENGTH_SHORT); t.show(); } } }); }else{ setContentView(R.layout.main2); } } String _patientDetails = ""; private void doLogin(){ final FileUtils file = new FileUtils(); _patientDetails = FileUtils.readFile("/TextFiles/patientDetails.txt"); if(_patientDetails.equalsIgnoreCase("register")){ setContentView(R.layout.main); }else{ ImageButton submit2 = (ImageButton) findViewById(R.id.btn_submit2); Button pid3 = (Button)findViewById(R.id.pid3); setContentView(R.layout.main2); Button btn = (Button)findViewById(R.id.pid3); btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { Toast t = Toast.makeText(v.getContext(), "Please reenter your login details.", Toast.LENGTH_SHORT); t.show(); } }); } } } A: Have you actually run it through a debugger? I'm pretty sure it runs but you're not seeing a Toast notification because of the context. Try passing in either the Activity or the Application context. Basically, I'm pretty sure you're not supposed to use getBaseContext(). View has getContext() instead but in this case you can just use the Activity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Visualize HTTPS in WireShark I am trying to do a http bot to make me, my online check in. I used the wireshark application to store the http request and response while i was make the check in.But when i try to visualize what was sent in the request/response i am not able to to see the https packets. For example : If i use the firebug plugin (firefox) i am able to see this information: This first link shows the headers(request/response) https://docs.google.com/leaf?id=0B9WcB03Ho2uzZmNlNTUyMDYtZjRhZC00YjljLTlkMDAtMDBiMmU4MDAzYjlk&hl=en_US This second list shows the paylod of the POST method https://docs.google.com/leaf?id=0B9WcB03Ho2uzNjllYjllYTQtZTg2MS00Zjc1LTgyODQtNTUyNTc5YTk5N2Nh&hl=en_US But in whireShark when i filter for example by the ip.dst_host , the only packets that appear are the TCP and TLSv1 and in each one i am not able to see the some information thar i am able to see in the firebug because that information is in the application layer(HTTP). The URL : https://checkin.si.amadeus.net/1ASIHSSCWEBTP/sscwtp/checkindirect A: HTTPS is explicitly designed to prevent you from seeing this traffic. If you have the server's private key, you can input it into WireShark to decrypt the packets. Otherwise, use Fiddler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: wrong og:description Facebook does not get information from description Open Graph tags I do get following error but not for description field The og:url property should be explicitly provided, even if a value can be inferred from other tags. I do have in header (Wordpress) <meta property="og:description" content="<?php echo strip_tags(the_excerpt()); ?>" /> bugzilla shows correct source of the page <meta property="og:description" content="<p>3D organs modeled for real-time DVD application</p>" /> But on fb page description shown is JavaScript code from google analytics :) "var _gaq = _gaq || []; _gaq.push(['_setAccount'..." Do you spot the error somewhere? By the way... I know fb caches information... is there a way to reset it? A: To refresh the cache run the url through Facebooks URL Linter here http://developers.facebook.com/tools/debug. What is the url you are trying to parse?
{ "language": "en", "url": "https://stackoverflow.com/questions/7627705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to generate dynamic elements using jQuery? How can I generate dynamic html elements using jQuery? Is it possible to remove it on button click? i.e. I have to generate textbox on button click and contain of textbox is going to display in one label. Like this: http://jsfiddle.net/kDSQa/5/ User can add upto 3 emails. And by clicking delete button the generated textbox will be deleted. How can I do that? I have referred to this: how can i get id/ generate id of dynamically generated elements in html using jquery? thread any suggestion? A: create a document.createElement() and use $().appendTo() to add it and $().remove() to obviously remove it A: I think you want something like - http://jsfiddle.net/rifat/NGgSB/ Though there are other ways to do it :) A: You can create new elements by passing the HTML as a string to jQuery, so for example, this: $('<tr><input type="text" id="email2"/><input type="button" id="add2"/></tr>') Returns a jQuery wrapper object holding a tr that contains two input elements. You can then use jQuery methods like append or appendTo to add these dynamically created elements into the appropriate location in your document. However, in this particular case, it looks like you want the add button to effectively copy some existing elements, give them unique ids, then add them into the document. You could do that by using the jQuery.clone method to duplicate the desired elements, use the attr or prop method to change the ids to something unique, then use append, appendTo, etc., to insert the cloned elements at the appropriate point in the document.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to unify validation across layers/tiers In a typical MVC application we have validation that occurs in many different places. It might be client-side, in the controller, and then again at the data level. If you have a business layer, then there is additional validation there as well. How do we unify all these so that we're not violating DRY, and causing support nightmares when validations change? A sub-question is how to enable dynamic validation based on the model across all layers. For example: We may have a ViewModel that has data annotation attributes. In MVC2/3 this unifies client-side and controller validation, but does not help with the data model (unless you are using your data model as your view model, which isn't a good practice). This means you have to add the same validations to the data model and business layers, duplicating it. What's more, the data model might have subtly different validation requirements than the view model (for instance, an entire data record might comprise several view models of a multi-step wizard. And only a complete record can be saved). Some people add complex validation to the data model when using an ORM like EF or L2S with partial classes, which i'm not sure is the right path either. It works for apps that are primarily data oriented (data entry type apps), but would not work for apps that have more non-data business logic. What I'd like is some way to either generate validation for all layers, or a way to hook into a single validation system. Does anything like that exist? A: "Fluent Validation" provides better re-usability. Please visit. http://fluentvalidation.codeplex.com/ Re-usable documents for Fluent Validation. http://fluentvalidation.codeplex.com/wikipage?title=CreatingAValidator&referringTitle=Documentation&ANCHOR#ReusingValidators http://fluentvalidation.codeplex.com/wikipage?title=CreatingAValidator&referringTitle=Documentation&ANCHOR#Collections Below one may be full fill your needs. http://tnvalidate.codeplex.com/ A: I guess I really don't understand your answer since rarely is your data model, business model, and view model all the same. If they are, just use the data model and put the validation on it. The validations across all your layers are specific to the layer. Example: Your ui should not contain business layer logic in case you ever change the ui layer, or create a new one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Node.js module for MongoDB There are several MongoDB modules available for Node.js in the following link - https://github.com/joyent/node/wiki/modules#wiki-db-nosql-mongo Please, suggest me one (I'd like to know why you choose that one?). A: Mongoose is a popular choice. But the documentation is just as bad (if not worse) than the MongoDB docs. A: I personally prefer Mongolian, it's the closest thing you get to the Mongo shell and it's straight forward to use. My fork adds very simple collection initialization. A: Mongoose doesn't support bulk insert and it is schema-based. When you try to create different schemas for same collection, it throws exception. Consider carefully its suitability to your case before start with it. A: It depends on what level of abstraction you want from your data. If you want something similar to an ORM, then Mongoose is the obvious choice and is popular. However, the node-mongodb-native driver gives you clean duplication of almost the entire MongoDB API and since BSON is translated to JSON and JavaScript is a flexible dynamic language, there's really no need for an ORM. The latter does have benefits such a defining a schema which helps with validation and other tasks, but it also limits your flexibility. Mongoskin is built atop node-mongodb-native but gives you the ability to have additional JavaScript method bindings and deal with connections and cursors easier. It's pretty lightweight, so you can stick with the basics or do more. This library is my personal preference and our team has built our own tooling and validation system around it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Ordering UITableView Sections Loaded From pList I have a sectioned UITableView being populated by data from a pList. The root of the pList is a dictionary, each key of this dictionary is loaded into an array, which is used to define the section headings (and presumably order). Currently my sections appear in the table in a random order, I would like to order them as they appear in the pList, or at least fake it by ordering the sections alphabetically. I understand that dictionaries have no order, which is why the output does not reflect the pList order, but I would prefer not to change the root to an array as it requires me to rewrite chunks of my app, plus Xcode 4 seems to prefer you using a dictionary as the root. Of course if changing the pList structure is the best method, I'll go with that. pList sample: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Section A</key> <array> <dict> <key>Details</key> <string>Details Here...</string> <key>Image</key> <string>X.png</string> <key>Name</key> <string>Person X</string> </dict> <dict> <key>Details</key> <string>Details Here...</string> <key>Image</key> <string>Y.png</string> <key>Name</key> <string>Person Y</string> </dict> </array> <key>Section B</key> <array> <dict> <key>Details</key> <string>Details Here...</string> <key>Image</key> <string>Z.png</string> <key>Name</key> <string>Person Z</string> </dict> </array> </dict> Code within 'TableViewController.m': - (void)viewDidLoad { [super viewDidLoad]; NSString *path = [[NSBundle mainBundle] pathForResource:@"Team" ofType:@"plist"]; NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:path]; self.teamDictionary = tempDict; [tempDict release]; NSArray *tempArray = [[NSArray alloc] init]; self.teamArray = tempArray; [tempArray release]; self.teamArray = [self.teamDictionary allKeys]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [self.teamArray count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [[self.teamDictionary valueForKey:[self.teamArray objectAtIndex:section]] count]; } - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { // this is here because I am altering the appearance of the header text UIView* customView = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, tableView.bounds.size.width, 44.0)] autorelease]; UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero]; // some custom formatting stuff has been removed from here... headerLabel.text = [self.teamArray objectAtIndex:section]; [customView addSubview:headerLabel]; [headerLabel release]; return customView; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSUInteger section = [indexPath section]; NSUInteger row = [indexPath row]; NSString *key = [teamArray objectAtIndex:section]; NSArray *teamMember = [teamDictionary objectForKey:key]; static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SectionsTableIdentifier] autorelease]; } // Configure the cell... NSDictionary *name = [teamMember objectAtIndex:row]; cell.textLabel.text = [name objectForKey:@"Name"]; } A: I can think of two options: * *Use an array as the root of your plist. Each item in the array would be a dictionary, with two keys: name/title and items. Name/title would be a string and items would be an array. *Keep your plist as is, order the keys alphabetically: NSArray *sortedKeys = [[dict allkeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]];
{ "language": "en", "url": "https://stackoverflow.com/questions/7627719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I want to implement TabBarController and add Navigation Controller View but in vain Iknow how to add a TabBar with two TabBar buttons on it by Interface Builder. And I link each button to a Navigation Controller. Now I want to learn how to do everything programmatically. Now I can see a TabBar in simulator but with no buttons on it. Can someone please help me with this. Thanks! Here's the TabBarAppDelegate.h. #import <UIKit/UIKit.h> @interface TabBarAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; UITabBarController *tabBarController; IBOutlet UINavigationController *navigationController1; IBOutlet UINavigationController *navigationController2; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) UITabBarController *tabBarController; @property (nonatomic, retain) IBOutlet UINavigationController *navigationController1; @property (nonatomic, retain) IBOutlet UINavigationController *navigationController2; @end Here's TabBarAppDelegate.m. #import "TabBarAppDelegate.h" #import "FirstViewController.h" #import "SecondViewController.h" @implementation TabBarAppDelegate @synthesize window=window; @synthesize tabBarController; @synthesize navigationController1; @synthesize navigationController2; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { tabBarController = [[UITabBarController alloc]init]; FirstViewController *firstViewController = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil]; firstViewController.title = @"First"; [self.navigationController1 pushViewController:firstViewController animated:NO]; SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; secondViewController.title = @"NavCal"; [self.navigationController2 pushViewController:secondViewController animated:NO]; tabBarController.viewControllers = [NSArray arrayWithObjects:navigationController1, navigationController2, nil]; [window addSubview:tabBarController.view]; [self.window makeKeyAndVisible]; [firstViewController release]; [secondViewController release]; return YES; } - (void)dealloc { [tabBarController release]; [window release]; [super dealloc]; } A: It looks like you are not initializing the navigation view controllers. See if this would work: TabBarAppDelegate.h * *Remove the properties navigationController1 and navigationController2 TabBarAppDelegate.m * *Replace [self.navigationController1 pushViewController:firstViewController animated:NO]; with UINavigationController *navigationController1 = [[UINavigationController alloc] initWithRootViewController:firstViewController]; * *Replace [self.navigationController2 pushViewController:secondViewController animated:NO]; with UINavigationController *navigationController2 = [[UINavigationController alloc] initWithRootViewController:secondViewController]; * *Release navigationController1 and navigationController2 after adding them to the tabBarController
{ "language": "en", "url": "https://stackoverflow.com/questions/7627722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a md5 hash of a string in C? I've found some md5 code that consists of the following prototypes... I've been trying to find out where I have to put the string I want to hash, what functions I need to call, and where to find the string once it has been hashed. I'm confused with regards to what the uint32 buf[4] and uint32 bits[2] are in the struct. struct MD5Context { uint32 buf[4]; uint32 bits[2]; unsigned char in[64]; }; /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void MD5Init(struct MD5Context *context); /* * Update context to reflect the concatenation of another buffer full * of bytes. */ void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len); /* * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ void MD5Final(unsigned char digest[16], struct MD5Context *context); /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ void MD5Transform(uint32 buf[4], uint32 const in[16]); A: As other answers have mentioned, the following calls will compute the hash: MD5Context md5; MD5Init(&md5); MD5Update(&md5, data, datalen); MD5Final(digest, &md5); The purpose of splitting it up into that many functions is to let you stream large datasets. For example, if you're hashing a 10GB file and it doesn't fit into ram, here's how you would go about doing it. You would read the file in smaller chunks and call MD5Update on them. MD5Context md5; MD5Init(&md5); fread(/* Read a block into data. */) MD5Update(&md5, data, datalen); fread(/* Read the next block into data. */) MD5Update(&md5, data, datalen); fread(/* Read the next block into data. */) MD5Update(&md5, data, datalen); ... // Now finish to get the final hash value. MD5Final(digest, &md5); A: To be honest, the comments accompanying the prototypes seem clear enough. Something like this should do the trick: void compute_md5(char *str, unsigned char digest[16]) { MD5Context ctx; MD5Init(&ctx); MD5Update(&ctx, str, strlen(str)); MD5Final(digest, &ctx); } where str is a C string you want the hash of, and digest is the resulting MD5 digest. A: I don't know this particular library, but I've used very similar calls. So this is my best guess: unsigned char digest[16]; const char* string = "Hello World"; struct MD5Context context; MD5Init(&context); MD5Update(&context, string, strlen(string)); MD5Final(digest, &context); This will give you back an integer representation of the hash. You can then turn this into a hex representation if you want to pass it around as a string. char md5string[33]; for(int i = 0; i < 16; ++i) sprintf(&md5string[i*2], "%02x", (unsigned int)digest[i]); A: Here's a complete example: #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined(__APPLE__) # define COMMON_DIGEST_FOR_OPENSSL # include <CommonCrypto/CommonDigest.h> # define SHA1 CC_SHA1 #else # include <openssl/md5.h> #endif char *str2md5(const char *str, int length) { int n; MD5_CTX c; unsigned char digest[16]; char *out = (char*)malloc(33); MD5_Init(&c); while (length > 0) { if (length > 512) { MD5_Update(&c, str, 512); } else { MD5_Update(&c, str, length); } length -= 512; str += 512; } MD5_Final(digest, &c); for (n = 0; n < 16; ++n) { snprintf(&(out[n*2]), 16*2, "%02x", (unsigned int)digest[n]); } return out; } int main(int argc, char **argv) { char *output = str2md5("hello", strlen("hello")); printf("%s\n", output); free(output); return 0; } A: It would appear that you should * *Create a struct MD5context and pass it to MD5Init to get it into a proper starting condition *Call MD5Update with the context and your data *Call MD5Final to get the resulting hash These three functions and the structure definition make a nice abstract interface to the hash algorithm. I'm not sure why you were shown the core transform function in that header as you probably shouldn't interact with it directly. The author could have done a little more implementation hiding by making the structure an abstract type, but then you would have been forced to allocate the structure on the heap every time (as opposed to now where you can put it on the stack if you so desire). A: All of the existing answers use the deprecated MD5Init(), MD5Update(), and MD5Final(). Instead, use EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_DigestFinal_ex(), e.g. // example.c // // gcc example.c -lssl -lcrypto -o example #include <openssl/evp.h> #include <stdio.h> #include <string.h> void bytes2md5(const char *data, int len, char *md5buf) { // Based on https://www.openssl.org/docs/manmaster/man3/EVP_DigestUpdate.html EVP_MD_CTX *mdctx = EVP_MD_CTX_new(); const EVP_MD *md = EVP_md5(); unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len, i; EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, data, len); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_free(mdctx); for (i = 0; i < md_len; i++) { snprintf(&(md5buf[i * 2]), 16 * 2, "%02x", md_value[i]); } } int main(void) { const char *hello = "hello"; char md5[33]; // 32 characters + null terminator bytes2md5(hello, strlen(hello), md5); printf("%s\n", md5); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: #include, error LNK2005 Alirhgt, i tried to sort this one out myslef but can't. So, i have a task to build a paint program in the console, i have a set of functions dealing with the console. My task being only to connect them logically to do something useful. The problem is that everytime i #include the two files given : the .h and the .cpp file, i get the LNK2005 error that they are already defined. If i only include the header file, the functions don't do anything( i tried using one function but the console just stood there doing nothing). Can anybody tell me what i'm doing wrong? I haven't worked with C++ in a bit, so i might be doing some stupid mistake. A: First off, you should never include cpp files. Second, you might need include guards. Format headers like this: #ifndef FILE_H #define FILE_H struct foo { int member; }; #endif You can read about why from here: http://en.wikipedia.org/wiki/Include_guard
{ "language": "en", "url": "https://stackoverflow.com/questions/7627729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP CLI: what directory? I have a php cli script which is executed from /, but the script lies in /opt/script/script.php. How can I get the dynamic location of the script from within the script $location = ... (Get the location of the script) echo $location == '/opt/script' ? 'YAY' : 'Stupid'; Output YAY That kind of thing. A: dirname(__FILE__) (or __DIR__ in newer versions) should be enough. You can find further reference at the Magic Constants chapter. A: Choose what you need, you might be looking for __FILE__ (a magic constant containing the filename of the current file) according to your comment: echo 'Filename (as called): ', var_dump($argv[0]); echo 'Current working directory (normally the directory called in): ', var_dump(getcwd()); echo 'Path of the script: ', var_dump(__FILE__); echo 'Directory of the script: ', var_dump(__DIR__);
{ "language": "en", "url": "https://stackoverflow.com/questions/7627735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I write data to file and access it from outside the app (without SD card)? I am pretty new to Android programming and writing my very first app for my Diploma Thesis. Now I am all but finished but have one thing left that I couldn´t get an answer to anywhere on the net. So maybe someone here can help. Part of what my app must do is write results from previous operations to a freely accessible file for later analysis. So what I got so far is that I am able to write a file to SD card with the following code: String packageName = this.getClass().getPackage().getName(); String path = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/Android/data/" + packageName + "/files/"; if (isExternalStorageAvailable() && isExternalStorageWritable()) { String filename = "_results.dat"; boolean exists = (new File(path)).exists(); if (!exists) { new File(path).mkdirs(); } // Open output stream FileOutputStream fOut = new FileOutputStream(path + filename,true); fOut.write("lalala".getBytes()); etc. } public static boolean isExternalStorageAvailable() { // Retrieving the external storage state String state = Environment.getExternalStorageState(); // Check if available if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; } public static boolean isExternalStorageWritable() { // Retrieving the external storage state String state = Environment.getExternalStorageState(); // Check if writable if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } That file I can later access, copy, whatever. Like I want it to be. Now the actual question is: Is there a way to achieve this without an SD card in the phone? Or can I only write into 'app-memory' (which wouldn´t suffice my needs)? I only ask because as of yet there are no SD cards in the phones where I am going to deploy the app. And we have to decide if we have to 'upgrade' the devices :). A: Well if you want to avoid having them upgrade the phone with an SD card, check out this link. It SAYS that files written to internal storage are not accessible by other apps, but if you read on, you can set other flags: MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: is it possible to scan the android classpath for annotations? I want to scan the classpath for certain annotations in Android. I have only found one solution to this problem: http://mindtherobot.com/blog/737/android-hacks-scan-android-classpath/ And as the author writes this solution works, but has several limitations. Are there any future-proof ways of doing this in android? Any libraries providing this functionality? A: This works for me using android 3.0 public static <T extends Annotation> List<Class> getClassesAnnotatedWith(Class<T> theAnnotation){ // In theory, the class loader is not required to be a PathClassLoader PathClassLoader classLoader = (PathClassLoader) Thread.currentThread().getContextClassLoader(); Field field = null; ArrayList<Class> candidates = new ArrayList<Class>(); try { field = PathClassLoader.class.getDeclaredField("mDexs"); field.setAccessible(true); } catch (Exception e) { // nobody promised that this field will always be there Log.e(TAG, "Failed to get mDexs field", e); } DexFile[] dexFile = null; try { dexFile = (DexFile[]) field.get(classLoader); } catch (Exception e) { Log.e(TAG, "Failed to get DexFile", e); } for (DexFile dex : dexFile) { Enumeration<String> entries = dex.entries(); while (entries.hasMoreElements()) { // Each entry is a class name, like "foo.bar.MyClass" String entry = entries.nextElement(); // Load the class Class<?> entryClass = dex.loadClass(entry, classLoader); if (entryClass != null && entryClass.getAnnotation(theAnnotation) != null) { Log.d(TAG, "Found: " + entryClass.getName()); candidates.add(entryClass); } } } return candidates; } I also created one to determin if a class was derived from X public static List<Class> getClassesSuperclassedOf(Class theClass){ // In theory, the class loader is not required to be a PathClassLoader PathClassLoader classLoader = (PathClassLoader) Thread.currentThread().getContextClassLoader(); Field field = null; ArrayList<Class> candidates = new ArrayList<Class>(); try { field = PathClassLoader.class.getDeclaredField("mDexs"); field.setAccessible(true); } catch (Exception e) { // nobody promised that this field will always be there Log.e(TAG, "Failed to get mDexs field", e); } DexFile[] dexFile = null; try { dexFile = (DexFile[]) field.get(classLoader); } catch (Exception e) { Log.e(TAG, "Failed to get DexFile", e); } for (DexFile dex : dexFile) { Enumeration<String> entries = dex.entries(); while (entries.hasMoreElements()) { // Each entry is a class name, like "foo.bar.MyClass" String entry = entries.nextElement(); // Load the class Class<?> entryClass = dex.loadClass(entry, classLoader); if (entryClass != null && entryClass.getSuperclass() == theClass) { Log.d(TAG, "Found: " + entryClass.getName()); candidates.add(entryClass); } } } return candidates; } enjoy - B
{ "language": "en", "url": "https://stackoverflow.com/questions/7627742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Django- Get Foreign Key Model How can I Get A Foreign Key Model Type? For Example: class Category(models.Model): name = models.CharField(max_length = 100) class SubCategory(models.Model): category = models.ForeignKey(Category) title = models.CharField(max_length = 100) I Want To Get category Model In SubCategory. How Can I Do It? A: also for django > = 2.0 >>> SubCategory._meta.get_field('category').related_model >>> <class 'my_app.models.Category'> >>> SubCategory._meta.get_field('category').related_model._meta.model_name >>> 'category' A: Try: subcategory = SubCategory.objects.get(pk=given_pk) subcategory.category EDIT: subcategory._meta.get_field('category').rel.to A: For Django>=2.0 >>> SubCategory._meta.get_field('category').remote_field.model >>> 'my_app.models.Category' To get the model name use the __name__ class property. >>> SubCategory._meta.get_field('category').remote_field.model.__name__ >>> 'Category' A: ForeignKeys are ReverseSingleRelatedObjectDescriptor objects. So that's what you are really working with. You'll get that if you run type(SubCategory.category). From here you can use two ways to get the actual Class/Model referred to. SubCategory.category.field.rel.to # <class 'path.to.Model'> SubCategory.category.field.rel.to.__name__ # 'Category' # or these will do the same thing SubCategory._meta.get_field('category').rel.to SubCategory._meta.get_field('category').rel.to.__name__ If you don't know the attribute name until run-time, then use getattr(SubCategory, attributeNameVariable) to get your ReverseSingleRelatedObjectDescriptor object for that ForeignKey field.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: How do I correctly call LsaLogonUser for an interactive logon? I'm trying to use LsaLogonUser to create an interactive logon session, but it always returns STATUS_INVALID_INFO_CLASS (0xc0000003). From what I have found in searching online, the memory layout of the KERB_INTERACTIVE_LOGON structure is tricky, but I'm pretty sure I've done that right. I've also tried using MSV1.0 instead of Kerberos, with MSV1_0_INTERACTIVE_LOGON for the authentication structure and MSV1_0_PACKAGE_NAME as the package name, but that fails with STATUS_BAD_VALIDATION_CLASS (0xc00000a7). Can anyone tell what I'm doing wrong here? Here's the code, with most of the error handling stripped. Clearly this isn't production-quality; I'm just trying to get a working sample. // see below for definitions of these size_t wcsByteLen( const wchar_t* str ); void InitUnicodeString( UNICODE_STRING& str, const wchar_t* value, BYTE* buffer, size_t& offset ); int main( int argc, char * argv[] ) { // connect to the LSA HANDLE lsa; LsaConnectUntrusted( &lsa ); const wchar_t* domain = L"mydomain"; const wchar_t* user = L"someuser"; const wchar_t* password = L"scaryplaintextpassword"; // prepare the authentication info ULONG authInfoSize = sizeof(KERB_INTERACTIVE_LOGON) + wcsByteLen( domain ) + wcsByteLen( user ) + wcsByteLen( password ); BYTE* authInfoBuf = new BYTE[authInfoSize]; KERB_INTERACTIVE_LOGON* authInfo = (KERB_INTERACTIVE_LOGON*)authInfoBuf; authInfo->MessageType = KerbInteractiveLogon; size_t offset = sizeof(KERB_INTERACTIVE_LOGON); InitUnicodeString( authInfo->LogonDomainName, domain, authInfoBuf, offset ); InitUnicodeString( authInfo->UserName, user, authInfoBuf, offset ); InitUnicodeString( authInfo->Password, password, authInfoBuf, offset ); // find the Kerberos security package char packageNameRaw[] = MICROSOFT_KERBEROS_NAME_A; LSA_STRING packageName; packageName.Buffer = packageNameRaw; packageName.Length = packageName.MaximumLength = (USHORT)strlen( packageName.Buffer ); ULONG packageId; LsaLookupAuthenticationPackage( lsa, &packageName, &packageId ); // create a dummy origin and token source LSA_STRING origin = {}; origin.Buffer = _strdup( "TestAppFoo" ); origin.Length = (USHORT)strlen( origin.Buffer ); origin.MaximumLength = origin.Length; TOKEN_SOURCE source = {}; strcpy( source.SourceName, "foobar" ); AllocateLocallyUniqueId( &source.SourceIdentifier ); void* profileBuffer; DWORD profileBufLen; LUID luid; HANDLE token; QUOTA_LIMITS qlimits; NTSTATUS subStatus; NTSTATUS status = LsaLogonUser( lsa, &origin, Interactive, packageId, &authInfo, authInfoSize, 0, &source, &profileBuffer, &profileBufLen, &luid, &token, &qlimits, &subStatus ); if( status != ERROR_SUCCESS ) { ULONG err = LsaNtStatusToWinError( status ); printf( "LsaLogonUser failed: %x\n", status ); return 1; } } size_t wcsByteLen( const wchar_t* str ) { return wcslen( str ) * sizeof(wchar_t); } void InitUnicodeString( UNICODE_STRING& str, const wchar_t* value, BYTE* buffer, size_t& offset ) { size_t size = wcsByteLen( value ); str.Length = str.MaximumLength = (USHORT)size; str.Buffer = (PWSTR)(buffer + offset); memcpy( str.Buffer, value, size ); offset += size; } A: You goofed up on one of the parameters to LsaLogonUser(); instead of &authInfo you should pass just authInfo. Happens to everyone :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Which ORM tool is compatibe with Firebird 2.5? I want to use Firebird 2.5 SuperServer as back-end to .NET 4.0 application. Which ORM tool is compatible to work with .NET 4.0 & Firebird 2.5? A: You could also try out Telerik OpenAccess ORM. A: People are using NHibernate with Firebird. The wiki docs list only Firebird 2.0.1, so I would download it with NuGet, check the supported dialects in the latest version, and test it. A: the Telerik OpenAccess ORM is free unless you want features that are not found in EF5. Basically the Telerik OpenAccess is as good as EF otherwise why not use free EF? I am looking for an ORM for Firebird 1.5 as the migration to 2.5 is too hard/costly and if one were to take the pain would be better to migrate to a more contemporary product, with more productive tooling such as MSSQL etc. A: Symbiotic ORM is free, but not open source. I haven't tried it on 2.5 but it does works on the latest 3.0 https://www.nuget.org/packages/Symbiotic_Micro_ORM_Net_Standard_x64/3.0.0 There's also a helper to create your poco classes from an existing schema: https://www.microsoft.com/store/productId/9NN20Q6WFKGS A: Entity Framework Core: EntityFrameworkCore.FirebirdSQL or FirebirdSql.EntityFrameworkCore.Firebird
{ "language": "en", "url": "https://stackoverflow.com/questions/7627751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Secure authentication system in python? I am making a web application in python and I would like to have a secure login system. I have done login systems many times before by having the user login and then a random string is saved in a cookie which is also saved next to that user in a database which worked fine but it was not very secure. I believe understand the principles of an advanced system like this but not the specifics: * *Use HTTPS for the login page and important pages *Hash the password saved in the database(bcrypt, sha256? use salt?) *Use nonces(encrypted with the page url and ip?) But apart from those I have no idea how to reliably check if the person logged in is really the user, or how to keep sessions between page requests and multiple open pages securely, etc. Can I have some directions (preferably specific ones since I am new to this advanced security programming. I am just trying to accomplish a basic user login-logout to one domain with security, nothing too complicated. A: This answer mainly addresses password hashing, and not your other subquestions. For those, my main advice would be don't reinvent the wheel: use existing frameworks that work well with GAE. It offers builtin deployments of Django, but also has a builtin install of WebOb, so various WebOb-based frameworks (Pyramid, Turbogears, etc) should also be considered. All of these will have premade libraries to handle a lot of this for you (eg: many of the WebOb frameworks use Beaker for their cookie-based session handling) Regarding password hashing... since you indicated in some other comments that you're using Google App Engine, you want to use the SHA512-Crypt password hash. The other main choices for storing password hashes as securely as possible are BCrypt, PBKDF2, and SCrypt. However, GAE doesn't offer C-accelerated support for these algorithms, so the only way to deploy them is via a pure-python implementation. Unfortunately, their algorithms do way too much bit-fiddling for a pure-python implementation to do a fast enough job to be both secure and responsive. Whereas GAE's implementation of the Python crypt module offers C-accelerated SHA512-Crypt support (at least, every time I've tested it), so it could be run at sufficient strength. As far as writing actual code goes, you can use the crypt module directly. You'll need to take care of generating your own salt strings when passing them into crypt, and when encrypting new passwords, call crypt.crypt(passwd, "$6$" + salt). The $6$ tells it to use SHA512-Crypt. Alternately, you can use the Passlib library to handle most of this for you (disclaimer: I'm the author of that library). For quick GAE deployment: from passlib.context import CryptContext pwd_context = CryptContext(schemes=["sha512_crypt"], default="sha512_crypt", sha512_crypt__default_rounds=45000) # encrypt password hash = pwd_context.encrypt("toomanysecrets") # verify password ok = pwd_context.verify("wrongpass", hash) Note: if care about password security, whatever you do, don't use a single HASH(salt+password) algorithm (eg Django, PHPass, etc), as these can be trivially brute-forced. A: It's hard to be specific without knowing your setup. However, the one thing you should not do is reinventing the wheel. Security is tricky, if your wheel is lacking something you may not know until it's too late. I wouldn't be surprised if your web framework came with a module/library/plugin for handling users, logins and sessions. Read its documentation and use it: it was hopefully written by people who know a bit about security. If you want to know how it's done, study the documentation and source of said module.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Has anyone created an FTP adapter for the Windows Azure Service Bus Brokered Messaging service? Let us say that I have an FTP server getting XML files sent each day, and that I want to post theese to the Windows Azure Service Bus Brokered Messaging service. Has anyone created a tool (and is willing to share) that will monitor a directoy and post these to the service bus? Alternative, has anyone implemented an FTP server that will accept files and then post to the service bus? Alternative, implementet FTP server in Azure that transforms messages to the service bus? A: Sort of. I use the Sync Framework instead. Take a look at the File Sync Provider. In my case, I went ahead and created a custom FTP sync provider to handle some aspects of the sync process that were specific to the application. When the sync session finishes, I post BrokeredMessages to a ServiceBus queue, where worker instances process those messages (mostly Uri's to the location of the files now in Blob Storage). Good luck! A: I have found this solution as well now: http://ftp2azure.codeplex.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7627755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using Old iPhone 3G for testing, remove the sim card? I just got an old iPhone 3G for testing. It doesn't have a plan attached to it, but I just put in the sim card and it said it will take a while to activate. When everyone has test devices, do you just leave the sim card out? What about when testing location based services that need to find cell towers? What do we do in situations like this? I don't want to pay for service. A: You won't get anything out of the cell towers without a valid SIM card. I use my wife's old iPhone 3G for testing, and it still has the old AT&T sim card, but of course there is no service because that sim card is not on our account anymore. I always leave it in Airplane mode. The main thing I'm verifying with the physical device is performance, UI responsiveness, and memory issues that present no problems in the simulator, but choke on this old device. The iPhone 3G is great to have on hand as a minimum baseline for that stuff. The location-based stuff you should be able to mock up without needing any "real" data. Do a google search for "iphone" "mock location" and see what that turns up. This looks promising: http://rssv2.blogspot.com/2010/03/mocking-core-location.html You don't want to have to develop with real, live data until you are in the beta stage anyways. Using real, live data during development is a huge hassle, not easily repeatable, and very time consuming. And this makes it impossible to write effective integration tests. A: The iPhone has a GPS receiver, you don't need cell towers they just help speed up the process of acquiring the GPS satellites and finding your location. WiFi service will do the same thing but is not required. With no cell data and no wifi it can take several minutes to acquire GPS satellites, download ephemeris from the satellites and get a good location, but it works. I use a 3G running 3.1.3 with no sim card for 3.1.3 testing and it works fine even for using location services, but I have wifi here. I also use a CoreLocation simulator which allows me to simulate and repeat motion scenarios without going anywhere, it can simulate acquisition time, varying horizontal accuracy and motion. The simulator is available on github.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Network traffic isolation behavior of network switches First-timer on Stack Overflow here. I'm surprised nobody seems to have asked this question, and I hope this is the right place to ask this. I'm trying to determine if I should expect regular network switches (just simple switches, not routers) to have the capability to isolate local network traffic (i.e. targeted traffic that is directed to another local port in the ame switch) within the switch? For example, if I have 2 machines connected to ports on the same switch (say, ports 2 and 3) and conversing using a directed, non-broadcast protocol (e.g. TCP), I wanted to make sure the traffic between these 2 machines are not forwarded the the rest of the network outside of the switched subnet. I'm building a home network and I wanted to build private network "subnets" or "zones" using switches where local subnet traffic does not get forwarded to the "backbone" or the rest of the network. Note that I am NOT trying to block any inbound or outbound traffic to/from/between these "zones", but I just wanted to implement a "need to know" basis for these zones to limit network-wide exposure for localized traffic destined within the same switch. Specifically, I wanted the backbone to have as little unnecessary traffic as possible. So back to the original question: is it fair to expect any network switch out there to be smart enough not to forward local traffic to the rest of the network? I would expect this to be the case, but I wanted to make sure. PS: You can assume I have a DHCP/WINS server somewhere on the network that will be assigning IP addresses and the such. I hope the question makes sense, and any help will be appreciated! - K. A: Short answer: yes, the switch is smart enough (otherwise it would be a hub). And if you need fancy stuff you might have a look a VLANs. And I believe this question belongs to serverfault or maybe superuser. That's probably why nobody asked it here :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails Rendering Issue Whenever I'm trying to render the games partial, the view it's being rendered in gives a nil return. here is the games partial: <%= flash[:notice] %> <tr> <% @games.each do |game| %> <td><%= game.name %></td> <td><%= link_to('Pick!', vote_up_game_path(game.id), :method => :post) %></td> </tr> <% end %> A: You should pass @games as a local variable to the partial. Consider looking at the documentation on its usage. I also feel the flash-notice should not belong inside the partial. You might also want to correct your code <% games.each do |game| %> <tr> <td><%= game.name %></td> <td><%= link_to 'Pick!', vote_up_game_path(game.id), :method => :post %></td> </tr> <% end %> You would render the partial as follows <%= render :partial => "game_partial", :locals => { :games => @games } %> It is also important to ensure @games isn't nil. If it is, you will still get your error - you should check your controller; typically I'd imagine your controller would have @games = Game.all, of course this is dependent on your particular implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: { int == nulltype } vs. { Integer == nulltype } Why java complains about // int i; if( i == null ){ } and not about // Integer i; if( i == null ){ } A: Because Integer is a reference type, and an int is not - that is, as int is not a pointer, it cannot point to nothing. A: int (primitive type) can't be null A: Because int is a primitive type , while Integer is its wrapper class . Said differently, int is a value type (and as such cannot be null) while Integer is a reference type (and as such can be null). In Java, every primitive type (such as boolean, double or char) is a value type. Since primitive types do not inherit from Object, a set of "wrapper classes" is offered (Boolean, Double, Character to name a few) when such behavior is needed (like, for instance, putting them in containers, or using them as generic type parameters). The result is that primitive types really are second class citizens in Java. A: Because int is a value type and it cannot be null - it's the object itself. Integer, on the other hand, is a reference type and can be null or hold a reference to an object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Model that references many of itself? Given the following class, how would I allow a node to have a many to many relationship with other nodes (such as parent_node and child_nodes)? class Node include MongoMapper::Document key :text, String end A: Can children have more than one parent? If not, many/belongs_to should work fine: class Node include MongoMapper::Document key :text, String key :parent_node_id, ObjectId belongs_to :parent_node, :class_name => 'Node' many :child_nodes, :foreign_key => :parent_node_id, :class_name => 'Node' end If nodes can have multiple parents... class Node include MongoMapper::Document key :text, String key :parent_node_ids, Array, :typecast => 'ObjectId' many :parent_nodes, :in => :parent_node_ids, :class_name => 'Node' # inverse of many :in is still forthcoming in MM def child_nodes Node.where(:parent_node_ids => self.id) end end # ... or store an array of child_node_ids instead ... class Node include MongoMapper::Document key :text, String key :child_node_ids, Array, :typecast => 'ObjectId' many :child_nodes, :in => :child_node_ids, :class_name => 'Node' # inverse of many :in is still forthcoming in MM def parent_nodes Node.where(:child_node_ids => self.id) end end Is that what you're looking for?
{ "language": "en", "url": "https://stackoverflow.com/questions/7627785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Margin problems in CSS IE vs Firefox I'm trying to make a banner in HTML/CSS. However, I'm having trouble with the margins in one of my div's. It works perfectly in Firefox, but not in IE. #lowerText{ float: left; margin-top: 50px; margin-left: -185px; color: rgb(255, 199, 142); font-family: 'Special Elite', cursive; font-size: 15px; text-transform: uppercase; display:inline; } #upperText{ float: left; margin-left: 20px; margin-top: -10px; color: rgb(255, 199, 142); font-family: 'Special Elite', cursive; font-size: 30px; text-transform: uppercase; display:inline; } It's an h3 tag in #lowerText which says "-Foo foo foo bar". In IE it only shows: "oo bar". The text in this div HAS to be right underneath #upperText at a specfic position. But the margin-left: 185px in #lowerText doesn't show in IE, but it shows in Firefox. What do I need to do to fix this? A: In your comment, you state your jsfiddle works in IE. jsfiddle auto inserts a doctype which I now assume you do not have in your original page. If so, IE is in quirks mode without the doctype and the cause of your problem (other than IE being the worst browser on the planet). EDIT: Didn't look first. jsfiddle shows a doctype. Did you put that there?
{ "language": "en", "url": "https://stackoverflow.com/questions/7627788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Non-selectable columns in HTML table I have a table with multiple columns. I want content of each column to be selected individually. When I start selecting first column, second, third ... are automatically getting selected. When I select one column I want make other columns non selectable. I have tried applying following class on elements and it worked fine in Firefox. No matter where you start selection from, its never selectable. .unselectable { user-select: none; /* CSS3 */ -moz-user-select: none; -khtml-user-select: none; } For IE I have tried property called unselectable="on", In Internet Explorer, it is still selectable if the selection starts outside. I want to prevent selection of certain columns even selection starts from outside. I have tried using onselectionstart and onmouseover but as the selection is starting outside of element these are not getting triggered. Do I have any hope ? A: I believe that for now there is no pure CSS solution. It may sound weird, but you could clone the content of the column you want the user to select into a separate table that will be positioned: absolutely over the original column. A: Instead of reinventing the wheel... check out http://www.datatables.net/ This is a JQuery table plug-in that'll knock your socks off. It looks like it is already doing what you would like to do and it is free. A: It might help to include a TH with a SCOPE attribute. Can't say it will work, but it does make for a more semantic table. CSS can hook the attribute, so a DOM solution can't be that far off.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Traverse Directory Depth First I need to traverse a directory depth first without using boost but I have not been able to find a good tutorial how to do this. I know how to list the files of the directory, but not sure how to about this one. This list the files of a directory: A: Use the ftw or nftw functions if your system has them. Or, grab the fts_* functions from, e.g., the OpenBSD source tree and study those, or use them directly. This problem is harder than you might think, because you can run out of file descriptors when recursing through deep filesystem hierarchies. A: Make sure you understand recursion. I assume you have a function walk(dir_path) which can list all files (and directries) in the dir_path directory. You need to modify it, so it calls it self (recursively) for each directory you find. That's it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What's the easiest and quickest way to get the MIME/Media/Content type of a given URL? So I'm going to transfer a file from a remote server to my server but before I transfer it I want to know what sort of file it is. If it's an HTML file I'll deal with it in a certain way, if it's a PDF file I'll deal with it in a different way, and if, for instance, it's an exe file, I don't want to transfer it at all. All I've got to go on is a URL. Now if that URL is explicit (i.e. http://example.com/file.pdf) it's not a problem, I can just check the file extension and we're sorted. However, I might only be given a URL such as http://example.com and it could be anything. Is it possible to check (with PHP) what type of file it is before I download it? Edit: I will be using cURL to transfer the file, but I believe that curl_getinfo can only be called after the file has been transferred? A: Try using PHP get_headers function, e.g.: $h = get_headers("http://google.com", $format = 1); $content_type = $h["Content-Type"]; // and now parse what you want from array A: Using an fopen handle, you can then call stream_get_meta_data() on it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: input type="file" is not opening the file browser from Chrome Extension I'm not sure if it's a bug or something simple that I just missed... Here is a simple test case. The index.html is: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Test file input field</title> </head> <body> <label for="file">File</label> <input type="file" name="file" id="file"/> </body> </html> The manifest is calling it inside a popup: "popup": "index.html" I was expecting to get the 'file browser' after clicking the 'file' button but it is vanish after 0.5sec. (It's on Mac 10.6.8 and Chrome 14.0.835.186) Any idea? Thanks... A: This is a bug, logged at http://crbug.com/98920
{ "language": "en", "url": "https://stackoverflow.com/questions/7627795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Creating communication protocol over TCP Sockets? I have an Arduino microcontroller with a Sparkfun WiFly shield. I build a simple program in C#/.NET that connects to the Arduino using System.Net.Sockets: Socket Soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); public void SendMsg(string msg) { try { byte[] buffer = StrToByteArray(msg); if (Soc.Connected) Soc.Send(buffer); else { Soc.Connect(this.remoteIP); Soc.Send(buffer); } } catch (Exception e){} } On the arduino I have: while(SpiSerial.available() > 0) { byte b = SpiSerial.read(); Serial.println(b); } When a socket connection does a handshake, I get: "*OPEN*" and when closed, I get: "*CLOS*". The problem is that I get the messages one byte by another and sometimes I don't get the full message on one while loop. So if I use the code I showed above on the Arduino, my serial terminal looks like: * O P E N * T E S T * C L O S * So how can I figure out the message the PC is trying to send? I know I need somehow to use a special byte that will symbolise the end of my message. (A special byte that I won't use in my message, only to symbolise the end of a message) But how can I do it? And which byte to use? A: You need to design your own protocol here. You should define a byte (preferably one that won't occur in the data) to indicate "start", and then you have three choices: * *follow the start byte with a "length" byte indicating how much data to read *define an "end" byte that marks the end of your data *read data until you have a complete message that matches one of the ones you expect The third option is the least extensible and flexible, of course, as if you already have a message "OPEN" you can't then add a new message "OPENED" for instance. If you take the second option and define an "end" byte then you need to worry about escaping that byte if it occurs within your data (or use another byte that is guaranteed not to be in your data). A: Looking at your current example, a good starting point would be to simply prefix each message with a length prefix. If you want to support long messages you can use a 2 byte length prefix, then you read the first 2 bytes to get the length and then you continue reading from the socket until you have read the number of bytes indicated by the length prefix. Once you have read a complete message you are then back to expecting to read the length prefix for the next message and so on until the communication is terminated by one of the parties. Of course in between all this you need to check for error conditions like the socket on one end being closed prematurely etc. and how to handle the potential partial messages that can result form the premature closing of the socket.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TypeError: 'in ' requires string as left operand, not generator in Python I'm trying to parse tweets data. My data shape is as follows: 59593936 3061025991 null null <d>2009-08-01 00:00:37</d> <s>&lt;a href="http://help.twitter.com/index.php?pg=kb.page&amp;id=75" rel="nofollow"&gt;txt&lt;/a&gt;</s> <t>honda just recalled 440k accords...traffic around here is gonna be light...win!!</t> ajc8587 15 24 158 -18000 0 0 <n>adrienne conner</n> <ud>2009-07-23 21:27:10</ud> <t>eastern time (us &amp; canada)</t> <l>ga</l> 22020233 3061032620 null null <d>2009-08-01 00:01:03</d> <s>&lt;a href="http://alexking.org/projects/wordpress" rel="nofollow"&gt;twitter tools&lt;/a&gt;</s> <t>new blog post: honda recalls 440k cars over airbag risk http://bit.ly/2wsma</t> madcitywi 294 290 9098 -21600 0 0 <n>madcity</n> <ud>2009-02-26 15:25:04</ud> <t>central time (us &amp; canada)</t> <l>madison, wi</l> I want to get the total numbers of tweets and the numbers of keyword related tweets. I prepared the keywords in text file. In addition, I wanna get the tweet text contents, total number of tweets which contain mention(@), retweet(RT), and URL (I wanna save every URL in other file). So, I coded like this. import time import os total_tweet_count = 0 related_tweet_count = 0 rt_count = 0 mention_count = 0 URLs = {} def get_keywords(filepath, mode): with open(filepath, mode) as f: for line in f: yield line.split().lower() for line in open('/nas/minsu/2009_06.txt'): tweet = line.strip().lower() total_tweet_count += 1 with open('./related_tweets.txt', 'a') as save_file_1: keywords = get_keywords('./related_keywords.txt', 'r') if keywords in line: text = line.split('<t>')[1].split('</t>')[0] if 'http://' in text: try: url = text.split('http://')[1].split()[0] url = 'http://' + url if url not in URLs: URLs[url] = [] URLs[url].append('\t' + text) save_file_3 = open('./URLs_in_related_tweets.txt', 'a') print >> save_file_3, URLs except: pass if '@' in text: mention_count +=1 if 'RT' in text: rt_count += 1 related_tweet_count += 1 print >> save_file_1, text save_file_2 = open('./info_related_tweets.txt', 'w') print >> save_file_2, str(total_tweet_count) + '\t' + srt(related_tweet_count) + '\t' + str(mention_count) + '\t' + str(rt_count) save_file_1.close() save_file_2.close() save_file_3.close() Following is the sample keywords Depression Placebo X-rays X-ray HIV Blood preasure Flu Fever Oral Health Antibiotics Diabetes Mellitus Genetic disorders I think my code has many problem, but the first error is as follws: Traceback (most recent call last): File "health_related_tweets.py", line 23, in if keywords in line: TypeError: 'in ' requires string as left operand, not generator Please help me out! A: The reason is that keywords = get_keywords(...) returns a generator. Logically thinking about it, keywords should be a list of all the keywords. And for each keyword in this list, you want to check if it's in the tweet/line or not. Sample code: keywords = get_keywords('./related_keywords.txt', 'r') has_keyword = False for keyword in keywords: if keyword in line: has_keyword = True break if has_keyword: # Your code here (for the case when the line has at least one keyword) (The above code would be replacing if keywords in line:)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: track how many times an if statement was used true I think the question speaks for itself, I'm writing a program in c++ and there is a part where the console asks the user which type of input they want to use while (loop == 5) { cout << "\nWould you like to enter a depoist or a check? "; //asks for a choice cin >> choice; //determines whether or not to close the program if(choice == 0 || depo == 0 || check == 0) { return 0; }//end close if //choses which type of input to make if( choice == 1) { cout << "\nPlease enter check amount: "; cin >> check; check += check; } else if(choice == 2) { cout << "\nPlease enter deposit amount: "; cin >> depo; depo += depo; }//end if } but how do i keep track of how many times the if statement was true? A: You can add a counter and increment it every time you enter the if-statement's true block. int true_counts = 0; while (loop == 5){ ... if( choice == 1){ true_counts++; ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7627804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In map, is it guaranteed that the int is initialized to zero? For example, count the occurrence the words in a book, I saw somebody simply wrote: map<string, int> count; string s; while (cin >> s) count[s]++; Is this the correct way of doing so? I tested on my machine and seems so. But is the initialization to zero guaranteed? If it is not, I would imagine a code like this: map<string, int> count; string s; while (cin >> s) if (count.find(s) != count.end()) count[s]++; else count[s] = 1; A: Yes, operator[] on a std::map will initialize the value with T(), which in the case of int, is zero. This is documented on section 23.4.4.3 of the C++ standard: T& operator[](const key_type& x); Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Confining a swipe gesture to a certain area (iPhone) I have just managed to implement detection of a swipe gesture for my app. However I would like to confine the area where the gesture is valid. Thinking about this I came up with a possible solution which would be to check whether the start & finish coordinates are within some area. I was just wondering if there's a better or preferred method of doing something like this. A: Simply create an invisible UIView (= with transparent background) and set its frame so it encloses the region you want to detect the gesture into. Then, simply add a UISwipeGestureRecognizer to that view, and you are done. Read the generic UIGestureRecognizer Class Reference and the part of the Event Handling Guide for iOS that talks about UIGestureRecognizers for more info. Of course you could also manage the detection of the swipe gesture by yourself using custom code like explained here in the very same guide but why bother when UIGestureRecognizers can manage everything for you?
{ "language": "en", "url": "https://stackoverflow.com/questions/7627807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenCL only reads/writes from/to 1/4 of the buffer memory and crashes sometimes I have a problem with OpenCL, which is that it executes the entire command queue, but it only reads only 1/4 of the input and writes only 1/4 of the result. No matter how many iterations, always 1/4. And also it sometimes randomly crashes..with debugging I dont get any information, since there is no debug symbols, where it crashes (0x4c4783f6 in ????, etc.) Source code: #include <iostream> #include <cl/cl.h> #include <cassert> #include <cstring> const char *progsrc[] = { "#pragma OPENCL EXTENSION cl_intel_printf : enable\n\ __kernel void add(__global const int *a, __global const int *b, __global int *out) \ { \ int tid = get_global_id(0);\ out[tid] = tid/*a[tid]+b[tid]*/;\ printf(\"krnl: %d = %d + %d \\n\", out[tid], a[tid], b[tid]);\ }"}; const int iterations = 20; #define CLCheck(a) \ do\ {\ if(a != CL_SUCCESS)\ {\ std::cerr << "OpenCL Error(" << a << ") at " << __LINE__ << std::endl;\ return -1;\ }\ } while(0) int main() { cl_int err = CL_SUCCESS; int *aH = NULL; int *bH = NULL; int *outH = NULL; cl_uint platnum, devnum; cl_device_id dev; cl_platform_id plat; err = clGetPlatformIDs(0, 0, &platnum); CLCheck(err); cl_platform_id pfids[platnum]; err = clGetPlatformIDs(platnum, pfids, &platnum); CLCheck(err); if(!platnum) { std::cerr << "No platform found." << std::endl; return -1; } else std::cout << platnum << " OpenCL platform(s) found.\n" << std::endl; for(unsigned int i = 0; i != platnum; i++) { char buf[4096]; err = clGetDeviceIDs(pfids[i], CL_DEVICE_TYPE_ALL, 0, 0, &devnum); CLCheck(err); cl_device_id devids[devnum]; err = clGetDeviceIDs(pfids[i], CL_DEVICE_TYPE_ALL, devnum, devids, &devnum); CLCheck(err); if(!devnum) { std::cerr << "No device found." << std::endl; return -1; } else std::cout << " " << devnum << " OpenCL device(s) found.\n" << std::endl; for(unsigned int i2 = 0; i2 != devnum; i2++) { char buf[1024]; std::cout << ": \n\tName: " << buf; err = clGetDeviceInfo(devids[i2], CL_DEVICE_VENDOR, 1024, buf, NULL); CLCheck(err); if(!strncmp(buf, "Intel", 5)) { dev = devids[0]; plat = pfids[i]; std::cout << "\n\tFound Intel(R) OpenCL device."; } } } cl_context_properties ctxprop[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)plat, 0}; cl_context ctx = clCreateContext(ctxprop, 1, &dev, NULL, NULL, &err); CLCheck(err); cl_program program = clCreateProgramWithSource(ctx, 1, progsrc, NULL, &err); CLCheck(err); err = clBuildProgram(program, 1, &dev, "", NULL, NULL); if(err != CL_SUCCESS) { size_t bufsz; err = clGetProgramBuildInfo(program, dev, CL_PROGRAM_BUILD_LOG, 0, 0, &bufsz); char buf[bufsz]; err = clGetProgramBuildInfo(program, dev, CL_PROGRAM_BUILD_LOG, bufsz, buf, &bufsz); std::cerr << "OpenCL program building failed: " << buf << std::endl; return -1; } err = clUnloadCompiler(); CLCheck(err); aH = new int[iterations]; bH = new int[iterations]; outH = new int[iterations]; memset(outH, 0, iterations*sizeof(int)); for(int i = 0; i != iterations; i++) { aH[i] = i; bH[i] = i*2; } cl_mem aCL = clCreateBuffer(ctx, CL_MEM_READ_ONLY, iterations, NULL, &err); cl_mem bCL = clCreateBuffer(ctx, CL_MEM_READ_ONLY, iterations, NULL, &err); CLCheck(err); cl_mem outCL = clCreateBuffer(ctx, CL_MEM_WRITE_ONLY, iterations, NULL, &err); CLCheck(err); cl_kernel krnl = clCreateKernel(program, "add", &err); CLCheck(err); err = clSetKernelArg(krnl, 0, sizeof(aCL), &aCL); CLCheck(err); err = clSetKernelArg(krnl, 1, sizeof(bCL), &bCL); CLCheck(err); err = clSetKernelArg(krnl, 2, sizeof(outCL), &outCL); CLCheck(err); cl_command_queue cmdqueue = clCreateCommandQueue(ctx, dev, 0, &err); cl_event evt; size_t global_work_size[1] = { iterations }; err = clEnqueueWriteBuffer(cmdqueue, aCL, CL_TRUE, 0, iterations, aH, 0, NULL, NULL); err = clEnqueueWriteBuffer(cmdqueue, bCL, CL_TRUE, 0, iterations, bH, 0, NULL, NULL); err = clEnqueueNDRangeKernel(cmdqueue, krnl, 1, NULL, global_work_size, NULL, 0, NULL, &evt); err = clWaitForEvents(1, &evt); err = clEnqueueReadBuffer(cmdqueue, outCL, CL_TRUE, 0, iterations, outH, 0, NULL, &evt); for(int i = 0; i != iterations; i++) { std::cout << outH[i] << std::endl; } err = clReleaseEvent(evt); err = clReleaseCommandQueue(cmdqueue); err = clReleaseKernel(krnl); err = clReleaseMemObject(outCL); err = clReleaseMemObject(bCL); err = clReleaseMemObject(aCL); err = clReleaseProgram(program); err = clReleaseContext(ctx); if(aH) delete aH; if(bH) delete bH; if(outH) delete outH; return 0; } output: 2 OpenCL platform(s) found. Platform 0 : Name: NVIDIA CUDA Vendor: NVIDIA Corporation Profile: FULL_PROFILE Version: OpenCL 1.1 CUDA 4.0.1 Extensions: cl_khr_byte_addressable_store cl_khr_icd cl_khr_gl_sharing c l_nv_d3d9_sharing cl_nv_d3d10_sharing cl_khr_d3d10_sharing cl_nv_d3d11_sharing c l_nv_compiler_options cl_nv_device_attribute_query cl_nv_pragma_unroll 1 OpenCL device(s) found. Device 0: Name: GeForce GT 425M Vendor: NVIDIA Corporation Profile: FULL_PROFILE Driver version: 280.26 OpenCL version: OpenCL C 1.1 Version: OpenCL 1.1 CUDA Extensions: cl_khr_byte_addressable_store cl_khr_icd cl_khr_gl_sharing c l_nv_d3d9_sharing cl_nv_d3d10_sharing cl_khr_d3d10_sharing cl_nv_d3d11_sharing c l_nv_compiler_options cl_nv_device_attribute_query cl_nv_pragma_unroll cl_khr_g lobal_int32_base_atomics cl_khr_global_int32_extended_atomics cl_khr_local_int32 _base_atomics cl_khr_local_int32_extended_atomics cl_khr_fp64 Platform 1 : Name: Intel(R) OpenCL Vendor: Intel(R) Corporation Profile: FULL_PROFILE Version: OpenCL 1.1 Extensions: cl_khr_fp64 cl_khr_global_int32_base_atomics cl_khr_global_i nt32_extended_atomics cl_khr_local_int32_base_atomics cl_khr_local_int32_extende d_atomics cl_khr_byte_addressable_store cl_intel_printf cl_ext_device_fission cl _intel_immediate_execution cl_khr_gl_sharing cl_khr_icd 1 OpenCL device(s) found. Device 0: Name: Intel(R) Core(TM) i3 CPU M 370 @ 2.40GHz Found Intel(R) OpenCL device. Vendor: Intel(R) Corporation Profile: FULL_PROFILE Driver version: 1.1 OpenCL version: OpenCL C 1.1 Version: OpenCL 1.1 (Build 15293.6650) Extensions: cl_khr_fp64 cl_khr_global_int32_base_atomics cl_khr_global_i nt32_extended_atomics cl_khr_local_int32_base_atomics cl_khr_local_int32_extende d_atomics cl_khr_byte_addressable_store cl_intel_printf cl_ext_device_fission cl _intel_immediate_execution cl_khr_gl_sharing krnl: 0 = 0 + 0 krnl: 1 = 1 + 2 krnl: 2 = 2 + 4 krnl: 3 = 3 + 6 krnl: 4 = 4 + 8 krnl: 5 = 0 + 0 krnl: 6 = 0 + 0 krnl: 7 = 0 + 0 krnl: 16 = 0 + 492859489 krnl: 17 = 0 + -1042621749 krnl: 18 = 0 + 1310105771 krnl: 19 = 0 + 134230852 krnl: 8 = 0 + 0 krnl: 9 = 0 + 0 krnl: 10 = 0 + -1094462526 krnl: 11 = 0 + -1094462526 krnl: 12 = 0 + -1230120245 krnl: 13 = 0 + 500723958 krnl: 14 = 0 + 530164160 krnl: 15 = 0 + 492859489 0 1 2 3 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Thanks :) A: I'm not familiar with openCL, but I think you're missing a few sizeof's here: err = clEnqueueWriteBuffer(cmdqueue, aCL, CL_TRUE, 0, iterations, aH, 0, NULL, NULL); should probably be: err = clEnqueueWriteBuffer(cmdqueue, aCL, CL_TRUE, 0, iterations * sizeof(int), aH, 0, NULL, NULL); And same applies the similar code following this. EDIT: And here's another place you may have missed a few sizeof()s: cl_mem aCL = clCreateBuffer(ctx, CL_MEM_READ_ONLY, iterations, NULL, &err); cl_mem bCL = clCreateBuffer(ctx, CL_MEM_READ_ONLY, iterations, NULL, &err); CLCheck(err); cl_mem outCL = clCreateBuffer(ctx, CL_MEM_WRITE_ONLY, iterations, NULL, &err); CLCheck(err);
{ "language": "en", "url": "https://stackoverflow.com/questions/7627808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get cell title from table view I have a custom table view and each cell has a title and a button. When the user clicks on the button, I need the title of that cell to appear on another view. How do I get this? A: It's not very tough here are the 2 solutions: When you are creating the cell, assign tag to the label you want to get the title value (or text value) second option is: If you want to get the title at the didselect select method just get the cell from the table view with the help of indexpPath.row and then extract the label and it's text. You can assign the tag in the custom cell design and then extract it from cell (once you get the cell).
{ "language": "en", "url": "https://stackoverflow.com/questions/7627810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Mysql Timeout Error tried everything * *connectTimeout=0&socketTimeout=0&autoReconnect=true *changed wait_timeout to 31536000 and interactive_timeout= 286399969 but still continue to get the error. com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet successfully received from the server was 70,399,485 milliseconds ago
{ "language": "en", "url": "https://stackoverflow.com/questions/7627815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drawable item don't show up I just started Android development and working on a little app related to google maps api. Am using the Google Map View for this and following this tutorial.. I've created a custom itemizedOverlay, which has a constructor like this(as told in the tutorial) - public pujaItemizedOverlay(Drawable defaultMarker, Context context) { super(defaultMarker); mContext = context; } I have a image file named sprite.png in the res/drawable/ forder. And here is my onCreate() function - public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); MapView mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); List<Overlay> mapOverlays = mapView.getOverlays(); Drawable drawable = this.getResources().getDrawable(R.drawable.sprite); pujaItemizedOverlay itemizedoverlay = new pujaItemizedOverlay(drawable, this); GeoPoint point = new GeoPoint(19240000,-99120000); OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!"); itemizedoverlay.addOverlay(overlayitem); mapOverlays.add(itemizedoverlay); } The problem is, The image named sprite doesn't show up on the map. One this I'd like to mention is that, according to the tutorial, they added a second paramete to the constructor of the custom itemizedOverlay of the class Context. But in their example, when they called that overlay, they provided only one parameter(check the tutorial page), like - HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable); Eclipse showed an obvious error in this line, so I added the second parameter as this to provide the current context. Am I doing it right here? Update: The image in question is here. A: Found the solution here. It seems that if the mapview doesn't know how to align the image it won't show it at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: java.lang.NullPointerException ERROR I'm getting this null error on this line but I'm doing an if check and setting an empty string if null. Am I doing this wrong? java.lang.NullPointerException at form.setSam((teamBean.getHead().getNone().getCode() == null) ? "" : teamBean.getHead().getNone().getSamCode().toString()); //SAM Code: public int show(Action action) throws Exception { HttpServletRequest request = action.getRequest(); String[] params; if (!isEmpty(params[0])) { String teamNumber= params[0]; TeamBean teamBean = DAO.getTeamDAO().getTeamByNumber(Long.parseLong(teamNumber)); Fake form = new fakeForm(); form.setMoor(teamBean.getHeader().getMoor()); form.setDoor(Double.toString(teamBean .getDoors())); form.setURC(Double.toString(teamBean.getURCS())); form.setUMC(Double.toString(teamBean.getUMCSt())); form.setWeek(Long.toString(teamBean.getHead().getWeek().getnow())); //WEEK ERROR HERE -->> form.setSam((teamBean.getHead().getNone().getCode() == null) ? "" : teamBean.getHead().getNone().getSamCode().toString()); //SAM A: For clarity, this is the expression that gives you the NullPointerException: teamBean.getHead().getNone().getCode() You aren't checking if getNone returns null. A: You get it because teamBean.getHead().getNone() is null. And since you're calling getCode() on this null value, you get a NullPointerException. Note that form.setSam((teamBean.getHead().getNone().getCode() == null) ? "" : ""); could be rewritten as form.setSac(""); (except you wouldn't have the NullPointerException)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where to call HttpResponse.RemoveOutputCacheItem()? I use the below code for caching public class HomeController : Controller { [OutputCache(Location=OutputCacheLocation.Server, Duration = 1000, VaryByParam = "id")] public ActionResult Index(string id) { ViewBag.Message = "Welcome to ASP.NET MVC!"; return View(); } protected override void OnActionExecuting(ActionExecutingContext filterContext) { //and trying to invalidate cache in here Response.RemoveOutputCacheItem(Request.Url.PathAndQuery); } } I try to invalidate the cache by overriding OnActionExecuting method but that method just called first time. So where do I have to try to call Response.RemoveOutputCacheItem() method to invalidate the cache ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7627825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using Curl to Automate Upload Files to ASP.NET Application I am trying to use cURL to automate some deployment tasks to an ASP.NET Application. But I am having some problems with it. The login part works perfectly but i guess the application for some reason has some sort of control for this kind of tools. These application was developed or an external company(real crappy app). Basically what i need to do is upload every month like 10 xml files by hand which is stupid!. I want to be able to automate this by using my own script(like ruby) and call cURL on the background to process the http requests. Does any one know about any problems using cURL and an ASP.NET app?. May be should I write my own C# tool for this?. Any ideas? A: There's no problem with curl and ASP.NET. curl speaks HTTP and offers many different features and ways to send data, including multiport formpost uploads etc. You most likely just haven't figured out exactly how to mimic a browser when doing your command lines.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Coordinates of world continents I am building a script that's powered by google maps where user chooses the a location from a map and save the long, lat in database aa a part of directory listing form. I was thinking to add a search functionality by world continent for (America, Asia, Europe, Africa). but this require having the coordinates of these locations like America long between 'xx' and 'yy', lat between 'aa' and 'bb' so I can look it up in the database.* And I don't seem to find these info any where, Any help would be appreciated. A: Ok, as a quick solution for this search functionality, I'd set-up two tables in a database. One would map every listing to a country, another would map every country to a continent, so that search could be performed joining these two tables. Use google geocoding to get country from latitude/longitude if needed. A mysql continent/country database can be found here. A: This website will help you quickly get your own bounding boxes: http://bboxfinder.com For example, for one project I didn't want to include Europe all the way North to Knivskjellodden or east to the Urals, so I drew this: A: There are no simple "lat/lng bounding boxes" for the continents because the continents have irregular boundaries. For example Ankara in Turkey has approximatively lat=40, lng=33. But the latitude 40 crosses Europe, Asia and America; and the longitude 33 crosses Europe, Asia and Africa. Similarly, there are no simple "lat/lng bounding boxes" for states. A: If you know the tiling algorithm of google maps you can try the spatial index to get all geo codes from a bounding box from a continent. Like the tiling algorithm this method is not very accurate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Documentation from all comments in Visual Studio 2010 How can create a documentation from all classes, methods and attributes comments in Visual Studio 2010 for the C# language? A: Try Sandcastle and the Sandcastle Helpfile Builder. It creates CHMs and MSHelpfiles or HTML Pages in MSDN Style. Its simple to use and it can load Soultion Files. Helpfile Builder with Sandcaste: http://shfb.codeplex.com/ Sandcastle only: http://sandcastle.codeplex.com/ A: You can create MSDN like documentation with Sandcastle A: Doxygen will generate nice HTML documentation from the comments in your code, provided that you follow a few simple formatting rules. A: First it is worth saying that it is commendable that you want to document the API of your libraries so that others (or even you at a future date:-) will be able to use your code without having to read your code. That is a great step in itself! There are a variety of tools that help automate this task, notably Doxygen and Sandcastle, as others have previously mentioned. I have not used Doxygen so I will restrict my comments to Sandcastle. Sandcastle, provided by Microsoft, is a great starting point but apparently is quite difficult to use, hence a number of motivated independent developers built more usable interfaces on top of Sandcastle. The premier one of these is Sandcastle Help File Builder (SHFB). With the GUI of SHFB you "simply" create a Sandcastle project, set the project properties to your liking, then build your documentation set as a web site or a CHM file or a couple other formats. I wrote simply in quotes above because working in SHFB is the smallest part of the task in front of you--the much more vast task is decorating your code with appropriate and correct documentation comments (doc-comments) that serve as the "source code" for Sandcastle or other documentation engine. It takes a substantial investment of your time and energy to document all your code but I believe, as you may have inferred, that it is definitely worth it. Besides the aforementioned reason that others will be able to use your code much more easily, I find that documenting my code has one other important benefit--it helps me write better code. As I start documenting a new method or class I often remark to myself "Oh, this parameter would be more clear if it was called Y rather than X." or "Oops--this method is not generic enough for others; I need to add a Z parameter." or "Hah! This class does not handle these corner cases quite right." In other words, the act of describing your class or method or parameter makes you think carefully about it and thus writing doc-comments leads to better code. So much for theory; for some practical advice and guideline for Sandcastle and SHFB, take a look at my article on Simple-Talk.com entitled Taming Sandcastle: A .NET Programmer's Guide to Documenting Your Code. This article thoroughly documents all the things I found through research and experimentation with SHFB. Accompanying the article is a handy wallchart that brings together all the documented and the undocumented elements and attributes that you may use in doc-comments. Here's a fragment of the wallchart to whet your appetite:
{ "language": "en", "url": "https://stackoverflow.com/questions/7627829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I debug EF? (analyze SQL queries) How can I debug the Entity Framework? Can I see which queries it is actually trying to execute to the SQL server, to troubleshoot issues? A: Check out the MVC Mini Profiler: http://code.google.com/p/mvc-mini-profiler/ It's very lightweight, doesn't intrude on your app, and is easily removed if need be. Plus, Stack Overflow uses it. A: You can cast your query to ObjectQuery and then use ObjectQuery.ToTraceString() - that returns the full SQL for your query. Alternatively of course you can simply use SQL Profiler on your database to see what SQL gets executed. A: You can use Entity Framework Profiler. http://efprof.com/. A: You could use a Monitoring tool from the Server to watch the queues directly. For MSSQL Server see: http://blog.pengoworks.com/index.cfm/2008/1/3/View-recently-run-queries-in-MSSQL-2005
{ "language": "en", "url": "https://stackoverflow.com/questions/7627831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: iOS Support Multiple Rotations without Animation I am recreating the Camera app interface for my iPhone app. When it is rotated on its side, instead of rotating the entire UI, I only rotate the icons, just like the normal camera app does. This has worked just fine, but with iOS 5 the notification center orientation depends on the app's orientation. Since my app technically stays in portrait orientation, you can only access the notification center from the top of the screen, even when held sideways. The default camera app has somehow avoided this problem. I figured the best way to do this is to silently update the UI to be in a different orientation, but from the user's perspective only the icons update. I've tried to achieve this by returning YES in shouldAutorotateToInterfaceOrientation:, and then setting the transform property to rotate the view in willAnimateRotationToInterfaceOrientation:duration:. This works, except it shows an animation where it moves the newly rotated view to its proper position. How can I achieve this without any visible animation? A: The answer is actually very simple. All I had to do was change the statusBarOrientation property on [UIApplication sharedApplication] to whatever UIInterfaceOrientation I wanted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sending an object via datagram sockets java I'm implementing this example as I want to broadcast to multiple clients. While trying to use the socket to send another object(which has been serialised), I'm getting an error which says that socket(in the example) can't send the object via it. Can't a datagram socket send/receive objects also? A: Not in general, no. Datagram packets are generally relatively small - you could try serializing your object to a ByteArrayOutputStream wrapped in an ObjectOutputStream, and then try to send the byte array afterwards - but you may well find it gets too big very quickly. Using a more efficient serialization format such as Protocol Buffers will probably allow you to get more information in a single packet, but typically you'd want to serialize to a stream instead of to a single packet... and as soon as you start trying to put a stream-based protocol over a datagram-based protocol - well, you end up with TCP reasonably quickly, as soon as it has to be reliable. If you can give us more details of what you're trying to do (including reliability constraints - how serious is it if a packet is lost?), we may be able to help you more. A: Your best bet is to either use TCP or another library such as jGroups JGroups is a toolkit for reliable multicast communication.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }