Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have been a long time C# and .Net developer, and have been playing with the idea of learning c++. One of the primary reasons I have been thinking about this, is how much faster C++ can be over apps using the .Net framework. But am I right in assuming that if I write a C++ app in Visual Studio, and/or reference .Net libraries in a C++ application that, that C++ is converted in MSIL (just like C#) - and therefor I'd loose any benefit from coding in it? So my question is really this: are C++ components of an application referencing .Net assemblies compiled in the "traditional" way, or comiled into MSIL?
Well it's a bit more complicated than that. There are actually two totally different versions of .NET-supporting C++. The old one, Managed Extensions for C++, was the only option available in Visual C++ 2002/2003. It's available in newer compilers under the option /clr:oldSyntax. It's kinda clumsy as it tries hard to integrate with standard C++, so all new keywords (and there's lots of them) are prefixed with double underscores, etc. Code generated by this compiler is a mixture of native and MSIL code, dubbed IJW "it just works". The new one, called C++/CLI, is a clean new language available in Visual C++ 2005 and newer. Most importantly, it supports several modes of code generation. The /clr option again generates a IJW mixture of native and MSIL code. /clr:pure results in a managed-only assembly, although it may translate native types into corresponding .net structures. The code therefore may not be type-safe and can use pointer arithmetic, pretty much like C# with /unsafe. And the strictest of options is /clr:safe, which produces type-safe, verifiable MSIL-only assembly, exactly like C# compiler does (without /unsafe, that is). For differences between MC++ and C++/CLI, see [wikipedia](http://en.wikipedia.org/wiki/C%2B%2B/CLI). For description of the compiler switches, see [MSDN](http://msdn.microsoft.com/en-us/library/k8d11d4s.aspx). PS. The .NET byte-code is called either MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). MIL can stand for Media Integration Layer, the undocumented low-level library used by WPF and Vista Desktop Window Manager.
It's probably a good idea to keep the concepts separate. First, C++ is a language, and it doesn't specify anything about what platform should be targeted. In principle, straight C++ code could be compiled to native x86 assembler, Java bytecode, MSIL or anything else you care to think of. I believe Adobe recently made a C++ compiler which generates Flash bytecode. Second, with typical indecisiveness, Microsoft has created two C++-derived languages targeting .NET. First, they made the "managed extensions for C++". Then they decided it sucked, ditched it and tried to pretend it never existed. Now their best bet for .NET-style C++ is called C++/CLI, but *it is not C++*. It extends and changes the language in a number of nonstandard ways. (And I believe the C++ standard committee requested that they change the name to avoid confusion. But they didn't) Visual Studio 2005 and newer supports C++/CLI. (in "Add project", they're listed under Visual C++ -> CLR) *However* (you didn't think it was that simple, did you?), Microsoft has done it again. After specifying C++/CLI, which is actually a reasonably well-designed attempt at integrating C++ with CLI, they realized that virtually no one uses it! Turns out that even C++ programmers generally prefer to use C# when they're working in .NET, and proper, native C++ otherwise. So now, they're focusing on making interop between *native* C++ and .NET simpler and more powerful. However, C++/CLI isn't likely to go away. It works, and in some cases it's useful. It's just not the C++-killer they originally hoped for. Visual Studio (since forever) also supports native C++ applications, compiled to x86 machine code, untainted by .NET. These are listed in the "Add Project" dialog under Visual C++ -> Win32. So if you want to learn C++, you have two choices: Learn C++/CLI, which limits you to a MS-only language which yes, generates MSIL instead of native machine code, and requires .NET to run, and generally isn't worth the bother because if you're going to take a dependency on .NET *anyway*, why not write in C#? Or learn proper C++, which is completely separate from .NET and can't directly reference .NET assemblies. The key takeaway point is that they're separate languages. Either you compile as C++/CLI, which means the compiler will allow you to reference .NET assemblies, and will generate MSIL code, or you compile as C++, in which case the .NET world doesn't exist. And finally, a note of caution. Despite my wording above ("proper C++" and "untainted by .NET"), C++ isn't "better". In many cases, it is not faster either. C++ has the *potential* to be faster, but it depends a lot more on the programmer. The C# compiler will turn pretty much anything into reasonably efficient code. C++ on the other hand, is full of pitfalls that will make your code *slower* than the equivalent C#. <http://blogs.msdn.com/ricom/archive/2005/05/10/416151.aspx> and the blog posts it references are worth a read for anyone curious about the performance of similar code written in the two languages. There is only one area where C++ applications will be consistently faster, and that's in startup time. a .NET application may have to load the .NET framework and JIT the MSIL code, where a native application... just starts. But other than that, it is probably a mistake to assume that C++ will be faster. It *can* be, because it gives you a bit more control. But usually, that just means the compiler is less able to save you from the inefficiencies you create in your code.
IS C++ converted into MSIL?
[ "", ".net", "c++", "compiler-construction", "cil", "" ]
I've realized you can have a property in an object run automatically like this: ``` var obj = { init:(function(){ alert('loaded');})(); } ``` I'm trying to use this method as an initializer for the object. The problem I'm running into is passing a reference to 'obj' to the init property. I suspect it generates errors because the obj hasn't been completely built in browser yet. I'm trying to do the following, but unsuccessfully. If there's a way to do this, I'd love to know how. ``` var obj = { prop:function(){ alert('This just ran.'); }, init:(function(){ obj.prop(); })(); } ```
If you want to create multiple instances of similar objects, you should use plain old constructor functions (remember to put shared properties in the prototype!). If you want to create a single object, consider using an anonymous constructor. Your example would read: ``` var obj = new (function() { this.prop = function() { alert('This just ran.'); } // init code goes here: this.prop(); }); ``` This has an additional benefit over object literals: the constructor function can be used as a closure over 'private' variables. Don't overuse object literals: they may make simple things simple, but complex things will get overly complicated.
This is not possible: obj doesn't exist until the whole block is interpreted.
Javascript - object initializer?
[ "", "javascript", "initialization", "" ]
I have a small utility that was originally written in VS2005. I need to make a small change, but the source code for one of the dlls has been lost somewhere. Is there a free or reasonably priced tool to reverse engineer the dll back to C++ code.
[Hex-Rays decompiler](https://www.hex-rays.com/products/decompiler/) is a great tool, but the code will be quite hard to read and you will have to spend a lot of time to reverse engineer the whole DLL.
You might also want to have a look at ***OllyDbg*** which is a 32-bit assembler level analysing debugger. It is used to analyze binary code in scenarios where you do not have a source code. It is light weight debugger. ***OllyDbg*** is a shareware so you can download & use it for free..!! Visit OllyDbg is home page [here](http://www.ollydbg.de/) **PS:** Back in the day crackers used [SoftICE](http://en.wikipedia.org/wiki/SoftICE) from NuMega for debugging into an executable & grab a snapshot at the values of registers. SoftICE was an advanced debugger. It was definitely the favorite tool for the crackers. I don't know about the present status of the product. NuMega's site had no information about it. I may have overlooked it but I could not find it. I recommend that you get your hands on a legacy version (4.0x) of SoftICE & apply the WindowsXP patch for SoftICE. Working with SoftICE is something of an "experience". **Further Read:** [Reversing: Secrets of Reverse Engineering by *Eldad Eilam*](https://rads.stackoverflow.com/amzn/click/com/0764574817)
Reverse engineer C++ DLL
[ "", "c++", "winapi", "dll", "reverse-engineering", "" ]
It seems that .NET can't open JP2 (Jpeg 2000) files using the GDI library. I've searched on google but can't find any libraries or example code to do this. Anybody got any ideas? I don't really want to pay for a library to do it unless I have to..
Seems like we can do it using [FreeImage](http://freeimage.sourceforge.net/) (which is free) ``` FIBITMAP dib = FreeImage.LoadEx("test.jp2"); //save the image out to disk FreeImage.Save(FREE_IMAGE_FORMAT.FIF_JPEG, dib, "test.jpg", FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL); //or even turn it into a normal Bitmap for later use Bitmap bitmap = FreeImage.GetBitmap(dib); ```
I was looking for something similar a while back, with a view to implementing one if I could; The [responses to my question](https://stackoverflow.com/questions/455018/extending-the-list-of-supported-image-formats-in-gdi) imply that there is no *documented* method to do this for GDI+ which the Image class in .Net uses. I believe that if you're writing a WPF application, then you can extend the list of supported image formats through [Windows Imanging Components codecs](http://msdn.microsoft.com/en-us/library/aa905327.aspx), and there *may* be one out there already (ask your local friendly search engine?) There is an option to use an addon such as [DotImage](http://www.atalasoft.com/products/dotimage/jpeg2000/?gclid=CN-e3Mmi-pgCFQtdQgodvHXfmA) which supports JPEG2000, although there may be more "effort" involved in loading images.
JPEG 2000 support in C#.NET
[ "", "c#", ".net", "gdi", "jpeg2000", "" ]
What is the point of writing an interface without members ? [INamingContainer](http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx) is one example in .NET Framework. And it's described in MSDN as : > Identifies a container control that > creates a new ID namespace within a > Page object's control hierarchy. This > is a marker interface only. Is it used for just this kind of blocks : ``` if (myControl is INamingContainer) { // do something } ``` Or are there other advantages of it ? **EDIT :** It was called [Marker Interface Pattern](http://en.wikipedia.org/wiki/Marker_interface_pattern) (thanks Preet)
This is to ensure that you can treat a collection of objects as the same type and then perform some operations on that type (You know that it must inherit from object). Think of it like attributes. It's type meta data. You also might want to perform an operation on a known type (e.g. System.Web.UI.Control) but only perform that operation if the type inherits from a certain interface (e.g. INamingContainer). ``` foreach(var ctrl in this.Controls) { if (ctrl is INamingContainer) { // Do something on the control } } ```
Memberless interfaces are used to provide mixin-like capabilities in C#. So given a class A: ``` class A : B { ... } ``` You can give it extra functionality (a-la multiple inheritance) by defining an interface IStuff: ``` interface IStuff {} ``` then 'implementing' it in A: ``` class A : B, IStuff { ... } ``` and then adding the extra features ``` class Methods { public static void Something(this IStuff stuff) { // some functionality here } } ```
Why do we use memberless interface?
[ "", "c#", ".net", "oop", "interface", "" ]
I wrote this: ``` using (GuiaMovilEntities guiaEntity = new GuiaMovilEntities()) { try { Cliente cliente = Cliente.CreateCliente(-1, datosCliente.Email, datosCliente.Password); } catch { } } ``` It's unfinished. If table Cliente (represented by Cliente object) has its first row (clienteID) as IDENTITY column. Is it correct to put -1 as clienteID value? Thanks!
Identity parameters are auto-generated - you shouldn't need to specify the value yourself.
Here's another option: ``` Cliente cliente = new Cliente { Email = datosCliente.Email, Password = datosCliente.Password }; ```
ADO.NET Entity Framework: Create an Object Using the Static Create Method (C#)
[ "", "c#", "entity-framework", "ado.net", "" ]
"Fluent interfaces" is a fairly hot topic these days. C# 3.0 has some nice features (particularly extension methods) that help you make them. FYI, a fluent API means that each method call returns something useful, often the same object you called the method on, so you can keep chaining things. Martin Fowler discusses it with a Java example [here](http://www.martinfowler.com/bliki/FluentInterface.html). The concept kooks something like this: ``` var myListOfPeople = new List<Person>(); var person = new Person(); person.SetFirstName("Douglas").SetLastName("Adams").SetAge(42).AddToList(myListOfPeople); ``` I have seen some incredibly useful fluent interfaces in C# (one example is the fluent approach for validating parameters found in [an earlier StackOverflow question I had asked](https://stackoverflow.com/questions/669678/what-is-the-smoothest-most-appealing-syntax-youve-found-for-asserting-parameter/670484#670484). It blew me away. It was able to give highly readable syntax for expressing parameter validation rules, and also, if there were no exceptions, it was able to avoid instantiating any objects! So for the "normal case", there was very little overhead. This one tidbit taught me a **huge** amount in a short time. I want to find more things like that). So, I'd like to learn more by looking at and discussing some excellent examples. So, **what are some excellent fluent interfaces you've made or seen in C#, and what made them so valuable?** Thanks.
Kudos for the method parameter validation, you've given me a new idea for our fluent APIs. I've hated our precondition checks anyways... I've built a extensibility system for a new product in development, where you can fluently describe the commands available, the user interface elements and more. This runs on top of StructureMap and FluentNHibernate, which are nice APIs too. ``` MenuBarController mb; // ... mb.Add(Resources.FileMenu, x => { x.Executes(CommandNames.File); x.Menu .AddButton(Resources.FileNewCommandImage, Resources.FileNew, Resources.FileNewTip, y => y.Executes(CommandNames.FileNew)) .AddButton(null, Resources.FileOpen, Resources.FileOpenTip, y => { y.Executes(CommandNames.FileOpen); y.Menu .AddButton(Resources.FileOpenFileCommandImage, Resources.OpenFromFile, Resources.OpenFromFileTop, z => z.Executes(CommandNames.FileOpenFile)) .AddButton(Resources.FileOpenRecordCommandImage, Resources.OpenRecord, Resources.OpenRecordTip, z => z.Executes(CommandNames.FileOpenRecord)); }) .AddSeperator() .AddButton(null, Resources.FileClose, Resources.FileCloseTip, y => y.Executes(CommandNames.FileClose)) .AddSeperator(); // ... }); ``` And you can configure all commands available like this: ``` Command(CommandNames.File) .Is<DummyCommand>() .AlwaysEnabled(); Command(CommandNames.FileNew) .Bind(Shortcut.CtrlN) .Is<FileNewCommand>() .Enable(WorkspaceStatusProviderNames.DocumentFactoryRegistered); Command(CommandNames.FileSave) .Bind(Shortcut.CtrlS) .Enable(WorkspaceStatusProviderNames.DocumentOpen) .Is<FileSaveCommand>(); Command(CommandNames.FileSaveAs) .Bind(Shortcut.CtrlShiftS) .Enable(WorkspaceStatusProviderNames.DocumentOpen) .Is<FileSaveAsCommand>(); Command(CommandNames.FileOpen) .Is<FileOpenCommand>() .Enable(WorkspaceStatusProviderNames.DocumentFactoryRegistered); Command(CommandNames.FileOpenFile) .Bind(Shortcut.CtrlO) .Is<FileOpenFileCommand>() .Enable(WorkspaceStatusProviderNames.DocumentFactoryRegistered); Command(CommandNames.FileOpenRecord) .Bind(Shortcut.CtrlShiftO) .Is<FileOpenRecordCommand>() .Enable(WorkspaceStatusProviderNames.DocumentFactoryRegistered); ``` Our view configure their controls for the standard edit menu commands using a service given to them by the workspace, where they just tell it to observe them: ``` Workspace .Observe(control1) .Observe(control2) ``` If the user tabs to the controls, the workspace automatically gets an appropriate adapter for the control and provides undo/redo and clipboard operations. It has helped us reduce the setup code dramatically and make it even more readable. --- I forgot to tell about a library we're using in our WinForms MVP model presenters to validate the views: [FluentValidation](http://www.codeplex.com/FluentValidation). Really easy, really testable, really nice!
This is actually the first time I've heard the term "fluent interface." But the two examples that come to mind are LINQ and immutable collections. Under the covers LINQ is a series of methods, most of which are extension methods, which take at least one IEnumerable and return another IEnumerable. This allows for very powerful method chaining ``` var query = someCollection.Where(x => !x.IsBad).Select(x => x.Property1); ``` Immutable types, and more specifically collections have a very similar pattern. Immutable Collections return a new collection for what would be normally a mutating operation. So building up a collection often turns into a series of chained method calls. ``` var array = ImmutableCollection<int>.Empty.Add(42).Add(13).Add(12); ```
What fluent interfaces have you made or seen in C# that were very valuable? What was so great about them?
[ "", "c#", "c#-3.0", "extension-methods", "fluent", "" ]
And how do I run it?
[Sphinx website](http://sphinx.pocoo.org/) says: ``` easy_install -U Sphinx ``` If you want that installed in system python you'd probably need elevated permissions with `sudo`: ``` sudo easy_install -U Sphinx ``` If you do not have `easy_install` yet, see <http://peak.telecommunity.com/DevCenter/EasyInstall>
How do I run it? <http://sphinx-doc.org/tutorial.html#running-the-build> Basically, the easiest way is to start with `sphinx-quickstart` command.
How do I install python's sphinx documentation generator in linux?
[ "", "python", "python-sphinx", "" ]
How do I find whether a DLL file written in C# is registered or not programmatically? I already tried this code, but it doesn't come off. If I register a DLL file and check using this code it returns. If I unregister it and run this same piece of code, it returns true again. I'm giving the full-path of the DLL file as argument. We developed a simple DLL file in [Visual C++](http://en.wikipedia.org/wiki/Visual_C%2B%2B#32-bit_versions). After that we registered it. Now we want to confirm whether it is registered. Bob, will you replace the piece of code on your own, it is still difficult for me? If I register a DLL file, is there an entry present in the registry? Shall I find those entries and judge whether the DLL file is registered or not?
You need to find out the GUID of a COM object defined in the DLL. Then look at this registry key: ``` HKEY_CLASSES_ROOT\CLSID\{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\InprocServer32 ``` Replace the x's with the GUID. It should have a default value that contains the full path to the DLL.
If you mean registered in GAC, here is my consideration: to be registered in GAC, an assembly must be signed with a strong name (have a **public key token** in it's name). So you can try load it using `Assembly.Load(string)`, if you got `FileNotFoundException` - assembly was not registered in GAC. If got no error, but result `Assembly.GetName().GetPublicKeyToken()` is null or empty -- this mean you found assembly in application directory, not in GAC.
How to check if a DLL file is registered?
[ "", "c#", ".net", "dllregistration", "" ]
I am creating a card game in C# for a school project. This card game is networked. The card game's game data is stored in a singleton object as gameData. gameData holds, the player names, which player the game is waiting on, player objects. Each player has 3 List objects. Where the cards are again custom objects. Originally I was going to create a ToByte() method for each card, player, and gameData object and serialize them to send over the network using TCPlistener. However running low on time I am looking for other ways. These are the solutions I have heard of: -SOAP (Have no clue how to implement this) -Database (seems overkill for LAN, unless if a small database server can be made to run on the fly) -Client Activated Object (but this create different singleton for each client) What I would like to do is make that each client use their own gameData but using the get, set it would talk to a server that host this singleton object data. What do you recommend?
WCF supports singleton services ``` [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] class MySingleton : ... {...} ``` This way you have one single service instance that serves all of your clients. WCF makes it easy to do network communication with very little network code. Check out [this article](http://msdn.microsoft.com/en-us/magazine/cc163590.aspx) for more details. Combine the singleton instance with any WCF tutorial you find, and you should have a good starting point. Good luck.
Since this is a school project, I think using .NET remoting is the fastest way to go :) To make things simple and reduce nasty debugging and object management stuff, I would suggest handling everything on the server using a singleton object and return marshal by value objects to clients as data (again, since it's a school project). Give each client an ID to pass to the server object.
How to go about serving a singleton object over the network in C#?
[ "", "c#", "singleton", "" ]
What is the fastest way to find out how many non-empty lines are in a file, using Java?
I am with Limbic System on the NIO recommendation. I've added a NIO method to Daphna's test code and bench marked it against his two methods: ``` public static void timeNioReader () throws IOException { long bef = System.currentTimeMillis(); File file = new File("/Users/stu/test.txt"); FileChannel fc = (new FileInputStream(file)).getChannel(); MappedByteBuffer buf = fc.map(MapMode.READ_ONLY, 0, file.length()); boolean emptyLine = true; int counter = 0; while (buf.hasRemaining()) { byte element = buf.get(); if (element == '\r' || element == '\n') { if (!emptyLine) { counter += 1; emptyLine = true; } } else emptyLine = false; } long after = System.currentTimeMillis() - bef; System.out.println("timeNioReader Time: " + after + " Result: " + counter); } ``` Here are the warmed up results for a 89MB file: ``` timeBufferedReader Time: 947 Result: 747656 timeFileReader Time: 670 Result: 747656 timeNioReader Time: 251 Result: 747656 ``` NIO is 2.5x faster than FileReader and 4x fastser than the BufferedReader! With a 6.4MB file the results are even better, although the warm up time is much longer. ``` //jvm start, warming up timeBufferedReader Time: 121 Result: 53404 timeFileReader Time: 65 Result: 53404 timeNioReader Time: 40 Result: 53404 //still warming up timeBufferedReader Time: 107 Result: 53404 timeFileReader Time: 60 Result: 53404 timeNioReader Time: 20 Result: 53404 //ripping along timeBufferedReader Time: 79 Result: 53404 timeFileReader Time: 56 Result: 53404 timeNioReader Time: 16 Result: 53404 ``` Make of it what you will.
The easiest way would be to use BufferedReader, and check which lines are empty. However, this is a relatively slow way, because it needs to create a String object for every line in the file. A faster way would be to read the file into arrays using read(), and then iterate through the arrays to count for line breaks. Here's the code for the two options; the second one took about 50% of the time on my machine. ``` public static void timeBufferedReader () throws IOException { long bef = System.currentTimeMillis (); // The reader buffer size is the same as the array size I use in the other function BufferedReader reader = new BufferedReader(new FileReader("test.txt"), 1024 * 10); int counter = 0; while (reader.ready()) { if (reader.readLine().length() > 0) counter++; } long after = System.currentTimeMillis() - bef; System.out.println("Time: " + after + " Result: " + counter); } public static void timeFileReader () throws IOException { long bef = System.currentTimeMillis(); FileReader reader = new FileReader("test.txt"); char[] buf = new char[1024 * 10]; boolean emptyLine = true; int counter = 0; while (reader.ready()) { int len = reader.read(buf,0,buf.length); for (int i = 0; i < len; i++) { if (buf[i] == '\r' || buf[i] == '\n') { if (!emptyLine) { counter += 1; emptyLine = true; } } else emptyLine = false; } } long after = System.currentTimeMillis() - bef; System.out.println("Time: " + after + " Result: " + counter); } ```
What is the fastest way to find out how many non-empty lines are in a file, using Java?
[ "", "java", "" ]
What is the most elegant way of restricting the input of a `TextBox` control (or anything else that comes standard with .NET 3.5) to floating point numbers? Currently, I'm doing all the heavy lifting myself by inheriting from `TextBox` and overriding `OnKeyPress`. However, I can't help but wonder if I'm reinventing the wheel.
Don't forget the following issues/corner-cases that you will be facing if you go down your proposed route: * Users can use `Ctrl`-`V` or `Shift`-`Insert` to paste "invalid" values in (That second one is a little trickier to catch) ... but users probably should be allowed to paste legal values into the control * Users can right click, paste invalid values in using the default context-menu * Even if you've tried to fix the previous issue by giving the textbox its own context menu, users can right-click outside your control, hold down the right button, drag over your textbox and let go to access the default context-menu (and paste in invalid values) * Whatever key processing you do shouldn't disable key combinations like `Alt` - `F4`, etc. (And yes, you will break this if you set `SuppressKeyPress` for everything that isn't a valid digit) * Users should probably be able to enter partial values (e.g. `"-."`, as they begin to type `"-.23"`) without your textbox punishing them * Numbers like `"-.1e-2"` could be considered legal * A user could feasibly enter a value which contains only digits, but which would overflow a `float` * **The worst one of all:** Some other mysterious corner case that your users will find after you've shipped (!!) The moral? It's can be very tricky to do what you're suggesting. You probably either want to do a combination of the following: * Use a control that someone that knows all the corner cases built (like microsoft) * Do basic validation in the `TextChanged` event (and doing something passive, like changing the textbox background color) * Save the validation until you actually try to use the value they've typed in * Use the system libraries to `Parse` the user's value for you
Take a look at the [MaskedTextBox](http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox(VS.80).aspx) control. It also inherits from TextBoxBase and probably has the functionality you're building into yours.
What is the best way to implement input restrictions on a TextBox in C#?
[ "", "c#", "winforms", "" ]
I'm trying to build a function that accepts an array in the following manner: ``` int inCommon = findCommon({54,56,2,10}, 4); int findCommon(int nums[], int len){ for(int i=0; i<len; i++) cout<<nums[i]<<endl; return 1; } ``` Note, that's not actually what my function does, but I do loop through the array. I'm just trying to determine if it's possible to pass an array like {54,56,2,10} instead of having to create an array and pass it? (like this: ``` int theArray[]= {54,56,2,10}; int inCommon = findCommon(theArray,4); ```
This is not possible at the time. However, in the next C++ standard C++0x, this will be done using initalizer lists: ``` int findCommon(std::initializer_list<int> nums) { std::initializer_list<int>::iterator it; for (it = nums.begin() ; it != nums.end() ; ++it) { std::cout << *it << std::endl; } return 1; } ``` See [this presentation](http://iap.cse.tamu.edu/IAP_Initializers) from Bjarne Stroustrup, and [this article](http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists) from Wikipedia If you want to try C++0x features, you can check the [last versions of gcc](http://gcc.gnu.org/projects/cxx0x.html), that supports some of them.
You need C++0x! <http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists>
Passing a list of numbers to a function in C++ without building array first?
[ "", "c++", "arrays", "function", "" ]
I have some special exception cases that I want to throw and catch, so I want to define my own exception classes. What are the best practices for that? Should I inherit from `std::exception` or `std::runtime_error`?
Yes, it's good practice to [inherit](https://isocpp.org/wiki/faq/exceptions#what-to-throw) from `std::runtime_error` or the [other standard exception classes](http://en.cppreference.com/w/cpp/error/exception) like `std::logic_error`, `std::invalid_argument` and so on, depending on which kind of exception it is. If all the exceptions inherit some way from `std::exception` it's easy to catch all common errors by a `catch(const std::exception &e) {...}`. If you have several independent hierarchies this gets more complicated. Deriving from the specialized exception classes makes these exceptions carry more information, but how useful this really is depends on how you do your exception handling.
I'm not a C++ developer, but one thing we did in our C# code was create a base class exception for our framework, and then log the exception thrown in the constructor: ``` public FrameworkException(string message, Exception innerException) : base(message, innerException) { log.Error(message, innerException); } ... ``` Any derived exception just has to invoke it's base constructor and we get consistent exception logging throughout. Not a big deal, but useful.
Best practices for defining your own exception classes?
[ "", "c++", "exception", "inheritance", "error-handling", "" ]
I've been playing with PyWinAuto today and having fun automating all sorts GUI tests. I was wondering if it is still state of the art or if there might be something else (also free) which does windows rich client automation better.
pywinauto is great because it's Python. Perhaps a bit more full featured is [AutoIT](http://www.autoitscript.com/autoit3/index.shtml), which has a COM server that you can automate (from Python using win32com), and some cool tools, like a "[Window Info](http://www.autoitscript.com/autoit3/docs/intro/au3spy.htm)" utility, which will give you the text (title), class, size, status-bar text, and so on for the window currently under the mouse cursor. There are some cases where pywinauto is a bit harder to use than AutoIt, and seems a little less polished. One example is automating Inno Setup programs. The Inno Setup "setup.exe" program launches a separate application that actually performs the install, and it's a pain to track this down with pywinauto, but AutoIt makes it easy.
I used to do test automation on our projects with AutoIt but switched over to pywinauto 3 months ago and have been very happy with that decision. There are some rough edges, but I've been able to fill them in with my own supplementary test functions. In addition I find that coding tests and support code in Python is *much* easier and more manageable compared to AutoIt. With Python I have way more powerful options for logging, debugging, documentation, process management and test configuration. For me it was absolutely the right way to go.
PyWinAuto still useful?
[ "", "python", "pywinauto", "" ]
In Java, you can have a List of Objects. You can add objects of multiple types, then retrieve them, check their type, and perform the appropriate action for that type. For example: (apologies if the code isn't exactly correct, I'm going from memory) ``` List<Object> list = new LinkedList<Object>(); list.add("Hello World!"); list.add(7); list.add(true); for (object o : list) { if (o instanceof int) ; // Do stuff if it's an int else if (o instanceof String) ; // Do stuff if it's a string else if (o instanceof boolean) ; // Do stuff if it's a boolean } ``` What's the best way to replicate this behavior in C++?
Your example using Boost.Variant and a visitor: ``` #include <string> #include <list> #include <boost/variant.hpp> #include <boost/foreach.hpp> using namespace std; using namespace boost; typedef variant<string, int, bool> object; struct vis : public static_visitor<> { void operator() (string s) const { /* do string stuff */ } void operator() (int i) const { /* do int stuff */ } void operator() (bool b) const { /* do bool stuff */ } }; int main() { list<object> List; List.push_back("Hello World!"); List.push_back(7); List.push_back(true); BOOST_FOREACH (object& o, List) { apply_visitor(vis(), o); } return 0; } ``` One good thing about using this technique is that if, later on, you add another type to the variant and you forget to modify a visitor to include that type, it will not compile. You *have* to support every possible case. Whereas, if you use a switch or cascading if statements, it's easy to forget to make the change everywhere and introduce a bug.
[`boost::variant`](http://www.boost.org/doc/libs/1_38_0/doc/html/variant.html) is similar to dirkgently's suggestion of `boost::any`, but supports the Visitor pattern, meaning it's easier to add type-specific code later. Also, it allocates values on the stack rather than using dynamic allocation, leading to slightly more efficient code. **EDIT:** As litb points out in the comments, using `variant` instead of `any` means you can only hold values from one of a prespecified list of types. This is often a strength, though it might be a weakness in the asker's case. Here is an example (not using the Visitor pattern though): ``` #include <vector> #include <string> #include <boost/variant.hpp> using namespace std; using namespace boost; ... vector<variant<int, string, bool> > v; for (int i = 0; i < v.size(); ++i) { if (int* pi = get<int>(v[i])) { // Do stuff with *pi } else if (string* si = get<string>(v[i])) { // Do stuff with *si } else if (bool* bi = get<bool>(v[i])) { // Do stuff with *bi } } ``` (And yes, you should technically use `vector<T>::size_type` instead of `int` for `i`'s type, and you should technically use `vector<T>::iterator` instead anyway, but I'm trying to keep it simple.)
Storing a list of arbitrary objects in C++
[ "", "c++", "collections", "types", "" ]
I have a few images with some text, I need to show the image with the relevant text in a listbox. Browsing google I came across this sample class, ``` public class Customer { public string Fname; public string Lname; public Customer(string firstName, string lastName) { Fname = firstName; Lname = lastName; } public override string ToString() { return Fname + " " + Lname; } } lstCustomers.Items.Add(new Customer("Foo","Bar")); ``` The above code works fine as it only returns string, how do I return an image and a string together so that it gets added to the listbox? Best Regards @nand
Just use a `DataTemplate` to display your objects in the `ListBox`. Create a data object that contains string properties and an Image property: ``` public class Img { public Img(string value, Image img) { Str = value; Image = img; } public string Str { get; set; } public Image Image { get; set; } } ``` Create a `DataTemplate` to display this: ``` <ListBox x:Name="lstBox"> <ListBox.ItemTemplate> <DataTemplate DataType="{x:Type local:Img}"> <StackPanel> <TextBlock Margin="3" Text="{Binding Str}"/> <ContentControl Margin="3" Content="{Binding Image}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> ``` Now add the `Img` items (or your data objects) to the `ListBox` like so: ``` lstBox.Items.Add(new Img("Value", myImage)); ```
You can't (without hacking around) put images in ListBoxes. You can put them in ListViews. You need to put your image(s) in an ImageList component, then attach the ImageList to your listview. Of course, you can encapsulate your image in your class by adding an Image property and adding that to the ImageList.Items collection. Then for each ListViewItem in the List, set the ImageIndex property to the index of the image in the listview. All this can be done using the designer.
Add image to listbox
[ "", "c#", "wpf", "image", "listbox", "return-value", "" ]
Has anyone out there actually succeeded in creating a prerequisitie for o2003.msi? There are a *lot* of people out there asking about this, but I cannot find anyone who actually succeeded. I find some extremely complicated solutions where you are required to comple .cpp-files for which the soure may or may not be supplied. I even tried to complie one of those but got configuration error on the target machine... :-( If I don't install o2003.msi, my Office "Shared Add-In" will throw an exception because office.dll cannot be found. So I would very much like to have it included in my installer. And a second question, regardless of the outcome of the previous one: what about a machine with Office 2007? 02203.msi complains that Office 2003 is not installed, so there seems to be a lot of things I need to get done in order to create a working installer for an "Office Shared Add-In"... anyone else going through the same nightmare? Update: It seems to be the PIA for Office.Core / "office.dll" which is the really thing to get on the traget machine. None of the "complicated" solutions (which I know I can get to work if I put some effort in it) talks how to detect this particular file, just PIAs for Word & Excel and then some. These seems to be in place anyway. It's office.dll that is the important file to check for and install o2003pia.msi if it is not properly installed!
This is probably too little too late, but here's a solution I've done for installing our company's office 2003 and 2007 addins using a small bit of C# code. Maybe it could work for you. I use the Product Codes for both the o2003pia and the o2007pia installations which are: 2003: **{91490409-6000-11D3-8CFE-0150048383C9}** 2007: **{50120000-1105-0000-0000-0000000FF1CE}** Then, by calling the MSI API you can get the install state for each. Here's an example of finding the 2003: ``` [DllImport("msi.dll")] private static extern MsiInstallState MsiQueryProductState (string productGuid); [DllImport("msi.dll")] private static extern uint MsiGetProductInfo (string productGuid, string propertyName, StringBuilder valueBuffer, ref Int32 bufferSize); bool IsPia2003Installed() { MsiInstallState state = MsiQueryProductState("{91490409-6000-11D3-8CFE-0150048383C9}"); return (state == MsiInstallState.msiInstallStateDefault); } ``` If you're trying to accomplish all of this entirely inside the setup project (I assume you're using Visual Studio?) then you can add a "Windows Installer Search" launch condition that checks for the above mentioned ProductCodes. If it's satisfied you can run a custom action that installs the PIAs. For more information on this solution I'd suggest starting here [here](http://msdn.microsoft.com/en-us/library/f09xywha(VS.80).aspx).
Not sure why, but I looked at the O2003PIA.MSI and O2007PIA.MSI, and got the following product codes: O2003PIAProductCode = "{90409419-0006-3D11-C8EF-10054038389C}" O2007PIAProductCode = "{00002105-5011-0000-0000-000000F01FEC}"
.NET Deploying Office 2003 Redistributable Primary Interop Assemblies (o2003pia.msi)
[ "", "c#", ".net", "deployment", "ms-office", "add-in", "" ]
Currently I have a the following way of retrieving data from my DB: ``` $school->get('studentCount'); ``` I required a shortcut to access these fields within the page and so came up with a format like this: ``` <p>Blah blah blah [[studentCount]]</p> ``` I have output buffering turned on but just need an easy way of replacing that key ('[[field-name]]') with its corresponding data from the DB. If it was just one field I could do a str\_replace on the output like this: ``` str_replace($output, '[[studentCount]]', $school->get('studentCount')) ``` Unfortunately that's not suitable. My ideal solution would grab whatever is between '[[' and ']]' and then run the 'get' method and replace the entire key ('[[...]]') with whatever is returned.
Well you could create two arrays, one with the field-name strings `[[field-name]]` and one with the responses `$school->get('field-name')`. Then throw those in `str_replace` as it supports arrays. Example from PHP Manual: ``` $phrase = "You should eat fruits, vegetables, and fiber every day."; $healthy = array("fruits", "vegetables", "fiber"); $yummy = array("pizza", "beer", "ice cream"); $newphrase = str_replace($healthy, $yummy, $phrase); // Resulting String: "You should eat pizza, beer, and ice cream every day." ``` If you still wanted to implement your suggestion (finding all [[]]s and replacing them), I'll try to write up a quick function. **Edit:** Here are two methods of doing it via your request: ``` $html = "Hello, [[FirstName]]! Welcome to [[SiteName]]."; $count = preg_match_all("/\[\[([\w]+)\]\]/", $html, $matches); for ($x = 0; $x < $count; $x++) $html = str_replace($matches[0][$x], $school->get($matches[1][$x]), $html); ``` Or using arrays: ``` $html = "Hello, [[FirstName]]! Welcome to [[SiteName]]."; $count = preg_match_all("/\[\[([\w]+)\]\]/", $html, $matches); for ($x = 0; $x < $count; $x++) $matches[1][$x] = $school->get($matches[1][$x]); $html = str_replace($matches[0], $matches[1], $html); ```
I'm pretty sure this will work. :) ``` <?php // $output contains the string preg_match_all('/\[{2}([^\[]+)\]{2}/', $output, $matches); $replaces = $matches['1']; foreach($replaces as $replace) $str = str_replace('[['.$replace.']]', $school->get($replace), $output); ?> ```
Replace 'keys' in file with DB data
[ "", "php", "" ]
Should a buffer of bytes be signed char or unsigned char or simply a char buffer? Any differences between C and C++? Thanks.
> Should a buffer of bytes be signed > char or unsigned char or simply a char > buffer? Any differences between C and > C++? A minor difference in how the language treats it. A **huge** difference in how convention treats it. * `char` = ASCII (or UTF-8, but the signedness gets in the way there) **textual** data * `unsigned char` = byte * `signed char` = rarely used And there is code that *relies* on such a distinction. Just a week or two ago I encountered a bug where JPEG data was getting corrupted because it was being passed to the `char*` version of our Base64 encode function — which "helpfully" replaced all the invalid UTF-8 in the "string". Changing to `BYTE` aka `unsigned char` was all it took to fix it.
If you intend to store arbitrary binary data, you should use `unsigned char`. It is the only data type that is guaranteed to have no padding bits by the C Standard. Each other data type may contain padding bits in its object representation (that is the one that contains all bits of an object, instead of only those that determines a value). The padding bits' state is unspecified and are not used to store values. So if you read using `char` some binary data, things would be cut down to the value range of a char (by interpreting only the value bits), but there may still be bits that are just ignored but still are there and read by `memcpy`. Much like padding bits in real struct objects. Type `unsigned char` is guaranteed to not contain those. That follows from `5.2.4.2.1/2` (C99 TC2, n1124 here): > If the value of an object of type char is treated as a signed integer when used in an > expression, the value of `CHAR_MIN` shall be the same as that of `SCHAR_MIN` and the > value of `CHAR_MAX` shall be the same as that of `SCHAR_MAX`. Otherwise, the value of > `CHAR_MIN` shall be 0 and the value of `CHAR_MAX` shall be the same as that of > `UCHAR_MAX`. *The value `UCHAR_MAX` shall equal `2^CHAR_BIT − 1`* From the last sentence it follows that there is no space left for any padding bits. If you use `char` as the type of your buffer, you also have the problem of overflows: Assigning any value explicitly to one such element which is in the range of `8` bits - so you may expect such assignment to be OK - but not within the range of a `char`, which is `CHAR_MIN`..`CHAR_MAX`, such a conversion overflows and causes implementation defined results, including raise of signals. Even if any problems regarding the above would probably not show in real implementations (would be a *very* poor quality of implementation), you are best to use the right type from the beginning onwards, which is `unsigned char`. For strings, however, the data type of choice is `char`, which will be understood by string and print functions. Using `signed char` for these purposes looks like a wrong decision to me. For further information, read [`this proposal`](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1310.htm) which contain a fix for a next version of the C Standard which eventually will require `signed char` not have any padding bits either. It's already incorporated into the [working paper](http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1362.pdf).
Should a buffer of bytes be signed or unsigned char buffer?
[ "", "c++", "c", "char", "buffer", "" ]
I want to calculate some trends based on the values I get in my SQL database. Particularly I am interested in getting the % increase of the values in one column (the value should be negative in case the values have decreased) Can someone please advice how I should do this? I cannot use stored procedures. Thanks. **My table has the following columns** Date (numeric), Month (numeric), Orders (numeric), Price (real) I want to calculate the % of change in the number of orders received from one month to next. I also want the direction to be a consideration i.e. the value returned should be -ve in case the sales have decreased.
I'm not sure if sqllite allows for variables, but this is the way I do it in MySQL. I've just tested this and worked like a charm: printed 100% for a 10 to 20 increase, -13.04% for 46 to 40 decrease. Hopefully it's similar in sqllite: ``` SELECT CONCAT( FORMAT( IF(@prev AND SUM(orders) <> @prev, -1 * 100 * (1 - SUM(orders) / @prev), 0 ) , 2) , '%') AS variation, @prev := SUM(orders) AS orders FROM (SELECT @prev := NULL) init, product GROUP BY id_product ORDER BY month ``` Of course, you'll need to tweak output as you need. This currently formats the precentages to 2 decimals and appends a "%" at the end.
In order to calculate trends, you will need to store historical data of the values you are interested in.
SQL - calculate percentage increase in values of a numeric column
[ "", "sql", "sqlite", "" ]
Please redirect me if a similar question exists.. I haven't been able to find anything, though I'm sure that my problem is fairly common... I have a page that has 5-6 divs that can be individually loaded through Ajax requests. Through a prototype ajax.request(), the server (php) echoes back the HTML code for the division before the client refreshes the divs's innerHTMLs. Here's my question : **What's the best practice for preserving the MVC pattern on the server side concerning the HTML code it throws out?** For now, my models return database data to the controller, enabling it to initiate a **really long** var containing the HTML code that it then echoes. My problem is that I end up with a lot of HTML code in my controller classes...
You could use [JSON](http://json.org/) for transporting data to the client-side and constructing it there. That way you'll have an abstracted data source not bound by your markup. JSON can be directly evaluated into a javascript object.
Do you really like to use MVC? The C can mostly be removed by Conventions / RESTful URLs. Like Andy said, you should use JSON to transfer the data to the client side. XML is also a wide used alternative (because it acts much better if other apps have to use your services). XML can be tranformed easily to JSON! And JSON code is valid JavaScript Object code. So you can use it to stich client side templates together with it. You should try [EJS](http://embeddedjs.com/) for browser/client side templating! If you do so, you have no HTML boilerplate in your controllers! Just business logic. That follows a lot of SOA best practices. The architecture pattern is called SOFEA or SOUI (which is the same). I've written my homepage with it. The evaluation of a lot template engines has clerified that EJS is the best candidate. Because: 1. It's fast! 2. It's free (MIT License)! 3. It works well with JQuery 4. It does realy modify the DOM, so other methods can access the used templates ([JS Repeater](http://jsrepeater.devprog.com/) doesn't). Other frameworks: 1. [JSmarty](http://code.google.com/p/jsmarty/): Not such as easy to use but it can use Smarty templates. It isn't enteprise prooven and still under heavy development. 2. [Trimpath Javascript Templates](http://code.google.com/p/trimpath/wiki/JavaScriptTemplates): Doesn't work well with JQuery/Prototype... Also still under development. 3. [jQSmarty](http://www.balupton.com/sandbox/jquery_smarty/): Nice, but it seems that the development has stopped. The last change was in 2008. 4. [seethrough\_js](http://wiki.github.com/bard/seethrough_js): Invasive template layouting. Nice for Erlang people. 5. [JsonML](http://jsonml.org/BST/): Also an invasive template format which is based on JSON. What do you think about it? I think designers should stay at their HTML/CSS elements, so no knowledge is wasted. 6. [JS Repeater](http://jsrepeater.devprog.com/): Reminds me at my own bad tries. I've checked it out and used it.. but it doesn't handle a lot of things very well. (Such es empty fields etc.) 7. [Pure](http://beebole.com/pure/): Time to start a relegios war on how to develop pages? I think that Pure isn't the answer. It's bloating if you define what's really to do and it fails to scale like JSF. It has no invasive syntax, thats very good. But the price of the hard to use rules for rendering issues are a no go for me. It just feels don't right. I've met other people which think completly different! Test it out and let me know what you think.
AJAX and the MVC pattern
[ "", "php", "ajax", "model-view-controller", "" ]
How to create and download excel document using asp.net ? The purpose is to use xml, linq or whatever to send an excel document to a customer via a browser. Edit : **Use case** The customer load a gridview ( made with ajax framework ) in a browser, the gridview is directly linked to an sql database. I put a button 'export to excel' to let customer save this gridview data on his computer ansd i would like to launch a clean download of an excel. The solutions proposed here are not clean, like send an html document and change the header to excel document etc, i'm searching a simple solution on codeplex right now, i will let you know.
## Starter kit First i have downloaded the [**Open XML Format SDK 2.0**](http://www.microsoft.com/downloads/details.aspx?FamilyID=c6e744e5-36e9-45f5-8d8c-331df206e0d0&DisplayLang=en). It comes with 3 useful tools in : C:\Program Files\Open XML Format SDK\V2.0\tools * `DocumentReflector.exe` wich auto generate the c# to build a spreadsheet from the code. * `OpenXmlClassesExplorer.exe` display Ecma specification and the class documentation (using an MSDN style format). * `OpenXmlDiff.exe` graphically compare two Open XML files and search for errors. I suggest anyone who begin to **rename** ***.xlsx*** **to** **.zip**, so you can see the XML files who drive our spreadsheet ( for the example our sheets are in "xl\worksheets" ). --- ## The code **Disclaimer** : I have stolen all the code from an [**MSDN technical article**](http://msdn.microsoft.com/en-us/library/dd452407.aspx) ;D The following code use an \*.xlsx template i made manually to be able to modify it. Namespaces references ``` using System.IO; using System.Xml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using DocumentFormat.OpenXml; // Database object DataClassesDataContext db = new DataClassesDataContext(); // Make a copy of the template file. File.Copy(@"C:\inetpub\wwwroot\project.Web\Clients\Handlers\oxml-tpl\livreurs.xlsx", @"C:\inetpub\wwwroot\project.Web\Clients\Handlers\oxml-tpl\generated.xlsx", true); // Open the copied template workbook. using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(@"C:\inetpub\wwwroot\project.Web\Clients\Handlers\oxml-tpl\generated.xlsx", true)) { // Access the main Workbook part, which contains all references. WorkbookPart workbookPart = myWorkbook.WorkbookPart; // Get the first worksheet. WorksheetPart worksheetPart = workbookPart.WorksheetParts.ElementAt(2); // The SheetData object will contain all the data. SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>(); // Begining Row pointer int index = 2; // Database results var query = from t in db.Clients select t; // For each item in the database, add a Row to SheetData. foreach (var item in query) { // Cell related variable string Nom = item.Nom; // New Row Row row = new Row(); row.RowIndex = (UInt32)index; // New Cell Cell cell = new Cell(); cell.DataType = CellValues.InlineString; // Column A1, 2, 3 ... and so on cell.CellReference = "A"+index; // Create Text object Text t = new Text(); t.Text = Nom; // Append Text to InlineString object InlineString inlineString = new InlineString(); inlineString.AppendChild(t); // Append InlineString to Cell cell.AppendChild(inlineString); // Append Cell to Row row.AppendChild(cell); // Append Row to SheetData sheetData.AppendChild(row); // increase row pointer index++; } // save worksheetPart.Worksheet.Save(); } ``` I havent finished yet, my second job is to auto download the spreadsheet after modification. --- Finally, i redirect the user to my generated spredsheet (from my aspx) ``` context.Response.Redirect("Oxml-tpl/generated.xlsx"); ```
just set Response.ContentType = "application/vnd.ms-excel" and your page will rendered as an excel sheet on the clients browser [Sample code here](http://www.thaicreate.com/asp.net/asp.net-excel-application-vnd.ms-excel.html)
how to create and download excel document using asp.net
[ "", "c#", "asp.net", "excel", "openxml", "" ]
I want to create a class (static?) that simply maps a name to a value (1 to 1). What's a clean way of doing something like this: ``` public static class FieldMapper { public static GetValue(string Name) { if (Name == "abc") return "Value1"; if (Name == "def") return "Value2"; } } ``` I might be having a mind block today. I am unable to think of a clean solution for a simple problem like this :( **Edit: All the values are known at compile time (There is no uniqueness - different keys can map to same value). I shouldn't be creating a datastructure that adds values at runtime. Also, I would like to avoid using a XML file**
If you want the collection to be created at compile time instead of at startup, you could just use a switch. If the switch contains more than a few items (five IIRC) it's implemented using a hash lookup, so it's very fast even if you put a lot of cases in it. (I.e. the access time is the same for any of the cases.) ``` public static class FieldMapper { public static string GetValue(string name) { switch (name) { case "abc": return "Value1"; case "def": return "Value2"; } throw new ArgumentException("Unknown name.", "name"); } } ```
Sounds like a job for a dictionary. ``` Dictionary<string, string> values = new Dictionary<string, string>(); values.Add("abc", "Value1"); values.Add("def", "Value2"); Console.WriteLine(values["abc"]); // Prints "Value1" ```
Creating a simple name value mapper class in C#
[ "", "c#", "" ]
I have a Java web application designed to be deployed on the internet. It needs a database connection. Depending upon hosting environments it may not be possible for the deployers of the web application to configure appropriate data sources so the application needs to store it's database connection information somewhere to be reloaded if the application is restarted. I also need to give one user administrator privilileges. If this is just the first user account created there is the small possibility that the admin account could be hijacked in between the time that the application is deployed and the time that the installer logs in. I need to do both of these tasks securely and in a way that is lowest common denominator for a web application. Clarification: Upon first use I want the application to set up an admin user. That admin user will have all security access in the system. Somehow I need to determine what that user is called and what their password will be. If the application gets deployed on a shared web host the application will be live from the moment it is deployed. If I allow the site to be configured through a web interface there is the small possibility that an unauthorised person will do the web configuration before the site owner effectively hijacking the site. I am looking for an elegant way to avoid this.
Ok, to answer your revised question... There isn't really that much you can do. If you don't want the admin to configure their account during installation on the server, then there will always be a small window where someone else might create it via the web before they do. All the solutions involve modifying something on the server (as this is how they prove they are the *real* admin). Yes, that can mean a config file... * Upon first connect, give the user a token. Basically a hash of some salt+theirIP+theirUserAgent, etc. Then ask them to log into the server and feed this token to your app, probably in a config file. If the generated token next time matches the one in the config, allow them to proceed. * A simpler solution is to let them put their IP address in the config from the start, and just allow this IP. (Assumes they know what their IP address is) * Alternatively, allow account creation, but refuse to do anything else until some file is removed from the server. Many PHP apps do this with an install.php, but the file could be anything you test for.
The most common way to do this is through a static configuration file, in some simple text format. The file resides on the same system as the application, and should be just as secure as the code (eg. if someone has access to modify the configuration who shouldn't be able to, couldn't they just as easily modify the code?)
What are some good patterns for performing initial configuration of a web application?
[ "", "java", "security", "web-applications", "" ]
I am creating a website and on one particular page, am wanting to send the user back to the previous page. I am fairly new to PHP/HTML and have been using some existing code for ideas and help. The existing code uses the following method: ``` if (! empty($HTTP_REFERER)) { header("Location: $HTTP_REFERER"); } else { header("Location: $CFG->wwwroot"); } ``` However, when I use this code the HTTP\_referer is always treated as empty and the user redirected to the root page. Any obvious flaws in this code?
You need to use: ``` $_SERVER['HTTP_REFERER'] ```
Don't rely on the HTTP Referrer being a valid or even non-empty field. People can choose to not have this set leaving any checks for that variable going to the empty side of the IF-ELSE clause. You can guard against this by sending along a parameter in either the URL or POST parameters that would hold a value that you can use to redirect the user back to.
php/html - http_referer
[ "", "php", "html", "http-referer", "" ]
I have created a user control with web controls defined in the aspx file and made it's codebehind class abstract. I extend this class with another user control, but the the controls in the initial markup file don't get generated. How do i generate them for every user control extending the abstract class and how do i make them accessible?
Create a Composite Control <http://wiki.asp.net/page.aspx/217/composite-controls/> and take a look at <http://msdn.microsoft.com/en-us/library/aa479016.aspx> basically you can create a custom control and add other controls in the back end
User Controls really can't be truely extended. You can base your code behind on abstract / extended classes but there is no way to do that with markup. Consider creating custom server based controls.
How do I extend a user control in asp.net?
[ "", "c#", "asp.net", "" ]
I implemented a simple button with an image in it: ``` <Button Command="{Binding ButtonCommand, ElementName=ImageButtonControl}"> <StackPanel Orientation="Horizontal"> <Image Source="{Binding ButtonImage, ElementName=ImageButtonControl}"/> <TextBlock Text="{Binding ButtonText, ElementName=ImageButtonControl}" Margin="2,0,0,0"/> </StackPanel> </Button> ``` As you can see, I expose a ButtonCommand property in order to be able to attach an ICommand to this UserControl: ``` public partial class ImageButton : UserControl { /// <summary> /// The dependency property that gets or sets the source of the image to render. /// </summary> public static DependencyProperty ImageSourceProperty = DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(ImageButton)); public static DependencyProperty TextProperty = DependencyProperty.Register("ButtonText", typeof(string), typeof(ImageButton)); public static DependencyProperty ButtonCommandProperty = DependencyProperty.Register("ButtonCommand", typeof(ICommand), typeof(ImageButton)); public ImageButton() { this.DataContext = this; InitializeComponent(); } /// <summary> /// Gets or sets the button command. /// </summary> public ICommand ButtonCommand { get { return (ICommand)GetValue(ImageButton.ButtonCommandProperty); } set { SetValue(ImageButton.ButtonCommandProperty, value); } } /// <summary> /// Gets or sets the button image. /// </summary> public ImageSource ButtonImage { get { return (ImageSource)GetValue(ImageButton.ImageSourceProperty); } set { SetValue(ImageButton.ImageSourceProperty, value); } } /// <summary> /// Gets or sets the button text. /// </summary> public string ButtonText { get { return (string)GetValue(ImageButton.TextProperty); } set { SetValue(ImageButton.TextProperty, value); } } } ``` Then when I declare my button it gives this: `<uc:ImageButton Grid.Row="1" Grid.Column="0" ButtonCommand="{Binding AttachContextCommand}" ButtonImage="{StaticResource AssociateImage}" ButtonText="Associer"/>` And badaboom, nothing never happen when I click on my ImageButton. When I replace the ImageButton with a simple button, the ICommand is called. I even tried to simply extends the Button class and bind an ICommand, but once again, it didn't work... Help appreciated ! Thx.
You can achieve this in a much cleaner way using a style and a couple of attached properties. The attached properties will store your specific information. The style will use these properties and build the look you want. The element will still be a button so the command and everything else will work. ``` public class ImageButton { public static ImageSource GetImage(DependencyObject obj) { return (ImageSource)obj.GetValue(ImageProperty); } public static void SetImage(DependencyObject obj, ImageSource value) { obj.SetValue(ImageProperty, value); } public static readonly DependencyProperty ImageProperty = DependencyProperty.RegisterAttached("Image", typeof(ImageSource), typeof(ImageButton), new UIPropertyMetadata(null)); public static String GetCaption(DependencyObject obj) { return (String)obj.GetValue(CaptionProperty); } public static void SetCaption(DependencyObject obj, String value) { obj.SetValue(CaptionProperty, value); } public static readonly DependencyProperty CaptionProperty = DependencyProperty.RegisterAttached("Caption", typeof(String), typeof(ImageButton), new UIPropertyMetadata(null)); } <Style TargetType="{x:Type Button}" x:Key="ImageButton"> <Setter Property="ContentTemplate"> <Setter.Value> <DataTemplate> <StackPanel Orientation="Horizontal"> <Image Source="{Binding Path=(local:ImageButton.Image), RelativeSource={RelativeSource AncestorType={x:Type Button}}}" /> <TextBlock Text="{Binding Path=(local:ImageButton.Caption), RelativeSource={RelativeSource AncestorType={x:Type Button}}}" Margin="2,0,0,0" /> </StackPanel> </DataTemplate> </Setter.Value> </Setter> </Style> ``` You can then use this to declare buttons: ``` <Button Style="{DynamicResource ImageButton}" local:ImageButton.Caption="Foo" local:ImageButton.Image="..." /> ``` Note: I'm pretty sure it would be cleaner to go through the "Template" property and use a ControlTemplate and TemplateBindings, but that would mean re-creating the border and other stuff around your content, so if you are looking to just define a default "Content", my example would be the way to go, I think.
If the only added functionality that you want for your button is to have an image on it, then I think you're approaching this from the wrong direction. WPF is as awesome as it is because the UI controls are **look-less.** This means that a Control is merely a definition of functionality + some template to define how it looks. This means that the template can be swapped out at any time to change the look. Also, almost any content can be placed inside of almost any control For instance, to define a button in your xaml that has the look your going for all you need is this: ``` <Window ...> ... <Button Command="{Binding AttachContextCommand}"> <StackPanel Orientation="Horizontal"> <Image Source="{StaticResource AssociateImage}"/> <TextBlock Text="Associer"/> </StackPanel> </Button> ... </Window> ``` Just keep in mind that with WPF you don't have to define a new CustomControl or UserControl every time you want to change the look and feel of something. The only time you should need a CustomControl is if you want to add functionality to an existing Control or to create functionality that doesn't exist in any other Control. **Edit Due to comment:** If you're wanting to keep from defining the content for the button every time, the other option is to just have a poco (plain old CLR object) class that would define everything your interested in (I'll write my example as if you're doing this for a tool bar, because it makes sense to me): ``` public class ToolBarItem : INotifyPropertyChanged { public string Text { get ... set ... } public ICommand Command { get ... set ... } public ImageSource Image { get ... set ... } } ``` That has a data template defined somewhere (App.xaml, Window.Resources, etc): ``` <DataTemplate DataType="{x:Type l:ToolBarItem}"> <Button Command="{Binding Command}"> <StackPanel Orientation="Horizontal"> <Image Source="{Binding Image}"/> <TextBlock Text="{Binding Text}"/> </StackPanel> </Button> </DataTemplate> ``` And then use the guy in your xaml like this: ``` <Window ...> ... <ContentControl> <ContentControl.Content> <l:ToolBarItem Image="..." Command="..." Text="..."/> </ContentControl.Content> </ContentControl> ... </Window> ``` I just don't know that the way you're trying to do it is the most WPF way you could do it. **EDIT Updated based on second comment** Sorry, I forgot to include the ContentControl surrounding that. Now that I remembered that, I realize that that's not much less verbose than the original where you are specifying the content manually. I'll post a new answer to help with your original question.
Attach ICommand in WPF UserControl
[ "", "c#", "wpf", "mvvm", "user-controls", "" ]
I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is *not* the largest, as it ought to be. So, this question is really two questions: 1. What exactly is [`numpy.correlate`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.correlate.html) doing? 2. How can I use it (or something else) to do auto-correlation?
To answer your first question, `numpy.correlate(a, v, mode)` is performing the convolution of `a` with the reverse of `v` and giving the results clipped by the specified mode. The [definition of convolution](http://mathworld.wolfram.com/Convolution.html), C(t)=∑ -∞ < i < ∞ aivt+i where -∞ < t < ∞, allows for results from -∞ to ∞, but you obviously can't store an infinitely long array. So it has to be clipped, and that is where the mode comes in. There are 3 different modes: full, same, & valid: * "full" mode returns results for every `t` where both `a` and `v` have some overlap. * "same" mode returns a result with the same length as the shortest vector (`a` or `v`). * "valid" mode returns results only when `a` and `v` completely overlap each other. The [documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html) for `numpy.convolve` gives more detail on the modes. For your second question, I think `numpy.correlate` *is* giving you the autocorrelation, it is just giving you a little more as well. The autocorrelation is used to find how similar a signal, or function, is to itself at a certain time difference. At a time difference of 0, the auto-correlation should be the highest because the signal is identical to itself, so you expected that the first element in the autocorrelation result array would be the greatest. However, the correlation is not starting at a time difference of 0. It starts at a negative time difference, closes to 0, and then goes positive. That is, you were expecting: autocorrelation(a) = ∑ -∞ < i < ∞ aivt+i where 0 <= t < ∞ But what you got was: autocorrelation(a) = ∑ -∞ < i < ∞ aivt+i where -∞ < t < ∞ What you need to do is take the last half of your correlation result, and that should be the autocorrelation you are looking for. A simple python function to do that would be: ``` def autocorr(x): result = numpy.correlate(x, x, mode='full') return result[result.size/2:] ``` You will, of course, need error checking to make sure that `x` is actually a 1-d array. Also, this explanation probably isn't the most mathematically rigorous. I've been throwing around infinities because the definition of convolution uses them, but that doesn't necessarily apply for autocorrelation. So, the theoretical portion of this explanation may be slightly wonky, but hopefully the practical results are helpful. [These](http://mathworld.wolfram.com/Autocorrelation.html) [pages](http://en.wikipedia.org/wiki/Autocorrelation) on autocorrelation are pretty helpful, and can give you a much better theoretical background if you don't mind wading through the notation and heavy concepts.
Auto-correlation comes in two versions: statistical and convolution. They both do the same, except for a little detail: The statistical version is normalized to be on the interval [-1,1]. Here is an example of how you do the statistical one: ``` def acf(x, length=20): return numpy.array([1]+[numpy.corrcoef(x[:-i], x[i:])[0,1] \ for i in range(1, length)]) ```
How can I use numpy.correlate to do autocorrelation?
[ "", "python", "math", "numpy", "numerical-methods", "" ]
I am trying to do a [Project Euler](https://projecteuler.net/problems) problem but it involves adding the digits of a very large number. (100!) Using Java int and long are too small. Thanks for any suggestions
Class [BigInteger](http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html) looks like it might be what you are looking for.
Use [BigInteger](http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigInteger.html). Here is an [example](http://www.java2s.com/Code/Java/Development-Class/BigIntegerdemo.htm) from the book *Java Examples in a Nutshell* that involves computing factorials, with caching. ``` import java.math.BigInteger; import java.util.ArrayList; /* * Copyright (c) 2000 David Flanagan. All rights reserved. * This code is from the book Java Examples in a Nutshell, 2nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or * implied. You may study, use, and modify it for any non-commercial * purpose. You may distribute it non-commercially as long as you * retain this notice. For a commercial use license, or to purchase * the book (recommended), visit * http://www.davidflanagan.com/javaexamples2. */ /** * This program computes and displays the factorial of a number * specified on the command line. It handles possible user input * errors with try/catch. */ public class FactComputer { public static void main(String[] args) { // Try to compute a factorial. // If something goes wrong, handle it in the catch clause below. try { int x = Integer.parseInt(args[0]); System.out.println(x + "! = " + Factorial4.factorial(x)); } // The user forgot to specify an argument. // Thrown if args[0] is undefined. catch (ArrayIndexOutOfBoundsException e) { System.out.println("You must specify an argument"); System.out.println("Usage: java FactComputer <number>"); } // The argument is not a number. Thrown by Integer.parseInt(). catch (NumberFormatException e) { System.out.println("The argument you specify must be an integer"); } // The argument is < 0. Thrown by Factorial4.factorial() catch (IllegalArgumentException e) { // Display the message sent by the factorial() method: System.out.println("Bad argument: " + e.getMessage()); } } } /** * This version of the program uses arbitrary precision integers, so it * does not have an upper-bound on the values it can compute. It uses an * ArrayList object to cache computed values instead of a fixed-size * array. An ArrayList is like an array, but can grow to any size. The * factorial() method is declared "synchronized" so that it can be safely * used in multi-threaded programs. Look up java.math.BigInteger and * java.util.ArrayList while studying this class. * Prior to Java 1.2, use Vector instead of ArrayList */ class Factorial4 { protected static ArrayList table = new ArrayList(); // create cache static { // Initialize the first element of the cache with !0 = 1. table.add(BigInteger.valueOf(1)); } /** The factorial() method, using BigIntegers cached in a ArrayList */ public static synchronized BigInteger factorial(int x) { if (x < 0) throw new IllegalArgumentException("x must be non-negative."); for (int size = table.size(); size <= x; size++) { BigInteger lastfact = (BigInteger) table.get(size - 1); BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size)); table.add(nextfact); } return (BigInteger) table.get(x); } /** * A simple main() method that we can use as a standalone test * program for our factorial() method. */ public static void main(String[] args) { for (int i = 0; i <= 50; i++) System.out.println(i + "! = " + factorial(i)); } } ```
What to do when you need to store a (very) large number?
[ "", "java", "numbers", "long-integer", "" ]
I have been struggling with managing some data. I have data that I have turned into a list of lists each basic sublist has a structure like the following ``` <1x>begins <2x>value-1 <3x>value-2 <4x>value-3 some indeterminate number of other values <1y>next observation begins <2y>value-1 <3y>value-2 <4y>value-3 some indeterminate number of other values ``` this continues for an indeterminate number of times in each sublist EDIT I need to get all the occurrences of <2,<3 & <4 separated out and grouped together I am creating a new list of lists [[<2x>value-1,<3x>value-2, <4x>value-3], [<2y>value-1, <3y>value-2, <4y>value-3]] EDIT all of the lines that follow <4x> and <4y> (and for that matter <4anyalpha> have the same type of coding and I don't know a-priori how high the numbers can go-just think of these as sgml tags that are not closed I used numbers because my fingers were hurting from all the coding I have been doing today. The solution I have come up with finally is not very pretty ``` listINeed=[] for sublist in biglist: for line in sublist: if '<2' in line: var2=line if '<3' in line: var3=line if '<4' in line: var4=line templist=[] templist.append(var2) templist.append(var3) templist.append(var4) listIneed.append(templist) templist=[] var4=var2=var3='' ``` I have looked at ways to try to clean this up but have not been successful. This works fine I just saw this as another opportunity to learn more about python because I would think that this should be processable by a one line function.
[itertools.groupby()](http://docs.python.org/library/itertools.html#itertools.groupby) can get you by. ``` itertools.groupby(biglist, operator.itemgetter(2)) ```
You're off to a good start by noticing that your original solution may work but lacks elegance. You should parse the string in a loop, creating a new variable for each line. Here's some sample code: ``` import re s = """<1x>begins <2x>value-1 <3x>value-2 <4x>value-3 some indeterminate number of other values <1y>next observation begins <2y>value-1 <3y>value-2 <4y>value-3""" firstMatch = re.compile('^\<1x') numMatch = re.compile('^\<(\d+)') listIneed = [] templist = None for line in s.split(): if firstMatch.match(line): if templist is not None: listIneed.append(templist) templist = [line] elif numMatch.match(line): #print 'The matching number is %s' % numMatch.match(line).groups(1) templist.append(line) if templist is not None: listIneed.append(templist) print listIneed ```
Reading and Grouping a List of Data in Python
[ "", "python", "list", "" ]
Does any one know how I can specify the Default value for a DateTime property using the System.ComponentModel DefaultValue Attribute? for example I try this: ``` [DefaultValue(typeof(DateTime),DateTime.Now.ToString("yyyy-MM-dd"))] public DateTime DateCreated { get; set; } ``` And it expects the value to be a constant expression. This is in the context of using with ASP.NET Dynamic Data. I do not want to scaffold the DateCreated column but simply supply the DateTime.Now if it is not present. I am using the Entity Framework as my Data Layer Cheers.
You cannot do this with an attribute because they are just meta information generated at compile time. Just add code to the constructor to initialize the date if required, create a trigger and handle missing values in the database, or implement the getter in a way that it returns DateTime.Now if the backing field is not initialized. ``` public DateTime DateCreated { get { return this.dateCreated.HasValue ? this.dateCreated.Value : DateTime.Now; } set { this.dateCreated = value; } } private DateTime? dateCreated = null; ```
Add below to the DateTime property ``` [DatabaseGenerated(DatabaseGeneratedOption.Computed)] ```
Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute
[ "", "c#", "asp.net", "entity-framework", "asp.net-core-2.1", "ef-core-2.1", "" ]
In Python, what is the best way to determine if an IP address (e.g., `'127.0.0.1'` or `'10.98.76.6'`) is on a [private network](http://en.wikipedia.org/wiki/Private_network)? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to consider, etc. Is there an existing library that does it?
Check out the [IPy](http://pypi.python.org/pypi/IPy/) module. If has a function `iptype()` that seems to do what you want: ``` >>> from IPy import IP >>> ip = IP('127.0.0.0/30') >>> ip.iptype() 'PRIVATE' ```
Since Python 3.3 there is an [ipaddress module](https://docs.python.org/3/library/ipaddress.html) in the stdlib that you can use. ``` >>> import ipaddress >>> ipaddress.ip_address('192.168.0.1').is_private True ``` If using Python 2.6 or higher I would strongly recommend to use [a backport of this module](https://pypi.python.org/pypi/py2-ipaddress/).
How do you determine if an IP address is private, in Python?
[ "", "python", "network-programming", "ip-address", "" ]
I am getting started with the notion of test-driven development, and kind of failing since I am finding that I know what the test is going to be kind of, but I can't figure out how to get it to do what I want. What I have is a property that has a `public` getter and an `internal` setter. I'd like to test the functionality by accessing the `internal` setter from the unit test, but I can't figure out just how to do it. Here is the test: ``` [Test()] public void HandleInput() { _requestType = _request.GetType(); PropertyInfo propStdin = _requestType.GetProperty("StandardInput", BindingFlags.Public | BindingFlags.NonPublic); if(propStdin == null) { // Bug in the test. throw new Exception("There is a bug in the test. Reflection of stdin property returned null."); } MethodInfo setStdin = propStdin.GetSetMethod(); // This will fail at the moment since nothing is here to make this happen. Assert.AreEqual("NewInputNewRequestInput", _request.StandardInput); } ``` Now, the problem is that when I run the test, I get: ``` [mono-2.4] mbt@zest:~/Projects/StaffASAP/Test.FastCGI/bin/Debug$ nunit-console2 Test.FastCGI.dll NUnit version 2.4.8 Copyright (C) 2002-2007 Charlie Poole. Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov. Copyright (C) 2000-2002 Philip Craig. All Rights Reserved. Runtime Environment - OS Version: Unix 2.6.29.0 CLR Version: 2.0.50727.1433 ( Mono 2.4 ) ..F Tests run: 2, Failures: 1, Not run: 0, Time: 0.111 seconds Test Case Failures: 1) Test.FastCGI.tRequest.HandleInput : System.Exception : There is a bug in the test. Reflection of stdin property returned null. at Test.FastCGI.tRequest.HandleInput () [0x00051] in /home/mbt/Projects/StaffASAP/Test.FastCGI/tRequest.cs:54 at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&) at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00057] in /media/disk/mono-2.4/sources/mono-2.4/mcs/class/corlib/System.Reflection/MonoMethod.cs:159 ``` So, I must be attempting to access the property incorrectly, but from looking at the documentation, I don't know what I am doing wrong. What *am* I doing wrong?
Are you missing | BindingFlags.Instance in the GetProperty(...) call? It would be much nicer however to expose the internal variables to the test program through the InternalsVisibleTo attribute, as you don't need to rely on reflection, and refactoring will propagate if the test project is part of your solution in Visual Studio.
You may want to look at the [`InternalsVisibleTo`](https://web.archive.org/web/20210128163616/http://geekswithblogs.net/jwhitehorn/archive/2007/11/09/116750.aspx) assembly attribute: > [Y]ou can expose an assembly's internal methods/properties/classes to a "friend" assembly. Normally internals are only accessible to members of the same assembly, and are often used to hide "plumbing" methods and utilities classes.
Quick question on reflection in C#
[ "", "c#", "reflection", "nunit", "" ]
This is a rather basic question, but it's one that's bugged me for awhile. My project has a bunch of .cpp (Implementation) and .hpp (Definition) files. I find that as I add additional classes and more class inter-dependencies, I have to #include other header files. After a week or two, I end up with #include directives in lots of places. Later, I'll try removing some of the #includes and discover that everything still works because some OTHER included class is also #including what I just removed. **Is there a simple, easy rule for putting in #includes that will stop this ugly mess from happening in the first place? What is the best practice?** For example, I've worked on projects where the Implementation .cpp file ONLY includes the corresponding Definition .hpp file, and nothing else. If there are any other .hpp files that need to be used by the Implementation .cpp, they are all referenced by the Definition .hpp file.
I always use the principle of least coupling. I only include a file if the current file actually needs it; if I can get away with a forward declaration instead of a full definition, I'll use that instead. My .cpp files always have a pile of #includes at the top. Bar.h: ``` class Foo; class Bar { Foo * m_foo; }; ``` Bar.cpp: ``` #include "Foo.h" #include "Bar.h" ```
Some best practices: * Every .cpp or .C file includes all headers it needs and does not rely on headers including other related headers * Every .hpp or .h file includes all its dependencies and does not rely on the included headers including other related headers * Every header is wrapped with: ``` #ifndef HEADER_XXX_INCLUDED #define HEADER_XXX_INCLUDED ... #endif /* HEADER_XXX_INCLUDED */ ``` * Headers do not include each others in cycles * Often: there is a single "project-wide header file" like "config.h" or ".h" which is always included *first* by any .cpp or .C file. Typically this has platform related configuration data, project-wide constants and macros etc. These are not necessarily "best practice", but rules which I usually follow also: * Project-specific headers are included as `#include "..."` and before the system-wide headers, which are included as `#include <...>` * Project-specific headers are included in *alphabetical* order as a way to ensure that there is no accidental, hidden requirement on which order they are included. As every header should include its dependents *and* the headers should be protected against multiple inclusion, you should be able to include them in any order you wish.
Is there a standard #include convention for C++?
[ "", "c++", "include", "" ]
As part of a large automation process, we are calling a third-party API that does some work calling services on another machine. We discovered recently that every so often when the other machine is unavailable, the API call will spin away sometimes up to 40 minutes while attempting to connect to the remote server. The API we're using doesn't offer a way to specify a timeout and we don't want our program waiting around for that long, so I thought threads would be a nice way to enforce the timeout. The resulting code looks something like: ``` Thread _thread = new Thread(_caller.CallServices()); _thread.Start(); _thread.Join(timeout); if (_thread.IsAlive) { _thread.Abort(); throw new Exception("Timed-out attempting to connect."); } ``` Basically, I want to let APICall() run, but if it is still going after timeout has elapsed, assume it is going to fail, kill it and move on. Since I'm new to threading in C# and on the .net runtime I thought I'd ask two related questions: Is there a better/more appropriate mechanism in the .net libraries for what I'm trying to do, and have I committed any threading gotchas in that bit of code?
Thread.Abort() is a request for the thread to abort, and gives no guarantee that it will do so in a timely manner. It is also considered bad practice (it will throw a thread abort exception in the aborted thread, but it seems like the 3rd party API offers you no other choices. If you know (programmatically) the address of the remote service host you should ping it before you transfer control to the 3rd party API. If not using a backgroundworker, you could set the thread's IsBackgroundThread to true, so it doesn't keep your program from terminating.
Bad idea. Thread.Abort doesn't necessarily clean up the mess left by such an interrupted API call. If the call is expensive, consider writing a separate .exe that makes the call, and pass the arguments to/from it using the command line or temporary files. You can kill an .exe much more safely than killing a thread.
A reasonable use of threading in C#?
[ "", "c#", "multithreading", "" ]
I have a Windows Service developed in C# and .NET 3.5 to perform various administrative tasks throughout our 3 domains. I've got an admin account in each domain that has the necessary rights/permissions for what this service is doing. For all the AD interactions, I can bind to AD using the correct username/password for the domain and all is good. However, I have a need now to launch an external process (robocopy) to perform some work and I cannot find any code examples anywhere for doing this in .NET 3.5. What I need to do is launch robocopy using alternate credentials in a hidden window, capture the standard output so I have a log of what was actually done, and capture the exit code so I can tell if it was successful. I found some old .NET 1.1 code from [K. Scott Allen's blog](http://odetocode.com/Blogs/scott/archive/2004/10/28/602.aspx) (see the last few comments for a good code listing) that extends the System.Diagnostics.Process object and calls the Win32 API function CreateProcessAsUserW. However, the code doesn't work due to some API changes in .NET 2.0. Using the code snippet from the last comment on the referenced blog where it is using reflection to call the private SetProcessHandle function of the Process object causes Access Denied errors when I try to interact with the process (to kill it or get exit code). Does anyone have a good example of how to accomplish this? EDIT: The built-in .NET Process and ProcessStartInfo API does allow you to specify alternate credentials but when you do, it wants to create a visible window (even if you specify CreateNoWindow or WindowStyle Hidden) which fails when running as a Windows Service. So those are not an option for this application. Impersonation doesn't work either since when the external process is launched, it uses the credentials of the parent process, not the impersonated credentials. SOLUTION: As Reed pointed out below, P/Invoke using one of the Win32 API functions should allow you to make this happen. I ended up going a slightly different route using an old [freeware NT4 utility called RunProcess](http://ss64.net/westlake/nt/) that allows you to specify a username/password on the command line. It worked on Vista and 2k3 and also worked correctly when launched by a windows service running as Local System.
I think you want to look at: [ProcessStartInfo](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.aspx) That provides a .NET only way to start a process under a different user with different credentials. No more need for the Win32 API. --- EDIT --- Other alternatives might be to use the P/Invoke as specified [here](http://www.dotnet247.com/247reference/msgs/32/160308.aspx) (look at the note at the bottom first) or more likely, using P/Invoke with [CreateProcessWithLogonW](http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/msg/3e2a3345bdd184d6?pli=1).
Just an unverified thought, but isn't using dynamic Impersonate valid for the entire code block in .net 2+? So Impersonate the required user and then do whatever you need within the impersonated context/scope, like starting a process the normal way? Think we did something like that to integrate mstsc.exe launching using already supplied credentials.
C# and .NET 3.5 - How to launch a process using different credentials, with a hidden window, and being able to capture standard output and exit code?
[ "", "c#", ".net", ".net-3.5", "process", "credentials", "" ]
I'm having some issues using XmlSerializer and XmlTextReader in c# when saving DataTables which do not contain any data. Is this a known issue and is there a workaround? When an empty datatable is saved using XMLSerializer the following XML is generated: ``` <Values> <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="Values" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="Values"> <xs:complexType> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1" /> </Values> ``` When the XML containing this is reloaded XMLTextReader fails silently and does not load content beyond the point at which the empty datatable is written to the XML. This issue appears to be caused by the lack of an xs:sequence / xs:element entry inside xs:complexType. Is this a bug and if so what is the workaround? The following c# program demonstrates the issue. It will output dt3 is null due to the issue described above: ``` public class Data { private DataTable dt1; private DataTable dt2; private DataTable dt3; public DataTable Dt1 { get { return dt1; } set { dt1 = value; } } public DataTable Dt2 { get { return dt2; } set { dt2 = value; } } public DataTable Dt3 { get { return dt3; } set { dt3 = value; } } public void TestDataTables() { if(dt1 == null) Console.WriteLine("dt1 is null"); if (dt2 == null) Console.WriteLine("dt2 is null"); if (dt3 == null) Console.WriteLine("dt3 is null"); } } class Program { static void Main(string[] args) { // Create test object Data data = new Data(); data.Dt1 = new DataTable("Test1"); data.Dt1.Columns.Add("Foo"); data.Dt2 = new DataTable("Test2"); // Adding the following line make serialization work as expected //data.Dt2.Columns.Add("Foo"); data.Dt3 = new DataTable("Test3"); data.Dt3.Columns.Add("Foo"); data.TestDataTables(); // Save to XML TextWriter filewriter = new StreamWriter("foo.xml"); XmlTextWriter writer = new XmlTextWriter(filewriter); writer.Formatting = Formatting.Indented; XmlSerializer s1 = new XmlSerializer(typeof(Data)); s1.Serialize(writer, data); writer.Close(); filewriter.Close(); // Reload from XML TextReader filereader = new StreamReader("foo.xml"); XmlTextReader reader = new XmlTextReader(filereader); XmlSerializer s2 = new XmlSerializer(typeof(Data)); Data newData = s2.Deserialize(reader) as Data; newData.TestDataTables(); } } ```
(after the edit) Thanks for the example code. Yes, I'd agree that this is a bug. For workarounds... well, you could add a column by default? To avoid the cross-contamination, you could use `ShouldSerialize*`: ``` public bool ShouldSerializeDt1() { return dt1 != null && dt1.Columns.Count > 0; } public bool ShouldSerializeDt2() { return dt2 != null && dt2.Columns.Count > 0; } public bool ShouldSerializeDt3() { return dt3 != null && dt3.Columns.Count > 0; } ``` At least then it is dt2 that gets omitted, instead of dt3.
I tend to use the write xml method on the dataset, you could try that as a work around. <http://msdn.microsoft.com/en-us/library/system.data.dataset.writexml.aspx>
Is there a bug in XmlTextReader when opening empty datatables?
[ "", "c#", "xml-serialization", "" ]
Is it acceptable to do this? First try to the add the entity. If the add fails, it doesn't matter because that means the entity already exists? Or is there a more elegant/easy solution? ``` EntityFrameworkEntities dal = EntityDataModelHelper.GetEntityDataModel(); try { dal.AddToXXXXXX(xxxxxxx); } catch { } try { dal.SaveChanges(); return true; } catch { return false; } ``` OK I shortened it to... ``` EntityFrameworkEntities dal = EntityDataModelHelper.GetEntityDataModel(); if(xxxxxxx.ID == 0) { dal.AddToXXXXXX(xxxxxxx); } try { dal.SaveChanges(); return true; } catch { return false; } ```
It is certainly **not** OK to do this. A catch statement with no type in C# means "catch any standard or non-standard exception". But you're intent is to prevent a duplicate Add. Adds can fail for a variety of reasons which are not indicative of an existing entry. For example, that method could throw a null reference and you'd assume it was added. If you want to check for a duplicate add, you **must** catch only the exception that is thrown for a duplicate add.
You would want to start with an IfExists style method, and then skip saving your changes unless you actually have changes. As noted by Lucas, try-catch blocks have a large overhead if you fall into the catch block, so generally you don't want to rely on that unless there is no possible way of determining if the item already exists. Don't use a try-catch to do an If statement's job. Try-catch is for unusual unanticipated events. **EDIT** In your updated code, you are failing to catch an exception that would be thrown by the "AddToXXXXXX" method. You should do ``` If(!XXXXXX.Contains(newItemValue)) { try { add... savechanges... } catch { } } ``` alternatively, you could separate out the Add and Savechanges into different try-catch blocks, but that is only necessary if SaveChanges gets executed even when Add fails.
Is it ok to rely on a try-catch in a CreateOrUpdate method for the Entity Framework?
[ "", "c#", "entity-framework", "exception", "try-catch", "" ]
I realize that I *should* be able to do this, but what can I say, I don't *get it*. I've even rtfm'ed until my eyes fried. I learn best by examples, not the deep explanations that Zend's docs give, or the typical "use decorators" response that this type of questions usually produce. What I need is markup like this: > ``` > <dt> > <label for="name">Name</label> > </dt> > <dd> > <input type="text" name="name" id="name" value=""> > <a href="#">My Link</a> > </dd> > ``` Its all vanilla, except the extra LINK after the input. Yes, its inside the dd, right next to the link, and that's what I can't get to happen. Here is the (slightly modified) code that I used to create the above HTML > ``` > $name = new Zend_Form_Element_Text( 'name' ); > $name->setLabel( 'Name' ); > $this->addElements( $name ); > $this->addDisplayGroup( array( 'name' ), 'people'); > ``` Any example code or better explanation would make this noob very very happy. Cheers!
See my reply to [this thread](http://www.nabble.com/Zend_Form_Element_Button-question-and-a-general-Zend_Form-question-tt22319567.html#a22319567) in the mailing list and my [blog post](http://monzee.wordpress.com/2009/02/23/decorators-are-hard-lets-go-shopping/) about this. It's basically the same process Aaron described. You can also go the decorator way, using the description property to hold the link (not tested): ``` <?php $foo = new Zend_Form_Element_Text('name'); $foo->setLabel('Name') ->setDescription('<a href="#">Link</a>') ->setDecorators(array( 'ViewHelper', array('Description', array('escape' => false, 'tag' => false)), array('HtmlTag', array('tag' => 'dd')), array('Label', array('tag' => 'dt')), 'Errors', )); $form->addElement($foo); ``` I'm not sure if the `'tag'=>false` in the `Description` decorator would work, but it's worth a shot. Sorry I can't test this now, my development box is broken at the moment. If it fails, try the manual decorator rendering method described in those two links.
I think you're looking for full control of the decorator via a View Script: [Zend Framework Manual](http:///framework.zend.com/manual/en/zend.form.standardDecorators.html#zend.form.standardDecorators.viewScript) Basically, you want to set the viewScript property of the element to the path to your script, and then pass any additional information you'd want to send, perhaps the linkHref or title of the link you're building. ``` $name = new Zend_Form_Element_Text( 'name' ); $name->setLabel( 'Name' ); $name->viewScript = 'path/to/viewScript.phtml'; $name->decorators = array('ViewScript', array('linkHref' => '#', 'linkTitle' => 'My Link'); $this->addElements( $name ); $this->addDisplayGroup( array( 'name' ), 'people'); ``` Then your viewScript would look like this, I'm not sure how all the Helpers are within an instance of a Zend\_Form\_Element, but its kinda like this: ``` <dt><?= $this->formLabel($this->element->getName(), $this->element->getLabel()) ?></dt> <dd><?= $this->{$this->element->helper}( $this->element->getName(), $this->element->getValue(), $this->element->getAttribs() ) ?> <a href="<?= $this->linkHref; ?>"><?= $this->linkTitle; ?></a> <?= $this->formErrors($this->element->getMessages()) ?> </dd> ``` Sometimes, doing it in a viewScript it better because it gives you 100% control of the element, while still being pretty DRY.
Zend Form: Add a link to the right of a text field
[ "", "php", "zend-framework", "zend-form", "" ]
I got a single table and it contain 4 fields ``` Id|Hospital| Doctor|patient 1 A D1 P11 2 B D6 P61 3 A D2 P21 4 A D1 P12 5 B D7 P71 6 B D6 P62 7 B D6 P63 ``` Doctors are unique to the Hospital. They don't work in other hospitals. Patients are unique to the doctor they don't visit any other doctor. Each hospital is having multiple Doctors. If you observe there are multiple patients for each doctor. Now the question is: How can I get "only one patient" related to the each doctor. It can be any patient from the record. I am looking forward to see some thing like this ``` Hospital Doctor Patient A D1 P11 A D2 P21 B D6 P61 B D7 P71 ``` I got the answer like select Hospital,doctor, max(patient) from table GROUP BY Hospital,Doctor ORDER BY Hospital,Doctor; How to get the id also which is unique from the above table like. ``` id Hospital Doctor Patient 1 A D1 P11 3 A D2 P21 2 B D6 P61 5 B D7 P71 ``` I am very sorry to repost this question.
Try something like: ``` select Id,Hospital,Doctor,Patient from table where Id in (select max(t.Id) from table t group by t.Hospital,t.Doctor) order by Hospital,Doctor; ```
``` SELECT m.* FROM ( SELECT ( SELECT id FROM mytable mi WHERE mi.hospital = md.hospital AND mi.doctor = md.doctor LIMIT 1 ) AS first_patient FROM ( SELECT DISTINCT hospital, doctor FROM mytable ) md ) mo, mytable m WHERE m.id = mo.first_patient ```
Extension of question many to many relationships in same table
[ "", "sql", "mysql", "" ]
I just built a asp.net 2.0 web site. Now I need add REST web service so I can communicate with another web application. I've worked with 2 SOAP web service project before, but have no experise with REST at all. I guess only a coupleweeks would works fine. after googling, I found it's not that easy. This is what I found: There is NO REST out of box of asp.net. [WCF REST Starter Kit Codeplex Preview 2](http://go.microsoft.com/?linkid=9653247) base on .net 3.5 and still in beta [Rest ASP.NET Example](http://intertwingly.net/wiki/pie/RestAspNetExample) [REST Web Services in ASP.NET 2.0 (C#)](http://www.codeproject.com/KB/aspnet/RestServicesInASPNET2.aspx) [Exyus](http://exyus.com/) [Handling POST and PUT methods with Lullaby](http://ryanolshan.com/technology/handling-post-and-put-methods-with-lullaby/) [ADO.NET Data Service](http://msdn.microsoft.com/en-us/data/bb931106.aspx) ... Now my question, a) Is a REST solution for .net 2.0? if yes, which one is best solution? b) if I have to, how hard to migrate my asp.net from 2.0 to 3.5? is it as simple as just compile, or I have to change a lot code? c) WCF REST Starter Kit is good enough to use in production? d) Do I have to learn WCF first, then WCF REST Starter Kit? where is the best place to start? I appreciate any help here. Thanks Wes
If your looking for a project that templates a REST service, you're correct in saying there is no out of the box solution. However, RESTful web services are possible using WCF. The key part is to use several attributes when defining your service functions that let the .NET framework know that the function is not expecting SOAP. The main attribute to use is the [WebInvoke](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webinvokeattribute.aspx) attribute. Here is an example from [developer.com](http://www.developer.com/net/article.php/10916_3695436_2): ``` [OperationContract] [WebInvoke(Method = "PUT", UriTemplate = "/admin/post/{id}")] void UpdatePost(string id, Post post); ``` The above code will actually be defined in an interface for your web service. The interface is created automatically when you create your WCF web service project. The actual code for the function will be placed in the class used to implement the web service. Check out the article on developer.com for a full tutorial. It might seem overwhelming at first if your new to WCF, but after you dive into it, I'm sure you'll start to pick things up quickly. Here is the link for the artile: <http://www.developer.com/net/article.php/10916_3695436_1> To answer all of your questions, a) In .NET 2.0 you should be able to build RESTful services using [WSE2.0](http://www.microsoft.com/downloads/details.aspx?familyid=fc5f06c5-821f-41d3-a4fe-6c7b56423841&displaylang=en), but if you have the option to use .NET 3.5, I would strongly recommend going the route of WCF since it is much easier and is designed with REST in mind. b) Converting your project won't be hard at all. It's just a matter of targetting the new version of the framework in your project settings. Converting a web service from a WSE2.0 service to a WCF service will be a bit trickier though. The easiest way to do so would be to copy the code from each of the different web service functions into the class where you implement the new version of the function. Copy-Paste shinanigans :) c) I'm not sure what this starter kit is that you're referring to. RESTful web services should be fully supported in WCF which was fully released as of 3.5 d) It would be helpful to understand WCF at least a little before beginning, but it's not crutial to understand it completely in order to get started. I would recommend just reading through the [MSDN article on WCF](http://msdn.microsoft.com/en-us/library/ms731082.aspx) at least once, and then begin working. I'm sure you will come across other questions as you begin, but you can look up those parts as you come across them. Anyway, I hope this information helps. Good luck to you. **Edit** Some improvements have been made in the REST world. As Darrel Miller mentioned in the comments, WCF was not in fact built with REST in mind. I mis-spoke previously. In fact the framework is built with SOAP in mind and the WebInvoke attribute fills the gap. Although there is a lot of debate around the topic (Web API vs WCF REST), ASP.NET Web API is a new option for building REST services in .NET. I would strongly recommend that anyone who reads this post and is able to use .NET 4.5 in their project look into it as an option.
If you want a framework built with REST in mind, you should have a look at OpenRasta... <http://openrasta.org/>
REST from asp.net 2.0
[ "", "c#", ".net", "wcf", "rest", "" ]
I remember a discussion I recently had with a fellow developer about the memory footprint of private vs public properties. I stated that private ones have less of a footprint than public ones. He claimed it makes no difference. By the way, we were talking about C#. **Who is right and why?** Apparently there are differences in languages. I'm curious what they are as well.
In the context of what language? **In most languages**, changing a method's accessibility from `public` to `private` or vice-versa **will not at all affect its memory footprint**. This is because the actual implementation and the actual invocation of the method does not change, only the way access to it is enforced (either at compile-time, or at run-time, based on the programming language in question.) **What *will* have an effect on memory footprint are other qualifiers**, such as **`final` in Java, `virtual` in C++, `static`, etc.** These qualifiers may either directly influence memory footprint (the presence or absence of a corresponding entry in the class [`vtable`](http://en.wikipedia.org/wiki/Virtual_table)), or indirectly influence memory footprint because of certain optimization assumptions that can be made by the compiler or by the runtime (e.g. non-`virtual`, `static` and/or `final` methods can be inlined, thus arguably increasing performance -- and *most definitely* increasing memory footprint.) --- **Of greater importance than memory footprint**, when discussing how a method should be qualified, is what you can do to both (1) have the compiler (or the runtime, as depending on the language) validate some of your assumptions and intentions, and (2) convey those assumptions and intentions to the programmer who will review, reverse-engineer, alter, re-factor etc. the code after you: * `private`: do other classes, or descendants of this class, need direct access to this method? If not, make it `private`. * `protected`: do descendants of this class (or this class itself), but no other classes (except maybe `friend` classes), need direct access to this method? If so, make it `protected`. * `static`: does the method require access to member variables or to `this`? If not, it should be `static` (e.g. a utility method that depends solely on its arguments) * `const`: does the method alter member variables or call non-`const` member methods on `this` or member variables? If not, it should be `const` (e.g. a getter) * `virtual`: will the method need to be overridden? If not, it should *not* be `virtual` * `abstract` (or pure virtual): does the method need to have an implementation in this class, if this class' descendants will override it? If not, make it `abstract` (or `pure virtual`) * etc. There are miscellaneous articles, lectures and posts out there regarding best practices for the above, transcending the boundaries of many a programming language: * [access permissions and encapsulation](https://agora.cs.illinois.edu/download/attachments/19923932/lecture19.pdf?version=1) * [encapsulation](http://yosefk.com/c++fqa/class.html#fqa-7.4) * [private vs. protected](https://stackoverflow.com/questions/224966/private-and-protected-members-c) * etc.
It makes no difference. The property itself is just code and the metadata for it. Both are needed whether the property is private or public. Why would it make a difference?
Private methods and properties vs public ones regarding their memory footprints in C# (and other languages)
[ "", "c#", "memory", "properties", "" ]
I have an annoying bug in on a webpage: > date.GetMonth() is not a function So, I suppose that I am doing something wrong. The variable `date` is not an object of type `Date`. **How can I check for a datatype in Javascript?** I tried to add a `if (date)`, but it doesn't work. ``` function getFormatedDate(date) { if (date) { var month = date.GetMonth(); } } ``` So, if I want to write defensive code and prevent the date (which is not one) to be formatted, how do I do that? Thanks! **UPDATE:** I don't want to check the format of the date, but I want to be sure that the parameter passed to the method `getFormatedDate()` is of type `Date`.
As an alternative to duck typing via ``` typeof date.getMonth === 'function' ``` you can use the `instanceof` operator, i.e. But it will return true for invalid dates too, e.g. `new Date('random_string')` is also instance of Date ``` date instanceof Date ``` This will fail if objects are passed across frame boundaries. A work-around for this is to check the object's class via ``` Object.prototype.toString.call(date) === '[object Date]' ```
You can use the following code: ``` (myvar instanceof Date) // returns true or false ```
How to check whether an object is a date?
[ "", "javascript", "date", "" ]
I'm using pygame to draw a line between two arbitrary points. I also want to append arrows at the end of the lines that face outward in the directions the line is traveling. It's simple enough to stick an arrow image at the end, but I have no clue how the calculate the degrees of rotation to keep the arrows pointing in the right direction.
Here is the complete code to do it. Note that when using pygame, the y co-ordinate is measured from the top, and so we take the negative when using math functions. ``` import pygame import math import random pygame.init() screen=pygame.display.set_mode((300,300)) screen.fill((255,255,255)) pos1=random.randrange(300), random.randrange(300) pos2=random.randrange(300), random.randrange(300) pygame.draw.line(screen, (0,0,0), pos1, pos2) arrow=pygame.Surface((50,50)) arrow.fill((255,255,255)) pygame.draw.line(arrow, (0,0,0), (0,0), (25,25)) pygame.draw.line(arrow, (0,0,0), (0,50), (25,25)) arrow.set_colorkey((255,255,255)) angle=math.atan2(-(pos1[1]-pos2[1]), pos1[0]-pos2[0]) ##Note that in pygame y=0 represents the top of the screen ##So it is necessary to invert the y coordinate when using math angle=math.degrees(angle) def drawAng(angle, pos): nar=pygame.transform.rotate(arrow,angle) nrect=nar.get_rect(center=pos) screen.blit(nar, nrect) drawAng(angle, pos1) angle+=180 drawAng(angle, pos2) pygame.display.flip() ```
We're assuming that 0 degrees means the arrow is pointing to the right, 90 degrees means pointing straight up and 180 degrees means pointing to the left. There are several ways to do this, the simplest is probably using the atan2 function. if your starting point is (x1,y1) and your end point is (x2,y2) then the angle in degrees of the line between the two is: ``` import math deg=math.degrees(math.atan2(y2-y1,x2-x1)) ``` this will you an angle in the range -180 to 180 so you need it from 0 to 360 you have to take care of that your self.
Rotation based on end points
[ "", "python", "geometry", "pygame", "" ]
I have two servers, one in a seperate domain and the other on the primary domain, that need to pass web service calls back and forth to each other. For security and various other reasons, I don't want these machines to talk directly to each other. I would like to have a server that sits between them to route these web service requests through to the other server. I started writing a .net web service application that mirrors the signatures of every possible web service call, but this doesn't seem very practical, and will need to be updated whenever a signature changes. The built in IIS forwarding doesn't seem to do what I want as it just redirects the calls to the other machine, which isn't what I want. These web services are passing serialized .net objects as input/output parameters. Do I have any options for just generically forwarding a web service call to another server? -EDIT- To answer some of the questions regarding the need for this: I mis-spoke when I said it was a DMZ, I should have said it was just a separate domain. I updated the question with this. The "various other reasons" I mentioned above for this architecture is because I'm dealing with a child company that accesses small parts of our network via secured VPN. This child company has no direct access at all to the sub domain. However, they do need to access the web services on a server in the sub domain. They way I was getting around this was to have a server that can communicate to their server, as well as to our server in the sub domain.
WCF supports [WS-Addressing](http://www.w3.org/Submission/ws-addressing/). Check out the MSDN on [how to setup a WCF router](http://msdn.microsoft.com/en-us/magazine/cc500646.aspx).
Architecturally speaking this is a redundancy. You should be looking to implement any security on the firewall. Your web service (sitting in the DMZ) should be allowed to do what it needs via appropriately secured ports on the firewall. I am confused as to why you need to do this? Without more detail on the security reasons for not allowing two machines to talk directly, or more detail on why these two web services need to pass calls for identical functionality between one another it seems like it will be hard to help. **UPDATE** So you would have the child company calling functions on an appropriately configured web service (see above) which was in the DMZ for your core domain. This way they would not need access to the sub-domain as the web-service would be calling into your domain not the child domain users per-se. Same architecture applies doesn't it?
Can you generically pass web service calls to another server?
[ "", "c#", "asp.net", "web-services", "iis-6", "" ]
There is a strange behaviour with `json_encode` and `json_decode` and I can't find a solution: My php application calls a php web service. The webservice returns json that looks like this: ``` var_dump($foo): string(62) "{"action":"set","user":"123123123123","status":"OK"}" ``` now I like to decode the json in my application: ``` $data = json_decode($foo, true) ``` but it returns `NULL`: ``` var_dump($data): NULL ``` I use php5. The Content-Type of the response from the webservice: `"text/html; charset=utf-8"` (also tried to use `"application/json; charset=utf-8"`) What could be the reason?
**EDIT:** Just did some quick inspection of the string provided by the OP. The small "character" in front of the curly brace is a [UTF-8 B(yte) O(rder) M(ark)](http://en.wikipedia.org/wiki/Byte-order_mark) `0xEF 0xBB 0xBF`. I don't know why this byte sequence is displayed as `` here. Essentially the system you aquire the data from sends it encoded in UTF-8 with a BOM preceding the data. You should remove the first three bytes from the string before you throw it into `json_decode()` (a `substr($string, 3)` will do). ``` string(62) "{"action":"set","user":"123123123123","status":"OK"}" ^ | This is the UTF-8 BOM ``` As [Kuroki Kaze](https://stackoverflow.com/questions/689185/jsondecode-returns-null-php/689237#689237) discovered, this character surely is the reason why `json_decode` fails. The string in its given form is not correctly a JSON formated structure (see [RFC 4627](http://www.ietf.org/rfc/rfc4627.txt))
Well, i had a similar issue and the problems was the PHP magic quotes in the server... here is my solution: ``` if(get_magic_quotes_gpc()){ $param = stripslashes($_POST['param']); }else{ $param = $_POST['param']; } $param = json_decode($param,true); ```
json_decode returns NULL after webservice call
[ "", "php", "json", "" ]
I want to know this info to reduce my code size so I will not waste my time optimize things that will be done by compiler or JIT. for example: if we assume the compiler inline the call to the get function of a property so I do not have to save the return value in a local variable to avoid function call. I want to recommend a good reference that describes what is going on?
You may want to take a look at these articles: [JIT Optimizations - (Sasha Goldshtein - CodeProject)](http://www.codeproject.com/KB/dotnet/JITOptimizations.aspx) [Jit Optimizations: Inlining I (David Notario)](http://blogs.msdn.com/davidnotario/archive/2004/10/28/248953.aspx) [Jit Optimizations: Inlining II (David Notario)](http://blogs.msdn.com/davidnotario/archive/2004/11/01/250398.aspx) To be honest you shouldn't be worrying too much about this level of micro-detail. Let the compiler/JIT'er worry about this for you, it's better at it than you are in almost all cases. Don't get hung up on [Premature Optimisation](http://en.wikipedia.org/wiki/Optimization_(computer_science)#When_to_optimize). Focus on getting your code working, then worry about optimisations later on if (a) it doesn't run fast enough, (b) you have 'size' issues.
If you are worried about performance, run a profiler. **Then** change code. Chances are that you will never in a million years guess 100% correctly where the time is going. You could be changing the 0.02% timing, and leaving the method that contributes 62% of the burden. You could also be making it worse. Without a profiler and evidence, you are blind. --- You can't **assume** that the JIT will inline a property getter. There are many reasons it may or may not do so; size of the method body, virtual, value vs reference type, architecture, debugger attached, etc. "Hoisting" still has a place, and can still achieve savings *if* the code is called repeatedly in a tight loop; for example: ``` var count = list.Count; for(int i = 0 ; i < count ; i++) {...} ``` (forget the `for` vs `foreach` debate fr the above - this is an orthogonal discussion). In the above, the "hoist" will help performance. But just to be *really* confusing - with arrays, it is the opposite, and it is more efficient to *not* hoist it: ``` for(int i = 0 ; i < arr.Length ; i++) {...} ``` The JIT recognises this and removes the bounds check (as arrays are fixed size).
At what level C# compiler or JIT optimize the application code?
[ "", "c#", ".net", "optimization", "compiler-construction", "jit", "" ]
I'm fairly new to java, and am used to enums essentially beeing nothing more than a named list of integers. Now I'm writing an implementation where a parent class has a couple of methods that take an enum value as argument. The enum will be defined in child classes, and will differ slightly. Since enums basically seem to behave like classes, this doesn't work the way I expected it to. Each enum defined will be considered a different type of object and the parent class will have to pick one of the defined enums to take as argument. Is there a good way to make the parent class accept any enum defined in it's child-classes? Or will I have to write a custom class for this? Edit: Here is my example, fixed as per Jon Skeets answer, for anyone who is looking into how to do this later on: ``` class Parent { protected interface ParentEvent {} private HashMap<ParentEvent, String> actions = new HashMap<ParentEvent, String>(); protected void doStuff(ParentEvent e){ if(actions.containsKey(e)){ System.out.println(actions.get(e)); } } } class Child extends Parent { enum Event implements ParentEvent {EDITED, ADDED, REMOVED} public void trigger(){ doStuff(Event.REMOVED); } } ```
You could make your enums implement an interface, then give your parent class method a parameter of that interface type. As you say, enums are rather different in Java. They're not named numbers - they're a fixed set of values, but those values are object-oriented (i.e. they can use polymorphism etc). Java enums pretty much rock, except for a few tricksy issues around initialization ordering.
if i understand you correctly, you want to have a common base class for your enum and want to define several unrelated sets of enums for the sub classes. This is not possible with java's typesafe enums, because they don't allow you to define a base class. Of course it is not an option just to have one enum defined and always extend its values because this clearly violates the open close principle. For such a use case I have fairly good experience with Josh Bloch's Typesafe Enum Pattern he describes in [Effective Java](http://java.sun.com/developer/Books/effectivejava/Chapter5.pdf) Just introduce your super class here and make distinct sub classes for each of enum values your client classes need.
Arbitrary Java enum argument
[ "", "java", "enums", "" ]
Does anyone knows what magic I have to use to change x list: > x = [1,2,3,4,5,11] into y list? > y = ['01','02','03','04','05','11'] Thank you all in advance for helping me...
You can use a list comprehension (Python 2.6+): ``` y = ["{0:0>2}".format(v) for v in x] ``` Or for Python prior to 2.6: ``` y = ["%02d" % v for v in x] ``` Or for Python 3.6+ using f-strings: ``` y = [f'{v:02}' for v in x] ``` Edit: Missed the fact that you wanted zero-padding...
You want to use the built-in [`map`](http://docs.python.org/library/functions.html#map) function: ``` >>> x = [1,2,3,4,5] >>> x [1, 2, 3, 4, 5] >>> y = map(str, x) >>> y ['1', '2', '3', '4', '5'] ``` **EDIT** You changed the requirements on me! To make it display leading zeros, you do this: ``` >>> x = [1,2,3,4,5,11] >>> y = ["%02d" % v for v in x] >>> y ['01', '02', '03', '04', '05', '11'] ```
Python - list transformation
[ "", "python", "list", "" ]
How do I get the local machine name?
[System.Environment.MachineName](http://msdn.microsoft.com/en-us/library/system.environment.machinename.aspx) It works unless a [machine name has more than 15 characters](https://stackoverflow.com/questions/42088346/environment-machinename-is-cropped-to-15-characters?noredirect=1&lq=1).
From [source](http://blog.xploiter.com/2008/09/17/get-your-local-machinecomputer-name-in-c/) Four ways to get your local network/machine name: ``` string name = Environment.MachineName; string name = System.Net.Dns.GetHostName(); string name = System.Windows.Forms.SystemInformation.ComputerName; string name = System.Environment.GetEnvironmentVariable("COMPUTERNAME"); ``` More information at: [Difference between SystemInformation.ComputerName, Environment.MachineName, and Net.Dns.GetHostName](https://stackoverflow.com/questions/1233217/difference-between-systeminformation-computername-environment-machinename-and-n)
How do I get the local machine name in C#?
[ "", "c#", "dns", "hostname", "" ]
We've been debugging this JBoss server problem for quite a while. After about 10 hours of work, the server goes into 100% CPU panic attacks and just stalls. During this time you cannot run any new programs, so you can't even `kill -quit` to get a stack trace. These high 100% SYS CPU loads last 10-20 seconds and repeat every few minutes. We have been working on for quite a while. We suspect it has something to do with the GC, but cannot confirm it with a smaller program. We are running on i386 32bit, RHEL5 and Java 1.5.0\_10 using `-client` and `ParNew GC`. Here's what we have tried so far: 1. We limited the CPU affinity so we can actually use the server when the high load hits. With `strace` we see an endless loop of `SIGSEGV` and then the sig return. 2. We tried to reproduce this with a Java program. It's true that SYS CPU% climbs high with `WeakHashMap` or when accessing null pointers. Problem was that `fillStackTrace` took a lot of user CPU% and that's why we never reached 100% SYS CPU. 3. We know that after 10 hours of stress, GC goes crazy and full GC sometimes takes 5 seconds. So we assume it has something to do with memory. 4. `jstack` during that period showed all threads as blocked. `pstack` during that time, showed MarkSweep stack trace occasionally, so we can't be sure about this as well. Sending `SIGQUIT` yielded nothing: Java dumped the stack trace AFTER the SYS% load period was over. We're now trying to reproduce this problem with a small fragment of code so we can ask Sun. If you know what's causing it, please let us know. We're open to ideas and we are clueless, any idea is welcome :) Thanks for your time.
Thanks to everybody for helping out. Eventually we upgraded (only half of the java servers,) to JDK 1.6 and the problem disappeared. Just don't use 1.5.0.10 :) We managed to reproduce these problems by just accessing null pointers (boosts SYS instead of US, and kills the entire linux.) Again, thanks to everyone.
If you're certain that GC is the problem (and it does *sound* like it based on your description), then adding the -XX:+HeapDumpOnOutOfMemoryError flag to your JBoss settings might help (in JBOSS\_HOME/bin/run.conf). You can read more about this flag [here](http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/clopts.html). It was originally added in Java 6, but was later [back-ported](http://blogs.oracle.com/alanb/entry/heapdumponoutofmemoryerror_option_in_5_0u7) to Java 1.5.0\_07. Basically, you will get a "dump file" if an OutOfMemoryError occurs, which you can then open in various profiling tools. We've had good luck with the [Eclipse Memory Analyzer](http://www.eclipse.org/mat/). This won't give you any "free" answers, but if you truly have a memory leak, then this will help you find it.
My JBoss server hits 100% SYS CPU on Linux; what can cause this?
[ "", "java", "performance", "jboss", "" ]
I have an array of "Range" objects with properties "Offset" and "Length", as shown below. Assume that it'll be sorted by "Offset" ascending. Range array contains: ``` Offset Length Index ------- ------- ------- 100 10 0 110 2 1 112 5 2 117 3 3 300 5 4 305 5 5 400 5 6 405 10 7 415 2 8 417 4 9 421 7 10 428 1 11 429 6 12 500 4 13 504 9 14 ``` The contiguous subsequences in this case would be: ``` Sequence #1 indices: 0, 1, 2, 3 Sequence #2 indices: 4, 5 Sequence #3 indices: 6, 7, 8, 9, 10, 11, 12 <-- (longest!!) Sequence #4 indices: 13, 14 ``` Assume that there will only be one longest sequence. Iterating through the items, i thought to create a new array for each contiguous sequence and return the biggest array, but that seem sub-optimal. Is there a better way to do this? I'm implementing in C# 2.0. The function should either return an array containing the elements of the longest subsequence, or the starting and ending indices of the longest subsequence in the original array. Thanks everyone for taking a stab at this.
This problem is not related to contiguous subsequence problem etc. but is a simple problem which can be solved in O(n) time. It seems to me that the "strings" represented by the array are not overlapping, so there is a very simple algorithm: put left index finger on the first row, and then run the right index finger downwards as long as you are within a contiguous sequence. When the sequence ends, store the length and the starting location. Then repeat this. Whenever you find a longer sequence than the previous record, you update the starting location.
A simple linear algorithm (Python, I'm sure the code can be improved): ``` # Your array arr = [ (100, 10), (110, 2), (112, 5), (117, 3), (300, 5), (305, 5), (400, 5), (405, 10), (415, 2), (417, 4), (421, 7), (428, 1), (429, 6), (500, 4), (504, 9) ] # Where does each element end? ends = map(sum, arr) s, e = 0, 0 # start and end of longest contiguous subseq cur = 0 # length of current contiguous subseq for j, i in enumerate(range(1, len(arr))): # See if current element is contiguous with the previous one if (arr[i][0] == ends[j]): cur += 1 elif cur > 0: # If not, we may have found the end of a (currently) longest subseq if cur > (e - s): e = j s = e - cur cur = 0 # reset subseq length # The longest contiguous subseq may be at the end of the array if cur > (e - s): e = j + 1 s = e - cur # print the start and end index of the longest contiguous subseq print(s, e) ```
Longest contiguous subsequence algorithm
[ "", "c#", "algorithm", "" ]
Why Cant I do something like this? If I have a `List<String> myList` populated with items, I want to be able to act on each member in a conditional way like so: ``` myList.ForEach(a => { if (a.Trim().Length == 0) a = "0.0"; }) ``` But this will not compile. Im guessing its something to do with missing a return value? Im trying to prepare a list of strings for conversion to doubles, and I want the empty items to show '0.0' so I can just convert the whole list in one go.
ForEach is not mutable, it doesn't change the data structure in any way. You can either: 1. Handle the loop yourself, with an index 2. Produce a new list, using .Select and .ToList (provided you're using .NET 3.5) Example of #1: ``` for (Int32 index = 0; index < myList.Count; index++) if (myList[index].Trim().Length == 0) myList[index] = "0.0"; ``` With .NET 3.5 and Linq: ``` myList = (from a in myList select (a.Trim().Length == 0) ? "0.0" : a).ToList(); ``` With .NET 3.5, not using the Linq-syntax, but using the Linq-code: ``` myList = myList.Select(a => (a.Trim().Length == 0) ? "0.0" : a).ToList(); ``` --- **Edit**: If you want to produce a new list of doubles, you can also do that in one go using Linq: ``` List<Double> myDoubleList = (from a in myList select (a.Trim().Length == 0 ? "0" : a) into d select Double.Parse(d)).ToList(); ``` Note that using "0.0" instead of just "0" relies on the decimal point being the full stop character. On my system it isn't, so I replaced it with just "0", but a more appropriate way would be to change the call to Double.Parse to take an explicit numeric formatting, like this: ``` List<Double> myDoubleList = (from a in myList select (a.Trim().Length == 0 ? "0.0" : a) into d select Double.Parse(d, CultureInfo.InvariantCulture)).ToList(); ```
What you possibly want is: ``` public static void MutateEach(this IList<T> list, Func<T, T> mutator) { int count = list.Count; for (int n = 0; n < count; n++) list[n] = mutator(list[n]); } ``` Which would allow: ``` myList.MutateEach(a => (a.Trim().Length == 0) ? "0.0" : a); ``` Just put the `MutateEach` method in a public static class of your own and make sure you have a using directive that will find it. Whether it's worth defining something like this depends on how often you'd use it. Note that it has to be an extension on `IList` instead of `IEnumerable`, so we can perform the updates, which makes it less widely applicable.
Using conditional lambda statements with a foreach Action on a list
[ "", "c#", "lambda", "" ]
I want to print a individual comment in drupal based on it's comment ID. How can I do this? Google and other sources have yielded me nothing. Thank you.
Eaton's suggestion is good (except it's `{comments}`, not `{comment}`) if you need to display the comment like core does it, including the info coming from the node. Except the default theme\_comment implementation in `modules/comment/comment.tpl.php` makes no use of $node. However, I'd do it slightly differently, because if you need to extract a single comment, displaying it with the normal content formatting provided by `comment.tpl.php` is likely to be inappropriate. ``` function print_comment($cid) { $sql = "SELECT * FROM {comment} c WHERE c.cid = %d"; if ($comment = db_fetch_object(db_rewrite_sql(db_query($sql, $cid), 'c'))) { return theme('my_special_comment_formatting', $comment); } } ``` And of course, define this special commment formatting in your module's `hook_theme()` implementation, inspired by what `comment.tpl.php` does. 2014-02 UPDATE: note that this is a 2009 question/answer. In Drupal 8, you just don't want to access the hypothetical underlying SQL database (and would not do it like this anyway, but use DBTNG), but just use something like: ``` if ($comment = entity_load('comment', $cid)) { return entity_view($comment, $view_mode); } ```
``` function print_comment($cid) { $sql = "SELECT * FROM {comments} WHERE cid = %d"; if ($comment = db_fetch_object(db_query($sql, $cid))) { $node = node_load($comment->nid); return theme('comment', $comment, $node); } } ```
How do I print a single comment in drupal?
[ "", "php", "drupal", "drupal-comments", "" ]
A buddy of mine is currently tinkering around with [JpCap](http://netresearch.ics.uci.edu/kfujii/jpcap/doc/index.html) in Java and we found some interesting (maybe?) problem regarding regular expressions in Java. Only HTTP traffic is being captured and subsequently analyzed. For this purpose he is using a pattern like this one: ``` Pattern p = Pattern.compile("(www)"); ``` But what both of us have not been able to find out: why does the above pattern produce no matches at all, while the following does: ``` Pattern p = Pattern.compile(".*(www).*"); ``` For what I can see, both of these should be identical, shouldn't they? I don't have that much experience regarding regular expressions, so there might be a very simple answer to this question :)
Oh, nevermind, I just found out we both were a little bit API-blind ;) We were using ``` Matcher.matches() ``` which matches the pattern against the entire string, instead of ``` Matcher.find() ``` which tries to find the pattern anywhere in the given string. Thanks for the answers, though! :)
Your first pattern only accepts the string 'www'. The second pattern accepts any string with 'www' in it, anywhere. This [website](http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html) has more information regarding Java regex.
Java RegExp problem - .*(www).* vs. (www)
[ "", "java", "regex", "" ]
I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice? I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices. Listing Token Types: In Java, for example, I would have a list of fields like so: ``` public static final int TOKEN_INTEGER = 0 ``` But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered. Returning Tokens From The Tokenizer: Is there a better alternative to just simply returning a list of tuples e.g. ``` [ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]? ```
Python takes a "we're all consenting adults" approach to information hiding. It's OK to use variables as though they were constants, and trust that users of your code won't do something stupid.
There's an undocumented class in the `re` module called `re.Scanner`. It's very straightforward to use for a tokenizer: ``` import re scanner=re.Scanner([ (r"[0-9]+", lambda scanner,token:("INTEGER", token)), (r"[a-z_]+", lambda scanner,token:("IDENTIFIER", token)), (r"[,.]+", lambda scanner,token:("PUNCTUATION", token)), (r"\s+", None), # None == skip token. ]) results, remainder=scanner.scan("45 pigeons, 23 cows, 11 spiders.") print results ``` will result in ``` [('INTEGER', '45'), ('IDENTIFIER', 'pigeons'), ('PUNCTUATION', ','), ('INTEGER', '23'), ('IDENTIFIER', 'cows'), ('PUNCTUATION', ','), ('INTEGER', '11'), ('IDENTIFIER', 'spiders'), ('PUNCTUATION', '.')] ``` I used re.Scanner to write a pretty nifty configuration/structured data format parser in only a couple hundred lines.
Pythonic way to implement a tokenizer
[ "", "python", "coding-style", "tokenize", "" ]
I'm working with silverlight and I want to filer an ObservableCollection. So I started to look att ICollectionView, because there is no CollectionViewSource in Silverlight and it contains an absure amount of methods and events. I've searched for a while and I wonder if anyone has example code of an implementation of ICollectionView?
Unfortunately ICollectionView is only used for the DataGrid in Silverlight 2.0, and its only implementation is ListCollectionView, which is internal to System.Windows.Controls.Data. If you are not binding to a DataGrid, ICollectionView will not give you much because it is not used by the basic controls (such as listbox) as far as I can tell, since it is defined in the Data controls assembly and not in the core. This is a pretty big difference with WPF. But to the point of your question, the assembly containing the DataGrid does have an implementation that might help you if you want to learn how it is done. Worst case, reflector is your friend...
CollectionViewSource is now available in Silverlight 3. Check out a good article about this [here](http://www.silverlightplayground.org/post/2009/07/10/Silverlight-30-RTW-The-CollectionViewSource.aspx).
How to create a CollectionView for ObservableCollection<T> in Silverlight
[ "", "c#", "silverlight", "" ]
How to know my processor is 32 or 64 bits in C#?
You can query the [WMI](http://msdn.microsoft.com/en-us/library/aa394582%28v=vs.85%29.aspx) class [`Win32_Processor`](http://msdn.microsoft.com/en-us/library/aa394373%28VS.85%29.aspx) using [`System.Management.ManagementObject`](http://msdn.microsoft.com/en-us/library/system.management.managementobject.aspx): ``` ManagementObject mo; mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'"); ushort i = (ushort)mo["Architecture"]; switch (i) { case 0: return "32 Bit"; break; case 9: return "64 Bit"; break; } ``` Take a look at [the MSDN Library description](http://msdn.microsoft.com/en-us/library/aa394373%28VS.85%29.aspx#properties) for other processor codes. A problem with this is that the user, who is running the program, needs privileges for viewing the WMI.
For anyone using .NET 4.0 or newer, there is a built-in property [`System.Environment.Is64BitOperatingSystem`](http://msdn.microsoft.com/en-us/library/system.environment.is64bitoperatingsystem.aspx) to give you this information.
How to know my processor is 32 or 64 bits in C#?
[ "", "c#", "" ]
I've serialized an object using Newtonsoft's JSON serializer, and the DateTime has come through as: ``` /Date(1237588418563+0000)/ ``` When I $.evalJSON() on that, it is an object but I can't find any normal Date methods like toUTCString on it. Any ideas what I can do with this?
Use one of the JsonConverters that come with Json.NET for working with dates to get a better format. JavaScriptDateTimeConverter will automatically give you a JavaScript date. ``` public class LogEntry { public string Details { get; set; } public DateTime LogDate { get; set; } } [Test] public void WriteJsonDates() { LogEntry entry = new LogEntry { LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc), Details = "Application started." }; string defaultJson = JsonConvert.SerializeObject(entry); // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"} string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter()); // {"Details":"Application started.","LogDate":new Date(1234656000000)} string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter()); // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"} } ``` Documentation: [**Serializing Dates in JSON with Json.NET**](http://james.newtonking.com/projects/json/help/index.html?topic=html/DatesInJSON.htm)
I came up with a different approach which might be useful to some. Basically I create my own *CustomDateConverter* that I call when I need it. The converter takes 2 parameters, a date format e.g. `yyyy-MM-dd HH:mm:ss` and a TimeZoneInfo, which allows me to convert the date from UTC to the user's time zone: ``` public class JSONCustomDateConverter : DateTimeConverterBase { private TimeZoneInfo _timeZoneInfo; private string _dateFormat; public JSONCustomDateConverter(string dateFormat, TimeZoneInfo timeZoneInfo) { _dateFormat = dateFormat; _timeZoneInfo = timeZoneInfo; } public override bool CanConvert(Type objectType) { return objectType == typeof(DateTime); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(value), _timeZoneInfo).ToString(_dateFormat)); writer.Flush(); } ``` You can use it like this: ``` var jsonString = JsonConvert.SerializeObject(myObject, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Converters = new List<JsonConverter>() { new JSONCustomDateConverter("yyyy-MM-dd HH:mm:ss", loggedUser.Timezone) } }); ``` Obviously you could remove anything related to time zone if you only want custom date formatting. Let me know it that helped!
Parsing JSON DateTime from Newtonsoft's JSON Serializer
[ "", "c#", "json", "datetime", "parsing", "json.net", "" ]
I have an application written in C# that needs to be able to configure the network adapters in Windows. I have this basically working through WMI, but there are a couple of things I don't like about that solution: sometimes the settings don't seem to stick, and when the network cable is not plugged in, errors are returned from the WMI methods, so I can't tell if they really succeeded or not. I need to be able to configure all of the settings available through the network connections - Properties - TCP/IP screens. What's the best way to do this?
You could use `Process` to fire off [netsh](http://support.microsoft.com/kb/242468) commands to set all the properties in the network dialogs. eg: To set a static ipaddress on an adapter ``` netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0 192.168.0.1 1 ``` To set it to dhcp you'd use ``` netsh interface ip set address "Local Area Connection" dhcp ``` To do it from C# would be ``` Process p = new Process(); ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address \"Local Area Connection\" static 192.168.0.10 255.255.255.0 192.168.0.1 1"); p.StartInfo = psi; p.Start(); ``` Setting to static can take a good couple of seconds to complete so if you need to, make sure you wait for the process to exit.
With my code SetIpAddress and SetDHCP ``` /// <summary> /// Sets the ip address. /// </summary> /// <param name="nicName">Name of the nic.</param> /// <param name="ipAddress">The ip address.</param> /// <param name="subnetMask">The subnet mask.</param> /// <param name="gateway">The gateway.</param> /// <param name="dns1">The DNS1.</param> /// <param name="dns2">The DNS2.</param> /// <returns></returns> public static bool SetIpAddress( string nicName, string ipAddress, string subnetMask, string gateway = null, string dns1 = null, string dns2 = null) { ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); NetworkInterface networkInterface = interfaces.FirstOrDefault(x => x.Name == nicName); string nicDesc = nicName; if (networkInterface != null) { nicDesc = networkInterface.Description; } foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true && mo["Description"].Equals(nicDesc) == true) { try { ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic"); newIP["IPAddress"] = new string[] { ipAddress }; newIP["SubnetMask"] = new string[] { subnetMask }; ManagementBaseObject setIP = mo.InvokeMethod("EnableStatic", newIP, null); if (gateway != null) { ManagementBaseObject newGateway = mo.GetMethodParameters("SetGateways"); newGateway["DefaultIPGateway"] = new string[] { gateway }; newGateway["GatewayCostMetric"] = new int[] { 1 }; ManagementBaseObject setGateway = mo.InvokeMethod("SetGateways", newGateway, null); } if (dns1 != null || dns2 != null) { ManagementBaseObject newDns = mo.GetMethodParameters("SetDNSServerSearchOrder"); var dns = new List<string>(); if (dns1 != null) { dns.Add(dns1); } if (dns2 != null) { dns.Add(dns2); } newDns["DNSServerSearchOrder"] = dns.ToArray(); ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDns, null); } } catch { return false; } } } return true; } /// <summary> /// Sets the DHCP. /// </summary> /// <param name="nicName">Name of the nic.</param> public static bool SetDHCP(string nicName) { ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); NetworkInterface networkInterface = interfaces.FirstOrDefault(x => x.Name == nicName); string nicDesc = nicName; if (networkInterface != null) { nicDesc = networkInterface.Description; } foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true && mo["Description"].Equals(nicDesc) == true) { try { ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder"); newDNS["DNSServerSearchOrder"] = null; ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null); ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null); } catch { return false; } } } return true; } ```
Best way to programmatically configure network adapters in .NET
[ "", "c#", ".net", "wmi", "" ]
i was in need of a regex which will return only 25,36,30 for me from > 25 10a 36 10b 30 as they are the only pure numbers in the sequence. I tried this but it did not work for me : ``` (^|[ ])\d+|($|[ ]) ``` Any suggestions?
Apply globally: ``` (?<=^|\s)\d+(?=\s|$) ```
You could use the [word boundary](http://www.regular-expressions.info/wordboundaries.html) option: ``` \b(\d+)\b ``` but some punctuation characters will be marked as a word boundary so this won't give what you want. So it looks like you'll have to explicitly look for whitespace: ``` /(^|\s+)(\d+)(\s+|$)/ ``` When extracting the number remember to get the second group as the first will only have spaces in it.
what will be a good regex to extract pure numbers out of "25 10a 36 10b 30"
[ "", "c#", ".net", "regex", "" ]
I have put few elements in array (e.g. 5 elements) The first element, index[0] of the array will automatically displayed without the user need to click the button. After the button clicked, it will print the next elements of array and the processes continue until the last element of array. Everytimes the button clicked, a file will be written on txt file. My problem here was, there are e.g. 5 elements of array (successfully displayed when button clicked), however only four files written on txt file. How to make it five...Helppp... Im in a dead road :-( ``` public class mainFrame extends JFrame implements ActionListener { ........ private JButton answer1 = new JButton(); String [] a = {"a","b","c","d","e"} in fileNumber = 0; } public mainFramme (){ System.out.println(a.get(fileNumber)) fileNumber++; answer1.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource==answer1) { System.out.println(a.get(fileNumber)) try { ..... fout = new FileOutputStream ("myfile.txt",true); Filename = new File(files.get(fileNumber)); new PrintStream(fout).println (Filename); new PrintStream(fout).println ("Answer 1"); fileNumber++; } ... } ``` }
Others have basically answered already, but from your comments I don't think it's clear. You are automatically displaying the first String to the screen, but not to a file. It would be better to move the file operations out of the actionPerformed() method. The way you have it written, the file operations are only called when the button is pressed, which is never the case for the first String. This might be clearer: ``` public class mainFrame extends JFrame implements ActionListener { ........ private JButton answer1 = new JButton(); String [] a = {"a","b","c","d","e"} in fileNumber = 0; } public mainFrame (){ nextString(); answer1.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource==answer1) nextString(); } private void nextString() { try { ..... System.out.println(a.get(fileNumber)) fout = new FileOutputStream ("myfile.txt",true); Filename = new File(files.get(fileNumber)); new PrintStream(fout).println (Filename); new PrintStream(fout).println ("Answer 1"); fileNumber++; } ... } ```
Your problem lies here: ``` public mainFramme (){ System.out.println(a.get(fileNumber)) fileNumber++ answer1.addActionListener(this); } ``` You're incrementing fileNumber before the button is pressed so it equals 1. Arrays are indexed from 0 in Java, meaning to get the first element in the array you use *array*[0] - Seeing as fileNumber will equal 1, you'll be getting the *second* element of the array - Thus missing the first. **EDIT DUE TO COMMENT:** Ok, then are you calling the flush() and close() methods on the file output stream? 'flush' ensures that any data in the stream is written out before it is closed. It may help if you post your entire actionPerformed method. Some of the code you posted in no ideal either (i.e the new PrintStream stuff) Perhaps this might help: ``` public void actionPerformed(ActionEvent e) { if(e.getSource() == answer1) { try { PrintWriter output = new PrintWriter(new FileOutputStream(fileName.txt)); // Write stuff to file using output.printLn(); output.flush(); output.close(); }catch (IOException e) { // exception handling } } } ```
Java array problems
[ "", "java", "arrays", "" ]
There is a Java `Void` -- uppercase V-- [reference type](https://docs.oracle.com/javase/9/docs/api/java/lang/Void.html). The only situation I have ever seen it used is to parameterize `Callable`s ``` final Callable<Void> callable = new Callable<Void>() { public Void call() { foobar(); return null; } }; ``` Are there any other uses for the Java `Void` reference type? Can it ever be assigned anything other than `null`? If yes, do you have examples?
`Void` has become convention for a generic argument that you are not interested in. There is no reason why you should use any other non-instantiable type, such as `System`. It is also often used in for example `Map` values (although `Collections.newSetFromMap` uses `Boolean` as maps don't have to accept `null` values) and `java.security.PrivilegedAction`.
You can create instance of Void using reflections, but they are not useful for anything. Void is a way to indicate a generic method returns nothing. ``` Constructor<Void> constructor = Void.class.getDeclaredConstructor(); constructor.setAccessible(true); Void v = constructor.newInstance(); System.out.println("I have a " + v); ``` prints something like ``` I have a java.lang.Void@75636731 ```
Uses for the Java Void Reference Type?
[ "", "java", "void", "" ]
Here I am again with another seemingly simple question I just cannot find the answer to. I would like to use an input type="button" but asp:Button always gives me a type="submit." ``` <asp:Button runat="server" bla bla bla /> ``` Thanks in advance.
Use the following ``` <asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="False" /> ``` I tested it and it renders an `<input type="button" />`
An **asp button** is set up by **default** to post a page back to the server when it is clicked, which is why it is rendered as a submit button. If you dont want a postback then there is no need to use the **asp:button control** ***Regular* html button should do the job**: ``` <input type="button" value="My Button"/> ``` you can still format html controls on the server ``` <input ID="MyButton" runat="server" type="button" value="My Button"/> ```
How do I get a button instead of a Submit
[ "", "c#", "asp.net", "" ]
I would like to extend a class generated by Linq To Sql to initialize when a new object (=row) is created. I want to add rows to a child table when a parent row is created. I was hoping to use the Oncreated (partial) method do something like this: ``` partial class Product { partial void OnCreated() { // Fill default rows for FK relations this.Columns.Add(new ProductColumn { Name = "Name", ColumnType = 1 }); this.Columns.Add(new ProductColumn { Name = "Producer", ColumnType = 2 }); } } ``` The OnCreated is called every time from the constructor. So also if the object will be loaded from the database after the call to OnCreated. And if the object is loaded from the database, do not want to execute the code. So where can I add logic to my model to initialize an object(-graph)?
I think you'd be better off in this instance to use a Factory to create your instances; So anywhere you current have code like: ``` Product p = new Product(); ``` You would instead have: ``` Product p = ProductFactory.CreateProduct(); ``` And your CreateProduct() method would look something like: ``` public Product CreateProduct() { var p = new Product(); p.Columns.Add(new ProductColumn { Name = "Name", ColumnType = 1 }); p.Columns.Add(new ProductColumn { Name = "Producer", ColumnType = 2 }); return p; } ```
There's no built in method for it in the Linq to SQL generated classes. They call OnLoaded specifically when called from the DB, but they do not call anything when it's not. I suspect because there's no way to know for sure... I'd recommend using the factory approach that Chris suggested.
Initialize a Linq to Sql object via business logic
[ "", "c#", ".net", "linq", "linq-to-sql", "business-logic", "" ]
I've seen these two things lately and I'm a bit confused. ``` var blah = new MyClass() { Name = "hello" } ``` and ``` var blah = new MyClass { Name = "hello" } ``` Whats the difference? and why do they both work? **Update:** Does this mean that if i have something in a constructor which does some computation that i would have to call the first one??
As far as I know, they're exactly equivalent. The C# specification (or at least Microsoft's implementation of it) allows you to omit the () when using the default constructor (no parameters) as long as you're using curly brackets (i.e. the syntax for [object initialisers](http://msdn.microsoft.com/en-us/library/bb384062.aspx)). Note that the object initializer makes no difference to the constructor here - the `new MyClass` bit still gets interpreted separately as a call to the default constructor. Personally, I would recommend you always include the round brackets () for consistency - you *need* them when you don't have an object initializer following.
There is no difference, first form just points out that you *are* also calling the constructor: ``` class Ö { public string Ä { get; set; } public string Å { get; set; } public Ö() { Å = "dear";} public Ö(string å) { Å = å; } } Console.WriteLine(new Ö { Ä = "hello" }.Å); Console.WriteLine(new Ö("world") { Ä = "hello" }.Å); ``` will result in: ``` dear world ```
Round brackets or not? Whats the difference?
[ "", "c#", "asp.net", "class", "conventions", "" ]
I've been told Java is not the greatest pick to follow an MVC architecture. I believe I've seen some Java framework solutions to ease this roadbump. However, I a bit confused on why this is. More specifically, why Java's attempt at MVC is often mocked as a "wannabe" approach. I come from a ObjC background (w/ Cocoa of course) and would love to hear from the seasoned programmers about why MVC with Java is said to fall short. Appreciate it!
You say you come from a Cocoa background so I'm assuming you're not talking about web-framework MVC. Most webframeworks that say they do MVC are actually using a different pattern called Front Controller, it's a bit of a different story from normal MVC because you need quite a lot of plumbing to make that work. Hence all the MVC frameworks in the web-world, originally MVC was a pattern for window-based applications. For these applications you can make MVC work without needing a framework. MVC is a pattern that can be implemented in any object oriented language. There's no reason why you can't do it in Java. The only reason I can think of why people would call MVC on Java a "wannabe" approach is that the UI libraries on Java like Swing do not actually require you to do MVC. They just give you the tools to implement a View. You'll have to create controller and model classes yourself. Discussions about what 'real MVC' is are usually not really constructive anyway. MVC is a pattern developed for smaltalk about 30 years ago. None of the implementations that are used now are exactly the same anymore, many implementations are improvements. You've got different flavours called MVP, MVVM, Document-View etc. And they are all usefull in some cases. The important thing to take away from this is that its a good idea to separate your UI logic from your application logic. Java can do this and so can most other languages. People claiming otherwise are probably just afraid to look outside the language they're comfortable with.
At it's roots, MVC is a programming model. I consider it to be platform and language agnostic. I used to follow the MVC principles in C++, so I'm not sure why any language would be considered as "falling short" with regard to following these principles. Admittedly, I'm a .NET person these days, but I think with a little effort they could be applied to Java. See [Java Model-View Controller](http://leepoint.net/notes-java/GUI/structure/40mvc.html) for some ideas.
MVC and Java in comparison with more strict MVC languages
[ "", "java", "cocoa", "model-view-controller", "" ]
I am trying to pull at list of resource/database names and IDs from a listing of resources that my school library has subscriptions to. There are pages listing the different resources, and I can use urllib2 to get the pages, but when I pass the page to BeautifulSoup, it truncates its tree just before the end of the entry for the first resource in the list. The problem seems to be in image link used to add the resource to a search set. This is where things get cut off, here's the HTML: ``` <a href="http://www2.lib.myschool.edu:7017/V/ACDYFUAMVRFJRN4PV8CIL7RUPC9QXMQT8SFV2DVDSBA5GBJCTT-45899?func=find-db-add-res&amp;resource=XYZ00618&amp;z122_key=000000000&amp;function-in=www_v_find_db_0" onclick='javascript:addToz122("XYZ00618","000000000","myImageXYZ00618","http://discover.lib.myschool.edu:8331/V/ACDYFUAMVRFJRN4PV8CIL7RUPC9QXMQT8SFV2DVDSBA5GBJCTT-45900");return false;'> <img name="myImageXYZ00618" id="myImageXYZ00618" src="http://www2.lib.myschool.edu:7017/INS01/icon_eng/v-add_favorite.png" title="Add to My Sets" alt="Add to My Sets" border="0"> </a> ``` And here is my python code: ``` import urllib2 from BeautifulSoup import BeautifulSoup page = urllib2.urlopen("http://discover.lib.myschool.edu:8331/V?func=find-db-1-title&mode=titles&scan_start=latp&scan_utf=D&azlist=Y&restricted=all") print BeautifulSoup(page).prettify ``` In BeautifulSoup's version, the opening `<a href...>` shows up, but the `<img>` doesn't, and the `<a>` is immediately closed, as are the rest of the open tags, all the way to `</html>`. The only distinguishing trait I see for these "add to sets" images is that they are the only ones to have name and id attributes. I can't see why that would cause BeautifulSoup to stop parsing immediately, though. Note: I am almost entirely new to Python, but seem to be understanding it all right. Thank you for your help!
I was using Firefox's "view selection source", which apparently cleans up the HTML for me. When I viewed the original source, this is what I saw ``` <img name="myImageXYZ00618" id="myImageXYZ00618" src='http://www2.lib.myschool.edu:7017/INS01/icon_eng/v-add_favorite.png' alt='Add to My Sets' title='Add to My Sets' border="0"title="Add to clipboard PAIS International (CSA)" alt="Add to clipboard PAIS International (CSA)"> ``` By putting a space after the `border="0"` attribute, I can get BS to parse the page.
You can try beautiful soup with html5lib rather than the built-in parser. ``` BeautifulSoup(markup, "html5lib") ``` html5lib is more lenient and often parses pages that the built-in parser truncates. See the docs at <http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-the-tree>
Why is Beautiful Soup truncating this page?
[ "", "python", "screen-scraping", "beautifulsoup", "" ]
I want to make a database restore function that will parse a dump made with phpMyAdmin and will execute all of the queries. I already have a MySQL class that does the query, but it only knows how to do a single query. I am looking of a way to split the file content into single queries. I tried to play with preg\_split ... but didn't managed to get it to work. ``` $queries = preg_split('/[(.+);\s*\n/', $content, -1, PREG_SPLIT_NO_EMPTY); ``` I am not very good with regular expressions. Is there a way I can accomplish my goal?
Eventually I managed to find the right regex: ``` $queries = preg_split('/[.+;][\s]*\n/', $content, -1, PREG_SPLIT_NO_EMPTY); ``` it splits the query after the ; sign and does not break even if the query spreads on multiple rows or the query contains ; since it looks for it at the end of a line.
don't try to parse sql with regular expressions. what if there is a `;` somewhere inside a sql string? i would try <http://pear.php.net/package/SQL_Parser>, or any of the [other php mysql parsers](http://www.google.com/search?q=php+sql+parser) out there. see also [PHP MySQL SQL parser (INSERT and UPDATE)](https://stackoverflow.com/questions/283087/php-mysql-sql-parser-insert-and-update) here on SO.
mysql split multiquery string with php
[ "", "php", "mysql", "multi-query", "" ]
I have a fairly complex Xcode project and I want to add Qt to it. I know that I can create a *new* project using `qmake -spec macx-xcode project.pro` but I don't want to have to hand configure my old project over the auto generated Qt project. Is there another option? [edited in a more general question below] It seems like it would be easier to simply use qmake as my build system. Hence, adding my old project build process to the *.pro* file and use that to generate a new *.xcodeproj*? I would only do this if I could comprehensively configure the .pro file so that I don't have to hand configure the *.xcodeproj* - is this doable? I really don't want to have to mess around with hand configuring the *.xcodeproj* each time I run qmake. Essentially, is qmake (or a meta-build in general) a valid substitute for a normal build system, such that I don't need to tweak the resulting build system generated by qmake? Are there better resources besides the [manual](http://doc.trolltech.com/4.5/qmake-manual.html) and [tutorial](http://doc.trolltech.com/4.5/qmake-tutorial.html) provided by Trolltech? I'm concerned that [wikipedia](http://en.wikipedia.org/wiki/Qmake) says that qmake is primarily for internal use and not well documented.
One of the main points of using Qt is the portability of the Gui. It only makes sense to extend this feature to your build process by using qmake and allowing users/developers generate whichever build system they want to use (make, visualstudio, xcode). No, qmake is not well documented and more poignantly there are not manifold examples like there are for make. But, it is similar to make and should be intuitive. Why not absorb the overhead to learn it and pass the benefit on to your users/developers?
Build an empty xcode project with qmake and incorporate the compiler settings to your existing project from the generated Makefile. Of course, you will have to set up your existing project to run qmake as a pre-build step if you are using Qt-specific extensions. > What do you think is the easiest method for integrating established projects with Qt? That depends on the nature of your work. I wish I could have given a more specific answer here but I really can't. Also, are you using Qt professional? In that case, you can get support (at least that's how it was, during 3.3 when I last worked on it for anything production-quality). If all you care about Qt is the graphics part, I'd say don't bother changing your build system, rather see to it that you get the code to compile and link and run just fine. But, if you are going to use signals and slots and what not -- think about moving over. > Would you recommend I do the xcodeproj merge I asked about and which you answered, or should I start from scratch with qmake like I edited a question about? Again, look at the size of your project. Assuming a fairly complex project, I'd hazard a guess that you have about 2/3 man-days worth of effort to rewrite the build system? Is this project a serious one, something that will be maintained over a period of time? Is this cross-platform? Will you be using Qt throughout? If there is an overbearing reason to feel that Qt is the way forward I'd suggest that you start using their build system.
Adding Qt to Xcode project?
[ "", "c++", "xcode", "qt", "" ]
Is it a good idea to learn JavaScript before learning a JavaScript framework library such as jQuery, Prototype, etc.? Sometimes I find myself struggling because I feel I don't know JavaScript as well as I should.
An emphatic **YES**. It won't take as long to learn as you fear and the rewards will be more than worth it.
> Sometimes I find myself struggling > because I feel I don't know Javascript > as well as I should? I think you answered your own question.
Is it a good idea to learn JavaScript before learning jQuery?
[ "", "javascript", "jquery", "" ]
That's what I've written so far: ``` string omgwut; omgwut = textBox1.Text; omgwut = omgwut.Replace(" ", "snd\\space.wav"); omgwut = omgwut.Replace("a", "snd\\a.wav"); ``` Now, the problem is that this code would turn ``` "snd\space.wav" ``` into ``` "snd\spsnd\a.wavce.wsnd\a.wavv" ``` in line four. Not what I'd want! Now I know I'm not good at C#, so that's why I'm asking. Solutions would be great! Thanks!
You'll still need to write the getSoundForChar() function, but this should do what you're asking. I'm not sure, though, that what you're asking will do what you want, i.e., play the sound for the associated character. You might be better off putting them in a List<string> for that. ``` StringBuilder builder = new StringBuilder(); foreach (char c in textBox1.Text) { string sound = getSoundForChar( c ); builder.Append( sound ); } string omgwut = builder.ToString(); ``` Here's a start: ``` public string getSoundForChar( char c ) { string sound = null; if (sound == " ") { sound = "snd\\space.wav"; } ... handle other special characters else { sound = string.Format( "snd\\{0}.wav", c ); } return sound; } ```
The problem is that you are doing multiple passes of the data. Try just stepping through the characters of the string in a loop and replacing each 'from' character by its 'to' string. That way you're not going back over the string and re-doing those characters already replaced. Also, create a separate output string or array, instead of modifying the original. Ideally use a StringBuilder, and append the new string (or the original character if not replacing this character) to it.
Replacing each letter of the alphabet in a string?
[ "", "c#", "string", "" ]
I'm new to interfaces and abstract classes. I want to create a couple of interfaces to define core methods and variables for the objects for a shopping cart system. Then I want to create abstract classes which implement the core functions. The idea is that they can be used by other classes in slightly different ways for different projects. Here are my (cut-down) interfaces: ``` public interface ICart { ... List<ICartItem> CartItems { get; set; } } public interface ICartItem { int ProductId { get; set; } int Quantity { get; set; } } ``` And here is my abstract Cart class (again, only showing relevant lines) which implements ICart: ``` public abstract class Cart : ICart { private List<CartItem> _cartItems = new List<CartItem>(); public List<CartItem> CartItems { get { return _cartItems; } } } ``` And my CartItem class which implements ICartItem: ``` public abstract class CartItem : ICartItem { ... } ``` When I try to compile the classes I get an error saying: 'Cart' does not implement interface member 'CartItems'. 'Cart.CartItems' cannot implement 'ICart.CartItems' because it does not have the matching return type of System.Collections.Generic.List<ICartItem>. I thought that the idea here is that the interface can be implemented by a number of classes which perform the core functions in different ways and add new methods, etc. Why would my interface need to know what class is actually being used, just as long as that class actually implements the interface correctly?
You need to user generics in C# 2 to achieve that: ``` public interface ICart<T> where T : ICartItem { // ... List<T> CartItems { get; set; } } public abstract class Cart : ICart<CartItem> { // ... public List<CartItem> CartItems { get; set; } } ```
In your abstract class, you should define that the return type of the CartItems property, is of type `List<ICartItem>`. But, if you really want that the property is of type `List<CartItem>`, you can maybe do this: ``` public interface ICart<TCartItem> where TCartItem : ICartItem { List<TCartItem> CartItems { get; set; } } public interface ICartItem { } public abstract class Cart : ICart<CartItem> { public List<CartItem> { get; set; } } public abstract class CartItem : ICartItem { } ```
How do I define the return type of an interface method to be another interface?
[ "", "c#", "interface", "" ]
I have a div of class `example` In JavaScript I have: ``` var selectWithThis = 'example' ``` Using this variable how would I write a `$()` selector to select this div?
``` var elements = $('.' + selectWithThis); ``` Note that it returns an array of all elements with the same class. If there is only one element, still an array with just an element.
$('.' + selectWithThis); To use what ever class/string is stored in the variable.
How to select elements by class with jQuery?
[ "", "javascript", "jquery", "" ]
I have a List<> in my program, filled with my custom class. I want to be able to extract an object from the list by simply specifying an integer, then returning all objects that have an integer property set to that integer. I was thinking of doing it like this: ``` int exampleint = 5; List<MyClass> extract = new List<MyClass>(); for(int i = 0; i < list.Length; i++) { if(list[i].Number == exampleint) extract.Add(list[i]); } return extract; ``` Is there any better or faster way do do this? Just wondering. Update: Chris, your answer was a little off. This: ``` List<MyClass> extract = list.FindAll(delegate(int obj) { return obj.Number == exampleint; }); ``` should in fact be this: ``` List<MyClass> extract = list.FindAll(new Predicate<MyClass>(delegate(MyClass obj) { return obj.Number == exampleint; })); ``` Your first example gave me errors. But thanks for pointing me in the right direction, it seems to work now.
``` List<MyClass> extract = list.FindAll(obj => obj.Number == exampleint); ``` OR (if you're using .NET 2.0 and can't use expressions) ``` List<MyClass> extract = list.FindAll(delegate(MyClass obj) { return obj.Number == exampleint; }); ```
If you only have C#2, try this: ``` public delegate bool Predicate<T>(T item); public static IEnumerable<T> Where(IEnumerable<T> source, Predicate pred) { foreach (T item in source) { if (pred(item)) yield return item; } } ``` You can reuse that whenever you have this kind of filtering requirement, like this: ``` IEnumerable<MyClass> filtered = Where(list, delegate(MyClass c) { return c.Number == exampleint; }); ``` It's essentially identical to the Linq solutions and it will enable you to get use to this style of list processing ready for when you can upgrade your compiler.
How do I get an item in a List<> based on an integer field?
[ "", "c#", "generics", "list", "" ]
I just learned about Java's Scanner class and now I'm wondering how it compares/competes with the StringTokenizer and String.Split. I know that the StringTokenizer and String.Split only work on Strings, so why would I want to use the Scanner for a String? Is Scanner just intended to be one-stop-shopping for spliting?
They're essentially horses for courses. * `Scanner` is designed for cases where you need to parse a string, pulling out data of different types. It's very flexible, but arguably doesn't give you the simplest API for simply getting an array of strings delimited by a particular expression. * `String.split()` and `Pattern.split()` give you an easy syntax for doing the latter, but that's essentially all that they do. If you want to parse the resulting strings, or change the delimiter halfway through depending on a particular token, they won't help you with that. * `StringTokenizer` is even more restrictive than `String.split()`, and also a bit fiddlier to use. It is essentially designed for pulling out tokens delimited by fixed substrings. Because of this restriction, it's about twice as fast as `String.split()`. (See my [comparison of `String.split()` and `StringTokenizer`](http://www.javamex.com/tutorials/regular_expressions/splitting_tokenisation_performance.shtml).) It also predates the regular expressions API, of which `String.split()` is a part. You'll note from my timings that `String.split()` can still tokenize **thousands of strings in a few milliseconds** on a typical machine. In addition, it has the advantage over `StringTokenizer` that it gives you the output as a string array, which is usually what you want. Using an `Enumeration`, as provided by `StringTokenizer`, is too "syntactically fussy" most of the time. From this point of view, `StringTokenizer` is a bit of a waste of space nowadays, and you may as well just use `String.split()`.
Let's start by eliminating [`StringTokenizer`](http://java.sun.com/javase/6/docs/api/java/util/StringTokenizer.html). It is getting old and doesn't even support regular expressions. Its documentation states: > `StringTokenizer` is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the `split` method of `String` or the `java.util.regex` package instead. So let's throw it out right away. That leaves [`split()`](http://java.sun.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)) and [`Scanner`](http://java.sun.com/javase/6/docs/api/java/util/Scanner.html). What's the difference between them? For one thing, `split()` simply returns an array, which makes it easy to use a foreach loop: ``` for (String token : input.split("\\s+") { ... } ``` `Scanner` is built more like a stream: ``` while (myScanner.hasNext()) { String token = myScanner.next(); ... } ``` or ``` while (myScanner.hasNextDouble()) { double token = myScanner.nextDouble(); ... } ``` (It has a rather [large API](http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#method_summary), so don't think that it's always restricted to such simple things.) This stream-style interface can be useful for parsing simple text files or console input, when you don't have (or can't get) all the input before starting to parse. Personally, the only time I can remember using `Scanner` is for school projects, when I had to get user input from the command line. It makes that sort of operation easy. But if I have a `String` that I want to split up, it's almost a no-brainer to go with `split()`.
Scanner vs. StringTokenizer vs. String.Split
[ "", "java", "java.util.scanner", "tokenize", "split", "" ]
I want to implement a logical operation that works as efficient as possible. I need this truth table: ``` p q p → q T T T T F F F T T F F T ``` This, according to wikipedia is called "[logical implication](http://en.wikipedia.org/wiki/Logical_implication)" I've been long trying to figure out how to make this with bitwise operations in C without using conditionals. Maybe someone has got some thoughts about it. Thanks
FYI, with gcc-4.3.3: ``` int foo(int a, int b) { return !a || b; } int bar(int a, int b) { return ~a | b; } ``` Gives (from objdump -d): ``` 0000000000000000 <foo>: 0: 85 ff test %edi,%edi 2: 0f 94 c2 sete %dl 5: 85 f6 test %esi,%esi 7: 0f 95 c0 setne %al a: 09 d0 or %edx,%eax c: 83 e0 01 and $0x1,%eax f: c3 retq 0000000000000010 <bar>: 10: f7 d7 not %edi 12: 09 fe or %edi,%esi 14: 89 f0 mov %esi,%eax 16: c3 retq ``` So, no branches, but twice as many instructions. And even better, with `_Bool` (thanks @litb): ``` _Bool baz(_Bool a, _Bool b) { return !a || b; } ``` ``` 0000000000000020 <baz>: 20: 40 84 ff test %dil,%dil 23: b8 01 00 00 00 mov $0x1,%eax 28: 0f 45 c6 cmovne %esi,%eax 2b: c3 retq ``` So, using `_Bool` instead of `int` is a good idea. Since I'm updating today, I've confirmed gcc 8.2.0 produces similar, though not identical, results for `_Bool:` ``` 0000000000000020 <baz>: 20: 83 f7 01 xor $0x1,%edi 23: 89 f8 mov %edi,%eax 25: 09 f0 or %esi,%eax 27: c3 retq ```
``` !p || q ``` is plenty fast. seriously, don't worry about it.
How could I implement logical implication with bitwise or other efficient code in C?
[ "", "c++", "c", "performance", "logic", "algebra", "" ]
How do I pull an item out of a Python dictionary without triggering a KeyError? In Perl, I would do: ``` $x = $hash{blah} || 'default' ``` What's the equivalent Python?
Use the [`get(key, default)`](http://docs.python.org/library/stdtypes.html#dict.get) method: ``` >>> dict().get("blah", "default") 'default' ```
If you're going to be doing this a lot, it's better to use [collections.defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict): ``` import collections # Define a little "factory" function that just builds the default value when called. def get_default_value(): return 'default' # Create a defaultdict, specifying the factory that builds its default value dict = collections.defaultdict(get_default_value) # Now we can look up things without checking, and get 'default' if the key is unknown x = dict['blah'] ```
How do I rewrite $x = $hash{blah} || 'default' in Python?
[ "", "python", "" ]
I have a class called ImageMatrix, which implements the C++ map in a recursive fashion; the end result is that I have a 3 dimensional array. ``` typedef uint32_t VUInt32; typedef int32_t VInt32; class ImageMatrix { public: ImageMatrixRow operator[](VInt32 rowIndex) private: ImageMatrixRowMap rows; }; typedef std::map <VUInt32, VInt32> ImageMatrixChannelMap; class ImageMatrixColumn { public: VInt32 &operator[](VUInt32 channelIndex); private: ImageMatrixChannelMap channels; }; typedef std::map<VUInt32, ImageMatrixColumn> ImageMatrixColumnMap; class ImageMatrixRow { public: ImageMatrixColumn operator[](VUInt32 columnIndex); private: ImageMatrixColumnMap columns; }; typedef std::map<VUInt32, ImageMatrixRow> ImageMatrixRowMap; ``` Each operator simply returns a map-wrapper class within, like so: ``` ImageMatrixRow ImageMatrix::operator[](VInt32 rowIndex) { return rows[rowIndex]; } ImageMatrixColumn ImageMatrixRow::operator[](VUInt32 columnIndex) { return columns[columnIndex]; } VInt32 &ImageMatrixColumn::operator[](VUInt32 channelIndex) { return channels[channelIndex]; } ``` Basically, when I set the value as say 100, and test the value to cout, it shows as 0, and not the number to which I had set it. ``` for (VUInt32 a = 0; a < GetRowCount(); a++) { for (VUInt32 b = 0; b < GetColumnCount(); b++) { for (VUInt32 c = 0; c < GetChannelCount(); c++) { VInt32 value = 100; matrix[a][b][c] = value; VInt32 test = matrix[a][b][c]; // pixel = 100, test = 0 - why? cout << pixel << "/" << test << endl; } } } ``` Note: I've altered the original code for this example so that it takes up less space, so some syntax errors may occur (please don't point them out).
The following operators return by value, no writes modify the actual data. ``` ImageMatrixRow ImageMatrix::operator[](VInt32 rowIndex); ImageMatrixColumn ImageMatrixRow::operator[](VUInt32 columnIndex); ``` Use: ``` ImageMatrixRow& ImageMatrix::operator[](VInt32 rowIndex) ImageMatrixColumn& ImageMatrixRow::operator[](VUInt32 columnIndex) ```
All your operator[] functions except one return values - they should all return references.
Why is my implementation of C++ map not storing values?
[ "", "c++", "dictionary", "" ]
I'm using `webClient.DownloadFile()` to download a file can I set a timeout for this so that it won't take so long if it can't access the file?
Try `WebClient.DownloadFileAsync()`. You can call `CancelAsync()` by timer with your own timeout.
My answer comes from [here](http://w3ka.blogspot.com/2009/12/how-to-fix-webclient-timeout-issue.html) You can make a derived class, which will set the timeout property of the base `WebRequest` class: ``` using System; using System.Net; public class WebDownload : WebClient { /// <summary> /// Time in milliseconds /// </summary> public int Timeout { get; set; } public WebDownload() : this(60000) { } public WebDownload(int timeout) { this.Timeout = timeout; } protected override WebRequest GetWebRequest(Uri address) { var request = base.GetWebRequest(address); if (request != null) { request.Timeout = this.Timeout; } return request; } } ``` and you can use it just like the base WebClient class.
Set timeout for webClient.DownloadFile()
[ "", "c#", ".net", "download", "webclient", "" ]
I have a form which gets introduced via XHR and I need to be able to bind an event on it, for submit. I've downloaded the jquery.form.js plugin. What's the best way to perform a late binding so that I can do something such as: ``` $(document).ready(function() { // bind 'myForm' and provide a simple callback function $('#myForm').ajaxForm(function() { alert("Thank you for your comment!"); }); }); ``` Unfortunately since the form isn't readily available when the DOM first populates, this won't work. \*\* EDIT \*\* I've tried binding to the form AFTER it is retrieved via XHR and haven't had much luck. Here's how it looks: ``` $.get("foo.php", function(data) { $('#my_form').ajaxForm(function() { alert("Thank you for your comment!"); }); }); ```
I think you don't do it right. The way I use jquery forms is this: ``` $('#myform').submit(function(){ $(this).ajaxSubmit(function(){ alert('Thanks for your comment'); }); return false }); ``` You call this after the form is injected into DOM. Another way to do this is to using `live` binding from [jquery](http://docs.jquery.com/Events/live#typefn) ``` $('#myform').live('submit', function(){ $(this).ajaxSubmit(function(){ alert('Thanks for your comment'); }); return false }); ``` Any way you pick, you must include this piece of code into `$(document).ready()`
jQuery 1.3 introduced ["Live" events](http://docs.jquery.com/Events/live#typefn), which will bind to any current, and future element defined by a selector. I've not done anything with them, but it seems reasonable that you should be able to do something like: ``` $(document).ready(function() { $('form').live("ready",function() { alert("Something"); }); }); ``` Not sure if the ready event would actually work in this case, but seems worth a shot.
How to do late binding with jQuery?
[ "", "javascript", "jquery", "" ]
Got this question from a professor, a physicist. I am a beginner in Python programming. I am not a computer professional I am a physicist. I was trying to write a code in python for my own research which involves a little image processing. All I need to do is to display an image and then select a region of interest using my mouse and finally crop out the selected region. I can do this in Matlab using the ginput() function. I tried using PIL. But I find that after I issue the command Image.show(), the image is displayed but then the program halts there unless I exit from the image window. Is there any way to implement what I was planning. Do I need to download any other module? Please advise.
While I agree with David that you should probably just use GIMP or some other image manipulation program, here is a script (as I took it to be an exercise to the reader) using [pygame](http://www.pygame.org/) that does what you want. You will need to install pygame as well as the PIL, usage would be: ``` scriptname.py <input_path> <output_path> ``` Actual script: ``` import pygame, sys from PIL import Image pygame.init() def displayImage( screen, px, topleft): screen.blit(px, px.get_rect()) if topleft: pygame.draw.rect( screen, (128,128,128), pygame.Rect(topleft[0], topleft[1], pygame.mouse.get_pos()[0] - topleft[0], pygame.mouse.get_pos()[1] - topleft[1])) pygame.display.flip() def setup(path): px = pygame.image.load(path) screen = pygame.display.set_mode( px.get_rect()[2:] ) screen.blit(px, px.get_rect()) pygame.display.flip() return screen, px def mainLoop(screen, px): topleft = None bottomright = None runProgram = True while runProgram: for event in pygame.event.get(): if event.type == pygame.QUIT: runProgram = False elif event.type == pygame.MOUSEBUTTONUP: if not topleft: topleft = event.pos else: bottomright = event.pos runProgram = False displayImage(screen, px, topleft) return ( topleft + bottomright ) if __name__ == "__main__": screen, px = setup(sys.argv[1]) left, upper, right, lower = mainLoop(screen, px) im = Image.open(sys.argv[1]) im = im.crop(( left, upper, right, lower)) im.save(sys.argv[2]) ``` Hope this helps :)
For what it's worth (coming from another physicist), I would just do this in an image processing program like [the GIMP](http://www.gimp.org). The main benefit of doing this task in Python (or any language) would be to save time by automating the process, but unless you - well, the professor - can somehow develop an algorithm to automatically figure out what part of the image to crop, there doesn't seem to be much time to be saved by automation. If I remember correctly, GIMP is actually scriptable, possibly with Python, so it might be possible to write a time-saving GIMP script to do what your professor friend wants.
Digital Image cropping in Python
[ "", "python", "image-processing", "" ]
> **Possible Duplicate:** > [Ternary conditional operator in Python](https://stackoverflow.com/questions/394809/ternary-conditional-operator-in-python) If I have some code like: ``` x = foo ? 1 : 2 ``` How should I translate it to Python? Can I do this? ``` if foo: x = 1 else: x = 2 ``` Will x still be in scope outside the if / then blocks? Or do I have to do something like this? ``` x = None if foo: x = 1 else: x = 2 ```
Use the ternary operator(formally [conditional expression](http://docs.python.org/reference/expressions.html#boolean-operations)) in Python 2.5+. ``` x = 1 if foo else 2 ```
A nice python trick is using this: ``` foo = ["ifFalse","ifTrue"][booleanCondition] ``` It creates a 2 membered list, and the boolean becomes either 0 (false) or 1 (true), which picks the correct member. Not very readable, but pythony :)
What's the best way to replace the ternary operator in Python?
[ "", "python", "" ]
I am currently developing a program in Qt and it uses the library libqextserialport.1.dylib. I build it and run in x-code and it spits back: ``` dyld: Library not loaded: libqextserialport.1.dylib Referenced from: /Users/samuelreh/Desktop/QtOpenCV/build/Debug/QtOpenCV.app/Contents/MacOS/QtOpenCV Reason: image not found ``` The library is located in /Users/samuelreh/Desktop/QtOpenCV/qextserialport/build/. I can run my program by changing to the executable folder /Users/samuelreh/Desktop/QtOpenCV/build/Debug/QtOpenCV.app/Contents/MacOS/ and entering: `install_name_tool -change libqextserialport.1.dylib /Users/samuelreh/Desktop/QtOpenCV/qextserialport/build/libqextserialport.1.dylib QtOpenCV` I know there is probably many solutions besides this. Anybody know the best / most-elegant / easiest to do from x-code?
If I understand your problem correctly, your app is building fine, no errors when linking, but when you try to launch it the library cannot be found. That's not surprising, since the dylib file is in some arbitrary directory not on the system path. You either need to copy it into `/usr/lib` (probably not a good idea) or include it in the application bundle. The latter is probably the better approach. I've never tried it, but apparently you need to use a [Copy Files Build Phase](http://developer.apple.com/DOCUMENTATION/DeveloperTools/Conceptual/XcodeBuildSystem/200-Build_Phases/bs_build_phases.html#//apple_ref/doc/uid/TP40002690-CJAHHAJI) to put the dylib inside your bundle and then [configure Xcode](http://www.codeshorts.ca/2007/nov/01/leopard-linking-making-relocatable-libraries-movin) so that your executable will know where to find it.
I've just done exactly this, with a Module Bundle project. This was being included into a larger project with a separate executable. I added a "Copy dylibs to frameworks" step, which copied the dylibs to /Foobar.bundle/Contents/Frameworks/Foobar/. Then I added a Run Script Phase to run as the final step, to fix the install names of the dylibs in the executable: ``` install_name_tool -change libBobDylan.dylib @executable_path/../Plugins/Foobar.bundle/Contents/Frameworks/Foobar/libBobDylan.dylib path/to/build/product/Foobar.Bundle/Contents/MacOS/Foobar ``` Of course, libBobDylan.dylib also linked to libBillyIdol.dylib. So I had to add another Run Script Phase at the very start of the Target to fix the install names here: ``` install_name_tool -change libBillyIdol.dylib @executable_path/../Plugins/FooBar.bundle/Contents/Frameworks/Foobar/libBillyIdol.dylib local/path/to/libBobDylan.dylib ``` I had over a dozen of these to link against; I had to persuade the supplier of the dylibs to pad their header to accommodate my many install\_name changes ...
How can I link a dynamic library in Xcode?
[ "", "c++", "xcode", "macos", "dylib", "" ]
I'm getting an xml file and want to get data from it. The source of the xml doesn't really matter but what I;ve got to get a certain field is: ``` tracks = xmlDoc.getElementsByTagName("track"); variable = tracks.item(i).childNodes.item(4).childNodes.item(0).nodeValue; ``` Now this works like a charm, EXCEPT when there is no value in the node. So if the structure is like this: ``` <xml> <one> <two>nodeValue</two> </one> <one> <two></two> </one> </xml> ``` the widget will crash on the second 'one' node, because there is no value in the 'two' node. The console says: ``` TypeError: tracks.item(i).childNodes.item(4).childNodes.item(0) has no properties ``` Any ideas on how to get the widget to just see empty as an empty string (null, empty, or ""), instead of crashing? I'm guessing something along the lines of *data*, *getValue()*, *text*, or something else. using ``` var track= xmlDoc.getElementsByTagName('track')[0]; var info= track.getElementsByTagName('artist')[0]; var value= info.firstChild? info.firstChild.data : ''; ``` doesn't work and returns "TypeError: track has no properties". That's from the second line where artist is called.
Yahoo! Widgets does not implement all basic javascript functions needed to be able to use browser-code in a widget. instead of using: ``` tracks = xmlDoc.getElementsByTagName("track"); variable = tracks.item(i).childNodes.item(4).childNodes.item(0).nodeValue; ``` to get values it's better to use Xpath with a direct conversion to string. When a string is empty in Yahoo! Widgets it doesn't give any faults, but returns the 'empty'. innerText and textContent (the basic javascript way in browsers, used alongside things like getElementsByTagName) are not fully (or not at all) implemented in the Yahoo! Widgets Engine and make it run slower and quite awfully react to xmlNodes and childNodes. an easy way however to traverse an xml Document structure is using 'evaluate' to get everything you need (including lists of nodes) from the xml. After finding this out, my solution was to make everything a lot easier and less sensitive to faults and errors. Also I chose to put the objects in an array to make working with them easier. ``` var entries = xmlDoc.evaluate("lfm/recenttracks/track"); var length = entries.length; for(var i = 0; i &lt; length; i++) { var entry = entries.item(i); var obj = { artist: entry.evaluate("string(artist)"), name: entry.evaluate("string(name)"), url: entry.evaluate("string(url)"), image: entry.evaluate("string(image[@size='medium'])") }; posts[i] = obj; } ```
Test that the ‘two’ node has a child node before accessing its data. childNodes.item(i) (or the JavaScript simple form childNodes[i]) should generally be avoided, it's a bit fragile relying on whitespace text nodes being in the exact expected place. I'd do something like: ``` var tracks= xmlDoc.getElementsByTagName('track')[0]; var track= tracks.getElementsByTagName('one')[0]; var info= track.getElementsByTagName('two')[0]; var value= info.firstChild? info.firstChild.data : ''; ``` (If you don't know the tagnames of ‘one’ and ‘two’ in advance, you could always use ‘getElementsByTagName('\*')’ to get all elements, as long as you don't need to support IE5, where this doesn't work.) An alternative to the last line is to use a method to read *all* the text inside the node, including any of its child nodes. This doesn't matter if the node only ever contains at most one Text node, but can be useful if the tree can get denormalised or contain EntityReferences or nested elements. Historically one had to write a recurse method to get this information, but these days most browsers support the DOM Level 3 textContent property and/or IE's innerText extension: ``` var value= info.textContent!==undefined? info.textContent : info.innerText; ```
How do I get my widget not to crash if there is no value in a xml node?
[ "", "javascript", "xml", "return-value", "yahoo-widgets", "" ]
On the build tab in a Web Application project I have a setting called "Warning Level". I can set a value from 0 to 4. What do these values mean? Will a value of 0 be more strict and generate more warnings, or vice versa? I haven't been able to find any documentation on it yet, but perhaps I'm looking in the wrong place.
[This link](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/warn-compiler-option) shows you the definitions of the warning levels (I'm assuming you are using C# code in your web project). Level 5 is the most strict. --- * 0: Turns off emission of all warning messages. * 1: Displays severe warning messages. * 2: Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members. * 3: Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to **true** or **false**. * 4: Displays all level 3 warnings plus informational warnings. This is the default warning level at the command line. * 5: Displays level 4 warnings plus additional warnings from the compiler shipped with C# 9.0. Anything greater than 5 is treated as 5.
Higher is stricter. It can be annoying to see all the warnings that may or may not mean much to your app, but taking the time to clear them up can teach you a lot.
Visual Studio warning level meanings?
[ "", "c#", "visual-studio", "warnings", "compiler-warnings", "" ]
Is it possible to create a temporary file that contains a "loop" of a wav file? Or is it possible to manipulate the stream sent to a stream reader/writer? Basically I want to play some wav file for a period of time and if that time is greater than the length of time that the wav file provides I want to loop.
``` AudioInputStream audioIn = AudioSystem.getAudioInputStream(url); Clip clip = AudioSystem.getClip(); clip.loop((int)(Math.ceil(timeRequested / audioIn.getFrameLength()))); ```
I think I'll use the frames per second and framesize information in the audio input stream to figure this out. Other useful information is in getMicrosecondPosition() method of the SourceDataLine object to determine the time/duration played so far. this along with mark and reset methods in the audio input stream probably take care of it all.
playing wav file in java - how do I extend or concatenate the sound played?
[ "", "java", "audio", "wav", "" ]
I'm trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called [timeit](http://docs.python.org/library/timeit.html) that purports to do exactly that: ``` import timeit def foo(): # ... contains code I want to time ... def dotime(): t = timeit.Timer("foo()") time = t.timeit(1) print "took %fs\n" % (time,) dotime() ``` However, this produces an error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in dotime File "/usr/local/lib/python2.6/timeit.py", line 193, in timeit timing = self.inner(it, self.timer) File "<timeit-src>", line 6, in inner NameError: global name 'foo' is not defined ``` I'm still new to Python and I don't fully understand all the scoping issues it has, but I don't know why this snippet doesn't work. Any thoughts?
Change this line: ``` t = timeit.Timer("foo()") ``` To this: ``` t = timeit.Timer("foo()", "from __main__ import foo") ``` Check out the link you provided at the very bottom. > To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement: I just tested it on my machine and it worked with the changes.
With Python 3, you can use `globals=globals()` ``` t = timeit.Timer("foo()", globals=globals()) ``` From the [documentation](https://docs.python.org/3/library/timeit.html#examples): > Another option is to pass `globals()` to the `globals` parameter, which > will cause the code to be executed within your current global > namespace. This can be more convenient than individually specifying > imports
Getting "global name 'foo' is not defined" with Python's timeit
[ "", "python", "scope", "timeit", "" ]
I'm new to C# and I am using VS08, I have created a form but where should I be placing my functional code? Right now I have 2 files: program.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace WindowsFormsApplication1 { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } ``` form1.cs - which contains my form.
Your code should be contained in the classes that make up your domain functionality. Program.cs creates an instance of your form (suggest you rename from `form1` to something more descriptive), and your form in turn should instantiate the classes it requires. If you are using databinding, add one or more binding sources to your form, set their datasources and bind during form load.
I would recommend you create a new class, when you put all your functional code. Use an instance of this class inside the form1.cs(rename it appropriately).
Where to place functional code in WinForms app
[ "", "c#", "winforms", "" ]
In Perl 5.10, I can say: ``` sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); ``` ...and it will print out: ``` 1 2 3 ``` Does Python have something like this?
The closest parallel is probably to attach values to the function itself. ``` def foo(): foo.bar = foo.bar + 1 foo.bar = 0 foo() foo() foo() print foo.bar # prints 3 ```
A class may be a better fit here (and is usually a better fit for anything involving "state"): ``` class Stateful(object): def __init__(self): self.state_var = 0 def __call__(self): self.state_var = self.state_var + 1 print self.state_var foo = Stateful() foo() foo() ```
Does Python have something like Perl 5.10's "state" variables?
[ "", "python", "perl", "" ]
If I had the following string "Blue Box", how could I get the bits that make up the string in c# and what datatype would I store it in. If I do just the letter "o", I get 111 as the bytes and 111 as the bits. Is it chopping off the 0's and if I do "oo", I get 111 for each o in the byte array, but for the bits, I get the value 28527. Why?
If you want the bits in a string format, you could use this function: ``` public string GetBits(string input) { StringBuilder sb = new StringBuilder(); foreach (byte b in Encoding.Unicode.GetBytes(input)) { sb.Append(Convert.ToString(b, 2)); } return sb.ToString(); } ``` If you use your "Blue Box" example you get: ``` string bitString = GetBits("Blue Box"); // bitString == "100001001101100011101010110010101000000100001001101111011110000" ```
You could do the following: ``` byte[] bytes = System.Text.UTF8Encoding.Default.GetBytes("Blue Box"); BitArray bits = new System.Collections.BitArray(bytes); ```
How could I get the bits from a string in c#?
[ "", "c#", "" ]
I'm new to c# and I'm trying to figure out if I can create multiple derived class libraries that each represent a specific item. I'll call the two class libraries ClassA & ClassB. Each class will share a BaseClass (namespace BaseNS). I then created a c# app that refrences both ClassA and ClassB. This generated an error because they both have the same BaseClass. No problem, I used 'Alias' on the reference. This worked fine. So I have: extern alias Class1Alias; extern alias Class2Alias; ... Here is where I am running into a problem. I want to make a function that takes BaseClass as an argument. public void SetData(BaseClass bc) { } Can't do this because BaseClass isn't defined because of the alias. So it has to be: public void SetData(Class1Alias.BaseNameSpace.BaseClass bc) {} This works, but now I want to do the following: ... ``` Class1Alias.Class1Space.Class1 c1 = new Class1Alias.Class1Space.Class1(); Class2Alias.Class2Space.Class2 c2 = new Class2Alias.Class2Space.Class2(); ``` this works ``` Class1Alias.BaseNameSpace.BaseClass bc = (Class1Alias.BaseNameSpace.BaseClass)c1; SetData(bc); ``` this doesn't ``` Class1Alias.BaseNameSpace.BaseClass bc = (Class1Alias.BaseNameSpace.BaseClass)c2; SetData(bc); ``` I tried casting it to Class2Alias, which works, but then I can't call my SetData function because it wants a Class1Alias. Is there anyway to work around this?
Your terminology is somewhat confusing. You refer to "class libraries" in a way that makes me think you mean just "class", but I'm not sure. For example "class libraries" cannot be "derived" from a base class. You said you are new to C#. Is there another language you are more familiar with? Maybe if you could express what you want to do in terms of that language, maybe someone can translate it to C#.
I am no sure if I understand the question correctly. Does the base class exist in a single assembly or it's copied and pasted in both assemblies? If it's copied and pasted, there's not much you can do as the compiler considers them as two different classes. Set the assembly reference alias in properties window of the specific referenced assembly. Assign something other than `global` to it. Then you can reference the type in that assembly with something like: ``` assemblyAlias::RootNamespace.OtherNamespace.Class ```
C# multiple class library with common base class/namespace problem
[ "", "c#", "namespaces", "" ]
I have a new laptop at work and code that worked earlier in the week does not work today. The code that worked before is, simplified: ``` while (dr.Read()) { int i = int.Parse(dr.GetString(1)) } ``` Now it fails when the database value is 0. Sometimes, but not reliably, this will work instead: ``` while (dr.Read()) { int i = Convert.ToInt32(dr["FieldName"])) } ``` Am I missing something stupid? Oddly enough, ReSharper is also having tons of weird errors with the same error message that I am getting with the above code: "input string was not in the correct format." (Starts before I even load a project.) Any ideas? Anyone having any SP issues? I did try to make sure all my SPs were up-to-date when I got the machine. EDIT: I understand how to use Try.Parse and error-handling. The code here is simplified. I am reading test cases from a database table. This column has only 0, 1, and 2 values. I have confirmed that. I broke this down putting the database field into a string variable s and then trying int.Parse(s). The code worked earlier this week and the database has not changed. The only thing that has changed is my environment. To completely simplify the problem, this line of code throws an exception ("input string was not in the correct format"): ``` int.Parse("0"); ``` EDIT: Thanks to everyone for helping me resolve this issue! The solution was forcing a reset of my language settings.
A possible [explanation](http://bartdesmet.net/blogs/bart/archive/2005/12/06/3792.aspx): > Basically, the problem was the > sPositiveSign value under > HKEY\_CURRENT\_USER\Control > Panel\International being set to 0, > which means the positive sign is '0'. > Thus, while parsing the "positive sign > 0" is being cut off and then the rest > of the string ("") is parsed as a > number, which doesn't work of course. > This also explains why int.Parse("00") > wasn't a problem. Although you can't > set the positive sign to '0' through > the Control Panel, it's still possible > to do it through the registry, causing > problems. No idea how the computer of > the user in the post ended up with > this wrong setting... Better yet, what is the output of this on your machine: ``` Console.WriteLine(System.Globalization.NumberFormatInfo.GetInstance(null).PositiveSign); ``` I'm willing to bet yours prints out a `0`... when mine prints out a `+` sign. I suggest checking your `Control Panel > Regional and Language Options` settings... if they appear normal, try changing them to something else than back to whatever language you're using (I'm assuming English).
I think it's generally not considered a good idea to call Convert.ToInt32 for the value reading out of database, what about the value is null, what about the value cannot be parsed. Do you have any exception handling code here. 1. Make sure the value is not null. 2. Check the value can be parsed before call Int32.Parse. Consider Int32.TryParse. 3. consider use a nullable type like int? in this case. HTH.
C# parse string "0" to integer
[ "", "c#", "" ]
Let's say that I'm new to Hibernate, is there a way to get my skills up to speed? Are there any good tutorials?
Hibernate.org is pointing this to begin with : [Getting Started with Hibernate](http://www.hibernate.org/152.html) I would then recommend reading this very good book : [Java Persistence with Hibernate (Christian Bauer and Gavin King)](http://www.manning.com/bauer2/)
Hibernate.org's tutorial: <http://www.hibernate.org/hib_docs/v3/reference/en/html/tutorial.html> Depends though, are you just trying to get into Hibernate with no actual knowledge about what Hibernate is, or are just going to dive into the first tutorial you come across? If you want a basic understanding of what Hibernate is, check out this link (very easy, short read): <http://www.laliluna.de/what-is-hibernate.html> They dumb it down enough for the layman who doesn't know anything (useful) about Hibernate to get a grasp on what it is and how it works.
Hibernate tutorials
[ "", "java", "hibernate", "" ]
All of a sudden I keep getting a `MetadataException` on instantiating my generated `ObjectContext` class. The connection string in App.Config looks correct - hasn't changed since last it worked - and I've tried regenerating a new model (edmx-file) from the underlying database with no change. Anyone have any ideas? Further details: I haven't changed any properties, I haven't changed the name of any output assemblies, I haven't tried to embed the EDMX in the assembly. I've merely waited 10 hours from leaving work until I got back. And then it wasn't working anymore. I've tried recreating the EDMX. I've tried recreating the project. I've even tried recreating the database, from scratch. No luck, whatsoever.
This means that the application is unable to load the EDMX. There are several things which can cause this. * You might have changed the MetadataArtifactProcessing property of the model to Copy to Output Directory. * The connection string could be wrong. I know you say you haven't changed it, but if you have changed other things (say, the name of an assembly), it could still be wrong. * You might be using a post-compile task to embed the EDMX in the assembly, which is no longer working for some reason. In short, there is not really enough detail in your question to give an accurate answer, but hopefully these ideas should get you on the right track. **Update:** I've written [a blog post with more complete steps for troubleshooting](http://www.craigstuntz.com/posts/2010-08-13-troubleshooting-entity-framework-connection-strings.html).
A minor amendment helped me with this problem. I had a solution with 3 project references: ``` connectionString="metadata=res://*/Model.Project.csdl|res://*/Model.Project.ssdl|res://*/Model.Project.msl; ``` which I changed to: ``` connectionString="metadata=res://*/; ```
MetadataException: Unable to load the specified metadata resource
[ "", "c#", ".net", "entity-framework", "ado.net", "" ]
Is there a way to set the log level in log4net programmatically? I'd assumed that there would be a property that would let you do this, but I can't seem to find one. What I want to do is have a configurable option to enter debug mode. which would cause extra logging. I'm using a separate log4net configuration xml file. At the moment the solutions I've come up with are as follows: 1. Edit the log file using the dom and then call XMLConfigurator to configure the log file as per the file. 2. Have two log configuration files, and on the option changing call xml Configurator to use the appropriate log configuration file. I'm leaning towards 2, is there any reason this wont work?
This is the way I'm configuring log4net programmatically: ``` //declared as a class variable private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); PatternLayout layout = new PatternLayout(@"%date %-5level %message%newline"); RollingFileAppender appender = new RollingFileAppender(); appender.Layout = layout; appender.File = "c:\log.txt"; appender.AppendToFile = true; appender.MaximumFileSize = "1MB"; appender.MaxSizeRollBackups = 0; //no backup files appender.Threshold = Level.Error; appender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(appender); ``` I think the Appender's Threshold property is what you looking for, it will control what levels of logging the appender will output. The log4net [manual](http://logging.apache.org/log4net/release/manual/configuration.html) has lots of good configuration examples.
You can programmatically change the Logging level of a log4net logger, but it's not obvious how to do so. I have some code that does this. Given this Logger: ``` private readonly log4net.ILog mylogger; ``` You have to do the following fancy footwork to set it to Debug: ``` ((log4net.Repository.Hierarchy.Logger)mylogger.Logger).Level = log4net.Core.Level.Debug; ```
Changing the log level programmatically in log4net?
[ "", "c#", "log4net", "" ]
I'm wondering if anyone has ever come across a plug-in for mootools that will show a hidden div (with embedded video in it) as a light box, upon a click on a link. What I wanted is somehow like how apple trailers site show the embedded quicktime player.
Give [Shadowbox.js](http://www.shadowbox-js.com/) a try... It supports multiple frameworks (MooTools, jQuery etc.), multiple players (img, iframe, html) and a lot of other options. You can also check [this matrix](http://planetozh.com/projects/lightbox-clones/) to see an overview of popular Lightbox clones with their capabilities.
You could also try moodalbox - not sure how it compares with milkbox, which I haven't used, but moodalbox should be able to do it: <http://www.e-magine.ro/web-dev-and-design/36/moodalbox/>
Mootools Lightbox for a html div?
[ "", "javascript", "html", "xhtml", "mootools", "lightbox", "" ]
I am trying to port code from using java [timers](http://java.sun.com/j2se/1.3/docs/api/java/util/Timer.html) to using [scheduledexecutorservice](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html) I have the following use case ``` class A { public boolean execute() { try { Timer t = new Timer(); t.schedule (new ATimerTask(), period, delay); } catch (Exception e) { return false; } } } class B { public boolean execute() { try { Timer t = new Timer(); t.schedule (new BTimerTask(), period, delay); } catch (Exception e) { return false; } } } ``` Should I just replace Timer instances in class A and class B with ScheduledExecutorService and make the ATimerTask and BTimerTask class to a Runnable class , for e.g ``` class B { public boolean execute() { try { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleWithFixedDelay (new BRunnnableTask(), period, delay); } catch (Exception e) { return false; } } } ``` Is this correct. EDIT: One of the primary motivation of porting is since runtime exceptions thrown in TimerTask kill that one thread and it cannot be scheduled further. I want to avoid the case so that ieven if I have runtime exception the thread should keep on executing and not halt.
**NOTE: The way you did this will leak threads!** If your class `B` will be kept around and *each instance* will eventually be closed or shut down or released, I would do it like this: ``` class B { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public boolean execute() { try { scheduler.scheduleWithFixedDelay(new BRunnnableTask(), period, delay); return true; } catch (Exception e) { return false; } } public void close() { scheduler.shutdownNow(); } } ``` If you will not do this kind of cleanup on each instance, then I would instead do this: ``` class B { static final ScheduledExecutorService SCHEDULER = Executors.newCachedThreadPool(); public boolean execute() { try { SCHEDULER.scheduleWithFixedDelay(new BRunnnableTask(), period, delay); return true; } catch (Exception e) { return false; } } } ``` Each `ExecutorService` you allocate in your code allocates a single `Thread`. If you make many instances of your class `B` then each instance will be allocated a `Thread`. If these don't get garbage collected quickly, then you can end up with many thousands of threads allocated (but not used, just allocated) and you can crash your whole server, starving every process on the machine, not just your own JVM. I've seen it happen on Windows and I expect it can happen on other OS's as well. A static Cached thread pool is very often a safe solution when you don't intend to use lifecycle methods on the individual object instances, as you'll only keep as many threads as are actually *running* and not one for each instance you create that is not yet garbage collected.
It looks ok. Depending on what you're doing, you may want to keep executor service around as a member so you can use it again. Also, you can get a ScheduledFuture back from the scheduleXX() methods. This is useful because you can call get() on it to pull any exceptions that occur in the timed thread back to your control thread for handling.
Porting code from using timers to scheduledexecutorservice
[ "", "java", "timer", "executorservice", "" ]
I maintain an application that has a .aspx page that loads on image from the database and uses Response.BinaryWrite() to write it back to the client. This worked perfectly not long ago. Two things have changed, we upgraded the application to .NET 3.5 and they upgraded all the computers at work to IE7. Everything works fine on Firefox, but all I get in IE7 is a red X. So I assume this issue is related to IE7? Is there a security setting somewhere that would stop it from loading images from a .aspx form? It's already set to display based on the content type and not the extension. Here is some of the code. Like I said, I just maintain this app and didn't write it. I know using Session is not a great way of doing it, but it's what I have and the switch statement is just a "wtf?". ``` <asp:image id="imgContent" runat="server" Visible="true" ImageUrl="ProductContentFormImage.aspx"></asp:image> protected void Page_Load(object sender, System.EventArgs e) { Hashtable hshContentBinary = (Hashtable)Session["hshContentBinary"]; byte[] content = (byte[]) hshContentBinary["content"]; string extension = (string) hshContentBinary["extension"]; string contentTypePrefix = "application"; switch(extension.ToLower()) { case "gif": case "jpg": case "bmp": contentTypePrefix = "image"; break; case "tif": contentTypePrefix = "image"; break; case "tiff": contentTypePrefix = "image"; break; case "eps": contentTypePrefix = "image"; break; default: Response.AppendHeader( "Content-disposition", "attachment; filename=content." + extension ); break; } Response.ContentType = contentTypePrefix + "/" + extension; Response.BinaryWrite(content); } ``` EDIT: OK, I followed your suggestions and through a little more research I have changed the method to the following, but it still doesn't work. ``` protected void Page_Load(object sender, System.EventArgs e) { Hashtable hshContentBinary = (Hashtable)Session["hshContentBinary"]; byte[] content = (byte[]) hshContentBinary["content"]; string extension = (string) hshContentBinary["extension"]; string contentType; string contentDisposition = "inline; filename=content." + extension; Response.ClearContent(); Response.ClearHeaders(); Response.Clear(); switch(extension.ToLower()) { case "gif": contentType = "image/gif"; break; case "jpg": case "jpe": case "jpeg": contentType = "image/jpeg"; break; case "bmp": contentType = "image/bmp"; break; case "tif": case "tiff": contentType = "image/tiff"; break; case "eps": contentType = "application/postscript"; break; default: contentDisposition = "attachment; filename=content." + extension; contentType = "application/" + extension.ToLower(); break; } Response.Buffer = true; Response.Expires = 0; Response.ContentType = contentType; Response.AddHeader("Content-Length", content.Length.ToString()); Response.AddHeader("Content-disposition", contentDisposition); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.BinaryWrite(content); Response.End(); } ```
The image was corrupted in a way that IE7 could not display it, but Firefox could. The image was large it wouldn't fit on the screen and I didn't see where it was cut off. Thanks for all your suggestions.
Your mime types are not correct. This works better, at least for the images: ``` string contentType = "application/" + extension.ToLower(); switch(extension.ToLower()) { case "gif": contentType = "image/gif"; break; case "jpg": case "jpeg": case "jpe": contentType = "image/jpeg"; break; case "bmp": contentType = "image/bmp"; break; case "tif": case "tiff": contentType = "image/tiff"; break; case "eps": contentType = "application/postscript"; break; default: Response.AppendHeader( "Content-disposition", "attachment; filename=content." + extension ); break; } Response.ContentType = contentType; ``` Hera are mime types and file extensions, if you need to add more: <http://www.w3schools.com/media/media_mimeref.asp>
.aspx page Response.BinaryWrite image on IE7
[ "", "c#", ".net", "image", "internet-explorer-7", "" ]