Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
3
121k
Q: Redirect to language version site using Url Rewriting IIS7 When user types www.domain.com he should be instantly redirected to his language version or if he have no language specified in his browser, to default language 'en'. The problem is to find the good rule to redirect the user to default language when he don't specify any. I'm trying the following expression without success: <rule name="www.domain.com" stopProcessing="true"> <match url="www.domain.com$" /> <action type="Redirect" url="/en/" /> </rule> It simply doesn't anything. I'll appreciate any help.
Q: Open Source/Free ASP.NET Webcontrol for Document Repository Is anyone aware of a good open source document repository webcontrol for ASP.NET? I'd like to give users the ability to upload files, create folders, etc. in particular paths on the web server. I want a full user interface so just the WebDAV API or a partial solution like Uploadify is not enough. A: I'm not sure if I correctly understand the question, but there are lots of free (and even more commercial) file manager controls for ASP.NET, e.g: essential objects, IZWebFileManager, ASP.NET AJAX Style Folder Explorer. Personally I'm using the (commercial) RadControls suite by telerik, which also contains a file explorer control. A: Check out KCFinder: http://kcfinder.sunhater.com/ It is a free open source alternative to CKFinder. I've worked with this on a corporate intranet site and it has served us beautifully.
Q: Getting familiar with .NET - What's the best way? I have a friend of mine who owns his own software consulting business. Most of the stuff his employees work on is .NET related development. He's been out of actual development for many years, and has been focused on building his business. He asked me the best way to get familiar with the whole .NET platform and development under .NET. Is anyone aware of a video training series, or something similar, that's designed to get someone up to speed on all aspects of .NET? A: This is the obligatory "port another project into .NET" answer. A: My guess is that he doesn't have to cover all of .NET, but a great way to get up to speed with both C# and a significant part of the .NET framework is the C# 4.0 in a Nutshell book. It assumes some programming experience and covers a lot of stuff. A: In my opinion the first step is to read a book which covers different parts of .Net Framework. Pro C# 2010 and the .NET 4 Platform is one possible book as it covers different technologies such as WPF, WCF, Linq, Ef, Asp.Net. They are not discussed in depth but is a good resource for getting familiar with current technology stack. Also, I would recommend actually developing in .Net as is many knowledge comes from the actually doing it. A: In addition to the other answers, maybe your friend could sit in on any code reviews, design sessions or even perform pair programming with the other developers once he gets a basic understanding of things on his own. I suppose this could be difficult in a consulting business vs. regular development shop though. A: In addition to all of the books and blogs which will be mentioned, I always recommend people start learning with something practical. When I'm teaching I make up simple exercises broken down into chunks like build a basic database, try simple things like displaying the data, filter the data using drop down, add auto postbacks and update panels, updating the data in the DB. It doesn't take long to get an overview of the basic concepts, techniques and tools when presented with examples. And then it's down to experimentation, imagination, and research! A: * *Buy Visual Studio and an MSDN membership - in case its a startup there maybe various options to reduce this cost (Bizspark/Websitespark) *Go through common walkthroughs - areas to go through are Winforms, Asp.net, Asp.net Ajax in that order. Can go through WCF, Silverlight and other framework options later. *Search the web for 'Azure trial' - supposedly, there is a one month free pass available. Dont know if this is real, but if it is, take it and deploy simple applications on the cloud - learn what Windows Azure and Sql azure are all about. After a while can learn about Appfabric messaging platform as well. After this, start deep-diving into any areas of the technology depending on project needs. A: Channel 9 ASP.NET getting started Dimecast DNR TV A: more than reading any book what made get started with .NET was doing projects. Start building a web site if you want to learn ASP.NET, you get to learn C# and VB as well like this. Just by reading a book each chapter would take lot of time. Initially you will do lot of mistakes and you will frequently get the dreaded yellow error page. The more mistakes you make, the merrier. My experience with .NET is limited to ASP.NET, C#,LINQ, web services, SQL Server 2008. But it took less than 20 days for me to get to know about all these stuff. Now I am trying to do WPF, WCF, Silverlight projects. IF I read any .NET book now, it wouldn't take much time for me to complete it. A: I realy suggest to use a step by step teach your self book. They are good for beginners and have some practices maybe something from SAMS publishing like Teach yourself c# in 21 days
Q: How can I connect to MSMQ over a workgroup? I'm writing a simple console client-server app using MSMQ. I'm attempting to run it over the workgroup we have set up. They run just fine when run on the same computer, but I can't get them to connect over the network. I've tried adding Direct=, OS:, and a bunch of combinations of other prefaces, but I'm running out of ideas, and obviously don't know the right way to do it. My queue's don't have GUIDs, which is also slightly confusing. Whenever I attempt to connect to a remote machine, I get an invalid queue name message. What do I have to do to make this work? Server: class Program { static string _queue = @"\Private$\qim"; static MessageQueue _mq; static readonly object _mqLock = new object(); static void Main(string[] args) { _queue = Dns.GetHostName() + _queue; lock (_mqLock) { if (!MessageQueue.Exists(_queue)) _mq = MessageQueue.Create(_queue); else _mq = new MessageQueue(_queue); } Console.Write("Starting server at {0}:\n\n", _mq.Path); _mq.Formatter = new BinaryMessageFormatter(); _mq.BeginReceive(new TimeSpan(0, 1, 0), new object(), OnReceive); while (Console.ReadKey().Key != ConsoleKey.Escape) { } _mq.Close(); } static void OnReceive(IAsyncResult result) { Message msg; lock (_mqLock) { try { msg = _mq.EndReceive(result); Console.Write(msg.Body); } catch (Exception ex) { Console.Write("\n" + ex.Message + "\n"); } } _mq.BeginReceive(new TimeSpan(0, 1, 0), new object(), OnReceive); } } Client: class Program { static MessageQueue _mq; static void Main(string[] args) { string queue; while (_mq == null) { Console.Write("Enter the queue name:\n"); queue = Console.ReadLine(); //queue += @"\Private$\qim"; try { if (MessageQueue.Exists(queue)) _mq = new MessageQueue(queue); } catch (Exception ex) { Console.Write("\n" + ex.Message + "\n"); _mq = null; } } Console.Write("Connected. Begin typing.\n\n"); _mq.Formatter = new BinaryMessageFormatter(); ConsoleKeyInfo key = new ConsoleKeyInfo(); while (key.Key != ConsoleKey.Escape) { key = Console.ReadKey(); _mq.Send(key.KeyChar.ToString()); } } } A: You need to use this format to connect to a remote private queue: FormatName:Direct=OS:machinename\\private$\\queuename There's a handy article here with a bit more info A: I got that working, once. My recommendation would be 1: don't do it, 2: don't do it, 3: only use private queues and assign the workstations static IP addresses in the 192.168.x.x subnet. Either provide each machine with a hostfile to map machine names to IP addresses or use the IP address directly in the format name. Relying on name resolution in a work group is hoping to win playing roulette in Vegas.
Q: Mesh from heightmap in Ogre3D Using the Ogre3D engine (C++), I would like to generate a mesh from a grayscale heightmap. I know that the Terrain tools can do that but I just want a simple mesh. What would be the best way to do that? This sounds pretty basic but I can't find my way in the Ogre3d doc. Thanks! A: One way to do it is extract all the height values and pump them into an Ogre::ManualObject. Then call ManualObject::convertToMesh(...) for the conversion. Fire up a MeshSerializer and use it to save the mesh out to a file. MeshPtr pmo = mo.convertToMesh( "GrassBladesMesh" ); MeshSerializer ser; ser.exportMesh( pmo.getPointer(), "grass.mesh" ); See Ogre::ManualObject link above for more info. HTH
Q: Unit testing installation of services Our installer program is going to be installing a number of system services, under both Windows and UNIX, using JavaServiceWrapper. There will be a class responsible for creating JavaServiceWrapper config files, installing the services, etc. Can I have some suggestions on how to unit-test this class? A: I would not struggle too much with unit testing such a class, rather I would go for integration / smoke tests. You need these anyway to verify that your installation works properly - preferably not only on your own machine, but also in the target environment, in real life, before you are about to demonstrate it to your boss and most important client :-) Update: I assume that the class in question would not contain much complicated logic, rather just gluing together different pieces supplied by other APIs. However, if this is not the case, and you feel you can't easily test a significant part of its functionality via integration tests, you can still try unit testing with good ol' mocks and/or dependency injection. A: Lol! Found this last night. Environmentally Friendly Deployment. I really think as more complex your deployment, the more you need to validate your environment.
Q: Strange behavior when overriding private methods Consider the following piece of code: class foo { private function m() { echo 'foo->m() '; } public function call() { $this->m(); } } class bar extends foo { private function m() { echo 'bar->m() '; } public function callbar() { $this->m(); } } $bar = new bar; $bar->call(); $bar->callbar(); Now, changing the visibility of the m() method, I get: (+ for public, - for private) Visibility bar->call() bar->callbar() ====================================================== -foo->m(), -bar->m() foo->m() bar->m() -foo->m(), +bar->m() foo->m() bar->m() +foo->m(), -bar->m() ERROR ERROR +foo->m(), +bar->m() bar->m() bar->m() (protected seems to behave like public). I was expecting everything to behave like it does when both are declared public. But although foo->call() and bar->callbar() are essentially the same thing, they yield different results depending on the visibility of m() in foo and bar. Why does this happen? A: According to the PHP manual: Members declared as private may only be accessed by the class that defines the member. http://www.php.net/manual/en/language.oop5.visibility.php EDIT they yield different results depending on the visibility of m() in foo and bar. Why does this happen? If m() in foo is public, it is overridable. When this is the case m() from bar overrides m() in foo. A: Inheriting/overriding private methods In PHP, methods (including private ones) in the subclasses are either: * *Copied; the scope of the original function is maintained. *Replaced ("overridden", if you want). You can see this with this code: <?php class A { //calling B::h, because static:: resolves to B:: function callH() { static::h(); } private function h() { echo "in A::h"; } } class B extends A { //not necessary; just to make explicit what's happening function callH() { parent::callH(); } } $b = new B; $b->callH(); Now if you override the private method, its new scope will not be A, it will be B, and the call will fail because A::callH() runs in scope A: <?php class A { //calling B::h, because static:: resolves to B:: function callH() { static::h(); } private function h() { echo "in A::h"; } } class B extends A { private function h() { echo "in B::h"; } } $b = new B; $b->callH(); //fatal error; call to private method B::h() from context 'A' Calling methods Here the rules are as follows: * *Look in the method table of the actual class of the object (in your case, bar). * *If this yields a private method: * *If the scope where the method was defined is the same as the scope of the calling function and is the same as the class of the object, use it. *Otherwise, look in the parent classes for a private method with the same scope as the one of the calling function and with the same name. *If no method is found that satisfies one of the above requirements, fail. *If this yields a public/protected method: * *If the scope of the method is marked as having changed, we may have overridden a private method with a public/protected method. So in that case, and if, additionally, there's a method with the same name that is private as is defined for the scope of the calling function, use that instead. *Otherwise, use the found method. Conclusion * *(Both private) For bar->call(), the scope of call is foo. Calling $this->m() elicits a lookup in the method table of bar for m, yielding a private bar::m(). However, the scope of bar::m() is different from the calling scope, which foo. The method foo:m() is found when traversing up the hierarchy and is used instead. *(Private in foo, public in bar) The scope of call is still foo. The lookup yields a public bar::m(). However, its scope is marked as having changed, so a lookup is made in the function table of the calling scope foo for method m(). This yields a private method foo:m() with the same scope as the calling scope, so it's used instead. *Nothing to see here, error because visibility was lowered. *(Both public) The scope of call is still foo. The lookup yields a public bar::m(). Its scope isn't marked as having changed (they're both public), so bar::m() is used. A: A private method is not overridable, as a private method is not visible even to its subclasses. Defining a method as protected means it is not visible outside of the class itself or its subclasses. If you have a method that you want to use from your parent class but want children to able to modify its behaviour, and don't want this method available externally, use protected. If you want functionality in your parent class that cannot be modified in any way by subclasses, define the method as private. EDIT: to clarify further, if you have two methods with the same name in a parent and subclass, and these methods are defined as private, essentially the subclass method has absolutely no relation to the parent method. As stated, a private method is COMPLETELY INVISIBLE to the subclass. Consider this: class foo { private function m() { echo 'foo->m() '; } private function z() { echo "foo->z();"; } public function call() { $this->m(); } } class bar extends foo { private function m() { echo 'bar->m() '; } public function callbar() { $this->m(); } public function callz() { $this->z(); } } Calling $bar->callz(); is going to produce an ERROR, because z does not exist in the subclass at all, not even as an inherited method.
Q: LINQ To SQL Dynamic Select Can someone show me how to indicate which columns I would like returned at run-time from a LINQ To SQL statement? I am allowing the user to select items in a checkboxlist representing the columns they would like displayed in a gridview that is bound to the results of a L2S query. I am able to dynamically generate the WHERE clause but am unable to do the same with the SELECT piece. Here is a sample: var query = from log in context.Logs select log; query = query.Where(Log => Log.Timestamp > CustomReport.ReportDateStart); query = query.Where(Log => Log.Timestamp < CustomReport.ReportDateEnd); query = query.Where(Log => Log.ProcessName == CustomReport.ProcessName); foreach (Pair filter in CustomReport.ExtColsToFilter) { sExtFilters = "<key>" + filter.First + "</key><value>" + filter.Second + "</value>"; query = query.Where(Log => Log.FormattedMessage.Contains(sExtFilters)); } A: The short answer is don't. A method has to have a known, specific return type. That type can be System.Object but then you have to use a lot of ugly reflection code to actually get the members. And in this case you'd also have to use a lot of ugly reflection expression tree code to generate the return value. If you're trying to dynamically generate the columns on the UI side - stop doing that. Define the columns at design time, then simply show/hide the columns you actually need/want the user to see. Have your query return all of the columns that might be visible. Unless you're noticing a serious performance problem selecting all of the data columns (in which case, you probably have non-covering index issues at the database level) then you will be far better off with this approach. It's perfectly fine to generate predicates and sort orders dynamically but you really don't want to do this with the output list. Some of the comments have forced me to seriously consider whether or not I was correct in my implication that a dynamic output list is actually possible, and I conclude that it is, in spite of being a dangerous swimming-against-the-current idea. In order to pull off this stunt, you'd have to: * *Generate a new type using Reflection.Emit. *Generate an expression tree that initializes it by using Expression.MemberInit. *Compile the expression and pass it to the Select method. *Return a weakly-typed System.Object from your method and use Reflection to access the members by name. It's not the kind of thing I would ever want to see in production code, but there you have it - it's possible. A: You don't need to do that at the query level (that would be pretty hard anyway, since you would need to dynamically create a type at runtime)... It's much easier to handle that in the GridView itself, by explicitly declaring the columns you want to display.
Q: Correct way to add objects to an ArrayList I am trying to add an object to an arraylist but when I view the results of the array list, it keeps adding the same object over and over to the arraylist. I was wondering what the correct way to implement this would be. public static ArrayList<Person> parsePeople(String responseData) { ArrayList<Person> People = new ArrayList<Person>(); try { JSONArray jsonPeople = new JSONArray(responseData); if (!jsonPeople.isNull(0)) { for (int i = 0; i < jsonPeople.length(); i++) { People.add(new Person(jsonPeople.getJSONObject(i))); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { } return People; } I have double checked my JSONArray data and made sure they are not duplicates. It seems to keep adding the first object over and over. A: Some quick tips: * *Consider following naming convention. Variable names starts with lowercase. *Effective Java 2nd Edition, Item 65: Don't ignore exceptions *Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces Having said that, you can add to an ArrayList the same way you add to ANY List: you can add(E) a single element or addAll an entire Collection<? extends E> to the end of the list. There are also overloads that takes an index if you want to add element(s) to a more specific location. On aliasing Always remember that objects are reference types, and references can be aliased. Unless you understand what this means, some behaviors may surprise you. This snippet shows an example of: * *Creating a List of 3 AtomicReference instances that all refers to the same AtomicInteger. *When the AtomicInteger is incremented, all AtomicReference sees this effect *One AtomicReference is then set to refer to a second AtomicInteger (There is nothing specific about concurrency in this example) import java.util.concurrent.atomic.*; //... List<AtomicReference<AtomicInteger>> refs = new ArrayList<AtomicReference<AtomicInteger>>(); AtomicInteger counter = new AtomicInteger(); for (int i = 0; i < 3; i++) { refs.add(new AtomicReference<AtomicInteger>(counter)); } // we now have 3 AtomicReference, // but only 1 AtomicInteger System.out.println(refs); // [0, 0, 0] counter.incrementAndGet(); System.out.println(refs); // [1, 1, 1] refs.get(1).set(new AtomicInteger(9)); System.out.println(refs); // [1, 9, 1] // we still have only 3 AtomicReference, // but we've also created a second AtomicInteger counter.incrementAndGet(); System.out.println(refs); // [2, 9, 2] Note that even though a new AtomicReference was used for List.add every time (meaning 3 different AtomicReference objects are created total), they were still referring to the same AtomicInteger. This sorts of aliasing may be the source of your problem. A: There is either a problem with the responseData string or the constructor. If the class receives a response Data object that looks like the following String responseData = "[{ \"first_name\" : \"fred\" , \"last_name\" : \"Nobody\" }, { \"first_name\" : \"John\" , \"last_name\" : \"Somebody\" }]"; Then your Contact class should look like public class Contact { String fname; String lname; public Contact(JSONObject obj){ System.out.println(obj); try { fname = (String)obj.get("first_name"); lname = (String)obj.get("last_name"); } catch (JSONException e) { e.printStackTrace(); } } //get and set methods } There should be no reason based on your logic to have the same record show up twice. Make sure your JSON string has the correct format coming in. I would suggest adding more System.out or Log4j calls in the application to determine every step. Worst case step through the application with a debug session. PS - I built you app by adding the above code and it worked fine. So you have the grasp on adding the elements to the ArrayList properly. Could you also show how you print the array back out? Maybe the issue is there. A: Don't you think Person.add(new Person(jsonPeople.getJSONObject(i))); should be like People.add(new Person(jsonPeople.getJSONObject(i))); i dono how you compiled the file in the first place, unless you have a static method called add(Person p) and a constructor that accepts Person(JSONObject j) in the class Person.
Q: Unable to get NSMutableArray value in function I am getting the nsMutaryOfDataObject value in the reload function but not getting it in in - (int)numberOfRowsInTableView:(NSTableView *)pTableViewObj... In this function mutablearray is getting nil. I'm unable to understand why. How can this happen? A: you have to retain the array, the other class that creates it probably releases it. - (void) setMutableArray:(NSMutableArray *)arr { [instanceVar release]; instanceVar = nil; instanceVar = [arr retain]; } You should be somewhat more clear with your code though, maybe add some logging calls when you "create" or set the array.
Q: What is the philosophy of managing memory in C++? What is the design factor in managing memory in C++? For example: why is there a memory leak when a program does not release a memory object before it exits? Isn't a good programming language design supposed to maintain a "foo-table" that takes care of this situation ? I know I am being a bit naive, but what is the design philosophy of memory management in C++ with respect to classes, structs, methods, interfaces, abstract classes? Certainly one cannot humanely remember every spec of C++. What is the core driving design of memory management? A: What is the core driving design of memory management ? In almost all cases, you should use automatic resource management. Basically: * *Wherever it is practical to do so, prefer creating objects with automatic storage duration (that is, on the stack, or function-local) *Whenever you must use dynamic allocation, use Scope-Bound Resource Management (SBRM; more commonly called Resource Acquisition is Initialization or RAII). Rarely do you have to write your own RAII container: the C++ standard library provides a whole set of containers (e.g., vector and map) and smart pointers like shared_ptr (from C++ TR1, C++0x, and Boost) work very well for most common situations. Basically, in really good C++ code, you should never call delete yourself1 to clean up memory that you've allocated: memory management and resource cleanup should always be encapsulated in a container of some kind. 1. Obviously, the exception here is when you implement an RAII container yourself, since that container must be responsible for cleaning up whatever it owns. A: It's not entirely clear whether you're asking about the philosophy of what's built into C++, or how to use it in a way that prevents memory leaks. The primary way to prevent memory leaks (and other resource leaks) is known as either RAII (Resource Acquisition Is Initialization) or SBRM (Scope Bound Resource Management). Either way, the basic idea is pretty simple: since objects with auto storage duration are automatically destroyed on exit from their scope, you allocate memory in the ctor of such an object, and free the memory in its dtor. As far as C++ itself goes, it doesn't really have a philosophy. It provides mechanisms, but leaves it up to the programmer to decide which mechanism is appropriate for the situation at hand. That's often RAII. Sometimes it might be a garbage collector. Still other times, other times it might be various sorts of custom memory managers. Of course, sometimes it's a combination of two or all three of those, or something else entirely. Edit: As to why C++ does things this way, it's fairly simple: almost any other choice will render the language unsuited to at least some kinds of problems -- including a number for which C++ was quite clearly intended to be suitable. One of the most obvious of these was being able to run on a "bare" machine with a minimum of support structure (e.g., no OS) A: why is there a memory leak when a program does not release a memory object before it exits ? Well, the OS typically clean up your mess for you. However, what happens when your program is running for an arbitrary amount of time and you have leaked so much memory that you can't allocate anymore? You crash, and that's not good. Isn't a good programming language design supposed to maintain a "foo-table" that takes care of this situation ? No. Some programming languages have automated memory management, some do not. There are benefits and drawbacks to both models. Languages with manual memory management allow you to say when and where resources are allocated and released, i.e., it is very deterministic. A relative beginner will however inevitably write code that leaks while they are getting used to dealing with memory management. Automated schemes are great for the programmer, but you don't get the same level of determinism. If I am writing a hardware driver, this may not be a good model for me. If I were writing a simple GUI, then I probably don't care about some objects persisting for a bit longer than they need to, so I will take an automated management scheme every time. That's not to say that GC'd languages are only for 'simple' tasks, some tasks just require a tighter control over your resources. Not all platforms have 4GB+ memory for you to play around in). There are patterns that you can use to help you with memory management. The canonical example would be RAII (Resource Allocation is Initialization) A: C and C++ take the position that you, the programmer, know when you are done with memory you have allocated. This avoids the need for the language runtime to know much of anything about what has been allocated, and the associated tasks (reference counting, garbage collection, etc.) needed to "clean up" when necessary. At the crux is the idea that: if you allocate it, you must free it. (malloc/free, new/delete) There are several methods of helping manage this so that you don't have to explicitly remember. RAII and the smart pointer implementations that provide containers that do it is extremely useful and powerful for managing memory based on object creation and destruction. They will save you hours of time. A: Philosophy-wise, I think there are two things that lead to C++ not having a garbage collector (which seems to be what you're getting at): * *Compatibility with C. C++ tries to be very compatible with C, for better or worse. C didn't have garbage collection, so C++ doesn't, at least not by default. I guess you could sum this up as "historical reasons". *The "you only pay for what you use" philosophy. C++ tries to avoid imposing any overhead above C unless you explicitly ask for it. So you only pay the price of exceptions if you actually throw one, etc. There's an argument that garbage collection would impose a cost whenever an object is allocated on the heap so it couldn't be the default behavior in C++. Note that there is actually quite a bit of debate about whether garbage collection is actually more or less efficient than manual memory management. The better garbage collectors generally want to be able to move stuff around though, and C++ has pointer arithmetic (again, inherited from C) that makes it very hard to make such a collector work with C++. Here's Stroustrup's (not really direct) answer to "Why doesn't C++ have garbage collection?": If you want automatic garbage collection, there are good commercial and public-domain garbage collectors for C++. For applications where garbage collection is suitable, C++ is an excellent garbage collected language with a performance that compares favorably with other garbage collected languages. See The C++ Programming Language (3rd Edition) for a discussion of automatic garbage collection in C++. See also, Hans-J. Boehm's site for C and C++ garbage collection. Also, C++ supports programming techniques that allows memory management to be safe and implicit without a garbage collector. C++0x offers a GC ABI. A: Isn't a good programming language design supposed to maintain a "foo-table" that takes care of this situation ? Is it? why? A good programming language is one that lets you solve problems, no more, no less. A garbage collector certainly lowers the barrier of entry, but it also takes control away from the programmer, which might be a problem in some cases. True, on a modern 2.5GHz quad-core computer, and with today's advanced and efficient garbage collectors, we can live with that. But C++ had to work with much more limited hardware, ranging from desktop computers with a whopping 16MB of RAM down to embedded platforms with 16KB, and everything in between. It has to be usable in realtime code, where you can not just pause the program for 0.5 seconds to run a garbage collection. C++ isn't just designed to be the language used on desktop computers. It's meant to be usable everywhere, on memory-limited systems, in hard realtime scenarios, on large supercomputers and everywhere else. C++'s guiding principle is "you don't pay for what you don't use". If you don't want a garbage collector, you shouldn't have to pay the (steep) price of one. There are very powerful techniques to manage memory in C++ and avoid memory leaks, even without a garbage collector. If a garbage collector was the only way to avoid memory leaks, then there'd be a strong argument in favor of adding one to the language. But it isn't. You just have to learn how to properly manage memory yourself in C++. A: What is the core driving design of memory management? The driving design (no pun intended) is a bit like that of stick-shift transmission cars, as opposed to automatic transmission cars. Like a stick-shift car, C++ gives you freedom and control over the machine, but it's not as easy to use as automatic ones that take care of many things for you. The following could easily have been written about C++ versus Java: People who drive stick shift cars know the difference and the advantages of having total control of your car engine; people who drive cars with automatic transmissions do not. (...) Race cars, for example, do not use automatic transmissions. (...) People who are used to shifting gears will focus more on their driving making it more efficient and safe. http://www.eslbee.com/contrast_stick_shift_or_automatic.htm I should add, though, that C++ does have some mechanism that handle the memory for you, like others have mentioned, e.g. RAII, smart pointers etc. A: C++ has no design philosophy wrt memory. All it has are two functions for allocating memory (new malloc) and two functions for freeing memory ( delete free ) and a frew related functions. Even those can be replaced by the programmer. This is because C++ aims to run on generic computers. Generic computers are a CPU, memory (RAM, varieties of ROM) and a bus/busses for peripherals. There is no built in memory management on generic computers. Now most computers come with memory ( typically a ROM variant ) which contains a bios/monitor. There you might see some rudimentary form of memory management --probably not. Some computers come with OSes which will have memory management, but even there it is often primitive, and it is easy for me to claim that most computers running a C++ program have no OS at all. If you expect C++ to run on any computer, it cannot have a memory management philosophy.
Q: truly unique random number generate by php? I'm have build an up php script to host large number of images upload by user, what is the best way to generate random numbers to image filenames so that in future there would be no filename conflict? Be it like Imageshack. Thanks. A: Easiest way would be a new GUID for each file. http://www.php.net/manual/en/function.uniqid.php#65879 A: Here's how I implemented your solution This example assumes i want to * *Get a list, containing 50 numbers that is unique and random, and *This list of # to come from the number range of 0 to 1000 Code: //developed by www.fatphuc.com $array = array(); //define the array //set random # range $minNum = 0; $maxNum = 1000; // i just created this function, since we’ll be generating // # in various sections, and i just want to make sure that // if we need to change how we generate random #, we don’t // have to make multiple changes to the codes everywhere. // (basically, to prevent mistakes) function GenerateRandomNumber($minNum, $maxNum){ return round(rand($minNum, $maxNum)); } //generate 49 more random #s to give a total of 50 random #s for($i = 1; $i <= 49; $i++){ $num1 = GenerateRandomNumber($minNum, $maxNum); while(in_array($num1, $array)){ $num1 = GenerateRandomNumber($minNum, $maxNum); } $array[$i] = $num1; } asort($array); //just want to sort the array //this simply prints the list of #s in list style echo '<ol>'; foreach ($array as $var){ echo '<li>'; echo $var; echo '</li>'; } echo '</ol>'; A: $better_token = uniqid(md5(mt_rand()), true); A: Keep a persistent list of all the previous numbers you've generated(in a database table or in a file) and check that a newly generated number is not amongst the ones on the list. If you find this to be prohibitively expensive, generate random numbers on a sufficient number of bits to guarantee a very low probability of collision. You can also use an incremental approach of assigning these numbers, like a concatenation of a timestamp_part based on the current time and a random_part, just to make sure you don't get collisions if multiple users upload files at the same time. A: You could use microtime() as suggested above and then appending an hash of the original filename to further avoid collisions in the (rare) case of exact contemporary uploads. A: There are several flaws in your postulate that random values will be unique - regardless of how good the random number generator is. Also, the better the random number generator, the longer it takes to calculate results. Wouldn't it be better to use a hash of the datafile - that way you get the added benefit of detecting duplicate submissions. If detecting duplicates is known to be a non-issue, then I'd still recommend this approach but modify the output based on detected collisions (but using a MUCH cheaper computation method than that proposed by Lo'oris) e.g. $candidate_name=generate_hash_of_file($input_file); $offset=0; while ((file_exists($candidate_name . strrev($offset) && ($offset<50)) { $offset++; } if ($offset<50) { rename($input_file, $candidate_name . strrev($offset)); } else { print "Congratulations - you've got the biggest storage network in the world by far!"; } this would give you the capacity to store approx 25*2^63 files using a sha1 hash. As to how to generate the hash, reading the entire file into PHP might be slow (particularly if you try to read it all into a single string to hash it). Most Linux/Posix/Unix systems come with tools like 'md5sum' which will generate a hash from a stream very efficiently. C. A: * *forge a filename *try to open that file *if it exists, goto 1 *create the file A: My solution is usually a hash (MD5/SHA1/...) of the image contents. This has the added advantage that if people upload the same image twice you still only have one image on the hard disk, saving some space (ofc you have to make sure that the image is not deleted if one user deletes it and another user has the same image in use). A: Using something based on a timestamp maybe. See the microtime function for details. Alternatively uniqid to generate a unique ID based on the current time. A: Guaranteed unique cannot be random. Random cannot be guaranteed unique. If you want unique (without the random) then just use the integers: 0, 1, 2, ... 1235, 1236, 1237, ... Definitely unique, but not random. If that doesn't suit, then you can have definitely unique with the appearance of random. You use encryption on the integers to make them appear random. Using DES will give you 32 bit numbers, while using AES will give you 64 bit numbers. Use either to encrypt 0, 1, 2, ... in order with the same key. All you need to store is the key and the next number to encrypt. Because encryption is reversible, then the encrypted numbers are guaranteed unique. If 64 bit or 32 bit numbers are too large (32 bits is 8 hex digits) then look at a format preserving encryption which will give you a smaller size range at some cost in time.
Q: android push notification service comparison Can anyone give me a comparison for android push notification services. Mainly I want to compare these services. MQTT - http://mqtt.org/ XTIFY - http://xtify.com/ Mobile Push - https://labs.ericsson.com/apis/mobile-push/ Google's C2DM server A: These are partially apples and oranges, however you can get the same push notification effect with varying degrees of difficulty. Full Disclosure I currently use Xtify in my Android app to great success. I'll try not to be biased, but I did choose it for a reason. MQTT is a wire protocol which specializes in low overhead and queue tolerance. You will need to implement (or find open source) server-side and client-side programs to use MQTT, which will require a fair amount of development time. Java's not great (unlike C) in my opinion at dealing with low level abstractions like network I/O. Benefits resulting from speed/reliability will depend on how good your implementation is. Xtify is a mature 3rd party push service with some cool features like geo-notifications, timed alerts, statistics, etc. Big benefit to you is that your overhead is low, and it will just work (no time spent debugging low level code). There are several APIs for creating and configuring notifications, pushing, and getting information. Integration of the Xtify SDK into your app will take some time, but I found their support to be very responsive. Xtify announced they will be supporting C2DM in the future. Mobile Push is another 3rd party push offering by Ericsson which has SMS capabilities (Xtify does not). They have a web API for sending pushes but you do have to write the code to handle the notification once it's received in the app. Another thing to note is that it doesn't look like this project is still under active development. The last version was released in September 2010. C2DM Is a google offering which is still technically in labs (active development) but is looking like it will be the suggested method to send pushes to Androids in the future. This is pretty barebones push and requires you to handle the notification once it's received like the other 3rd parties. A key discriminator is that only Android OS's 2.2 and above can be reached by C2DM. Summary In terms of getting not locked into a product, either Xtify or Mobile Push seem to be pretty good. You can always rewrite web API's but switching to a new solution after writing your own protocol specific interfaces will be harder. In terms of features Xtify wins out, plus if you ever decide to convert your app to iPhone or Blackberry, it's the same interface. In terms of simplicity probably Mobile Push is the winner, but again, I would be wary of building production code around out of development or orphaned APIs. Good Luck! Hope this helps.
Q: Is TRUNCATE a DML statement? Can we classify/say that TRUNCATE belongs to/falls under DML statement? Check here for PostgreSQL TRUNCATE compatibility. NOTE: TRUNCATE is part of SQL standard ANSI SQL 2008 - F200 A: PostgreSQL I would say it's a DML statement in PostgreSQL: PostgreSQL has a TRUNCATE trigger but PostgreSQL doesn't have DDL triggers. So it can't be a DDL statement. It acquires an ACCESS EXCLUSIVE lock on each table it operates on and it's not MVCC-safe but it's transactionsafe and you can do a rollback. The ability to fire triggers for TRUNCATE is a PostgreSQL extension of the SQL standard. A: As TRUNCATE manipulates data and does not change any definition, I clearly see it as a DML statement.
Q: Is there a way to Start and Stop a SwingWorker more than once..? I have a start and stop button. I was told that I must use a SwingWorker. The code that I have now works fine. I start it and I stop it. But what if i want to start it again..? I am reading that the doinBackground method will only be executed once. Is there a way to fire it off again..?? Right now I cannot create a new instance of that Swing Worker because in my Swing Worker I have a while loop that says while(isSet) which is set to True when I click on the Start Button and set to False when I click on the stop button. Is there a way around this..?? Thanks A: The SwingWorker API doc answers your question: SwingWorker is only designed to be executed once. Executing a SwingWorker more than once will not result in invoking the doInBackground method twice. SwingWorker API docs You'll need to create a new SwingWorker instance each time your start button is pressed. A: What I would suggest is having an object encapsulate the SwingWorker. When the "go" button is pressed have that object create a SwingWorker and set it going. When the "stop" flag is set have the SwingWorker finish itself and tell the encapsulating object that it's finished. When the "go" button is pressed again the encapsulating object creates a new SwingWorker, and so on. A: Each SwingWorker is designed to be executed once, as you say. In that respect each object represents a single execution. So one valid (and probably the most straightforward) way to do what you're after, is to create a new SwingWorker for each click of the start button, if you really do want to spawn another instance of the action each time.
Q: How to read a pdf in android I want to read a PDF file in android. I placed my PDF files in the assets folder. How can i read the PDF file from there? PDF Reader Link I have checked the above link but it does not work for me. It gives me an error saying that the Activity was not found. And I also want to open a PDF file in WebView. So is it possible to read PDF in WebView? A: You need to have a application which can support that mimetype and open it. In your device/emulator that app is not installed so it is throwing error A: Another great solution to read pdf using externally installed application like Adobe Reader. private void openPDF(final String pathToPDF) { File file = new File(pathToPDF); Uri path = Uri.fromFile(file); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setDataAndType(path, "application/pdf"); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show(); } } A: u can download PDFbox API to read PDF in android try this link: http://pdfbox.apache.org/ A: Google cached displays formats like pdf, ppt, docx, etc. And you don't need to install any application at all. Search the link in google and go to Cached. A: private void openPDF(final String path) { File file = new File(path); Uri uri; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file); } else { uri = Uri.fromFile(file); } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setDataAndType(path, "application/pdf"); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show(); } }
Q: jquery, unselect checkbox by value i have many checkbox: <input type="checkbox" name="checkbox_user" value = "1"/> <input type="checkbox" name="checkbox_user" value = "2"/> <input type="checkbox" name="checkbox_user" value = "3"/> ... and checkbox with value 2 is selected. Is possible unselect checkbox (with jQuery) when i now only value. A: $("input:checkbox[value=2]").attr("checked", true);
Q: MongoDB index/RAM relationship I'm about to adopt MongoDB for a new project and I've chosen it for flexibility, not scalability so will be running it on one machine. From the documentation and web posts I keep reading that all indexes are in RAM. This just isn't making sense to me as my indexes will easily be larger than the amount of available RAM. Can anyone share some insight on the index/RAM relationship and what happens when both an individual index and all of my indexes exceed the size of available RAM? A: It is the working set size plus MongoDB's indexes which should ideally reside in RAM at all times i.e. the amount of available RAM should ideally be at least the working set size plus the size of indexes plus what the rest of the OS (Operating System) and other software running on the same machine needs. If the available RAM is less than that, LRUing is what happens and we might therefore get significant slowdown. One thing to keep in mind is that in an index btree buckets are cached, not individual index keys i.e. if we had a uniform distribution of keys in an index including for historical data, we might need more of the index in RAM compared to when we have a compound index on time plus something else. With the latter, keys in the same btree bucket are usually from the same time era, so this caveat does not happen. Also, we should keep in mind that our field names in BSON are stored in the records (but not the index) so if we are under memory pressure they should be kept short. Those who are interested in MongoDB's current virtual memory usage (which of course also is about RAM), can have a look at the status of mongod. @see http://www.markus-gattol.name/ws/mongodb.html#sec7 A: MongoDB keeps what it can of the indexes in RAM. They'll be swaped out on an LRU basis. You'll often see documentation that suggests you should keep your "working set" in memory: if the portions of index you're actually accessing fit in memory, you'll be fine.
Q: Windows C++ App crash I have a Windows C++ app that crashes on user computers from time to time. I didnt write the app and it doesnt have its own logging. Is there a tool / utility I could use that is able to log some useful information when the application exits (e.g. the file and line number where the crash occurred)? The end user's component does not have Visual Studio. A: "the file and line number where the crash occurred" That would be possible only if the code were built with debug information included. If your users are prepared to install VC++ Express, they could attach to the process with its debugger after the crash, but without the source they will simply see assembler code, and without debug information that may be of limited help in any case. A: You can use BugTrap which catches unhandled exceptions and reports them via email or other means. The setup is pretty simple. The only difficulty will be to correctly setup the *.pdb *.dll *.exe for the minidump. A: By adding dump generating to the program, you can use post-mortem debugging. Crash dump is created by MiniDumpWriteDump function. This dump can be sent to developer computer and debugged. More about this here: http://www.codeproject.com/KB/debug/postmortemdebug_standalone1.aspx
Q: Create Null Object Unmarshalling Empty Element with JAXB I am using JAXB (EclipseLink implementation) in a JAX-RS webservice. When an empty element is passed in the XML request an empty object is created. Is it possible to set JAXB to create a null object instead? Example XML: <RootEntity> <AttributeOne>someText</AttributeOne> <EntityOne id="objectID" /> <EntityTwo /> </RootEntity> When unmarshalling, an instance of EntityOne is created and the id attribute set to "objectID" and an instance of EntityTwo is created with null attributes. Instead I would like a null object for EntityTwo as having an empty object is causing me problems with JPA persistence operations. A: You can specify this behaviour using MOXy's NullPolicy. You will need to create a DescriptorCustomizer to modify the underlying mappings. Don't worry it's easier than it sounds, I'll demonstrate below: import org.eclipse.persistence.config.DescriptorCustomizer; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.oxm.mappings.XMLCompositeObjectMapping; import org.eclipse.persistence.oxm.mappings.nullpolicy.XMLNullRepresentationType; public class RootEntityCustomizer implements DescriptorCustomizer { @Override public void customize(ClassDescriptor descriptor) throws Exception { XMLCompositeObjectMapping entityTwoMapping = (XMLCompositeObjectMapping) descriptor.getMappingForAttributeName("entityTwo"); entityTwoMapping.getNullPolicy().setNullRepresentedByEmptyNode(true); entityTwoMapping.getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.EMPTY_NODE); } } Below is how you associate the customizer with your model class: import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.eclipse.persistence.oxm.annotations.XmlCustomizer; @XmlRootElement(name="RootEntity") @XmlCustomizer(RootEntityCustomizer.class) public class RootEntity { private String attributeOne; private Entity entityOne; private Entity entityTwo; @XmlElement(name="AttributeOne") public String getAttributeOne() { return attributeOne; } public void setAttributeOne(String attributeOne) { this.attributeOne = attributeOne; } @XmlElement(name="EntityOne") public Entity getEntityOne() { return entityOne; } public void setEntityOne(Entity entityOne) { this.entityOne = entityOne; } @XmlElement(name="EntityTwo") public Entity getEntityTwo() { return entityTwo; } public void setEntityTwo(Entity entityTwo) { this.entityTwo = entityTwo; } } In the next version of MOXy (2.2) you will be able to do this via annotations. @XmlElement(name="EntityTwo") @XmlNullPolicy(emptyNodeRepresentsNull=true, nullRepresentationForXml=XmlMarshalNullRepresentation.EMPTY_NODE) public Entity getEntityTwo() { return entityTwo; } You can try this now with one of the EclipseLink 2.2.0 nightly builds: * *http://www.eclipse.org/eclipselink/downloads/nightly.php
Q: Recommendation for integrating nodejs with php application I have an existing app written in PHP (using Kohana framework) and I want to do long polling. From some things I read it seems that doing long polling with PHP is not advisable and using something like nodejs is a better choice. My question is what's the best way to integrate nodejs (or some other well suited tool for long polling) with an existing application? For clarification my app basically is a browser plugin that you can use to send data to groups of other people. When that data is sent, I want the recipients, if they are online and also have the browser plugin, to instantly receive that data and be notified. A: Possibly the best way is to let node.js listen to a port and to let PHP send messages to that port. In Node.js you can just open a socket for listening and in PHP you can use cURL to send messages. The messages can be in JSON-format. If the Node.js-part receives a message, it can forward it, possibly after some processing, directly to the long-polling browser. A: I am creating a small hack that would allow you to do this with ease. It is in a very early stage but it has enough code for it to work: https://github.com/josebalius/NodePHP I plan on updating the readme later today.
Q: Does Time.to_i always return number of seconds since EPOCH in UTC? Is the timezone difference always ignored, regardless in which zone the time is expressed in? Intuitively, the number of seconds passed since EPOCH should be higher for those who are, for example, in UTC+2. However, this seems not to be the case. A: Epoch is based on the utc timezone https://en.wikipedia.org/wiki/Unix_time it does not depend of the timezone you're currently in.
Q: Rewrite (or hijack) an absolute URL request made from a flash (swf) file in a browser Is there a way to rewrite (or hijack) an absolute URL request made from a flash (swf) file in a browser? Eg I have a flash application that is requesting http://example.com/myImage.png The code in the flash application cannot be changed but I want to be able to either use another flash or some javascript to write that URL as the image is beging requested - to something like example.com/myImage.png?u=123456 A: You could have a chance of doing it your are talking about an AS2 swf. The AVM1 is very permissive for that kind of dirty tricks, but AVM2 won't allow you. So, assuming an AS2 SWF, you could write a wrapper swf that hijacks either MovieClipLoader or loadMovie or whatever the original swf is using (you might have to decompile it to know). The hijacking bit would be rather straight forward, something like: _global['MovieClipLoader'] = MyClass; Once MyClass gets the calls, you add whatever you want and then make the actual call. Having said that, I know the _global trick works for custom classes, but not sure it does for native classes like MovieClipLoader. Sorry, that's the best I can come up with :/ Juan
Q: convert Base64 string to image in android In an android application we are receiving a byte64 string.I need to convert these strings to images. I tried getting it but couldnot find any. Please let me know your valuable suggestions Thanks in advance :) A: I had a similar problem for a week. So I built a phonegap plugin for Andriod which i shared here. Hope that helps. :)
Q: Getting header response code This is part of a PHP script I am putting together. Basically a domain ($domain1) is defined in a form and a different message is displayed, based on the response code from the server. However, I am having issues getting it to work. The 3 digit response code is all I am interested in. Here is what I have so far: function get_http_response_code($domain1) { $headers = get_headers($domain1); return substr($headers[0], 9, 3); foreach ($get_http_response_code as $gethead) { if ($gethead == 200) { echo "OKAY!"; } else { echo "Nokay!"; } } } A: If you have PHP 5.4.0+ you can use the http_response_code() function. Example: var_dump(http_response_code()); // int(200) A: $domain1 = 'http://google.com'; function get_http_response_code($domain1) { $headers = get_headers($domain1); return substr($headers[0], 9, 3); } $get_http_response_code = get_http_response_code($domain1); if ( $get_http_response_code == 200 ) { echo "OKAY!"; } else { echo "Nokay!"; } A: Here is my solution for people who need send email when server down: $url = 'http://www.example.com'; while(true) { $strHeader = get_headers($url)[0]; $statusCode = substr($strHeader, 9, 3 ); if($statusCode != 200 ) { echo 'Server down.'; // Send email } else { echo 'oK'; } sleep(30); } A: You directly returned so function wont execute further foreach condition which you written. Its always better to maintain two functions. function get_http_response_code($domain1) { $headers = get_headers($domain1); return substr($headers[0], 9, 3); //**Here you should not return** foreach ($get_http_response_code as $gethead) { if ($gethead == 200) { echo "OKAY!"; } else { echo "Nokay!"; } } }
Q: Classic ASP Request.Form removes spaces? I'm trying to figure this oddity out... in classic ASP i seem to be losing spaces in Request.Form values... ie, Request.Form("json") is {"project":{"...","administrator":"AlexGorbatchev", "anonymousViewUrl":null,"assets":[],"availableFrom":"6/10/20104:15PM"... However, CStr(Request.Form) is json={"project":{"__type":"...":"Alex Gorbatchev", "anonymousViewUrl":null,"assets":[],"availableFrom":"6/10/2010 4:15 PM"... Here's the entire code :) <%@ language="VBSCRIPT"%> <% Response.Write(CStr(Request.Form("json"))) Response.Write(CStr(Request.Form)) %> Somebody please tell me I haven't lost all my marbles... A: aaand I found the problem 5 minutes after... as usual :) posted values need to be url encoded.
Q: have list slide up and append the first item to the end of the list I want to basically slide all my li's up and the top one, will append to the bottom and it will be a rotation of upcoming events. This is what i have so far. It slides the first one up and appends it to the end of ul, but then it just keeps appending that same li to the ul every 1000 ms. Why doesn't it keep sliding the first one up? I'm assuming i have to use the live function somehow?? $(document).ready(function() { function scroll() { $('#events ol li:first').slideUp(); $('#events ol li:last').appendTo($('#events ol')); } setInterval(scroll, 1000); }); A: You need to change it up a bit to append itself after sliding up, like this: $(function() { function scroll() { $('#events ol li:first').slideUp(function() { $(this).show().parent().append(this); }); } setInterval(scroll, 1000); }); You can see it in a demo here. What we're doing is after the .slideUp() completes, the callback runs, which takes the element, shows it (since it was hidden at the end of the .slideUp()) and does a .append() of itself to its parent...moving it to the end. A: One mistake I see, is that your appending the last li, appending the last item will not do any difference because it's already the last item... demo $(document).ready(function() { function scroll() { $('#events ol li:first-child').slideUp(function(){ $(this).appendTo($('#events ol')).show(); }); } setInterval(scroll, 1000);​ });
Q: set the second image by dragging on first image and then save it What exactly I have to do is I have 2 images one is mask and another is Photo. Mask.png is just the layout of the person and Photo.png is the image of the person in the position as per the mask.png. Now the main problem is I want the Photo.png to be resized and moved in such a way that it can be adjusted in that Mask.png. below is the example of mask and Photo Now I want that red color must come on the below two legs of the star for that I need to move the Flowers image as per my convininece and then save them whole as one Image. Im my case theres a outlay of person instead of star and the Photo of person instead of flowers image. Kindly help... Any help would realy be appreciated. Thanks in advance. A: At first you have to decide how to let the user move and resize your image in a user-friendly manner. If your image were rectangular, you could decide for resizing when the user drags on one of the edges and for moving when he drags from a point inside the rectangle. You might do the same with your star shape, but I doubt that it will be intuitive enough for the users. Then you can implement moving and dragging by overriding touchesMoved, checking whether the first touch is inside your shape (or on the edge), and move (or resize) to the last touch. You will find that the calculations are not so easy, but that is the only way [I know] to do it. A: I was recently working on something similar. You could override touchesMoved, but I would recommend using UIGestureRecognizers which you would add to the UIImages themselves. UIRotationGestureRecognizer *rotationRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotate:)]; [rotationRecognizer setDelegate:self]; [someImageView addGestureRecognizer:rotationRecognizer]; then implement some rotate: method There is a sample project by apple called Touches which should have all you need to get started. Hope this helps.
Q: Data Access example using Entity Framework Does anyone know of or having any good examples of how to use Entity Framework version 2 in the Data Access layer and put an interface on it so the business layer uses the interface rather than knowing about EF? I have found some examples but they are all from 2009 and I'm not sure how they relate to Entity Framework version 2. A: This article specifically references Entity Framework 4, which is the latest release of EF. A: I found the following link more helpful with separating the DAL and being able to apply TDD. http://blogs.msdn.com/b/adonet/archive/2009/12/17/walkthrough-test-driven-development-with-the-entity-framework-4-0.aspx
Q: Reading/writing a list of nested dictionaries to/from a CSV file (Python) I have a data structure that looks like this: data =[ {'key_1': { 'calc1': 42, 'calc2': 3.142 } }, {'key_2': { 'calc1': 123.4, 'calc2': 1.414 } }, {'key_3': { 'calc1': 2.718, 'calc2': 0.577 } } ] I want to be able to save/and load the data into a CSV file with the following format key, calc1, calc2 <- header key_1, 42, 3.142 <- data rows key_2, 123.4, 1.414 key_3, 2.718, 0.577 What's the 'Pythonic' way to read/save this data structure to/from a CSV file like the one above? A: Just to show a version that does use the csv module: from csv import DictWriter data =[ {'key_1': { 'calc1': 42, 'calc2': 3.142 } }, {'key_2': { 'calc1': 123.4, 'calc2': 1.414 } }, {'key_3': { 'calc1': 2.718, 'calc2': 0.577 } } ] with open('test.csv', 'wb') as f: writer = DictWriter(f, ['key', 'calc1', 'calc2']) writer.writerow(dict(zip(writer.fieldnames, writer.fieldnames))) # no automatic header :-( for i in data: key, values = i.items()[0] # each dict in data contains only one entry writer.writerow(dict(key=key, **values)) # first make a new dict merging the key and the values A: I don't think that it would be possible to use csv module, due to all the idiosyncrasies in your requirements and the structure, but you could do it quite easily writing it manually: >>> with open('test.txt', 'w') as f: f.write(','.join(['key', 'calc1', 'calc2']) + '\n') f.writelines('{},{},{}'.format(k, *v.values()) + '\n' for l in data for k,v in l.items()) A: I feel the by far easiest approach is to transform the dictionary first into a pandas dataframe and from there very convenient into a csv file. import pandas as pd df = pd.DataFrame.from_dict(data, orient='index') # it is either ‘columns’ or ‘index’ (simple transpose) df.to_csv('filepath/name.csv') To load the file back into the dict form df.to_csv('filepath/name.csv') data_dict = df.to_dict() For more complicated cases have a look into the pandas documentation http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.html and http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html
Q: How to maximize Visual Studio panels? Is there a way to quickly maximize (and then restore) Visual Studio 2010 panels? For instance, I'd like to temporarily maximize the Output window or unit test results window. In Eclipse, I would just double-click the window tab, but in VS, this undocks the window. The desired behavior is: double-click to maximize the window, then double-click it again to restore the panel to its original position. A: Use this keyboard shortcut: Shift-Alt-Enter It will maximize your current panel similar to Eclipse, but it will use the full screen unfortunately, not just the whole Visual Studio window. I prefer the way Eclipse does it, but this does help in Visual Studio land. A: In Visual Studio 2017, on a focused tab Alt + -, F Alt + Space, X (see UPDATE) UPDATE (Windows 10) Win + Up A: From the View menu, pick Full Screen menuitem. Note: when you select the View menu, you will notice that the shortcut for selecting Full Screen is mentioned, Shift+Alt+Enter (which was mentioned previously in the Answers). Platform: Visual Studio Professional 2017, Version 15.5.7 on Windows 10, 64-bit A: Closest the Eclipse behavior is to follow these steps: * *Right-click the window title bar, select Float *Double-click the window title to maximize *Right-click the window title, select Dock After these steps, double-clicking and Ctrl+double-clicking the window maximizes / restores itself A: This feature has been added to Visual Studio Productivity Power Tools 2013 ("Double click to maximize windows"), which is free to download. This new feature allows double-clicking any window tab to maximize it to full-screen mode and restore it back to its initial docked state - without having to worry about float operations or changes to your window layout. A: Here it is as a key board shortcut for commando types: * *Ctrl+Tab Switch to your desired window/panel. *Alt+- Show the dock menu. *T Choose 'Dock as tabbed document' A: In Visual Studio 2010, you can double-click the title bar of a given panel to put it into float mode, then use it just like any other window (maximize, Windows 7 dock, etc.). Ctrl-double-clicking it again will turn it back into a docked panel. You can also right-click on the title bar and select Dock as Tabbed Document to display the panel in the same way the code windows are displayed. A: Right click title bar, then choose 'float', it will only get that window, not the whole panel. Then double-click to maximize. Also, the commands are Window.Float Window.Dock and you can assign them keyboard shortcuts under tools\options. So for example I mapped them to Ctrl-Shift-F7 and Ctrl-Shift-F8, and then after once maximizing the Output window, henceforth if I have the output window docked, I just focus it and then a key makes it big and other puts it back, hurray. A: If you have already installed Productivity Power Tools 2017 (PPT), and the double click file tab is not working or any other feature in PPT, just reset the PPT and it should work just fine after restarting visual studio 2017.
Q: International merchant account services...exchange rate conversions I'm not sure if this is where to post this but I couldn't find any answers. Hoping some developers have run accross this before. I am building a subscription based product that can be used internationally. I would like to offer the subscription in the foreign currency of the customer. I have contacted a couple of merchant account services and they will transact a credit card from another country and deposit the money in USD into my bank account (Im in the US). However the problem is how they do the currency conversion. Say I want to have my customer in the UK sign up for a monthly subscription price of 65 GBP. Every month my UK customer expects the statement to be 65 GBP, but the US merchants I've looked at can't do this. They want me to send them a file with say $100 USD and based on that day's exchange rate they will charge the UK credit card for 62 GBP one month, then possible 64 GBP another month, or 68 GBP another and then deposit the $100 into my USD bank account. Is there a merchant account out there that will provide international transactions, but do the exchange conversion the other way? In other words, charge the UK customer 65 GBP then deposit say $97 into my US bank account...i'm ok, with having the deposits into the bank account fluctuate, i'm more concerned for international users being charged the same price each month and not having it fluctuate, because this is what I would want as a customer. Is this possible? How are others handling international customers and foreign currencies? A: Edit Just read your question again. Well, I think that's exactly how banks work. You put GBP 65 and if your account is in USD, you will receive converted value. Irrelevant I don't think that will answer your question (as it regards to specific business problem), but there is actually service that serves exchange rates.
Q: In MySQL, how to write an INSERT-INTO-VALUES query so that it to be silently discarded if a record with same primary key value already exists? I have to import a large set of records which can contain duplicates. The table is a MyISAM table with a composite primary key and no foreign keys. How do I specify that if a primary key values combination of a record being inserted already exists in the table, it will just discard the particular insert without throwing an error or inserting a duplicate? A: You may want to use the IGNORE keyword in your INSERTs: If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued. (Source) Example: CREATE TABLE my_table ( id int, name varchar(10), value int, PRIMARY KEY (id, name) ); Query OK, 0 rows affected (0.03 sec) INSERT IGNORE INTO my_table (id, name, value) VALUES (1, 'a', 100), (1, 'b', 200), (1, 'b', 300); Query OK, 2 rows affected (0.00 sec) Records: 3 Duplicates: 1 Warnings: 0 SELECT * FROM my_table; +----+------+-------+ | id | name | value | +----+------+-------+ | 1 | a | 100 | | 1 | b | 200 | +----+------+-------+ 2 rows in set (0.00 sec) A: You need to use the IGNORE keyword: INSERT IGNORE INTO ... or LOAD DATA INFILE ... IGNORE ... Details of how to use the latter can be found here.
Q: maintaing a sorted list that is bigger than memory I have a list of tuples. [ "Bob": 3, "Alice": 2, "Jane": 1, ] When incrementing the counts "Alice" += 2 the order should be maintained: [ "Alice": 4, "Bob": 3, "Jane": 1, ] When all is in memory there rather simple ways (some more or some less) to efficiently implement this. (using an index, insert-sort etc) The question though is: What's the most promising approach when the list does not fit into memory. Bonus question: What if not even the index fits into memory? How would you approach this? A: A relational database such as MySQL is specifically designed for storing large amounts of data the sum of which does not fit into memory, querying against this large amount of data, and even updating it in place. For example: CREATE TABLE `people` ( `name` VARCHAR(255), `count` INT ); INSERT INTO `people` VALUES ('Bob', 3), ('Alice', 2), ('Jane', 1); UPDATE `people` SET `count` = `count` + 2; After the UPDATE statement, the query SELECT * FROM people; will show: +-------+-------+ | name | count | +-------+-------+ | Bob | 5 | | Alice | 4 | | Jane | 3 | +-------+-------+ You can save the order of people in your table by adding an autoincrementing primary key: CREATE TABLE `people` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(255), `count` INT, PRIMARY KEY(`id`) ); INSERT INTO `people` VALUES (DEFAULT, 'Bob', 3), (DEFAULT, 'Alice', 2), (DEFAULT, 'Jane', 1); A: B+ trees order a number of items using a key. In this case, the key is the count, and the item is the person's name. The entire B+tree doesn't need to fit into memory - just the current node being searched. You can set the maximum size of the nodes (and indirectly the depth of the tree) so that a node will fit into memory. (In practice nodes are usually far smaller than memory capacity.) The data items are stored at the leaves of the tree, in so-called blocks. You can either store the items inline in the index, or store pointers to external storage. If the data is regularly sized, this can make for efficient retrieval from files. In the question example, the data items could be single names, but it would be more efficient to store blocks of names, all names in a block having the same count. The names within each block could also be sorted. (The names in the blocks themselves could be organized as a B-tree.) If the number of names becomes large enough that the B+tree blocks are becoming ecessively large, the key can be made into a composite key, e.g. (count, first-letter). When searching the tree, only the count needs to be compared to find all names with that count. When inserting, or searcing for a specific name with a given count, then the full key can be compared to include filtering by name prefix. Alternatively, instead of a composite key, the data items can point to offsets/blocks in an external file that contains the blocks of names, which will keep the B+tree itself small. If the blocks of the btree are linked together, range queries can be efficiently implemented by searching for the start of the range, and then following block pointers to the next block until the end of the range is reached. This would allow you to efficiently implement "find all names with a count between 10 and 20". As the other answers have noted, an RDBMS is the pre-packaged way of storing lists that don't fit into memory, but I hope this gives an insight into the structures used to solve the problem. A: RDMS? Even flat file versions like SQLite. Otherwise a combination utilizing lazy loading. Only keep X records in memory the top Y records & the Z most recent ones that had counts updated. Otherwise a table of Key, Count columns where you run UPDATEs changing the values. The ordered list can be retrieved with a simple SELECT ORDER BY. A: Read about B-trees and B+-trees. With these, the index can always be made small enough to fit into memory. A: An interesting approach quite unlike BTrees is the Judy Tree A: What you seem to be looking for are out of core algorithms for container classes, specifically an out of core list container class. Check out the stxxl library for some great examples of out of core alogorithms and processing. You may also want to look at this related question A: As far as "implementation details tackling this 'by hand'", you could read about how database systems do this by searching for the original papers on database design or finding graduate course notes on database architecture. I did some searching and found a survey article by G. Graefe titled "Query evaluation techniques for large databases". It somewhat exhaustively covers every aspect of querying large databases, but the entire section 4 addresses how "query evaluation systems ... access base data stored in the database". Also, Graefe's survey was linked to by the course page for CPS 216: Advanced Databases Systems at Duke, Fall 2001. Week 5 was on Physical Data Organization which says that most commerical DBMS's organize data on-disk using blocks in the N-ary Storage Model (NSM): records are stored from the beginning of each block and a "directory" exists at the end. See also: * *Spring 2004 CPS 216 lecture notes *MIT OCW 6.830 Database Systems A: Of course I know I could use a database. This question was more about the implementation details tackling this "by hand" So basically, you are asking "How does a database do this?" To which the answer is, it uses a tree (for both the data and the index), and only stores part of the tree in memory at any one time. As has already been mentioned, B-Trees are especially useful for this: since hard-drives always read a fixed amount at a time (the "sector size"), you can make each node the size of a sector to maximize efficiency. A: You do not specify that you need to add or remove any elements from the list, just keep it sorted. If so, a straightforward flat-file approach - typically using mmap for convenience - will work and be faster than a more generic database. You can use a bsearch to locate the item, or maintain a set of the counts of slots with each value. As you access an item, so the part of the file it is in (think in terms of memory 'pages') gets read into RAM automatically by the OS, and the slot and it's adjacent slots even gets copied into the L1 cache-line. You can do an immediate comparison on it's adjacent slots to see if the increment or decrement causes the item to be out-of-order; if it is, you can use a linear iteration (perhaps augmented with a bsearch) to locate the first/last item with the appropriate count, and then swap them. Managing files is what the OS is built to do.
Q: Multiplying a double value by 100.0 introduces rounding errors? This is what I am doing, which works 99.999% of the time: ((int)(customerBatch.Amount * 100.0)).ToString() The Amount value is a double. I am trying to write the value out in pennies to a text file for transport to a server for processing. The Amount is never more than 2 digits of precision. If you use 580.55 for the Amount, this line of code returns 58054 as the string value. This code runs on a web server in 64-bit. Any ideas? A: You could use decimal values for accurate calculations. Double is floating point number which is not guaranteed to be precise during calculations. A: I'm guessing that 580.55 is getting converted to 58054.99999999999999999999999999..., in which case int will round it down to 58054. You may want to write your own function that converts your amount to a int with some sort of rounding or threshold to make this not happen. A: Try ((int)(Math.Round(customerBatch.Amount * 100.0))).ToString() A: You should really use decimal for money calculations. ((int)(580.55m * 100.0m)).ToString().Dump(); A: My suggestion would be to store the value as the integer number of pennies and take dollars_part = pennies / 100 and cents_part = pennies % 100. This will completely avoid rounding errors. Edit: when I wrote this post, I did not see that you could not change the number format. The best answer is probably using the round method as others have suggested. EDIT 2: As others have pointed out, it would be best to use some sort of fixed point decimal variable. This is better than my original solution because it would store the information about the location of the decimal point in the value where it belongs instead of in the code. A: You really should not be using a double value to represent currency, due to rounding errors such as this. Instead you might consider using integral values to represent monetary amounts, so that they are represented exactly. To represent decimals you can use a similar trick of storing 580.55 as the value 58055. A: no, multiplying does not introduce rounding errors but not all values can by represented by floating point numbers. x.55 is one of them ) A: Decimal has more precision than a double. Give decimal a try. http://msdn.microsoft.com/en-us/library/364x0z75%28VS.80%29.aspx
Q: Windows Workflow Foundation 4.0 connector I'm trying to create a custom activity with multiple connectors using WWF 4.0. Could you tell me how to declare connectors at activity level and register to click event on a flowswitch connector? Thank you A: I'll be going with approach described here
Q: NHibernate - Querying from a collection of Value Types (non-Entity) to solve Select N+1 I have an entity that represents a Tweet from Twitter like so: public class Tweet { public virtual long Id { get; set; } public virtual string Username { get; set; } public virtual string Message { get; set; } // other properties (snip)... public virtual ISet<long> VoterIds { get; protected set; } } I'm trying to run a query in NHibernate that selects a list of tweets with an additional column that denotes whether a particular user by their UserId has voted for each Tweet. When I user votes for a Tweet, it's stored in the 'VoterIds' collection above. I'm using a collection of value Types for this, since I'm only really interested in the Twitter UserId to determine if a user has already voted for a particular tweet. Hence why it's an ISet<long> instead of ISet<Vote> I'm trying to use projections like so: long userId = 123; IList<TweetReport> tweets = Session.CreateCriteria<Tweet>() .SetProjection(Projections.ProjectionList() .Add(Projections.Id(), "Id") .Add(Projections.Property("Username"), "Username") .Add(Projections.Property("Message"), "Message") .Add(Projections.Conditional( //---- WHAT GOES HERE!!?? .SetResultTransformer(Transformers.AliasToBean<TweetReport>()) .List<TweetReport>(); I thought the correct method was to use Projections.Conditional, but I'm not sure how to use it. Can someone help me fill in the //---- WHAT GOES HERE!!?? bit in the above code. I tried using Expressions.In: .Add(Projections.Conditional(Expressions.In("VoterIds", new object[] { userId }), Projections.Constant(true), Projections.Constant(false))) ...but it gave me a 'Cannot use collections with InExpression' error. Please help! Update: I'm beginning to think that it isn't possible to query collections of value types at all, and that I should be using a full-blown entity like so: public virtual ISet<Vote> Votes { get; protected set; } ...would this be the case? A: You can do that, but modifying the domain model to get around a limitation of NHibernate is painful to the soul. It's possible to query value collections with HQL, but ICriteria is really handy for constructing queries with logic. The only way I know how to query value collections using ICriteria is with custom SQL. This is painful also, and ties your code to your database (!), but to me it's the lesser of the three evils. My rationale is that ICriteria will eventually allow this sort of query and the pain can be refactored out later. The trick is to use a subquery in the custom SQL so that a join to the collection table is possible. Using a table alias that won't step on NHibernate aliases is also a good idea (in this case custom_sql_t_v). And note the {alias} and ? placeholders which NHibernate will swap out. Here's an example based on the assumption your Tweet class is mapped something like this... <class name="Tweet" table="Tweet"> <id name="Id" unsaved-value="0"> <generator class="identity"/> </id> <version name="Version" unsaved-value="0"/> <property name="UserName"/> <property name="Message"/> <set name="Votes" table="Tweet_Votes"> <key column="Tweet"/> <element type="Int64" column="Vote"/> </set> </class> Here's the modified query using T-SQL (i.e. Microsoft SQL Server)... IList<TweetReport> tweets = Session.CreateCriteria<Tweet>() .SetProjection(Projections.ProjectionList() .Add(Projections.Id(), "Id") .Add(Projections.Property("UserName"), "UserName") .Add(Projections.Property("Message"), "Message") .Add(Projections.Conditional( Expression.Sql( "EXISTS (SELECT 1 FROM [Tweet_Votes] custom_sql_t_v WHERE custom_sql_t_v.[Tweet] = {alias}.[Id] AND custom_sql_t_v.[Vote] = ?)", userId, NHibernateUtil.Int64), Projections.Constant(true), Projections.Constant(false)), "DidVote")) .SetResultTransformer(Transformers.AliasToBean<TweetReport>()) .List<TweetReport>(); The final SQL generated by NHibernate (I used NHibernate 2.1.2.4000) looks like this... exec sp_executesql N'SELECT this_.Id as y0_, this_.UserName as y1_, this_.Message as y2_, (case when EXISTS (SELECT 1 FROM [Tweet_Votes] custom_sql_t_v WHERE custom_sql_t_v.[Tweet] = this_.[Id] AND custom_sql_t_v.[Vote] = @p0) then @p1 else @p2 end) as y3_ FROM Tweet this_',N'@p0 bigint,@p1 char(1),@p2 char(1)',@p0=123,@p1='Y',@p2='N' The upside of all this is that doing a LIKE against a string collection is possible -- something that I don't think can be done with HQL.
Q: How to calculate the correct image size in out pdf using itextsharp? I' am trying to add an image to a pdf using itextsharp, regardless of the image size it always appears to be mapped to a different greater size inside the pdf ? The image I add is 624x500 pixel (DPI:72): alt text http://www.freeimagehosting.net/uploads/727711dc70.png And here is a screen of the output pdf: alt text http://www.freeimagehosting.net/uploads/313d49044d.png And here is how I created the document: Document document = new Document(); System.IO.MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); document.Open(); System.Drawing.Image pngImage = System.Drawing.Image.FromFile("test.png"); Image pdfImage = Image.GetInstance(pngImage, System.Drawing.Imaging.ImageFormat.Png); document.Add(pdfImage); document.Close(); byte[] buffer = stream.GetBuffer(); FileStream fs = new FileStream("test.pdf", FileMode.Create); fs.Write(buffer, 0, buffer.Length); fs.Close(); Any idea on how to calculate the correct size ? I alreay tried ScaleAbsolute and the image still renders with incorrect dimensions. A: I forget to mention that I' am using itextsharp 5.0.2. It turned out that PDF DPI = 110, which means 110 pixels per inch, and since itextsharp uses points as measurment unit then : * *n pixels = n/110 inches. *n inches = n * 72 points. Having a helper method to convert pixels to points is all I needed: public static float PixelsToPoints(float value,int dpi) { return value / dpi * 72; } By using the above formula and passing a dpi value of 110 it worked perfectly: Note: Since you can create pdf documents in any size you want, this may lead to incorrect scaling when printing out your documents. To overcome this issue all you need to do is to have the correct aspect ratio between width and height [approximately 1:1.4142] (see : Paper Size - The international standard: ISO 216 ). A: Multiply the image's height and width by 72 and divide them by the dpi(ppi): points = pixels * 72 / dpi.
Q: How can I extract the words from this string " !!one!! **two** @@three@@" using Regex in Ruby In IRB, I can do this: c = /(\b\w+\b)\W*(\b\w+\b)\W*(\b\w+\b)\W*/.match(" !!one** *two* @@three@@ ") And get this: => MatchData "one** *two* @@three@@ " 1:"one" 2:"two" 3:"three" But assuming I don't know the number of words in advance, how can I still extract all words out of the string". For example, it might be " !!one** *two* @@three@@ " in one instance, but might be " !!five** *six* " in another instance. Thanks. A: > " !!one** *two* @@three@@ ".scan(/\w+/) => ["one", "two", "three"] Also, scan can return array of arrays in case of using (). > "Our fifty users left 500 posts this month.".scan(/([a-z]+|\d+)\s+(posts|users)/i) => [["fifty", "users"], ["500", "posts"]] http://ruby-doc.org/core/classes/String.html#M000812
Q: RewriteRule question Is there any way i can use RewriteRule to show these links: /articles_history.php /articles_geography.php as /articles/history.html /articles/geography.html I created a .htacesss file on my root directory and would like to know if the above is possible by placing some kind of code in the .htaccess file. A: RewriteEngine On RewriteRule /articles/(.+)\.html /articles_$1.php [L,QSA] A: Yes it is. See http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html In addition to RewriteRule, you also need to usually turn the rewrite engine on by the RewriteEngine directive. A: Try this in your .htaccess: RewriteEngine on RewriteRule ^article/([^/]+)\.html$ articles_$1.php [L] And for an arbitrary input: RewriteEngine on RewriteRule ^([^/]+)/([^/]+)\.html$ $1_$2.php [L]
Q: How widely used is Mono for real-world applications? Followup question to comments here My impression had been that Mono is a science project. Is that inaccurate? Extra credit for recounting personal usage. A: This page on the Mono site lists the applications published using Mono: http://www.mono-project.com/Software Some quite well-known ones include Unity3D, SourceGear Vault and Sims3. A: I built a javascript interpreter/compiler with F# on an Ubuntu workstation and compiled it with Mono! Mono saved me from using Windows to develop my application. A: My impression had been that Mono is a science project. Is that inaccurate? That is correct. A simple Wikipedia search gives details on the Mono project: "Mono is a project created as an entry for Paul Revere High School's 2005 Science Fair, located on the west side of Boston. Although judges responded favorably to the project, it did not win or place in the fair. Its creator, Miguel de Icaza, received a B+ for his entry." A: Mono is not a science project and is used in many real-world applications. It is an implementation of the Common Language Infrastructure ECMA standard. See this list on the mono site. It is used by wikis, SCMs, games, game development environments and many online applications. A: The best example for me is Unity, it uses Mono/C# as it's scripting language. A: completely inaccurate. mono is an implementation of a spec (just like .net is another implementation). its extremely complete and very usable. I'm working on an asp.net mvc project that's being written in monodevelop and running in xsp2 (for now. I will probably set up an apache with mod_mono). I've been a .net/mono guy for about 5-6 years and here are some things I've worked on: * *instrumentation devices that work over gpib/serial/usb to do fiberoptics testing, moving robot arms, etc *networking tools *projects when I was in school in command line, AND in windows forms. *personal projects *image processing tools *monotouch to write iphone apps I also use monodevelop as my main c# development platform. I do have visual studio 2008, but I prefer monodevelop as its lighter and runs on my mac. A: Sure it's a science project. Just like Lisp, the Universal Turing Machine, REST, HTTP 1.1, google, and the basic idea that if we can treat functions as data and vice-versa then it should be possible to create programmable computing machines. Such machines could almost be called "computers" because they would be able to do much the same jobs as computers - the people hired in corporations and govt. departments to do mathematical calculations. Perhaps they'd even open up possibilities of doing things that a team of clerks with slide-rules couldn't do. Starting as a science project doesn't mean the most it can ever achieve is a blue ribbon and an A+. A: Mono is used in a wide of of industries. From gaming (second life) to the embedded industrie. Maybe it started as a science project, mono is doing it good and will be doing it good (a part is that there has not to be paid license money for some part of the use of it (not embedded part although where there has to be paid fees). Probelley some goodscentance to end: the makers of google started that as a university project too. So to be answer quick, NO A: Hey guys! Don't forget Plastic SCM!! Check the screenshots in the gallery. There are other projects but we do the best graphics :P Some of our biggest production servers on big, big companies run Mono/Linux. And some even Mono/Solaris... And we rely on Mono for Mac too, of course.
Q: Passing a float between multiple viewcontrollers Im using tabs to switch between two view controllers. How do I retrieve a float in the secondviewcontroller, thats been initiated in the firstviewcontroller? should i make some sort of global variable? Where and how do I do this? Thanks guys :) A: Global variables are never desirable, I would strongly recommend using some messaging pattern, s.th. SecondViewController and FirstViewController can synchronize whenever they change anything of interest to the other. On first glance, I only found this guideline http://www.informit.com/articles/article.aspx?p=1398611 telling about messaging-patterns in cocoa, I guess there will already be sample-implementations for iPhone floating around. A: Use AppDelegate For This +(BOOL)SetData:(float)Value { GlobalValue=Value; } +(float)ReturnData { return GlobalValue; } and Call like This [YourAppDelegate ReturnData]; A: You could make that variable a property of your app delegate, which would be accessible from anywhere within your app. If you don't want that for whatever reason, you could create a "helper" singleton to keep such variables and make them properties again.
Q: Where can I find a list of all possible messages that an XmlException can contain? I'm writing an XML code editor and I want to display syntax errors in the user interface. Because my code editor is strongly constrained to a particular problem domain and audience, I want to rewrite certain XMLException messages to be more meaningful for users. For instance, an exception message like this: '"' is an unexpected token. The expected token is '='. Line 30, position 35 .. is very technical and not very informative to my audience. Instead, I'd like to rewrite it and other messages to something else. For completeness' sake that means I need to build up a dictionary of existing messages mapped to the new message I would like to display instead. To accomplish that I'm going to need a list of all possible messages XMLException can contain. Is there such a list somewhere? Or can I find out the possible messages through inspection of objects in C#? Edit: specifically, I am using XmlDocument.LoadXml to parse a string into an XmlDocument, and that method throws an XmlException when there are syntax errors. So specifically, my question is where I can find a list of messages applied to XmlException by XmlDocument.LoadXml. The discussion about there potentially being a limitless variation of actual strings in the Message property of XmlException is moot. Edit 2: More specifically, I'm not looking for advice as to whether I should be attempting this; I'm just looking for any clues to a way to obtain the various messages. Ben's answer is a step in the right direction. Does anyone know of another way? A: Technically there is no such thing, any class that throws an XmlException can set the message to any string. Really it depends on which classes you are using, and how they handle exceptions. It is perfectly possible you may be using a class that includes context specific information in the message, e.g. info about some xml node or attribute that is malformed. In that case the number of unqiue message strings could be infinite depending on the XML that was being processed. It is equally possible that a particular class does not work in this way and has a finite number of messages that occur under specific circumstances. Perhaps a better aproach would be to use try/catch blocks in specific parts of your code, where you understand the processing that is taking place and provide more generic error messages based on what is happening. E.g. in your example you could simply look at the line and character number and produce an error along the lines of "Error processing xml file LineX CharacterY" or even something as general as "error processing file". Edit: Further to your edit i think you will have trouble doing what you require. Essentially you are trying to change a text string to another text string based on certain keywords that may be in the string. This is likely to be messy and inconsistent. If you really want to do it i would advise using something like Redgate .net Reflector to reflect out the loadXML method and dig through the code to see how it handles different kinds of syntax errors in the XML and what kind of messages it generates based on what kind of errors it finds. This is likely to be time consuming and dificult. If you want to hide the technical errors but still provide useful info to the user then i would still recomend ignoring the error message and simply pointing the user to the location of the problem in the file. A: Just my opinion, but ... spelunking the error messages and altering them before displaying them to the user seems like a really misguided idea. First, The messages are different for each international language. Even if you could collect them for English, and you're willing to pay the cost, they'll be different for other languages. Second, even if you are dealing with a single language, there's no way to be sure that an external package hasn't injected a novel XmlException into the scope of LoadXml. Last, the list of messages is not stable. It may change from release to release. A better idea is to just emit an appropriate message from your own app, and optionally display -- maybe upon demand -- the original error message contained in the XmlException.
Q: how to find out if a checkbox is checked in jQuery is there a simple way to find out if a checkbox is checked in jquery. something like .checked or ischecked A: el.is(':checked') That's the jQuery way. At its core, though, it's just a bit more parsing to get down to el[0].checked, using the raw DOM property, so take whichever you prefer. The DOM method is probably better for actually testing an element, whereas :checked is better for selecting it in the first place.
Q: Does a page that uses OpenID for login need to be served over https? A site that uses username/password for users to log in obviously needs that login process to run over https. Does the same apply when only using OpenID, or is the provider using https enough to ensure security? A: Everything still must be HTTPS to be secure. Otherwise an attacker can intercept the OpenID string the user provides and replace it with their own malicious OpenID server. That would be bad, and trick all but the most savvy users into entering their password into the wrong server. They could even replace your referral to the client with one to the real OpenID server, and let the client (ineffectually) log in before returning to your site... If they do this, they don't get to steal the user's password, but they still get to have a backdoor into their account. Perhaps more importantly, if you're not using HTTPS, the session cookies you send aren't secure. So an attacker can just wait until a user is logged in, and then steal their session.
Q: How to represent the following data in XML? How to represent the following data in XML format? commandA ( a | b | c ) position = pos [(m | n | o )] [space = space] [(m|n|o)] [option1] [option2 = "Hello"] [option3] Note: [ ] --> denotes optional, ( ) --> denotes mandatory | --> denotes anyone of the value Eg: commandA a position = 1.0<m> space = 2.0<n> option1 option2="Hello" How to effectively represent this data in xml? I tried something like this, <command name="commandA" position = "position" > <option name="option1"/> <option name="option2" value = "Hello"/> <option name="option3"/> </command> But how to handle the command value i.e a|b|c and position i.e m|n|o ? EDIT: Command: Syntax: commandA (a|b|c) pos=0[w|x|y|z] [spa=0.0[w|x|y|z]] [str="Hello"] commandA a pos=0w spa=0.0z str="Hello" I tried something like this, <command name="commandA"> <direction> <direction name="a"/> <direction name="b"> <direction name="c"/> </direction> <parameter> <position value="pos=0" /> <spacing value="spa=0.0" /> <options> <option name="w"/> <option name="x"/> <option name="y"/> <option name="z"/> </options> </parameter> <string value="str=" /> </command> Any suggestions on this? A: How about something like this. It combines tags to guide the autocompletion, along with tags for the command DOM: <ac:autocomlete> <command> <command-name>commandA</command-name> <separator> </separator> <ac:choice> <command-type>a</command-type> <command-type>b</command-type> <command-type>c</command-type> </ac:choice> <separator> </separator> <pos> <pos-text>pos=</pos-text> <pos-value><ac:match regex="\d+"/></pos-value> <ac:optional> <ac:choice> <pos-unit>w</pos-unit> <pos-unit>x</pos-unit> <pos-unit>y</pos-unit> <pos-unit>z</pos-unit> </ac:choice> </ac:optional> </pos> <ac:optional> <spa-separator> </spa-separator> <spa> <spa-text>spa=</spa-text> <spa-value><ac:match regex="\d+\.\d+"/></spa-value> <ac:optional> <ac:choice> <spa-unit>w</spa-unit> <spa-unit>x</spa-unit> <spa-unit>y</spa-unit> <spa-unit>z</spa-unit> </ac:choice> </ac:optional> </spa> </ac:optional> <ac:optional> <arg-separator> </arg-separator> <arg-name>str=</arg-name> <arg-value><ac:match regex='"[^"]*"'/></arg-value> </ac:optional> </command> </autocomlete> The autocompletion code matches literal element text exactly once, unless it is contained in a choice or optional tag, which changes the behavior accordingly. I've put these autocomplete tags in a separate namespace, to separate what the auto-complete code recognises, and what is the DOM, although you don't have to maintain a separate namespace if you don't want to. The match tag matches/completes text according to a regular expression. When building the DOM, the match tags are replaced with the literal text that was entered. The auto-complete tags tell the auto-completion how to deal with child tags. The names of the child tags are arbitrary and are not used by auto-completion, but can be used in building a DOM for your command that the user has typed in: once the auto-complete has built the model, and auto-complete tags removed, what remains is a DOM for the command the user typed in. A: <command value="a"> <position type="m">1.0</position> <space type="m">2.0</space> <option1 /> <option2>Hello</option2> <option3 /> </command> Is that what you're looking for? Or do you want a DTD?
Q: WPF Combobox binding clears value only on first click I'm working on a wpf c# app, I have a combobox which is binded to an xml value of a selected item of a list box. Here is the code for the combobox: <ComboBox Margin="164.301,268.036,8,0" VerticalAlignment="Top" ToolTip="Cue trigger" DataContext="{Binding SelectedItem, ElementName=listBox_Copy}" SelectedValue="{Binding XPath=Type}" Style="{DynamicResource CUE_StyleCombo}" SelectedValuePath="Content" SelectionChanged="Save"> <ComboBoxItem Content="go"/> <ComboBoxItem Content="follow direct"/> <ComboBoxItem Content="follow after"/> </ComboBox> Now when starting the program, I click an item of the listbox, the value to which is the combobox is binded is set to zero! Only on this first click. How can I solve this? Elaboration: // On startup : <Trigger>go</Trigger> // Clicked a random item within the listbox <Trigger></Trigger>
Q: Erasing components on Canvas The problem is when background of top or below label is changed, the top or below button is erased. <mx:Canvas width="100%" height="100%"> <mx:LinkButton icon="{icon1}" width="25" x="10" y="10"/> <mx:LinkButton icon="{icon2}" width="25" x="10" y="100" /> <s:VGroup width="100%" height="100%" id="lst" click="highlight(event.target as Label)" gap="0"> <s:Label /> <s:Label /> <s:Label selected="true" /> <s:Label /> <s:Label creationComplete="fillList()"/> </s:VGroup> </mx:Canvas> private function highlight(label:Label):void { setStyle("backgroundColor", "#DDDDDD"); } So do anyone know the possible solution for this problem? A: You are sitting the VGroup on top of the buttons, so when you fill the background of a label, its obscuring the button. If you reorder the components so that the buttons are sitting on top of the VGroup, this won't happen. Literally put the VGroup before the buttons in the list of children in the Canvas.
Q: How do I build a page preloader for a php page? I want to include a page preloader for all pages on my application. Something like what Gmail displays when its loading the entire page in the background. I don't want a prelaoding bar just the mechanism to display immediately a preloading message while the entire page loads in the background and upon successful load is displayed. Take for an example the site: http://www.emirates.com/ae/english/ just run a search for any flight - you see a preloading message after which teh page is loaded. I don't see any redirects here. How do I implement this - my site is built using php and tonnes of javascript. A: I would use a wrapper DIV element for all the content of your <body> element and hide it via CSS visibility property. Did work with javascript and at the end I would display the DIV element. The preloader would be absolutely positioned and hiden when DIV element would be displayed. Visibility property has the advantage that the layout will be ready when you change it to value visible (not as with the property display) EDIT: I think that you can almost always avoid pre-loaders. You can speed up your sql queries by indexes. Display less results and so on. I personally don't like to wait and preloader doesn't comfort me much. A: Your HTML writes out a pre-loading message, and you then set up a javascript onload event. This event calls JavaScript code to load whatever data you need via AJAX, then finally hide the loading message and shows the actual page. Of course, this means people with no JavaScript will have problems - you have to sort something for them or decide you can live without them. ADD: Oh, and you may want to check the disability laws in your country before deciding you can live without them - you may have a legal responsibility to make your site accessible to the disabled. I've only ever used this technique on sites that rely on JS so heavily they can't run without it. Note GMail has 2 interfaces - one JS and one plain HTML. This is how they make their service accessible. ADD: http://code.google.com/p/bobchess/ is some code I've done that does this. A loading message and then an onload event to start the application. A: I agree with MartyIX but the problem is the number of queries your system can handle, indexing is an option but it depends on volume of transactions on your servers. I do think we missed the whole point though, pre-loaders we meant to beautify the site, so the customers don't see ugly blank page while they wait :)
Q: Help making a singly linked list in Java This is for homework but please know that I have looked online for help (such as http://www.sethi.org/classes/class_stuff/cis435/others/notes-java/data/collections/lists/simple-linked-list.html) and my textbook but I am still having some issues. Any help would be appreciated... Right now I'm trying to just insert values in but nothing is working. Whether it's the first item, whether it's being added as the last one, or somewhere in between. Node header = null; // First element of list. Node back = null; // Last element of list. public void insert(int i, double value){ //insert value before i-th element Node e = new Node(); e.num = value; Node curr = header; for(int x=0;x<i;x++) { if (i == 1) { //we want to insert as first thing if (size == 0) { //its the FIRST time we add something header.next = e; e.next = back; break; } else if (size == 1){ e.next = header.next; //i.e. the second thing in the list header.next = e; break; } else { e.next = header.next.next; //i.e. the second thing in the list header.next = e; break; } } else if (x == (i-1)) { e.next = curr.next; curr.next = e; break; } curr = curr.next; } size = size+1; } Not really sure why it isn't working. Thanks! A: For some reason, people who are still learning to program make things far more complicated then they need to be. I did it when I was learning java, I still do it when I am just getting into a new language, and students that I have marked find new and amazing ways to do it. You have more going on in your insert then there needs to be, for example, a method that inserts a value at a specific index should not check if it's the first item to be inserted (not saying it shouldn't check bounds). Here is the pseudo code of what I would do. insert(index, value) if index>size throw null pointer traverse to index -1 //lets call this nodeI create newnode and set value set newnode.next to nodeI.next set nodeI.next to newnode increase size. Couple of handy hints for you, you should have a function to get an element from the link list, something that returns a node? public node elementAt(int index) for example? use that to traverse the linked list. If you want to append to the Linked list, try this append(value) insert(size-1,value) and if you want to insert at the beginning? same idea insert(value) insert(0,value) A: A few suggestions: * *implement java.util.List *Think about generics *Read this. Start with "insert at the end" before you think about "insert at i". A: * *In the line e.next = header.next.next what would happen if header.next points to a 'null'? Is it possible to get there? *What are the corner cases you have to deal with and have you taken them all into account? *Can you start with the simplest case first, adding either an element to the front or an element to the back? Then use those functions to implement the insert? A: I have tried a simple program, which will be useful for you guys, I am also learning Java, please bear with me for any mistakes, but this program works fine. I am posting a very simple singly linked list program in Java, which I tried out today. I hope it will help all. LinkList.java class LinkList { public static void main(String args[]) { Node node = new Node(1); node.addAtLast(2); node.addAtLast(3); node.addAtLast(4); node.addAtLast(5); node.printList(); } } Node.java class Node { private int data; private Node link; public Node(int mydata) { data = mydata; link = null; } public void printList() { System.out.print("|"+data+"|"+"->"); if(link != null) { //recursive call link.printList(); } else { //marking end of list as NULL System.out.print("|NULL|"); } } public void addAtLast(int mydata) { if(link == null) { link = new Node(mydata); } else { link.addAtLast(mydata); } } } OUTPUT : The below is our output |1|->|2|->|3|->|4|->|5|->|NULL|
Q: Is there a way to apply a mask to the textbox of a DatePicker? I'm working on my first WPF app. In this case, using VS 2010. My users are used to typing the date like this: "09082010" (without the double quotes; this would represent today). After they enter that, then it gets converted to 9/8/2010. I've put the DatePicker control onto the WPF page, but if the user enters 09082010, then it doesn't recognize it as a date and ignores it. I've applied a IValueConverter, to no effect, again because it doesn't recognize "09082010" as a date. So, I'm wondering, is it possible to apply a mask to the textbox of the DatePicker in VS 2010, so that when a user enters 09082010 it will change that to 09/08/2010 (at least)? A: Here's something you could probably do: handle the TextBox.TextChanged event in the DatePicker, then in the event handler, put your custom logic to parse the current text. Something like this: <DatePicker x:Name="dp" TextBoxBase.TextChanged="DatePicker_TextChanged"/> private void DatePicker_TextChanged(object sender, TextChangedEventArgs e) { DateTime dt; DatePicker dp = (sender as DatePicker); string currentText = (e.OriginalSource as TextBox).Text; if (!DateTime.TryParse(currentText, out dt)) { try { string month = currentText.Substring(0,2); string day = currentText.Substring(2,2); string year = currentText.Substring(4,4); dt = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day)); dp.SelectedDate = dt; } catch (Exception ex) { dp.SelectedDate = null; } } } I know it ain't pretty. But this could be a start.
Q: Google App Engine w/ Django - InboundMailHandler appears to only work once I'm writing an app for Google App Engine (with Python and Django) that needs to receive email and add some elements of the received email messages to a datastore. I am a very novice programmer. The problem is that the script I specify to handle incoming email appears to only run once (until the script is touched). Sending a test email from the local admin console to, say, 'test@downloadtogo.appspotmail.com' causes an entity to be added to the local datastore correctly. Sending a second, third, etc. test email has no effect - the entity is not added. 'Touching' handle_incoming_email.py (which I understand to mean adding or deleting a space and then saving), then sending another test email, will cause the entity to be added correctly. app.yaml: application: downloadtogo version: 1 runtime: python api_version: 1 handlers: - url: /static static_dir: static - url: /.* script: main.py - url: /_ah/mail/.+ script: handle_incoming_emaril.py login: admin inbound_services: - mail handle_incoming_email.py: from downloadtogo.models import Email import logging, email import wsgiref.handlers import exceptions from google.appengine.api import mail from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.webapp.mail_handlers import InboundMailHandler class MailHandler(InboundMailHandler): def receive(self, message): email = Email() email.from_address = message.sender email.put() def main(): application = webapp.WSGIApplication([MailHandler.mapping()], debug=True) wsgiref.handlers.CGIHandler().run(application) main() models.py: from appengine_django.models import BaseModel from google.appengine.ext import db class Email(db.Model): from_address = db.StringProperty() to_address = db.StringProperty() body = db.StringProperty(multiline=True) added_on = db.DateTimeProperty(auto_now_add=True) A: Handlers are matched in order. .* matches any request, so the email handler will never match at all. Put .* last.
Q: open other activity from view How to open activity from view? I am develop a game if game is over I need to move user to main menu activity. A: Thank you all. i got solution myself. Activity activity=(Activity)this; i passed this activity object to my view and then i have done activity.finish();
Q: Variable row size list field in blackberry I have created an application that contains a list field(custom) If a certain condition is satisfied I want rowheight to be 100, else it should be 50 How can I do that? I tried setRowHeight(index,size); But it didn't work. Moreover it's undocumented to. A: i did some manipulations in the drawListRow method of the custom list field and i could make a list field with variable row size if(mycondition==true) setRowHeight(50); else setRowHeight(100); also in drawrow method i wrote layout(width, 100); and it worked for me.... but i m still testing it to check whether it works on all devices and in all conditions and may be some body else help me to make it better!!!!!
Q: Why is There A Need to Separate "Edit"(update) and "Add"(insert) actions in most CMS? the CMS our chief coder designed has the update/insert actions handled by one controller. Most of the CMS's I see has separate handlers for update and insert. Why are most CMS's designed this way? Even the REST pattern has separate actions for update and insert (I don't know what they're exactly called though). A: Probably because it's two of the four basic CRUD operations found in user interfaces. It's more intuitive, easier and safer to perform a single "Edit" operation on data than performing a "Remove" operation then an "Add" operation. A: Depending on how the data is persisted, an "update" will not change the identity/primary key, while a remove/insert combination could result in a new identity/primary key. If that primary key is referenced elsewhere (say, in a URL), then that reference will no longer work.
Q: Weird behaviour with lxml getiterator() I have the following XML document: <x> <a>Some text</c> <b>Some text 2</b> <c>Some text 3</c> </x> I want to get the text of all the tags, so I decided to use getiterator(). My problem is, it adds up blank lines for a reason I can't understand. Consider this: >>> for text in document_root.getiterator(): ... print text.text ... Some text Some text 2 Some text 3 Notice the two extra blank lines before 'Some text'. What is the reason for this? If I pass a tag to the getiterator() method, there are no blank lines, as it should be. >>> for text in document_root.getiterator('a'): ... print text.text ... Some text So my question is, what is causing those extra blank lines in case I pass getiterator() without a tag and how do I remove them? A: By default lxml.etree will regard empty text between tags as the textual content for that tag and in your case the whitespace being displayed comes from <x>. If you want a parser that ignores the whitespace you'll want to do something like: from lxml import etree parser = etree.XMLParser(remove_blank_text=True) tree = etree.XML("""\ <x> <a>Some text</a> <b>Some text 2</b> <c>Some text 3</c> </x> """, parser) for node in tree.iter(): if node.text == None: continue print node.text Note how node.text will return None if there is no text at all. Also note that the API documentation for lxml states that getiterator() is deprecated in favor of iter(). For more information see The lxml.etree Tutorial: Parser objects. A: Although Im not sure, I would assume it's trying to read text within < x >. Anyhow, what's wrong with for text in document_root.getiterator(): if text.strip() == '': continue print text
Q: git: Apply changes introduced by commit in one repo to another repo I have a repo1 and repo2 on local machine. They are very similar, but the latter is some kind of other branch (repo1 is not maintained anymore). /path/to/repo1 $ git log HEAD~5..HEAD~4 <some_sha> Add: Introduce feature X How to apply changes made by commit <some_sha> in repo1 to repo2? Do I need to prepare some patch, or is it possible to do some cherry-pick between the repos? How about doing the same but for range of commits? A: I wrote a small script for applying the diff output of repo diff https://github.com/raghakh/android-dev-scripts/commit/a57dcba727d271bf2116f981392b0dcbb22734d0 A: As a hack, you can try modifying recipe for comparing commits in two different repositories on GitTips page, i.e.: GIT_ALTERNATE_OBJECT_DIRECTORIES=../repo/.git/objects \ git cherry-pick $(git --git-dir=../repo/.git rev-parse --verify <commit>) where ../repo is path to the other repository. With modern Git you can use multiple revisions and revision ranges with cherry-pick. The $(git --git-dir=../repo/.git rev-parse --verify <commit>) is here to translate <commit> (for example HEAD, or v0.2, or master~2, which are values in the second repository you copy from) into SHA-1 identifier of commit. If you know SHA-1 of a change you want to pick, it is not necessary. NOTE however that Git can skip copying objects from source repository, as it doesn't know that the alternate object repository is only temporary, for one operation. You might need to copy objects from the second repository with: GIT_ALTERNATE_OBJECT_DIRECTORIES=../repo/.git/objects git repack -a -d -f This puts those objects borrowed from second repository in original repository storage Not tested. A not so hacky solution is to follow knittl answer: * *Go to second repository you want to copy commits from, and generate patches from commits you want with git format-patch *Optionally, copy patches (0001-* etc.) to your repository *Use git am --3way to apply patches A: You probably want to use git format-patch and then git am to apply that patch to your repository. /path/to/1 $ git format-patch sha1^..sha1 /path/to/1 $ cd /path/to/2 /path/to/2 $ git am -3 /path/to/1/0001-…-….patch Or, in one line: /path/to/2 $ git --git-dir=/path/to/1/.git format-patch --stdout sha1^..sha1 | git am -3 A: You can do cherry-pick if you add the second repo as a remote to the first (and then fetch).
Q: Python or SQL Logistic Regression Given time-series data, I want to find the best fitting logarithmic curve. What are good libraries for doing this in either Python or SQL? Edit: Specifically, what I'm looking for is a library that can fit data resembling a sigmoid function, with upper and lower horizontal asymptotes. A: If your data were categorical, then you could use a logistic regression to fit the probabilities of belonging to a class (classification). However, I understand you are trying to fit the data to a sigmoid curve, which means you just want to minimize the mean squared error of the fit. I would redirect you to the SciPy function called scipy.optimize.leastsq: it is used to perform least squares fits.
Q: a fairly complex django query I've got class Supplier(Model) : pass class Customer(Model) : pass class Dock(Model) : pass class SupplierDockAccess(Model) : supplier = ForeignKey(Supplier) dock = ForeignKey(Dock) class SupplierCustomerAccess(Model): supplier = ForeignKey(Supplier) customer = ForeignKey(Customer) I have an instance of Customer, and I'd like to get all Docks that the customer has access to. Customers have access to Suppliers via SupplierCustomerAccess, and Suppliers have access to Docks via SupplierDockAccess. I can do it like so: # get the suppliers the customer has access to supplier_customer_accesses = SupplierCustomerAccess.objects.filter(customer=customer) suppliers = [s.supplier for s in supplier_customer_accesses] # get the docks those suppliers have access to supplier_dock_accesses = SupplierDockAccess.objects.filter(supplier__in=suppliers) docks = [s.dock for s in supplier_dock_accesses] ... but then the resulting list of docks contains duplicates, and I really think it oughtta be possible to do it in one go. Anyone feel like demonstrating some mighty django-fu? A: Alright, I figured it out. One of those things where talking about it seems to do the trick: docks = Dock.objects.filter(supplierdockaccess__supplier__suppliercustomeraccess__customer=customer).distinct() ...and looking at the sql, it does indeed do it in one big join. Nice. Sorry about answering my own question. A: Easiest way I can think of to do this is a combination of ManyToManyFields and a custom QuerySet/Manager. from django.db import models class CustomQuerySetManager(models.Manager): """ Class for making QuerySet methods available on result set or through the objects manager. """ def get_query_set(self): return self.model.QuerySet(self.model) def __getattr__(self, attr, *args): try: return getattr(self.__class__, attr, *args) except AttributeError: return getattr(self.get_query_set(), attr, *args) class Customer(models.Model): suppliers = models.ManyToManyField(through=SupplierCustomerAccess) objects = CustomQuerySetManager() class QuerySet(QuerySet): def docks(self): return Dock.objects.filter( supplierdockaccess__supplier__in=self.suppliers ).distinct() ... class Supplier(models.Model): docks = models.ManyToManyField(through=SupplierDockAccess) ... You should see only one or two hits to the database (depending on if you used select_related when you got your customer), and your code is insanely clean: docks = customer.docks() suppliers = customer.suppliers.all() ...
Q: Expression Equals So, I'm trying to figure out Expression trees. I'm trying to add in a dynamic equals to a Queryable where T is one of several different tables. I'm first checking the table contains the field I want to filter on. ParameterExpression param = Expression.Parameter(typeof(TSource), "x"); Expression conversionExpression = Expression.Convert(Expression.Property(param, _sourceProperty), typeof(TList)); Expression<Func<TSource, TList>> propertyExpression = Expression.Lambda<Func<TSource, TList>>(conversionExpression, param); Expression<Func<TList, TList, bool>> methodExpression = (x, y) => x.Equals(y); ReadOnlyCollection<ParameterExpression> parameters = propertyExpression.Parameters; InvocationExpression getFieldPropertyExpression = Expression.Invoke( propertyExpression, parameters.Cast<Expression>()); MethodCallExpression methodBody = methodExpression.Body as MethodCallExpression; MethodCallExpression methodCall = Expression.Call(methodBody.Method, Expression.Constant(equalTo), getFieldPropertyExpression); Expression<Func<TSource, bool>> equalsStatement = Expression.Lambda<Func<TSource, bool>>(methodCall, parameters); return source.Where(equalsStatement); When I execute this, I get an issue with the MethodInfo in the Call statement. It tells me; Static method requires null instance, non-static method requires non-null instance. I'm no master of Expression trees, but I think I understand about 75% of what I'm doing here and know what I'm trying to achieve. The TList is a bad name right now, but I took this from an example that works to produce an In statement just fine. I'm really looking for an explanation here so I can work through the code myself, or a solution with an explanation of what I was missing. Edit: Ok, so after a very frustrating afternoon and still not quite feeling like I understand what I'm looking at entirely, I think I have an answer. ParameterExpression sourceObject = Expression.Parameter(typeof(TSource), "x"); Expression<Func<TSource, bool>> check = Expression.Lambda<Func<TSource, bool>> ( Expression.Equal( Expression.MakeMemberAccess(sourceObject, typeof(TSource).GetProperty(_sourceProperty)), Expression.Constant(equalTo) ), sourceObject ); return source.Where(check); Is anybody able to explain to me why the original just wasn't fit for what I was trying to do? I want to understand more about the actual process, but I feel I'm not picking it up as fast as I would like. A: Expression.Call has two sets of overloads (with lots of overloads in each). One set is for instance methods and the other set is for static methods. In those for static methods, the first argument is a MethodInfo object -- exactly like you have. For instance methods, the first argument should be an Expression representing the target (i.e. the left-hand-side of the "." in a method call.) Given the error you are receiving, it sounds like the MethodInfo represents a non-static method, and therefore you must provide an expression representing the instance as the first argument.
Q: Windows cli tool to monitor semaphores? In Windows, is there a tool to view semaphores from the command line? SysInternals "Process Explorer" does a great job from a gui, and the SysInternals "handle.exe" view handles from the command line, but I've not found anything to enumerate semaphores from the command line? A: handle.exe -s -p [processid] will give the number of semaphores for that process id. Here is the output of handle.exe -s -p 388 where 388 is the process id of a Chrome tab I have running. Handle v3.51 Copyright (C) 1997-2013 Mark Russinovich Sysinternals - www.sysinternals.com Handle type summary: ALPC Port : 2 Desktop : 1 Directory : 4 EtwRegistration : 25 Event : 37 File : 14 IoCompletion : 2 Key : 7 KeyedEvent : 1 Mutant : 4 Section : 14 Semaphore : 27 Thread : 16 Timer : 1 TpWorkerFactory : 8 WindowStation : 2 Total handles: 165 handle.exe -a -p [processid] will list all the handles with their types; you could use something like grep: handle.exe -a -p 388 | grep Semaphore to get output like this: 20C: Semaphore 210: Semaphore 218: Semaphore 21C: Semaphore 220: Semaphore
Q: Web log file analysis software to measure search crawlers I need to analyze the search engine crawling going on in my site. Is there a good tool for this? I've tried AWStats and Sawmill. But both of those give me very limited insight into the crawling. I need to know information like how many unique/distinct webpages in a section of my site was crawled by a specific crawler within a time period. Google analytics doesn't track crawling at all due to its javascript tracking mechanism. A: Upon following a link to the first page of your Site, the major Search Engine crawlers will first request a file called robots.txt which of course tells the search crawler which pages it is permitted by the Site owner to visit and which files or directories are off limits. What if you don't have a robots.txt? Nearly always, the crawler 'interprets' this to mean that no pages/directories are off limits and it will proceed to crawl your entire Site. So why include a robots.txt file if that's what you want--i.e., for the crawler to index your entire Site? Because if it's there, the Crawler will nearly always request it so it can read it--this request of course shows up as a line in your server access log file, which is a pretty strong signature for a Crawler. Second, a good server access log parser such as Webalyzer or Awstats. compare user agent and ip addresses against published, authoritative lists: IAB (http://www.iab.net/sites/spiders/login.php) and the user-agents.org publish the two lists that seem to be the most widely used for this purpose. The former is a few thousand dollars per year and up; the latter is free. Both Webalyzer and AWStats can do what you want, though i recommend AWStats for the following reasons: it was updated fairly recently (approx. one year ago) while Webalyzer was last updated over eight years ago. In addition, AWStats has much nicer report templates. The advantage of Webalyzer is that is is much faster. Here's sample output from AWStats (based on out-of-the-box config) that is probably what you are looking for:
Q: Different application settings depending on configuration mode Is anyone aware of a way that I can set application (or user) level settings in a .Net application that are conditional on the applications current development mode? IE: Debug/Release To be more specific, I have a url reference to my webservices held in my application settings. During release mode I would like those settings to point to http://myWebservice.MyURL.com during debug mode I would love those settings to be http://myDebuggableWebService.MyURL.com. Any ideas? A: There is, as far as I know, no built in way of doing this. In our project we maintain 4 different settings files, and switch between them by copying each into the active file in the prebuild step of the build. copy "$(ProjectDir)properties\settings.settings.$(ConfigurationName).xml" "$(ProjectDir)properties\settings.settings" copy "$(ProjectDir)properties\settings.designer.$(ConfigurationName).cs" "$(ProjectDir)properties\settings.Designer.cs" This has worked flawlessly for us for a few years. Simply change the target and the entire config file is switched as well. Edit: The files are named e.g. settings.settings.Debug.xml, settings.settings.Release.xml etc.. Scott Hanselman has described a slightly 'smarter' approach, the only difference is that we don't have the check to see if the file has changed: http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx A: If you want to keep everything in one configuration file you can introduce a custom configuration section to your app.settings to store properties for debug and release modes. You can either persist the object in your app that stores dev mode specific settings or override an existing appsetting based on the debug switch. Here is a brief console app example (DevModeDependencyTest): App.config : <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="DevModeSettings"> <section name="debug" type="DevModeDependencyTest.DevModeSetting,DevModeDependencyTest" allowLocation="true" allowDefinition="Everywhere" /> <section name="release" type="DevModeDependencyTest.DevModeSetting,DevModeDependencyTest" allowLocation="true" allowDefinition="Everywhere" /> </sectionGroup> </configSections> <DevModeSettings> <debug webServiceUrl="http://myDebuggableWebService.MyURL.com" /> <release webServiceUrl="http://myWebservice.MyURL.com" /> </DevModeSettings> <appSettings> <add key="webServiceUrl" value="http://myWebservice.MyURL.com" /> </appSettings> </configuration> The object to store your custom configuration (DevModeSettings.cs): using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; namespace DevModeDependencyTest { public class DevModeSetting : ConfigurationSection { public override bool IsReadOnly() { return false; } [ConfigurationProperty("webServiceUrl", IsRequired = false)] public string WebServiceUrl { get { return (string)this["webServiceUrl"]; } set { this["webServiceUrl"] = value; } } } } A handler to access your custom configuration settings (DevModeSettingsHandler.cs) : using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; namespace DevModeDependencyTest { public class DevModeSettingsHandler { public static DevModeSetting GetDevModeSetting() { return GetDevModeSetting("debug"); } public static DevModeSetting GetDevModeSetting(string devMode) { string section = "DevModeSettings/" + devMode; ConfigurationManager.RefreshSection(section); // This must be done to flush out previous overrides DevModeSetting config = (DevModeSetting)ConfigurationManager.GetSection(section); if (config != null) { // Perform validation etc... } else { throw new ConfigurationErrorsException("oops!"); } return config; } } } And finally your entry point to the console app (DevModeDependencyTest.cs) : using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; namespace DevModeDependencyTest { class DevModeDependencyTest { static void Main(string[] args) { DevModeSetting devMode = new DevModeSetting(); #if (DEBUG) devMode = DevModeSettingsHandler.GetDevModeSetting("debug"); ConfigurationManager.AppSettings["webServiceUrl"] = devMode.WebServiceUrl; #endif Console.WriteLine(ConfigurationManager.AppSettings["webServiceUrl"]); Console.ReadLine(); } } } A: SlowCheetah adds the functionality you ask for not only for App.config but for any XML file in your project - http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5 A: This is somewhat late to the party, but I stumbled upon a nice way of implementing the web.transform approach for app.config files. (i.e. it makes use of the namespace http://schemas.microsoft.com/XML-Document-Transform) I think it is "nice" because it is a pure xml approach and doesn't require 3rd party software. * *A parent / default App.config file is descended from, according to your various build configurations. *These descendants then only override what they need to. In my opinion this is much more sophisticated and robust than having to maintain x number of config files which get copied in their entirety, such as in other answers. A walkthrough has been posted here: http://mitasoft.wordpress.com/2011/09/28/multipleappconfig/ Look, Mom - No explicit post-build events in my IDE! A: I know this was asked years ago, but just in case anyone is looking for a simple and effective solution that I use. * *Go to project properties, Settings tab (you'll see your web service URL or any other settings already listed here). *Click the "View Code" button available on the Settings page. *Type this in the constructor. this.SettingsLoaded += Settings_SettingsLoaded; *Add the following function under the constructor: void Settings_SettingsLoaded(object sender, System.Configuration.SettingsLoadedEventArgs e) { #if(DEBUG) this["YOUR_SETTING_NAME"] = VALUE_FOR_DEBUG_CONFIGURATION; #else this["YOUR_SETTING_NAME"] = VALUE_FOR_RELEASE_CONFIGURATION; #endif } Now whenever you run your project, it will compile only the line that matches the current build configuration. A: I had a similar problem to solve and ended up using the XDT (web.config) transform engine, that was already suggested in the answer from ne1410s that can be found here: https://stackoverflow.com/a/27546685/410906 But instead of doing it manually as described in his link I used this plugin: https://visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859 The plugin is only helping to setup the configuration, it's not needed to build and the solution can be built on other machines or on a build server without the plugin or any other tools being required.
Q: PHP external page Want to grab list of players from http://www.atpworldtour.com/Rankings/Singles.aspx There is a table with class "bioTableAlt", we have to grab all the <tr> after the first one (class "bioTableHead"), which is used for table heading. Wanted content looks like: <tr class="oddRow"> <td>2</td> <td> <a href="/Tennis/Players/Top-Players/Novak-Djokovic.aspx">Djokovic, Novak</a> (SRB) </td> <td> <a href="/Tennis/Players/Top-Players/Novak-Djokovic.aspx?t=rb">6,905</a> </td> <td>0</td> <td> <a href="/Tennis/Players/Top-Players/Novak-Djokovic.aspx?t=pa&m=s">21</a> </td> </tr> <tr> <td>3</td> <td> <a href="/Tennis/Players/Top-Players/Roger-Federer.aspx">Federer, Roger</a> (SUI) </td> <td> <a href="/Tennis/Players/Top-Players/Roger-Federer.aspx?t=rb">6,795</a> </td> <td>0</td> <td> <a href="/Tennis/Players/Top-Players/Roger-Federer.aspx?t=pa&m=s">21</a> </td> </tr> I think the best idea is to create an array(), make each <tr> an unique row and throw final code to the list.txt file, like: Array ( [2] => stdClass Object ( [name] => Djokovic, Novak [country] => SRB [rank] => 6,905 ) [3] => stdClass Object ( [name] => Federer, Roger [country] => SUI [rank] => 6,795 ) ) We're parsing each <tr>: * *[2] is a number from first <td> *[name] is text of the link inside second <td> *[country] is a value between (...) in second <td> *[rank] is the text of the link inside third <td> In final file list.txt should contain an array() with ~100 IDS (we are grabbing the page with first 100 players). Additionally, will be amazing, if we make a small fix for each [name] before adding it to an array() - "Federer, Roger" should be converted to "Roger Federer" (just catch the word before comma, throw it to the end of the line). Thanks. A: Below is how to do it with PHP's native DOM extension. It should get you halfway to where you want to go. The page is quite broken in terms of HTML validity and that makes loading with DOM somewhat tricky. Normally, you can use load() to load a page directly. But since the HTML is quite broken, I loaded the page into a string first and used the loadHTML method instead, because it handles broken HTML better. Also, there is only one table at that page: the ranking table. The scoreboards are loaded via Ajax once the page loaded, so their HTML will not show up in the source code when you load it with PHP. So you can simply grab all TR elements and iterate over them. libxml_use_internal_errors(TRUE); $dom = new DOMDocument; $dom->loadHTML( file_get_contents('http://www.atpworldtour.com/Rankings/Singles.aspx')); libxml_clear_errors(); $rows = $dom->getElementsByTagName('tr'); foreach($rows as $row) { foreach( $row->childNodes as $cell) { echo trim($cell->nodeValue); } } This would output all table cell contents. It should be trivial to add those to an array and/or to write them to file. A: SimpleHTMLDOM will make this very easy for you. The first few lines would look something like this (untested): // Create DOM from URL or file $html = file_get_html('http://www.atpworldtour.com/Rankings/Singles.aspx'); // Find all images foreach($html->find('table[id=bioTableAlt] tr[class!=bioTableHead]') as $element) { } (not sure about the tr[class!=bioTableHead], if it doesn't work, try a simple tr)
Q: jquery How to refresh pages when resize happens? I have some indicator displays settings which float above a menu. Problem is when someone resizes the 'indicators stays on the same place', the page needs to 'refreshed to position correctly'. How to have a page refresh by itself when it detects the page is being resized? or is there any better way to do it? jQuery function findPosY(b) { var a = 0; if (b.offsetParent) { while (1) { a += b.offsetTop; if (!b.offsetParent) { break } b = b.offsetParent } } else { if (b.y) { a += b.y } } return a } function findPosX(b) { var a = 0; if (b.offsetParent) { while (1) { a += b.offsetLeft; if (!b.offsetParent) { break } b = b.offsetParent } } else { if (b.x) { a += b.x } } return a } function setNotifications() { $("#shortcut_notifications span").each(function () { if ($(this).attr("rel") != "") { target = $(this).attr("rel"); if ($("#" + target).length > 0) { var a = findPosY(document.getElementById(target)); var b = findPosX(document.getElementById(target)); $(this).css("top", a - 31 + "px");//-24 $(this).css("left", b + 83 + "px")//+60 } } }); $("#shortcut_notifications").css("display", "block") } CSS #shortcut_notifications { display:none; } .notification { color:#fff; font-weight:700; text-shadow:1px 0 0 #333; background:transparent url(../images/bg_notification.png) no-repeat center; position: absolute;/*absolute*/ width:37px;/*37*/ height:37px; display:block; text-align:center; padding-top:17px; color:#ffffff; } #nav li { display:block; float:right; padding:19px 21px; text-align: left; position:relative; height:24px; font-size:16px; } HTML <li class="settings"><a class="settings" href="#">Settings</a> <ul> <li><a href="#">Game Settings</a></li> <li><a href="#">Transactions </a></li> </ul> </li> A: You can use the .resize() handler, like this: $(window).resize(setNotifications); A: There is a window resize event that can be hooked into. Just rerun the code you used to initially position the indicators and it should all work. This question has good answers on using the resize event: Cross-browser window resize event - JavaScript / jQuery A: I think this works well . checked on IE Chrome and Firefox . $(window).bind('resize',function(){ window.location.href = window.location.href; });
Q: Override a Rails Engine controller action i'm using a Rails engine, but i need to customize some controllers actions. I actually forked the engine, and implementing those customizations into my own fork, but i was wondering if there is an official way in Rails Engines to override and customize controllers. A: Just define a controller with the same name in your own app\controllers folder, and it will be found first. That way you can easily customize it. Please note: because it is found first, you replace the entire controller from the engine. This could be exactly what you want. In some cases, you just want to adjust a little, then it is much better to reopen the class, and only redefine what is needed. Examples to do is can be found here: http://edgeguides.rubyonrails.org/engines.html#overriding-models-and-controllers A: The link in the accepted answer does not actually provide an example to overriding a controller. They mention "open classing" the file, but don't explain how exactly to do it. If you open the engine class in your app, you will get a circular dependency error because you are referencing/opening a class that is currently in the process of being defined. Therefore, you need to make sure you load the engine's actual class first. # in my app # app/controllers/blazer/base_controller.rb load Blazer::Engine.root.join('app/controllers/blazer/base_controller.rb') Blazer::BaseController.class_eval do filter_access_to :all end In my case, I'm using the Blazer gem and adding authentication to it. Since I use declarative authorization, which Blazer does not directly support, I need to open up Blazer's base controller and add my authorization requirement to it.
Q: ie8 playing funny with list-style-position: inside Ok, So problem here... when using list-style-position:inside in IE8 the first like is indented but every line after that is not. So the new lines appear under the bullet. This is fine, but when I use a list with that css applied with an a tag within the li then the text automatically gets pushed to the second line, and the first line is empty. ie8 bug http://www.rocketspark.co.nz/bug_images/ie8_list.png When I remove the a tag from the li then it jumps back up. Any idea on why this might be or is this a bug in the ie8 world or do I just need to double check my css? Any insights would be much appreciated. As asked here is some code <div id="sub_nav"> <ul> ... <li><a class="active_page" href="#">Liposculpture</a> <ul> <li><a href="#">What is Liposculpture?</a></li> <li><a href="#">About Liposculpture surgery</a></li> <li><a href="#" class="active_sub">After Liposculpture surgery</a></li> <li><a href="#">Post Op Instructions</a></li> <li><a href="#">Liposculpture Side Effects</a></li> <li><a href="#">Liposuction Introduction to</a></li> <li><a href="#">Tumescent Liposculpture</a></li> </ul> </li> ... </ul> </div> For the CSS I will try and show it best I can #sub_nav li { width: 200px; padding:4px 0; border-bottom: 1px #CCC solid; } #sub_nav li a { text-decoration: none; color:#555; padding:7px 15px 7px 15px; display: block; } #sub_nav li ul li { list-style-position: inside; list-style-type: disc; font: 11px Arial; padding-left:15px; color:#FFF; border-bottom: none; } #sub_nav li ul li a { padding:0; margin:0; text-indent: 0; } Hope this helps A: change #sub_nav li a { text-decoration: none; color:#555; padding:7px 15px 7px 15px; display: block; } to #sub_nav li a { text-decoration: none; color:#555; padding:7px 15px 7px 15px; display: inline-block; *display: inline; *zoom: 1; } A: @salgiza posted the answer in the comments above... "it looks like IE8 is having problems when calculating the width of the "a" (displayed as block) and pushing it down to a new line. The first thing I would try would be adding a width to the "a" element, to see if that's the problem."
Q: Typecasting to get Value from json object I'm having a bit of trouble working something out with regards to javascript and Json. I have a function that contains a json object blah=function(i){ var hash= ({ "foo" : "bar", "eggs":"bacon", "sausage":"maple syrup" }); var j=eval(hash); // Convert to Object console.log(j.toSource()); // Yes I know it's only in firefox! console.log(j.i); // Attempt to get the value of for example foo - which is bar } then call the function with blah('foo'); to attempt it to console log "bar" form the json object. THe trouble is all I get is "undefined" because the function is treating "i" as a string. My quertion is how can I typecast the "i" variable to be soemthing that can access the json object. Please help .. my head hurts and google has coem up short!. Thanks in advance Alex A: Well... j[i] :)
Q: ASP.NET MVC - HTML.BeginForm and SSL I am encountering an issue with what should be a simple logon form in ASP.NET MVC 2. Essentially my form looks a little something like this: using (Html.BeginForm("LogOn", "Account", new { area = "Buyers" }, FormMethod.Post, new { ID = "buyersLogOnForm" })) I have a RequiresHTTPS filter on the LogOn Action method but when it executes I receive the following message The requested resource can only be accessed via SSL At this point the only solution that worked was to pass in an extra action htmlattribute as follows: var actionURL = "https://" + Request.Url.Host + Request.Url.PathAndQuery; using (Html.BeginForm("LogOn", "Account", new { area = "Buyers" }, FormMethod.Post, new { ID = "buyersLogOnForm", @action = actionURL })) While this works I wonder a) why i am seeing this issue in the first place and b) if there is a more straightforward way of posting to https from a http page? [Edit] I should have stated that the logon dropdown will be available on many public pages. I do not want all of my pages to be HTTPS. For instance, my hope page - which ANYONE can see - should not be HTTPS based. Essentially I need to specify the protocol in my form but have no idea how to do that, or if it is possible. I would appreciate any advice/suggestions. Thanks in advance JP A: Use the [RequireHttps] attribute on both the action that renders the form and the one you are posting to. A: Update: Review the comments below about the security vulnerabilities of this approach before considering the use of this code. I found that a hybrid of JP and Malcolm's code examples worked. using (Html.BeginForm("Login", "Account", FormMethod.Post, new { @action = Url.Action("Login","Account",ViewContext.RouteData.Values,"https") })) Still felt a bit hacky though so I created a custom BeginForm helper. The custom helper is cleaner and does not require https when running locally. public static MvcForm BeginFormHttps(this HtmlHelper htmlHelper, string actionName, string controllerName) { TagBuilder form = new TagBuilder("form"); UrlHelper Url = new UrlHelper(htmlHelper.ViewContext.RequestContext); //convert to https when deployed string protocol = htmlHelper.ViewContext.HttpContext.Request.IsLocal == true? "http" : "https"; string formAction = Url.Action(actionName,controllerName,htmlHelper.ViewContext.RouteData.Values,protocol); form.MergeAttribute("action", formAction); FormMethod method = FormMethod.Post; form.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true); htmlHelper.ViewContext.Writer.Write(form.ToString(TagRenderMode.StartTag)); MvcForm mvcForm = new MvcForm(htmlHelper.ViewContext); return mvcForm; } Example usage: @using (Html.BeginFormHttps("Login", "Account")) A: You could use <form action =" <%= Url.Action( "action", "controller", ViewContext.RouteData.Values, "https" ) %>" method="post" >
Q: How can I create a horizontal table in a single foreach loop in MVC? Is there any way, in ASP.Net MVC, to condense the following code to a single foreach loop? <table class="table"> <tr> <td> Name </td> <% foreach (var item in Model) { %> <td> <%= item.Name %> </td> <% } %> </tr> <tr> <td> Item </td> <% foreach (var item in Model) { %> <td> <%= item.Company %> </td> <% } %> </tr> </table> Where model is an IEnumerable<SomeObject>: public class SomeObject { public virtual Name {get;set;} public virtual Company {get;set;} } This would output a table as follows: Name | Bob | Sam | Bill | Steve | Company | Builder | Fireman | MS | Apple | I know I could probably use an extension method to write out each row, but is it possible to build all rows using a single iteration over the model? This is a follow on from this question as I'm unhappy with my accepted answer and cannot believe I've provided the best solution. A: Check the following mat it help you <table class="table"> <tr> <td> <table> <tr><td>Name</td></tr> <tr><td>Item</td></tr> <table> </td> <% foreach (var item in Model) { %> <td> <table> <tr><td><%= item.Name %></td></tr> <tr><td><%= item.company %></td></tr> <table> </td> <% } %> </tr> </table> Note:- No check though :) A: If you are not restricted to using pure tables, then this would work for you. <table class="table"> <tr> <th> Name<br/> Item<br/> </th> <% foreach (var item in Model) { %> <td> <%= Html.Encode(item.Name) %><br/> <%= Html.Encode(item.company) %><br/> </td> <% } %> </tr> </table> You can definitely improve this by using span and css stylings. A: Very old thread, but... I've used the following (but was looking for a better approach when I came across this question) Create a code block that loops through the objects and creates the HTML for each row in a variable, then output the variable. The plus is you're only looping once and do not have nested tables (so things are more likely to line up) but the minus is the string manipulation of html. Should probably use stringbuilder rather than string, but principle is the same. @code Dim tr1 As String = "<th>Name</th>" Dim tr2 As String = "<th>Company</th>" For Each thingy As object In Model tr1 += "<th>" & thingy.Name & "</th>" tr2 += "<th>" & thingy.Company & "</th>" Next End Code @<table class="table table-condensed"> <tr>@Html.Raw(tr1)</tr> <tr>@Html.Raw(tr2)</tr> </table>
Q: md5 hash or simpler hash implemtation in android j2me Is there any way to encrypt data passing between two android phones in j2me? Not to mention I am using BT as medium. A: Yes simple base64 encoding and decoding can be implemented in j2me.. use class of Base64, just google for it...
Q: Force annotated Class to contain annotated Field Is it possible to force (at compile-time) an annotated Class to have a an annotated Field? I have this annotations: @Target(value = ElementType.TYPE) @interface MyClass {} @Target(value = ElementType.FIELD) @interface MyField {} and now I would like that the compilation of a Class like this fails: @MyClass class Customer { } whereas this should work: @MyClass class Customer { @MyField String text; } A: Yes, using apt (annotation processing tool). But for such simply tasks it will be an overkill. You can make some listener that is triggered on application startup and checks this requirement. Finally, you can avoid this by assuming reasonable defaults - i.e. if the class is annotated, then consider all fields annotated as well, with the default values.
Q: Splitting a WPF PathGeometry into "tiles" I have a rather large PathGeometry (over 100,000 points and stroked but not filled) to display for the user, but only a small portion of the path will be visible at any one time. To clarify, the path itself is not predetermined but will be created from data. The problem: I want to provide very smooth panning so the user can explore areas of the larger path. I have a possible solution but I'm not sure how to pull it off. I'd like to use a tiling technique--split the geometry into tiles and only load the visible tiles. So, how do split a stroke-only path geometry into tiles. More specifically, how do I determine the portion of the path that exists in a given rectangular tile? I know I can use a CombinedGeometry to determine the intersect between the path geometry and a rectangle, but that will include the "walls" of the rectangle (which will be stroked). Is there a better way to tile a stroke-only PathGeometry? Thanks! A: Perhaps instead of tiling just have the one pathgeometry and change the pathdata programatically using databinding or whatever to represent the segment of path you are zoomed in on. A bit like DeepZoom but with paths. This will mean you won't have to mess around merging paths. I am doing something similar to you but the numbers I am using In my paths are slightly less so I havn't considered using any virtualisation methods. However, I have not noticed massive performance problems. I have a path in a scrollviewer representing about 1000 - 10000 points and it only gets laggy when I zoom in only if the points are very far apart. If the points in the path are relativly close to their neighbours (e.g. a nice sweeping sine wave) then WPF performs some kind of optimisation on them to prevent any percievable lagging. Eg: this path... ...will take longer to draw than this path: even though they contain the same amount of points describing it. Although in reality the path needs to start looking like the image below before you notice any difference in performance. Because the path is representing an audio wave I intend to get rid of any future problems like this by performing some kind of check to see if the points are creating a massive dark blue block and replacing it with something less power hungry but this may not be a sufficient solution for you. (sorry about the size difference in the images, the bit that calculates the sine wave is out of action at the moment so i've had to use old jpegs) A: I was thinking about this myself recently, so perhaps my experiences may help you. Firstly, you can get better performance if you're able to use a StreamGeometry rather than a PathGeometry. I would recommend creating a single StreamGeometry as the Data property of a Path, placing it on a canvas, and then applying Scale and Translate transforms to navigate the shape. I was getting decent performance with 5 or 6 SeriesGeometries each with 1000 points (obviously much fewer than the number you mentioned), though I believe the WPF graphics engine will scale quite well as long as you don't have all the points on the screen at the same time. If you need to support being "fully zoomed out", i.e. all the points would be visible, then I would recommend creating low-res versions of the geometry (i.e. either a simpler set of points or a bitmap) and swapping the high and low-res versions when the zoom reaches some level. Does that make sense? Good luck! A: One way would be, you load the whole geometry in a canvas. Then apply a zoom to the canvas. You may use third party controls like ab2d. I have created such a canvas like one in photoshop with lot of drawings(created by user) in form of geometries lying in there. I have used ab2d to zoom in out with its menucontrol and it works fine. You can also set a predefined zoom to a part of it. Thanks / subho100
Q: Flight game AI algorithm? Greetings all, I am in the designing phase of one of my hobby project.I am going to develop an 3D air-combat game . (inspired by HAWX). But I am wondering how the AI works for enemy crafts ? I guess ,they do not move along a path (path finding on a graph)as in FPS games . What kind of algorithms can I use for enemy craft movement? Are there any AI libraries I can use for this? Note: I use irrlicht engine,C++ as my development environment. A: A simple answer for finding an interception point... At any point in time, make a straight-lines assumption. You and your target are travelling in straight lines at fixed speeds. Therefore, you can subtract your position and motion from your targets, and work with the targets relative position and velocity. An interesting point in time is when your target is as close (on that line) as it will ever be - the closest point on that line. IIRC, that can be calculated with vector dot products... P . V t = - ----- V . V Assuming I got that right, at this point the targets path is at a right angle to the line from you to the target (NOT the same as the angle between its and your motions). You could get an equivalent answer using trigonometry (a dot product is related to the cosine), and I even worked it out (not knowing better) using a simultaneous equations method once, for a 2D game that I started but never finished many years ago (think combat between oids/thrust style rotate-and-thrust ships with gravity). From this, you can determine where that closest point is and how far it is. Calculate this time for small variations on your current speed and direction and you can iteratively optimise for a near future interception. Of course minimising t brings in the possibility that t might get ever further into the past - running away! Maybe minimising t squared would be better, but then you have other complications - if the enemy is right behind you, do you really want to slow down? Anyway, this is probably enough for a simple guided missile, but of course very little use in a dogfight. My impression of that is more like a kind of analogue real-time chess where you can't see most of the board most of the time. You can't minimax that, obviously, so you need a higher level model of what the moves are than just joystick and other control settings. That'll need a fair bit of research into human-experience based tactics before you start designing an AI engine for it. For exploiting cover in terrain, though, you can probably do something much simpler. A graph-based path-finder may well be relevant to plotting a route through valleys. Do most of the pathfinding in 2D, and tweak the map relatively-smooth-variations "lies" to ensure you don't fly straight into a cliff. Probably you need a system of different types of goals and tactics, with a way of weighting and choosing between them. A long way from your target, your more likely to try to stay in cover than when you get closer. When you have a missile on your own tail, that'll take priority over any offensive actions you might take, and so on. BTW - none of this is from real experience of games development (and I've certainly never been a pilot of any description) so treat it is vague suggestions that may not pan out. And beware - one reason that 2D game of mine never got finished was because trying to work out AI code was at first so interesting, then later so frustrating - it's so annoying when the only way your best attempt at an AI can beat you is by having many times more ships and an infinite supply of ammo.
Q: Jquery thickbox to work with Url.Action link in Asp.net mvc I want to implement a Jquery thickbox to show an image that is generated from my database in ASP.Net MVC. My link looks roughly like this: <a href="<%=Url.Action("ShowPhoto", "Item", new { id = pic.pictureID }) %>" class="thickbox"><img src="<%= Url.Action( "ShowThumbnail", "Item", new { id = pic.pictureID } ) %>" alt="" width="100px" /></a> However, I'm having errors popping out caused by the Url.Action link. Someone please help me!! EDIT: Sorry, I forgot to put the error in. In the Visual Studio: NullReferenceException was unhandled by user code. Object reference not set to an instance of an object. (This is highlighted in UnitofWork.CurrentUnitOfWork.Dispose();) In my error log: System.Web.HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (&). at System.Web.HttpRequest.ValidateInputIfRequiredByConfig() at System.Web.HttpApplication.ValidateRequestExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) System.Web.HttpException (0x80004005): File does not exist. at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String physicalPath, HttpResponse response) at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context, String overrideVirtualPath) at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) A: I let the Html.ActionLink helper render out the links that include code for me, like this: <%=Html.ActionLink(Resources.Localize.Routes_WidgetsCreate, "Create", "Widget", new { modal = true }, new { rel = "shadowbox;height=600;width=700", title = Resources.Localize.Routes_WidgetsCreate })%> Explanation: Resources.Localize.Routes_WidgetsCreate is a reference to Resources class to get localized string, "Create" is the controller action, "Widget" is the controller, "new { model = true }" is QueryString parameter, "new { rel ... } " these are the tag attributes. This is an example of a Shadowbox link that opens modal window with the contents that ~/Widget/Create returns. HTH A: I don't think that this is to do with thickbox, but can you confirm that your two snippets of code (below) actually render a url? <%=Url.Action("ShowPhoto", "Item", new { id = pic.pictureID }) %> and <%= Url.Action("ShowThumbnail", "Item", new { id = pic.pictureID }) %>
Q: Calculating the Moment Of Inertia for a concave 2D polygon relative to its orgin I want to compute the moment of inertia of a (2D) concave polygon. I found this on the internet. But I'm not very sure how to interpret the formula... Formula http://img101.imageshack.us/img101/8141/92175941c14cadeeb956d8f.gif 1) Is this formula correct? 2) If so, is my convertion to C++ correct? float sum (0); for (int i = 0; i < N; i++) // N = number of vertices { int j = (i + 1) % N; sum += (p[j].y - p[i].y) * (p[j].x + p[i].x) * (pow(p[j].x, 2) + pow(p[i].x, 2)) - (p[j].x - p[i].x) * (p[j].y + p[i].y) * (pow(p[j].y, 2) + pow(p[i].y, 2)); } float inertia = (1.f / 12.f * sum) * density; Martijn A: #include <math.h> //for abs float dot (vec a, vec b) { return (a.x*b.x + a.y*b.y); } float lengthcross (vec a, vec b) { return (abs(a.x*b.y - a.y*b.x)); } ... do stuff ... float sum1=0; float sum2=0; for (int n=0;n<N;++n) { //equivalent of the Σ sum1 += lengthcross(P[n+1],P[n])* (dot(P[n+1],P[n+1]) + dot(P[n+1],P[n]) + dot(P[n],P[n])); sum2 += lengthcross(P[n+1],P[n]); } return (m/6*sum1/sum2); Edit: Lots of small math changes A: I think you have more work to do that merely translating formulas into code. You need to understand exactly what this formula means. When you have a 2D polygon, you have three moments of inertia you can calculate relative to a given coordinate system: moment about x, moment about y, and polar moment of inertia. There's a parallel axis theorem that allows you to translate from one coordinate system to another. Do you know precisely which moment and coordinate system this formula applies to? Here's some code that might help you, along with a JUnit test to prove that it works: import java.awt.geom.Point2D; /** * PolygonInertiaCalculator * User: Michael * Date: Jul 25, 2010 * Time: 9:51:47 AM */ public class PolygonInertiaCalculator { private static final int MIN_POINTS = 2; public static double dot(Point2D u, Point2D v) { return u.getX()*v.getX() + u.getY()*v.getY(); } public static double cross(Point2D u, Point2D v) { return u.getX()*v.getY() - u.getY()*v.getX(); } /** * Calculate moment of inertia about x-axis * @param poly of 2D points defining a closed polygon * @return moment of inertia about x-axis */ public static double ix(Point2D [] poly) { double ix = 0.0; if ((poly != null) && (poly.length > MIN_POINTS)) { double sum = 0.0; for (int n = 0; n < (poly.length-1); ++n) { double twiceArea = poly[n].getX()*poly[n+1].getY() - poly[n+1].getX()*poly[n].getY(); sum += (poly[n].getY()*poly[n].getY() + poly[n].getY()*poly[n+1].getY() + poly[n+1].getY()*poly[n+1].getY())*twiceArea; } ix = sum/12.0; } return ix; } /** * Calculate moment of inertia about y-axis * @param poly of 2D points defining a closed polygon * @return moment of inertia about y-axis * @link http://en.wikipedia.org/wiki/Second_moment_of_area */ public static double iy(Point2D [] poly) { double iy = 0.0; if ((poly != null) && (poly.length > MIN_POINTS)) { double sum = 0.0; for (int n = 0; n < (poly.length-1); ++n) { double twiceArea = poly[n].getX()*poly[n+1].getY() - poly[n+1].getX()*poly[n].getY(); sum += (poly[n].getX()*poly[n].getX() + poly[n].getX()*poly[n+1].getX() + poly[n+1].getX()*poly[n+1].getX())*twiceArea; } iy = sum/12.0; } return iy; } /** * Calculate polar moment of inertia xy * @param poly of 2D points defining a closed polygon * @return polar moment of inertia xy * @link http://en.wikipedia.org/wiki/Second_moment_of_area */ public static double ixy(Point2D [] poly) { double ixy = 0.0; if ((poly != null) && (poly.length > MIN_POINTS)) { double sum = 0.0; for (int n = 0; n < (poly.length-1); ++n) { double twiceArea = poly[n].getX()*poly[n+1].getY() - poly[n+1].getX()*poly[n].getY(); sum += (poly[n].getX()*poly[n+1].getY() + 2.0*poly[n].getX()*poly[n].getY() + 2.0*poly[n+1].getX()*poly[n+1].getY() + poly[n+1].getX()*poly[n].getY())*twiceArea; } ixy = sum/24.0; } return ixy; } /** * Calculate the moment of inertia of a 2D concave polygon * @param poly array of 2D points defining the perimeter of the polygon * @return moment of inertia * @link http://www.physicsforums.com/showthread.php?t=43071 * @link http://www.physicsforums.com/showthread.php?t=25293 * @link http://stackoverflow.com/questions/3329383/help-me-with-converting-latex-formula-to-code */ public static double inertia(Point2D[] poly) { double inertia = 0.0; if ((poly != null) && (poly.length > MIN_POINTS)) { double numer = 0.0; double denom = 0.0; double scale; double mag; for (int n = 0; n < (poly.length-1); ++n) { scale = dot(poly[n + 1], poly[n + 1]) + dot(poly[n + 1], poly[n]) + dot(poly[n], poly[n]); mag = Math.sqrt(cross(poly[n], poly[n+1])); numer += mag * scale; denom += mag; } inertia = numer / denom / 6.0; } return inertia; } } Here's the JUnit test to accompany it: import org.junit.Test; import java.awt.geom.Point2D; import static org.junit.Assert.assertEquals; /** * PolygonInertiaCalculatorTest * User: Michael * Date: Jul 25, 2010 * Time: 10:16:04 AM */ public class PolygonInertiaCalculatorTest { @Test public void testTriangle() { Point2D[] poly = { new Point2D.Double(0.0, 0.0), new Point2D.Double(1.0, 0.0), new Point2D.Double(0.0, 1.0) }; // Moment of inertia about the y1 axis // http://www.efunda.com/math/areas/triangle.cfm double expected = 1.0/3.0; double actual = PolygonInertiaCalculator.inertia(poly); assertEquals(expected, actual, 1.0e-6); } @Test public void testSquare() { Point2D[] poly = { new Point2D.Double(0.0, 0.0), new Point2D.Double(1.0, 0.0), new Point2D.Double(1.0, 1.0), new Point2D.Double(0.0, 1.0) }; // Polar moment of inertia about z axis // http://www.efunda.com/math/areas/Rectangle.cfm double expected = 2.0/3.0; double actual = PolygonInertiaCalculator.inertia(poly); assertEquals(expected, actual, 1.0e-6); } @Test public void testRectangle() { // This gives the moment of inertia about the y axis for a coordinate system // through the centroid of the rectangle Point2D[] poly = { new Point2D.Double(0.0, 0.0), new Point2D.Double(4.0, 0.0), new Point2D.Double(4.0, 1.0), new Point2D.Double(0.0, 1.0) }; double expected = 5.0 + 2.0/3.0; double actual = PolygonInertiaCalculator.inertia(poly); assertEquals(expected, actual, 1.0e-6); double ix = PolygonInertiaCalculator.ix(poly); double iy = PolygonInertiaCalculator.iy(poly); double ixy = PolygonInertiaCalculator.ixy(poly); assertEquals(ix, (1.0 + 1.0/3.0), 1.0e-6); assertEquals(iy, (21.0 + 1.0/3.0), 1.0e-6); assertEquals(ixy, 4.0, 1.0e-6); } } A: For reference, here's a mutable 2D org.gcs.kinetic.Vector implementation and a more versatile, immutable org.jscience.mathematics.vector implementation. This article on Calculating a 2D Vector’s Cross Product is helpful, too. A: I did it with Tesselation. And take the MOI's all together.
Q: trigger onresize in cross browser compatible manner I would like to trigger the onresize event from my C# code behind. I think this can be done with Page.clientScript.RegisterScriptBlock(this.getType(), "id", "javascript code"); I have tried element.onresize() but it doesnt seem to work in firefox. What is the correct way to trigger an onresize event similar to the following jQuery? $("body").trigger("resize"); Using jQuery itself isn't an option. A: This should do the trick, DOM Level 2, no idea whether this works in IE6, quirks mode still has no information on this stuff: if (document.createEvent) { var e = document.createEvent('HTMLEvents'); e.initEvent('resize', true, false); document.body.dispatchEvent(e); } else if (document.createEventObject) { document.body.fireEvent('onresize'); } Tested in FF, Chrome and Opera. A: use this $(window).resize(); (tested in FF, chrome, IE8) // old answer, fails in FF document.body.onresize()
Q: Exploratory SPARQL queries? whenever I start using SQL I tend to throw a couple of exploratory statements at the database in order to understand what is available, and what form the data takes. e.g. show tables describe table select * from table Could anyone help me understand the way to complete a similar exploration of an RDF datastore using a SPARQL endpoint? A: Well, the obvious first start is to look at the classes and properties present in the data. Here is how to see what classes are being used: SELECT DISTINCT ?class WHERE { ?s a ?class . } LIMIT 25 OFFSET 0 (LIMIT and OFFSET are there for paging. It is worth getting used to these especially if you are sending your query over the Internet. I'll omit them in the other examples.) a is a special SPARQL (and Notation3/Turtle) syntax to represent the rdf:type predicate - this links individual instances to owl:Class/rdfs:Class types (roughly equivalent to tables in SQL RDBMSes). Secondly, you want to look at the properties. You can do this either by using the classes you've searched for or just looking for properties. Let's just get all the properties out of the store: SELECT DISTINCT ?property WHERE { ?s ?property ?o . } This will get all the properties, which you probably aren't interested in. This is equivalent to a list of all the row columns in SQL, but without any grouping by the table. More useful is to see what properties are being used by instances that declare a particular class: SELECT DISTINCT ?property WHERE { ?s a <http://xmlns.com/foaf/0.1/Person>; ?property ?o . } This will get you back the properties used on any instances that satisfy the first triple - namely, that have the rdf:type of http://xmlns.com/foaf/0.1/Person. Remember, because a rdf:Resource can have multiple rdf:type properties - classes if you will - and because RDF's data model is additive, you don't have a diamond problem. The type is just another property - it's just a useful social agreement to say that some things are persons or dogs or genes or football teams. It doesn't mean that the data store is going to contain properties usually associated with that type. The type doesn't guarantee anything in terms of what properties a resource might have. You need to familiarise yourself with the data model and the use of SPARQL's UNION and OPTIONAL syntax. The rough mapping of rdf:type to SQL tables is just that - rough. You might want to know what kind of entity the property is pointing to. Firstly, you probably want to know about datatype properties - equivalent to literals or primitives. You know, strings, integers, etc. RDF defines these literals as all inheriting from string. We can filter out just those properties that are literals using the SPARQL filter method isLiteral: SELECT DISTINCT ?property WHERE { ?s a <http://xmlns.com/foaf/0.1/Person>; ?property ?o . FILTER isLiteral(?o) } We are here only going to get properties that have as their object a literal - a string, date-time, boolean, or one of the other XSD datatypes. But what about the non-literal objects? Consider this very simple pseudo-Java class definition as an analogy: public class Person { int age; Person marriedTo; } Using the above query, we would get back the literal that would represent age if the age property is bound. But marriedTo isn't a primitive (i.e. a literal in RDF terms) - it's a reference to another object - in RDF/OWL terminology, that's an object property. But we don't know what sort of objects are being referred to by those properties (predicates). This query will get you back properties with the accompanying types (the classes of which ?o values are members of). SELECT DISTINCT ?property, ?class WHERE { ?s a <http://xmlns.com/foaf/0.1/Person>; ?property ?o . ?o a ?class . FILTER(!isLiteral(?o)) } That should be enough to orient yourself in a particular dataset. Of course, I'd also recommend that you just pull out some individual resources and inspect them. You can do that using the DESCRIBE query: DESCRIBE <http://example.org/resource> There are some SPARQL tools - SNORQL, for instance - that let you do this in a browser. The SNORQL instance I've linked to has a sample query for exploring the possible named graphs, which I haven't covered here. If you are unfamiliar with SPARQL, honestly, the best resource if you get stuck is the specification. It's a W3C spec but a pretty good one (they built a decent test suite so you can actually see whether implementations have done it properly or not) and if you can get over the complicated language, it is pretty helpful. A: SELECT DISTINCT * WHERE { ?s ?p ?o } LIMIT 10 A: I often refer to this list of queries from the voiD project. They are mainly of a statistical nature, but not only. It shouldn't be hard to remove the COUNTs from some statements to get the actual values. A: Especially with large datasets, it is important to distinguish the pattern from the noise and to understand which structures are used a lot and which are rare. Instead of SELECT DISTINCT, I use aggregation queries to count the major classes, predicates etc. For example, here's how to see the most important predicates in your dataset: SELECT ?pred (COUNT(*) as ?triples) WHERE { ?s ?pred ?o . } GROUP BY ?pred ORDER BY DESC(?triples) LIMIT 100 I usually start by listing the graphs in a repository and their sizes, then look at classes (again with counts) in the graph(s) of interest, then the predicates of the class(es) I am interested in, etc. Of course these selectors can be combined and restricted if appropriate. To see what predicates are defined for instances of type foaf:Person, and break this down by graph, you could use this: SELECT ?g ?pred (COUNT(*) as ?triples) WHERE { GRAPH ?g { ?s a foaf:Person . ?s ?pred ?o . } GROUP BY ?g ?pred ORDER BY ?g DESC(?triples) This will list each graph with the predicates in it, in descending order of frequency. A: I find the following set of exploratory queries useful: Seeing the classes: select distinct ?type ?label where { ?s a ?type . OPTIONAL { ?type rdfs:label ?label } } Seeing the properties: select distinct ?objprop ?label where { ?objprop a owl:ObjectProperty . OPTIONAL { ?objprop rdfs:label ?label } } Seeing the data properties: select distinct ?dataprop ?label where { ?dataprop a owl:DatatypeProperty . OPTIONAL { ?dataprop rdfs:label ?label } } Seeing which properties are actually used: select distinct ?p ?label where { ?s ?p ?o . OPTIONAL { ?p rdfs:label ?label } } Seeing what entities are asserted: select distinct ?entity ?elabel ?type ?tlabel where { ?entity a ?type . OPTIONAL { ?entity rdfs:label ?elabel } . OPTIONAL { ?type rdfs:label ?tlabel } } Seeing the distinct graphs in use: select distinct ?g where { graph ?g { ?s ?p ?o } }
Q: iPad built in dictionary Is the built-in dictionary in iBooks etc available to developers? If so how would I go about using it? A: Unfortunately, I believe the system dictionary is only available through a private API. Personal conjecture: It's one of the many "features" locked away by Apple to separate the iBooks app from 3rd party e-book reader competition. However, at the rate Apple is going, I would expect the API to become public at some point in the next few years. A: It's not available to developers. You could use an open source dictionary like this one from Project Gutenberg, but it might take substantial munging to make it presentable. A: I think that it might be a copyright issue. I had the same problem about a year ago and not much has changed since then. My solution was to embed an offline dictionary inside my app and I later turned it into a static library that others can use (for a small fee). If you're looking for a full-blown dictionary you can check it out at www.lexicontext.com If you just need a spell checker, you can also use UITextChecker
End of preview. Expand in Data Studio

Dataset Card for "check_stackexchange"

More Information needed

Downloads last month
5