Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
We have a system with an Oracle backend to which we have access (though possibly not administrative access) and a front end to which we do not have the source code. The database is quite large and not easily understood - we have no documentation. I'm also not particularly knowledgable about Oracle in general. One aspect of the front end queries the database for a particular set of data and displays it. We have a need to determine what query is being made so that we can replicate and automate it without the front end (e.g. by generating a csv file periodically). What methods would you use to determine the SQL required to retrieve this set of data? Currently I'm leaning towards the use of an EeePC, Wireshark and a hub (installing Wireshark on the client machines may not be possible), but I'm curious to hear any other ideas and whether anyone can think of any pitfalls with this particular approach.
Clearly there are many methods. The one that I find easiest is: (1) Connect to the database as SYS or SYSTEM (2) Query V$SESSION to identify the database session you are interested in. Record the SID and SERIAL# values. (3) Execute the following commands to activate tracing for the session: ``` exec sys.dbms_system.set_bool_param_in_session( *sid*, *serial#*, 'timed_statistics', true ) exec sys.dbms_system.set_int_param_in_session( *sid*, *serial#*, 'max_dump_file_size', 2000000000 ) exec sys.dbms_system.set_ev( *sid*, *serial#*, 10046, 5, '' ) ``` (4) Perform some actions in the client app (5) Either terminate the database session (e.g. by closing the client) or deactivate tracing ( exec sys.dbms\_system.set\_ev( *sid*, *serial#*, 10046, 0, '' ) ) (6) Locate the udump folder on the database server. There will be a trace file for the database session showing the statements executed and the bind values used in each execution. This method does not require any access to the client machine, which could be a benefit. It does require access to the database server, which may be problematic if you're not the DBA and they don't let you onto the machine. Also, identifying the proper session to trace can be difficult if you have many clients or if the client application opens more than one session.
Start with querying Oracle system views like V$SQL, v$sqlarea and v$sqltext.
How to determine an Oracle query without access to source code?
[ "", "sql", "oracle", "networking", "" ]
Is there any RDBMS that implements something like `SELECT * EXCEPT`? What I'm after is getting all of the fields except a specific TEXT/BLOB field, and I'd like to just select everything else. Almost daily I complain to my coworkers that someone should implement this... It's terribly annoying that it doesn't exist. **Edit:** I understand everyone's concern for `SELECT *`. I know the risks associated with `SELECT *`. However, this, at least in my situation, would not be used for any Production level code, or even Development level code; strictly for debugging, when I need to see all of the values easily. As I've stated in some of the comments, where I work is strictly a commandline shop, doing everything over ssh. This makes it difficult to use any gui tools (external connections to the database aren't allowed), etc etc. Thanks for the suggestions though.
As others have said, it is not a good idea to do this in a query because it is prone to issues when someone changes the table structure in the future. However, there is a way to do this... and I can't believe I'm actually suggesting this, but in the spirit of answering the ACTUAL question... Do it with dynamic SQL... this does all the columns except the "description" column. You could easily turn this into a function or stored proc. ``` declare @sql varchar(8000), @table_id int, @col_id int set @sql = 'select ' select @table_id = id from sysobjects where name = 'MY_Table' select @col_id = min(colid) from syscolumns where id = @table_id and name <> 'description' while (@col_id is not null) begin select @sql = @sql + name from syscolumns where id = @table_id and colid = @col_id select @col_id = min(colid) from syscolumns where id = @table_id and colid > @col_id and name <> 'description' if (@col_id is not null) set @sql = @sql + ',' print @sql end set @sql = @sql + ' from MY_table' exec @sql ```
Create a view on the table which doesn't include the blob columns
SELECT * EXCEPT
[ "", "sql", "sql-except", "" ]
Is it safe to assume that event subscribers are called in order of subscription? Example: ``` void One(object sender, EventArgs e) {} void Two(object sender, EventArgs e) {} event EventHandler foo; foo += One; foo += Two; ``` Is One() always called before Two() when the event is fired? Edit: You should ofcourse not rely on it, I was just thinking. The idea was, that multicast delegates are similary to the COMMAND pattern. So I was just wondering. Ususally you would use a collection that keeps the order for COMMANDs so you can do undo/redo/whatever.
Given that implementation, yes, they will always be called in that order. If the event actually uses some weird and wonderful way of handling subscriptions, it could do different things - but "normal" implementations will do the right thing. To be clear, subscribing to an event handler just means invoking the appropriate "add" part of an event. If the event handles this by doing something like: ``` myHandler += value; ``` that gets translated into ``` myHandler = Delegate.Combine(myHandler, value); ``` and [Delegate.Combine](http://msdn.microsoft.com/en-us/library/30cyx32c.aspx) guarantees the ordering. However, if you had an event like this: ``` private LinkedList<EventHandler> eventHandlers = new LinkedList<EventHandler>; public event EventHandler Foo { add { eventHandlers.AddFirst(value); } remove { // do stuff here too } } ``` and then fired the event by doing something like: ``` foreach (EventHandler handler in eventHandlers) { handler(this, EventArgs.Empty); } ``` then the handlers would be called in the reverse order. **Summary**: For all sane events, you can rely on the ordering. In theory, events can do what they like, but I've never seen an event which *doesn't* maintain the appropriate ordering.
Pay very close attention to the caveats given by Jon Skeet - "Given that implementation...". In other words, make the slightest change (multiple threads, other handlers, etc.) and you risk losing the order-of-execution invariance. *Do **NOT** rely on event ordering*. All event dispatches should be logically independent, as if they were occurring in parallel. Events are logically independent actions. I'll go one step further, and assert that if you have to assume an order for events firing, you have a serious design flaw and/or are misusing events.
Are event subscribers called in order of subscription?
[ "", "c#", ".net", "events", ".net-2.0", "c#-2.0", "" ]
In C++, I can't think of a case in which I would like to inherit private/protected from a base class: ``` class Base; class Derived1 : private Base; class Derived2 : protected Base; ``` Is it really useful?
It is useful when you want to have access to some members of the base class, but without exposing them in your class interface. Private inheritance can also be seen as some kind of composition: the [C++ faq-lite](http://www.parashift.com/c++-faq-lite/private-inheritance.html) gives the following example to illustrate this statement ``` class Engine { public: Engine(int numCylinders); void start(); // Starts this Engine }; class Car { public: Car() : e_(8) { } // Initializes this Car with 8 cylinders void start() { e_.start(); } // Start this Car by starting its Engine private: Engine e_; // Car has-a Engine }; ``` To obtain the same semantic, you could also write the car Class as follow: ``` class Car : private Engine { // Car has-a Engine public: Car() : Engine(8) { } // Initializes this Car with 8 cylinders using Engine::start; // Start this Car by starting its Engine }; ``` However, this way of doing has several disadvantages: * your intent is much less clear * it can lead to abusive multiple inheritance * it breaks the encapsulation of the Engine class since you can access its protected members * you're allowed to override Engine virtual methods, which is something you don't want if your aim is a simple composition
Private can be useful in quite a few circumstances. Just one of them are policies: [Is partial class template specialization the answer to this design problem?](https://stackoverflow.com/questions/356294/is-partial-class-template-specialization-the-answer-to-this-design-problem#356576). Another occasion where it is useful is to forbid copying and assigning: ``` struct noncopyable { private: noncopyable(noncopyable const&); noncopyable & operator=(noncopyable const&); }; class my_noncopyable_type : noncopyable { // ... }; ``` Because we don't want that the user has a pointer of type `noncopyable*` to our object, we derive privately. That counts not only for noncopyable, but many other such classes too (policies being the most common).
Why do we actually need Private or Protected inheritance in C++?
[ "", "c++", "inheritance", "private", "protected", "c++-faq", "" ]
In JavaScript the % operator seems to behave in a very weird manner. I tried the following: ``` >>> (0 - 11) % 12 -11 ``` Why does it return -11 instead of 1 (as in Python)? I am sure I am doing or expecting something wrong, but the docs don't tell me what.
fmod from the math module behaves correctly in python: ``` >>> from math import * >>> fmod(-11, 12) -11.0 ``` -11 is the correct answer..
It's behaving correctly according to the way the language is specified (e.g. [ECMA 262](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf)), where it's called the remainder operator rather than the modulus operator. From the spec: > The result of an ECMAScript floating-point remainder operation is determined by the rules of IEEE arithmetic: > > * If either operand is NaN, the result is NaN. > * The sign of the result equals the sign of the dividend. > * If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN. > * If the dividend is finite and the divisor is an infinity, the result equals the dividend. > * If the dividend is a zero and the divisor is nonzero and finite, the result is the same as the > dividend. > * In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the > floating-point remainder `r` from a dividend `n` and a divisor `d` is defined by the mathematical > relation `r = n - (d * q)` where `q` is an integer that is negative only if `n/d` is negative and > positive only if `n/d` is positive, and whose magnitude is as large as possible without > exceeding the magnitude of the true mathematical quotient of `n` and `d`. `r` is computed and > rounded to the nearest representable value using IEEE 754 round-to-nearest mode. In your case `n/d` is negative, so the result is negative. See the [Wikipedia entry on modulo](http://en.wikipedia.org/wiki/Modulo_operation) for more details, including a list of languages with the behaviour in terms of the sign of the result.
What is the correct way to use the modulus (%) operator in JavaScript?
[ "", "javascript", "modulo", "" ]
we have this scenario: A server which contains needed data and client component which these data wants. On the server are stored 2 types of data: - some information - just a couple of strings basically - binary data We have a problem with getting binary data. Both sides are written in Java 5 so we have couple of ways.... Web Service is not the best solution because of speed, memory etc... So, What would you prefer? I would like to miss low level socket connection if possible... thanks in advance Vitek
I think the only way to do LARGE amounts of data is going to be with raw socket access. You will hit the Out of Memory issues on large files with most other methods. Socket handling is really pretty straight forward in Java, and it will let you stream the data without loading the entire file into memory (which is what happens behind the scenes without your own buffering). Using this strategy I managed to build a system that allowed for the transfer of arbitrarily large files (I was using a 7+ GB DVD image to test the system) without hitting memory issues.
Take a look at the W3C standard MTOM to transfer binary data as part of a SOAP service. It is efficient in that it sends as a binary and can also send as buffered chunks. It will also interop with other clients or providers: [How to do MTOM Interop](http://blogs.msdn.com/smguest/archive/2005/06/30/434218.aspx) [Server Side - Sending Attachments with SOAP](http://www.theserverside.com/tt/articles/article.tss?l=SendingAttachmentsWithSOAP)
Large amount of data - what is the best way to send them?
[ "", "java", "networking", "data-transfer", "" ]
Is there a way at all of altering the clipboard of the user via JavaScript? I want it that they click a given point on a map, and it adds the coordinates of the position to their clipboard. I do however assume that this is not possible for JavaScript to achieve.
You could try using the [zeroclipboard](http://code.google.com/p/zeroclipboard/ "zeroclipboard") library, which involves placing an invisible flash element on the page to do the actual copy of text to the clipboard.
It is in Internet Explorer, but not in other browsers although support can be [hacked together](http://www.webtips.co.in/javascript/copy-to-clipboard-with-javascript-on-mozilla-firefox-and-ie.aspx) in other browsers by inserting a [Flash](http://en.wikipedia.org/wiki/Adobe_Flash) file each time you want to do a copy. Not very useful I would say, as it [imposes usability drawbacks as well](http://www.rodsdot.com/ee/cross_browser_clipboard_copy_with_pop_over_message.asp).
Copy to clipboard in JavaScript
[ "", "javascript", "clipboard", "" ]
HI, I am doing ERP solution in C#(2.0) windows application and SQL2005 Database.The network application communicate through Database.I used normal technique for user login and logout, keeping a status bit.My problem is that when my application interrupted with any other reason user status might not change.That will cause the user can't login at next time.How can I solve this problem? Could you give any new technique for user manipulation?
If your intention is to disallow sharing of one username on different computers, after logging with valid password, log the unique token on that computer to **staff.last\_logged\_at** = **@unique\_token**. On logout, set staff.last\_logged\_at = ''. This way even if the computer was interrupted(program crash due to virus, or accidentally pressed the reset button of the computer, etc, hence last\_logged\_at was not reset to '') the user can still logged in, just check if the token of the computer the user is currently logging in is same with last\_logged\_at. If it is the same, he/she can still logged on. If some user tried to login using the username of other user, just check if the machine token of some user's computer is the same with the other user's last\_logged\_at, if it is not equal, disallow logging in, it means two users share the same password. Now the scenario if the computer crashes *really hard* (processor melts, hard disk crash, OS needs reinstalling, etc). User must be allowed to use other computers. Make an **administrative module** that can **reset** the last\_logged\_at of the user. For @unique\_token, just use anything that is **unique and permanent** on a computer, let's say MAC address, or hash anything on OS settings. pseudo code: ``` Logging In: if (select count(*) from staff where staff_name = @staff_name and password = 'correct' and (last_logged_at = '' or last_logged_at = @unique_token) ) <> 0 then then -- allow login update staff set last_logged_at = @unique_token where staff_name = @staff_name else if (select count(*) from staff where staff_name = @staff_name and password = 'correct' and last_logged_at <> @unique_token) <> 0 then then -- disallow login throw exception "You cannot use the same user name on two or more computers. Contact the administrator if you have any concerns" else -- disallow login throw exception "Wrong password" end if Logging Out: update staff set last_logged_at = '' where staff_name = @staff_name ```
How about keeping track of user logins by maintaining a session for each login? The quick-and-dirty solution is to then offer an option to have them login from a "new location" and invalidate the old session. Then when you go to perform an operation, first check if the session is still valid. The better implementation is to keep the session alive and specify a timeout. (i.e. if the session is x-minutes old, invalidate it.) Then you won't see "phantom logins" from old orphaned connections - they automatically expire.
User Login technique C# Win App
[ "", "c#", "winforms", "" ]
There are times when I want to test new code from the forums or when I need to help my friends with specific C# problem. The problem is I don't want to create new "project" in Visual Studio each time just to code/run only this small code. Java & Eclipse IDE comes up with "Scrapbook" feature which allows the execution of arbitrary Java expressions. What are the choices for C# programmers?
~~[Snippet Compiler](http://www.sliver.com/dotnet/SnippetCompiler/) is great for this.~~ [LINQPad](http://www.linqpad.net/) is also good for testing out all sorts of C#, F# or VB code, not just LINQ queries. --- **EDIT** I suppose it's time that I mention that Snippet Compiler hasn't been updated in over five years, and is therefore no longer the best option. However, I undersold LINQPad originally. As Will Dean mentioned in the comments, LINQPad is excellent for all sorts of code, not just LINQ queries. In fact, it has become an indispensable tool for me. I use it daily, not only to quickly test out short snippets, but for relatively complex mini programs. Its advanced output formatting makes it extremely easy to quickly examine intermediate and final results.
A bit late to the party, but I came here while searching for this myself. The best suitable solution for me was using the `C# Interactive`-window inside **Visual Studio** 2015 or later. You can access it by opening it via `View` > `Other Windows` > `C# Interactive`, or by selecting some c# code and clicking on `Execute in Interactive` in the right-click context menu. Here is a link on how to use it: <http://dailydotnettips.com/2016/01/12/use-c-interactive-window-for-your-coding-experiment-in-visual-studio-2015/> I know it works in VS2015, I don't think it works in older versions.
How to quickly code and run small C# code
[ "", "c#", "visual-studio", "testing", "" ]
Anyone have a link to what the C++ standard says regarding a compiler removing global and static symbols? I thought you weren't guaranteed that the compiler will remove global symbols if they're not referenced. A colleague of mine asserts that if your global symbols are included in the main translation unit, those symbols will not be removed even if they're not referenced.
Interestingly, all I can find on this in the C++2003 standard is this: > 3.7.1 Static storage duration [basic.stc.static] > > All objects which neither have dynamic > storage duration nor are local have > static storage duration. The storage > for these objects shall last for the > duration of the program (3.6.2, > 3.6.3). > > If an object of static storage > duration has initialization or a > destructor with side effects, it shall > not be eliminated even if it appears > to be unused, except that a class > object or its copy may be eliminated > as specified in > 12.8. This implies that the standard permits elimination of items in static storage if initialization and destruction of them have no side effects and they are otherwise unused. If there's a more direct permission, I didn't see it (but maybe someone else will). However, it should be noted that having the linker eliminate unused objects in the final image is a very common optimization.
You're asking a question about linking, and although the C++ Standard says that linking should occur as the final phase of translation, it says nothing about *how* that should happen. For example, it says that function references are resolved, but it doesn't require them to be resolved by name, and it doesn't say what happens to the references after resolution. To determine what symbols the compiler includes in the object code, and which ones the linker does or doesn't remove, you'll need to consult the documentation for the compiler and linker, respectively, that you're using.
C++ Standard and Global Symbol Removal
[ "", "c++", "compiler-construction", "linker", "" ]
Even something very rudimentary is fine. Like entering and evaluating something like x+1, where x is a variable I get to specify. I was thinking of writing my own using Strings for each formula, regex for parsing them, etc., but let's assume my goal is to be as lazy as I can possibly get away with, and that if there's another option (especially a formal one), I'd rather try to use that instead, first. Is there anything out there that does something like this?
You can think about using [scripting](http://java.sun.com/javase/6/docs/technotes/guides/scripting/) from Java 6. The reference JDK comes with a JavaScript implementation, and you can plug in other languages too.
I know the following libraries: * [Symja Parser](https://github.com/axkr/symja_android_library) (GPL License) supports Mathematica like syntax * [Jep - Java Math Expression Parser](http://www.singularsys.com/jep/) (commercial - older versions under GNU Public License?) * [JFormula](http://www.japisoft.com/formula/) (commercial) * [MathEval - Math Expression Evaluator](http://softwaremonkey.org/code/MathEval/index.html) (public domain and very small footprint)
Java: Is there a tool available that can allow me input, store, and evaluate math formulas?
[ "", "java", "math", "formulas", "" ]
Is there any java chart library that supports OLAP data, like [ChartFX Olap](http://www.softwarefx.com/Extensions/filmsLarge.aspx?movieName=olapAxesLarge&movieWidth=749&movieHeight=565) or [Dundas Chart](http://www.dundas.com/Gallery/Chart/NET/index.aspx?Img=OLAP6) ? Thanks
In order to display any data as a chart, it will need to be reduced to a 2D recordset - which is what OLAP gives you when you run an MDX query. If you've got that 2D data, you can pass it to any chart/graph code really. I used to use ASP to run the MDX, and write out XML. This was turned into a chart with client-side JavaScript. I wrote the lot myself and it was a nightmare! Use Google charts or Flot.
[JFreeChart](http://www.jfree.org/jfreechart/) or [JasperReports](http://jasperforge.org/plugins/project/project_home.php?group_id=102) would be my recommendations.
Java Chart library for OLAP
[ "", "java", "charts", "olap", "" ]
I'm currently trying to make a small application that performs different duties. Right now I have a console app pop up and ask what I want to do, but sometimes I would rather just launch it with something like MyApp.exe -printdocuments or some such thing. Are there any tutorials out there that can show me a simple example of this?
In C++, your `main()` function can have `argc` and `argv` parameters, which contain the arguments passed on the command line. The `argc` is the count of arguments (including the executable name itself), and `argv` is an array of pointers to null-terminated strings of length `argc`. For example, this program prints its arguments: ``` #include <stdio.h> int main(int argc, char *argv[]) { for (int i = 0; i < argc; i++) { printf("argv[%d]: %s\n", i, argv[i]); } return 0; } ``` Any C or C++ tutorial will probably have more information on this.
You can use boost::program\_options to do this, If you don't want to use boost library, you must parse main function arguments by yourself.
Adding parameters for a program at launch
[ "", "c++", "parameters", "" ]
I want to capture the screen in my code to get an image - like using the 'print screen' button on the keyboard . Does anyone have an idea how to do this? I have no starting point.
You can use the [`Graphics.CopyFromScreen()`](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.copyfromscreen) method. ``` //Create a new bitmap. var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); // Create a graphics object from the bitmap. var gfxScreenshot = Graphics.FromImage(bmpScreenshot); // Take the screenshot from the upper left corner to the right bottom corner. gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); // Save the screenshot to the specified path that the user has chosen. bmpScreenshot.Save("Screenshot.png", ImageFormat.Png); ```
I had two problems with the accepted answer. 1. It doesn't capture all screens in a multi-monitor setup. 2. The width and height returned by the `Screen` class are incorrect when display scaling is used and your application is not declared per monitor [dpiAware](https://learn.microsoft.com/en-us/windows/win32/hidpi/setting-the-default-dpi-awareness-for-a-process). Here's my updated solution using the `Screen.AllScreens` static property and calling `EnumDisplaySettings` using p/invoke to get the real screen resolution. ``` using System.Runtime.InteropServices; const int ENUM_CURRENT_SETTINGS = -1; foreach (Screen screen in Screen.AllScreens) { var dm = new DEVMODE(); dm.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE)); EnumDisplaySettings(screen.DeviceName, ENUM_CURRENT_SETTINGS, ref dm); using var bmp = new Bitmap(dm.dmPelsWidth, dm.dmPelsHeight); using var g = Graphics.FromImage(bmp); g.CopyFromScreen(dm.dmPositionX, dm.dmPositionY, 0, 0, bmp.Size); bmp.Save(screen.DeviceName.Split('\\').Last() + ".png"); } [DllImport("user32.dll")] static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode); [StructLayout(LayoutKind.Sequential)] public struct DEVMODE { private const int CCHDEVICENAME = 0x20; private const int CCHFORMNAME = 0x20; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] public string dmDeviceName; public short dmSpecVersion; public short dmDriverVersion; public short dmSize; public short dmDriverExtra; public int dmFields; public int dmPositionX; public int dmPositionY; public ScreenOrientation dmDisplayOrientation; public int dmDisplayFixedOutput; public short dmColor; public short dmDuplex; public short dmYResolution; public short dmTTOption; public short dmCollate; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] public string dmFormName; public short dmLogPixels; public int dmBitsPerPel; public int dmPelsWidth; public int dmPelsHeight; public int dmDisplayFlags; public int dmDisplayFrequency; public int dmICMMethod; public int dmICMIntent; public int dmMediaType; public int dmDitherType; public int dmReserved1; public int dmReserved2; public int dmPanningWidth; public int dmPanningHeight; } ``` References: <https://stackoverflow.com/a/36864741/987968> <http://pinvoke.net/default.aspx/user32/EnumDisplaySettings.html?diff=y>
Capture the Screen into a Bitmap
[ "", "c#", ".net", "screenshot", "" ]
I'm a C# developer looking to get into home automation as a hobby. I have done a little research, but was wondering if anyone knows of a good .NET library that supports Insteon hardware. I'd rather use Insteon than X10 due to reliability issues. My ultimate objective at this point is to have a simple home automation server (maybe lights and climate control) with a secure ASP.NET web application interface. I'm more interested in actually building it and learning about it rather than finding an existing solution. Thanks for any suggestions or comments. Edit: Thanks for the help, everyone. Does anyone have experience with [Z-wave technology](http://www.z-wave.com)? Seems promising - appears to be higher quality hardware, includes a core library, supports .NET, etc. [ControlThink](http://www.controlthink.com/) appears to have a pretty good controller and SDK. Here's an interesting application to consider: [Stall Status: Know Before You Go](http://www.controlthink.com/)
We found there really wasn't much developer support for Insteon unless you wanted to buy their SDK and agree to their rather heavy-handed license agreement. Rather than go that route, we wrote our own .NET library called [FluentDwelling](http://soapboxautomation.com/products/fluentdwelling/) and we open-sourced it. You can find a download link, and some get-you-started code samples if you follow that link. The source code comes with a full suite of unit tests (requires NUnit, also free), so you can add improvements and make changes if you like.
I would avoid X10 like the plague. Between things like modern TV's and power strips, bridged power junction boxes and just plain strange wiring, X10 signals tend to just "disappear" and never get to their destination. If you really want to give X10 a shot, I've got a box of X10 stuff in the garage that was worth $250+ new and it's all completely useless in my house, so you can have it. Some of it worked in my old house, but it won't so much as turn a light on 2 outlets away where I live now. X10 is viewed by most modern electronics as "noise" on the line (which, technically, it is) and something to be filtered out rather than passed along or left alone.
Home Automation Library
[ "", "c#", "asp.net", ".net", "home-automation", "" ]
Quick question: what is the compiler flag to allow g++ to spawn multiple instances of itself in order to compile large projects quicker (for example 4 source files at a time for a multi-core CPU)?
You can do this with make - with gnu make it is the -j flag (this will also help on a uniprocessor machine). For example if you want 4 parallel jobs from make: ``` make -j 4 ``` You can also run gcc in a pipe with ``` gcc -pipe ``` This will pipeline the compile stages, which will also help keep the cores busy. If you have additional machines available too, you might check out [distcc](http://distcc.samba.org/), which will farm compiles out to those as well.
There is no such flag, and having one runs against the Unix philosophy of having each tool perform just one function and perform it well. Spawning compiler processes is conceptually the job of the build system. What you are probably looking for is the -j (jobs) flag to GNU make, a la ``` make -j4 ``` Or you can use pmake or similar parallel make systems.
Compiling with g++ using multiple cores
[ "", "c++", "compiler-construction", "makefile", "g++", "multicore", "" ]
I want to be able to get the projects I have in Sourcesafe and their total lines of code (perhaps also with total number of classes, etc). Is there an SDK for Sourcesafe (I use 2005 edition) which will allow me to do this? Or is there a document in Sourcesafe which lists all the projects in SS? Using this, I could work towards getting the line count. Thanks
There is no specific line counting API. There is an API to access the files but its way too slow. It would probably be better if you set up a shadow folder on the root project (this is done via the admin tool). A simple app could then open all the source files recursively from the shadow folder and do some line counting.
I realize this is not exactly what you're asking for, but you might be able to adapt the following to suit your needs: <http://richnewman.wordpress.com/2007/07/01/c-and-vbnet-line-count-utility/> I've used this before, and works very well. It differentiates between comments and auto-generated code as well.
Is there a Sourcesafe API to get total lines of code in source control?
[ "", "c#", "visual-sourcesafe", "" ]
I have a function called: ``` void initializeJSP(string Experiment) ``` And in my MyJSP.h file I have: ``` 2: void initializeJSP(string Experiment); ``` And when I compile I get this error: > MyJSP.h:2 error: variable or field initializeJSP declared void Where is the problem?
It for example happens in this case here: ``` void initializeJSP(unknownType Experiment); ``` Try using `std::string` instead of just `string` (and include the `<string>` header). C++ Standard library classes are within the namespace `std::`.
This is not actually a problem with the function being "void", but a problem with the function parameters. I think it's just g++ giving an unhelpful error message. EDIT: As in the accepted answer, the fix is to use `std::string` instead of just `string`.
variable or field declared void
[ "", "c++", "string", "void", "" ]
Some of my script are using different encoding, and when I try to combine them, this has becom an issue. But I can't change the encoding they use, instead I want to change the encodig of the result from script A, and use it as parameter in script B. So: is there any simple way to change a string from UTF-8 to ISO-88591 in PHP? I have looked at utf\_encode and \_decode, but they doesn't do what i want. Why doesn't there exsist any "utf2iso()"-function, or similar? I don't think I have characters that can't be written in ISO-format, so that shouldn't be an huge issue.
Have a look at [`iconv()`](http://php.net/function.iconv) or [`mb_convert_encoding()`](http://php.net/function.mb-convert-encoding). Just by the way: why don't [`utf8_encode()`](http://php.net/function.utf8-encode) and [`utf8_decode()`](http://php.net/function.utf8-decode) work for you? > **utf8\_decode** — Converts a string with > ISO-8859-1 characters encoded with > UTF-8 to single-byte ISO-8859-1 > > **utf8\_encode** — Encodes an ISO-8859-1 > string to UTF-8 So essentially ``` $utf8 = 'ÄÖÜ'; // file must be UTF-8 encoded $iso88591_1 = utf8_decode($utf8); $iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $utf8); $iso88591_2 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8'); $iso88591 = 'ÄÖÜ'; // file must be ISO-8859-1 encoded $utf8_1 = utf8_encode($iso88591); $utf8_2 = iconv('ISO-8859-1', 'UTF-8', $iso88591); $utf8_2 = mb_convert_encoding($iso88591, 'UTF-8', 'ISO-8859-1'); ``` all should do the same - with `utf8_en/decode()` requiring no special extension, `mb_convert_encoding()` requiring ext/mbstring and `iconv()` requiring ext/iconv.
First of all, don't use different encodings. It leads to a mess, and UTF-8 is definitely the one you should be using everywhere. Chances are your input is not ISO-8859-1, but something else (ISO-8859-15, Windows-1252). To convert from those, use [iconv](http://php.net/manual/function.iconv.php) or [`mb_convert_encoding`](http://php.net/function.mb-convert-encoding). Nevertheless, `utf8_encode` and `utf8_decode` should work for ISO-8859-1. It would be nice if you could post a link to a file or a [uuencoded](http://php.net/manual/function.convert-uuencode.php) or [base64](http://php.net/manual/function.base64-encode.php) example string for which the conversion fails or yields unexpected results.
Convert utf8-characters to iso-88591 and back in PHP
[ "", "php", "encoding", "utf-8", "iso-8859-1", "" ]
I have three tables. This query will write down the right answer (x-lines for btv.id\_user with appropriate btv.cas and race.id\_zavod ``` SELECT `btv.id_user`, `btv.id_zavod`,`btv.cas` FROM `btv` JOIN `btu` ON `btv.id_user` = `btu.id_user` JOIN `race` ON 'btv.id_zavod' = `race.id_zavod` WHERE `race.type` = '8' AND `btv.id_user` = '607' ``` Result: ``` | 607 | 512 | 03:15:58 | | 607 | 730 | 03:01:18 | | 607 | 164 | 03:07:26 | | 607 | 767 | 02:58:31 | | 607 | 1147 | 03:06:47 | | 607 | 1149 | 03:09:41 | | 607 | 1178 | 03:24:20 | ``` But when I try to aggregate it to one row by the id\_user it return correct min btv.cas but wrong join wrong race.id\_zavod ``` SELECT `btv.id_user`, `btv.id_zavod`, MIN( `btv.cas` ) FROM `btv` JOIN `btu` ON `btv.id_user` = `btu.id_user` JOIN `race` ON 'btv.id_zavod' = `race.id_zavod` WHERE `race.type` = '8' AND `btv.id_user` = '607' GROUP BY `btv.id_user` ``` Result: ``` | 607 | 512 | 02:58:31 | ```
When you use GROUP BY, the columns in the select-list must satisfy one of the following: * Column is named in the GROUP BY (e.g. `btv.id_user` in your example) * Column is inside an aggregate function (e.g. `MIN( btv.cas )` ) * Column is a *functional dependency* of the column(s) you named in the GROUP BY. This is the error in your query: `btv.id_zavod` has many values for each value of `btv.id_user`. This does not satisfy functional dependency. There must be only one value in `id_zavod` for each value of `id_user` for it to be a functional dependency. In some database brands, this query would actually give you an error. MySQL is more flexible, trusting you to name only columns in the select-list that are functional dependencies of the column(s) you named in the GROUP BY. Here's a query that returns what you want, the MIN value of `btv.cas` per `id_user`, with the corresponding value of `btv.id_zavod`: ``` SELECT b1.id_user, b1.id_zavod, b1.cas FROM btv AS b1 JOIN btu ON (b1.id_user = btu.id_user) JOIN race ON (b1.id_zavod = race.id_zavod) LEFT OUTER JOIN btv AS b2 ON (b1.id_user = bt2.id_user AND (b1.cas > b2.cas OR (b1.cas = b2.cas AND b1.primarykey > b2.primarykey)) WHERE race.type = '8' AND b1.id_user = '607' AND b2.id_user IS NULL; ``` In other words, you need to do your join as before, but then join that to `btv` again, to see if there's another row with the same `id_user` value and a smaller value in `cas`. Use an OUTER JOIN, because you're looking for the case where there is no match. You can test for that with `b2.id_user IS NULL`, because OUTER JOIN makes all columns NULL when there is no match. Note that there could be ties, so we add the extra term using the primary key as the tiebreaker. You don't need to use GROUP BY in this query. That's taken care of implicitly, because there will be only one row that satisfies the OUTER JOIN condition.
The query you have written: ``` SELECT `btv.id_user`, `btv.id_zavod`, MIN( `btv.cas` ) FROM `btv` JOIN `btu` ON `btv.id_user` = `btu.id_user` JOIN `race` ON 'btv.id_zavod' = `race.id_zavod` WHERE `race.type` = '8' AND `btv.id_user` = '607' GROUP BY `btv.id_user` ``` won't run. You need a group by id\_zavod or something. Can you tell us what query you are really running? And what result set you expect?
Problem with table JOIN in MySQL and aggregation
[ "", "sql", "mysql", "join", "" ]
I want to open a ZIP-file, that have no entries with java.util.zip.ZipFile. But on the constructor I get the following exception: 'java.util.zip.ZipException: error in opening zip file'. How can I open the empty ZIP? That ZIP-file is created by the commandline zip-program under linux. I simply deleted all entries from a ZIP-file. I need this as testdata for a class I write. The class should simply return an empty list for this case, but broken ZIP-files should return an error. For some more explanation on the problem. I have an interface, for extracting some documents from different sources. Other implementations gather them from webservices or directories, this implementation from ZIP-files. The interface give an Iterator with some more functionality. So I want to decide, if the ZIP-file is empty or broken.
My solution for this problem is now, that I simply use ZipInputStream instead of ZipFile. This class works well with empty ZIP-files. I don't know about the reason, why one works and the other not.
hack: you can assume that all empty ZIPs are the same and just hardcode it's length/chechsum to validate against.
Why I get an Exception on opening an empty ZIP-file with java.util.zip.ZipFile?
[ "", "java", "exception", "zip", "" ]
I'm sure I've done this before, but can't find any example of it! Grrr... For example, I want to convert an `IList<T>` into a `BindingList<T>`: ``` public class ListHelper { public static BindingList<T> ToBindingList(IList<T> data) { BindingList<T> output = new BindingList<T>(); foreach (T item in data) output.Add(item); return output; } } ```
``` ToBindingList <T> (...) ``` --- ``` public class ListHelper { public static BindingList<T> ToBindingList<T>(IList<T> data) { BindingList<T> output = new BindingList<T>(); foreach (T item in data) { output.Add(item); } return output; } } ```
Wouldn't this be simpler? ``` public static class Extensions { public static BindingList<T> ToBindingList<T>(this IList<T> list) { return new BindingList<T>(list); } } ``` It's so simple that we don't need an extension method ... Am I missing something?
Generic method in a non-generic class?
[ "", "c#", "generics", "" ]
I have this scenario where I need data integrity in the physical database. For example, I have a variable of `@email_address VARCHAR(200)` and I want to check if the value of `@email_address` is of email format. Anyone has any idea how to check format in T-SQL? Many thanks!
I tested the following query with many different wrong and valid email addresses. It should do the job. ``` IF ( CHARINDEX(' ',LTRIM(RTRIM(@email_address))) = 0 AND LEFT(LTRIM(@email_address),1) <> '@' AND RIGHT(RTRIM(@email_address),1) <> '.' AND CHARINDEX('.',@email_address ,CHARINDEX('@',@email_address)) - CHARINDEX('@',@email_address ) > 1 AND LEN(LTRIM(RTRIM(@email_address ))) - LEN(REPLACE(LTRIM(RTRIM(@email_address)),'@','')) = 1 AND CHARINDEX('.',REVERSE(LTRIM(RTRIM(@email_address)))) >= 3 AND (CHARINDEX('.@',@email_address ) = 0 AND CHARINDEX('..',@email_address ) = 0) ) print 'valid email address' ELSE print 'not valid' ``` It checks these conditions: * No embedded spaces * '@' can't be the first character of an email address * '.' can't be the last character of an email address * There must be a '.' somewhere after '@' * the '@' sign is allowed * Domain name should end with at least 2 character extension * can't have patterns like '.@' and '..'
AFAIK there is no good way to do this. The email format standard is so complex parsers have been known to run to thousands of lines of code, but even if you were to use a simpler form which would fail some obscure but valid addresses you'd have to do it without regular expressions which are not natively supported by T-SQL (again, I'm not 100% on that), leaving you with a simple fallback of somethign like: `LIKE '%_@_%_.__%'` ..or similar. My feeling is generally that you shouln't be doing this at the last possible moment though (as you insert into a DB) you should be doing it at the first opportunity and/or a common gateway (the controller which actually makes the SQL insert request), where incidentally you would have the advantage of regex, and possibly even a library which does the "real" validation for you.
T-SQL: checking for email format
[ "", "sql", "sql-server", "t-sql", "email", "" ]
My problem is thus: I need a way to ensure only one given class can instantiate another. I don't want to have to make the other a nested inner class or something dumb like that. How do I do this? I forget offhand.
Make the constructor private. Create a static factory method that takes an instance of the class that is allowed access. Have the factory method create a suitable object and use a settor on the object that is allowed access to the created object to give that class the created copy. ``` public class AllowedAccess { private SecureClass secure; public setSecureClass( SecureClass secure ) { this.secure = secure; } ... } public class SecureClass { private SecureClass() {} public static void Create( AllowedAccess allowed ) { allowed.setSecureClass( new SecureClass() ); } ... } ``` BTW, I'm suspicious of this design. Seems too highly coupled to me.
A private static inner class is exactly what you want. Nothing dumb about it. ``` public class Creator { private static class Created { } } ``` Otherwise you can only protect instantiation on the package level. ``` public class Created { Created() { } } ``` Which gives only classes from the same package access to the constructor.
Quick Java Question: Instantiating a given class only from another?
[ "", "java", "class", "instantiation", "" ]
I want to write a script in Ruby to clean up some messed up keys in several copies of the same MySQL schema. I'd like to do something like SHOW CREATE TABLE, then look at what comes back and delete keys if they exist. I know in the Rails environment you can do this... ``` ActiveRecord::Base.connection.execute( some sql ) ``` But what you get back is a "Result" object. For this task I need a String so I can analyze it and act accordingly.
You could check the [mysql-ruby](http://rubyforge.org/projects/mysql-ruby/) gem. Here is a write-up on how to use it: [Using the Ruby MySQL Module](http://www.kitebird.com/articles/ruby-mysql.html) More can be found via google
This should help you: ``` >> result = ActiveRecord::Base.connection.execute("SHOW TABLES") => #<Mysql::Result:0x37ecb30> >> result.class.instance_methods - Object.instance_methods => ["all_hashes", "field_seek", "row_tell", "fetch_field_direct", "free", "field_tell", "fetch_lengths", "num_fields", "data_seek", "fetch_row", "num_rows", "fetch_field", "each", "each_hash", "fetch_hash", "row_seek", "fetch_fields"] ``` Look at #all\_hashes on the MySql::Result instance
How do you talk SQL directly to MySQL from Ruby?
[ "", "sql", "mysql", "ruby-on-rails", "ruby", "activerecord", "" ]
How do you declare a method in C# that should be overridden (or overridable) by a dereived class - possibly even outside your assembly - but that should be callable only from within the actual class? (i.e. like a private virtual function in C++) **[edit]** *`private`* `virtual` is exactly what I intend: "Here's a way to modify my behavior, but you are still not allowed to call this function directly (because calling it requires arcane invocations that only my base class shall do)" So to clarify it: what is the best expression for that in C#?
C# makes a stronger guarantee for "private" than C++ does. In C++, you can indeed override a private virtual method. But that means that code in a base class can execute code in a derived class. Breaking the promise that the private method is truly private and can only be called by methods in the same class. Something that doesn't help here is that C++ doesn't require repeating the virtual keyword. Leading up to hard to reverse-engineer mysteries like this one: ``` #include "stdafx.h" #include <iostream> class Base { private: virtual void Method() = 0; public: void Test() { Method(); } }; class Derived : public Base { private: void Method() { std::cout << "Who the heck called me?"; } }; int _tmain(int argc, _TCHAR* argv[]) { Base* p = new Derived; p->Test(); } ``` I agree there's a possible role for private inheritance. The C# language designers said No! though.
When you say it should only be callable "within the actual class" do you mean the base class or the derived class? Neither of these is feasible on its own. The closest is to use a protected method, which means it can be called from the declaring class, the derived class, and any further-derived class.
override but don't call
[ "", "c#", "inheritance", "virtual", "access-modifiers", "" ]
I'm using JUnit 4.4 and Maven and I have a large number of long-running integration tests. When it comes to parallelizing test suites there are a few solutions that allow me to run each test method in a single test-class in parallel. But all of these require that I change the tests in one way or another. I really think it would be a much cleaner solution to run X different test classes in X threads in parallel. I have hundreds of tests so I don't really care about threading individual test-classes. Is there any way to do this?
From junit 4.7 it's now possible to run tests in parallel without using TestNG. Actually it has been possible since 4.6, but there are a number of fixes being made in 4.7 that will make it a viable option. You may also run parallel tests with spring, which you can read about [here](http://incodewetrustinc.blogspot.com/2009/07/run-your-junit-tests-in-parallel-with.html)
Use maven plugin: ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.7.1</version> <configuration> <parallel>classes</parallel> <threadCount>5</threadCount> </configuration> </plugin> </plugins> </build> ```
Running junit tests in parallel in a Maven build?
[ "", "java", "maven", "junit", "" ]
How do YOU reduce compile time, and linking time for VC++ projects (native C++)? Please specify if each suggestion applies to debug, release, or both.
It may sound obvious to you, but we try to use forward declarations as much as possible, even if it requires to write out long namespace names the type(s) is/are in: ``` // Forward declaration stuff namespace plotter { namespace logic { class Plotter; } } // Real stuff namespace plotter { namespace samples { class Window { logic::Plotter * mPlotter; // ... }; } } ``` It greatly reduces the time for compiling also on others compilers. Indeed it applies to all configurations :)
Use [the Handle/Body pattern](http://c2.com/cgi/wiki?HandleBodyPattern) (also sometimes known as "pimpl", "adapter", "decorator", "bridge" or "wrapper"). By isolating the implementation of your classes into your .cpp files, they need only be compiled once. Most changes do not require changes to the header file so it means you can make fairly extensive changes while only requiring one file to be recompiled. This also encourages refactoring and writing of comments and unit tests since compile time is decreased. Additionally, you automatically separate the concerns of interface and implementation so the interface of your code is simplified.
How do YOU reduce compile time, and linking time for Visual C++ projects (native C++)?
[ "", "c++", "visual-c++", "compilation", "" ]
I need to write a component for an application that interacts tightly with a command line application. The command line application asks a series of questions, performs some computations, then terminates (which i need to detect). Essentially, i want to wrap up this interaction in a wrapper class. Has any one achieved similar in the past? If so, how did you go about it? Did you notice a pattern, or maybe some good build in classes to use? Cheers!
You would need to redirect both the input and output streams, using `Process`; it is slightly trickier handling both, since you need to be careful that things aren't lost in the buffers (causing deadlock). * MSDN : [Redirecting input](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardinput.aspx) * MSDN : [Redirecting output](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx) * [Here's](http://www.c-sharpcorner.com/UploadFile/edwinlima/SystemDiagnosticProcess12052005035444AM/SystemDiagnosticProcess.aspx) a basic alternative example. You might also want to look at [OutputDataReceived](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx) for event-based responses.
I get dinged when my responses are just links to elsewhere. I don't see where the link to the C# Corner article helps much. The question is 10 years old today but it should have been clarified. The question does not specify whether there are line endings (CrLf) at the end of each question. Assuming there are, as in the following: ``` string Answer; Console.Out.WriteLine("First question: "); Answer = Console.In.ReadLine(); Console.Out.WriteLine("Another question: "); Answer = Console.In.ReadLine(); Console.Out.WriteLine("Final question: "); Answer = Console.In.ReadLine(); ``` Then the following can be used to respond to it: ``` class Program { const string FirstQuestion = "First question: "; const string SecondQuestion = "Another question: "; const string FinalQuestion = "Final question: "; static AutoResetEvent Done = new AutoResetEvent(false); static void Main(string[] args) { const string TheProgram = @" ... "; Process p = new Process(); ProcessStartInfo psi = new ProcessStartInfo(TheProgram); psi.UseShellExecute = false; psi.CreateNoWindow = true; psi.RedirectStandardInput = true; psi.RedirectStandardOutput = true; p.StartInfo = psi; Console.WriteLine("Executing " + TheProgram); p.Start(); DoPromptsAsync(p); Done.WaitOne(); } private static async Task DoPromptsAsync(Process p) { StreamWriter sw = p.StandardInput; StreamReader sr = p.StandardOutput; string Question; Question = await sr.ReadLineAsync(); if (Question != FirstQuestion) return; sw.WriteLine("First answer"); Console.WriteLine(Question + "answered"); Question = await sr.ReadLineAsync(); if (Question != SecondQuestion) return; sw.WriteLine("Second answer"); Console.WriteLine(Question + "answered"); Question = await sr.ReadLineAsync(); if (Question != FinalQuestion) return; sw.WriteLine("Final answer"); Console.WriteLine(Question + "answered"); Done.Set(); } } ``` The following works in a WPF application; I used a double-click event to test but this could be used in other WPF events. ``` const string TheProgram = @" ... "; Process p = new Process(); ProcessStartInfo psi = new ProcessStartInfo(TheProgram); psi.UseShellExecute = false; //psi.CreateNoWindow = true; psi.RedirectStandardInput = true; psi.RedirectStandardOutput = true; p.StartInfo = psi; p.Start(); const string FirstQuestion = "First question: "; const string SecondQuestion = "Another question: "; const string FinalQuestion = "Final question: "; StreamWriter sw = p.StandardInput; StreamReader sr = p.StandardOutput; string Question; StringBuilder sb = new StringBuilder("Executing " + TheProgram + "\r\n"); Question = await sr.ReadLineAsync(); if (Question != FirstQuestion) return; sw.WriteLine("First answer"); sb.Append(Question + "answered\r\n"); Question = await sr.ReadLineAsync(); if (Question != SecondQuestion) return; sw.WriteLine("Second answer"); sb.Append(Question + "answered\r\n"); Question = await sr.ReadLineAsync(); if (Question != FinalQuestion) return; sw.WriteLine("Final answer"); sb.Append(Question + "answered\r\n"); ResultBox.Text = sb.ToString(); ``` I think it will be more complicated if there are not line endings after each question.
Best way to interact with Command Line application
[ "", "c#", "windows", ".net-3.5", "" ]
Starting to build web applications for mobile devices (any phone). What would be the best approach using ASP.NET 3.5/ASP.NET 4.0 and C#? UPDATE (feb2010) Any news using windows mobile 7?
It depends if you really want to **support every cell phone** or only high end or new phone like the iPhone which don't have many limitations rendering web pages. If you could ask for real **HTML rendering, Javascript and cookies support on the phone as requirement**, then the real constraint is the **limited size of the screen**. You should do fine with "normal" web development in ASP.NET taking care to the the size of the pages. If that is the case, *you could stop reading here.* If you **really want to support every cell phone**, especially old ones, you should be aware that there are different types of phones. Many of them have **limitations and constraints** showing web pages. Some of them can use JavaScript, but many of them do not. Some of them can display HTML content, but many others can not. They have to rely on the "Wireless Markup Language" standard for accessing web. So, it's not easy to build a website that supports all of these different devices. Here are some links to general content (not ASP.NET specific), which could help getting the whole picture: * [Mobile Web Best Practices 1.0 (W3C)](http://www.w3.org/TR/mobile-bp/) * [Mobile Web Developer#s Guide (dotMobi)](http://mobiforge.com/starting/story/dotmobi-mobile-web-developers-guide) Their main limitation however is, as I already mentioned, the smaller screen than on normal PC's. And many cell phones do not support JavaScript, Cookies and some even don't show images. There are special markup standards for cell phones. **WML pages** is for example a widely adopted standard for cellphones. WML stands for "Wireless Markup Language" which is based on XML. You can find a description and reference of WML [here on w3schools.com](http://www.w3schools.com/WAP/wml_reference.asp). The code below shows a sample WML page: ``` <?xml version="1.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml"> <wml> <card id="card1" title="Stackoverflow"> <do type="accept" label="Menu"> <go href="#card2"/> </do> <p> <select name="name"> <option value="Questions">Questions</option> <option value="MyAccount">My account</option> <option value="FAQ">FAQ</option> </select> </p> </card> <card id="card2" title="Menu"> <p> You selected: $(name) </p> </card> </wml> ``` The good news is, that ASP.NET renders WML (and other mobile markup standards) content automatically. You don't have to write WML files yourself. A built-in mechanism detects the type of device (cell phone) of the web requests. However, mobile device detection on ASP.NET does not work correctly for some (newer) devices. Take a look at [WURFL](http://wurfl.sourceforge.net/), an XML configuration file which contains information about capabilities and features of many mobile devices. You can test the pages you develop in ASP.NET in a standard web browser, but it would not give th right picture of what you have developed. There are some emulators available for this problem, which simulate a cell phone on your desktop computer. There is a [Microsoft support article](http://support.microsoft.com/?scid=kb%3Ben-us%3B320977&x=6&y=14) which explains where you can download them. ## ASP.NET Mobile Controls The ASP.NET Mobile Controls, formerly knowns as the "Microsoft Mobile Internet Toolkit" extend the .NET Framework and Visual Studio to build mobile Web applications by enabling ASP.NET to deliver markup to a wide variety of mobile devices. The ASP.NET mobile controls render the appropriate markup (HTML 3.2, WML 1.1, cHTML, XHTML) while dealing with different screen sizes, orientations and device capabilities. Learn more [here on the official web site](http://www.asp.net/mobile/).
A couple things I should mention since I work on a wireless network in Canada. Try and keep any images small (or even non existent) to increase load times and reduce data charges. On our network, if the user is not subscribed to a plan, our network charges $15/mb. Some unoptimized images a phone tries to download could easily cost the user, and those large images won't look good anyways. I know it doesn't affect you, but if you use any other protocols, such as streaming, or any UDP based protocols, set the Maximum Packet Size to atleast 1300 bytes or lower. Just because of the way a mobile works as it's moves around the network, extra header information get's added. With TCP/IP we use MSS-clamping to protect against large packet issues, but this cannot be applied to any UDP transmissions, or anything secure protocol that uses an Authentication Header. If the mobiles you are targetting are offered by RIM, this point can be ignored completely. Some mobiles may use a WAP proxy when talking to you're server, if this is a case, try avoiding using any connections that require a keep-alive TCP/IP. Some proxies are set to not allow any keep-alive sessions go through them, even though I beleive most of the new ones are fine. I'm sure there is more, the most important thing you should keep in you're mind that the IP connectivity to the mobile is alot more complex then someone opening up a web browser. This transport can be extremely tricky, so if you try to do something really fancy, even if it works now, it may not always work. Also one last quick point, the latency and packet loss can fluctuate wildly, so if you're doing anything real-time, you latency could hit 200+ms, and I've seen packet loss spike to 20-30% levels for short times. Good Luck, and if you have any specific questions, be sure to ask them.
Web for mobile devices - best practices for ASP.NET
[ "", "c#", "mobile", "windows-phone-7", "windows-phone", "" ]
In PHP, if you define a class, and then instantiate an object of that class, it's possible to later arbitrarily add new members to that class. For example: ``` class foo { public $bar = 5; } $A = new foo; $A->temp = 10; ``` However, I'd like the ability to make it impossible to add new members this way. Basically I want the class to ONLY have the members that are specified in its definition; if you try to set any other members, it fatally errors. The intent here is that I want to define a class as a very specific set of properties, and ensure that ONLY those properties exist in the class, so that the class contents are well-defined and cannot change later on (the values of each member can change, but not the members themselves). I realize I can do this with the \_\_set method, and simply have it fatal error if you try to set a member which doesn't already exist, but that's annoying to have to include in every class definition (although I could define each of my classes to extend a base class with that method, but that's also annoying). E.g.: ``` class foo { public $bar = 5; private function __set($var, $val) { trigger_error("Cannot dynamically add members to a class", E_USER_ERROR); } } ``` Is there any other (preferably more convenient) way to do this? Aside from modifying PHP itself to disallow this behavior?
No. There's no better way than `__set` in a base class — yet. This is a known problem and is [planned to be addressed in the future](http://wiki.php.net/todo/php53): > Introduce concept of “strict classes” that do not permit dynamic property creation
Nop, only \_\_set. Perhaps you can use inheritance to avoid rewriting it everywhere.
Locking class members in PHP
[ "", "php", "oop", "class", "" ]
Currently I am using FOP to generate a pdf from java code and an xslt document. The FOP spits out a PDF file that is displayed (embeded) into a webpage. The documents can range between one and several thousand pages long, and it can take some time to generate them. Is there a better tool that and do this? Is FOP the best option in the opensource and free world?
This answer is too late for you, but in case it helps other searchers, [Docmosis](http://www.docmosis.com) can generate documents at a fairly hefty rate, and can spread a high load across multiple machines. It uses OpenOffice as the underlying format conversion engine, adding document population and manipulation facilities via the Docmosis Java API. Several thousand page documents are going to take most systems a while, but if the system (or your code) allows you to parallelise and distribute the effort, then at least the average document rate can be high, even if the individual document time may be significant. [JODReports](http://jodreports.sourceforge.net/) is another similar option.
We use [iText](http://www.lowagie.com/iText/). Here is a blog entry [Comparing Apache FOP with iText](http://blog.xebia.com/2008/03/03/comparing-apache-fop-with-itext/). Judging by your usage (generate a pdf from java code and an xslt document) it seems like FOP is the better choice for you. EDIT: This forum post about [FOP Vs IText](http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=64&t=001845) includes the following: > iText is more feature rich than FOP as far as PDF is concerned: you can add annotations, create AcroForms, digitally sign a PDF document. **Also iText is the only solution if you need to generate PDF documents containing thousands or ten thousands of pages.**
Creating a PDF from Java and Displaying it in a webpage
[ "", "java", "pdf-generation", "apache-fop", "" ]
I have a view which is derived from CEditView. It is read only. I would like to set the text as a kind of logging, but nothing shows up on the screen. If I inspect `temp` in the debugger after `GetEditCtrl().GetWindowText(temp);` I can see that the text is indeed changing internally, but I see nothing on the screen. ``` // HistoryView.cpp : implementation file // #include "stdafx.h" #include "HistoryView.h" // CHistoryView IMPLEMENT_DYNCREATE(CHistoryView, CEditView) CHistoryView::CHistoryView() { } CHistoryView::~CHistoryView() { } BEGIN_MESSAGE_MAP(CHistoryView, CEditView) END_MESSAGE_MAP() // CHistoryView diagnostics #ifdef _DEBUG void CHistoryView::AssertValid() const { CEditView::AssertValid(); } #ifndef _WIN32_WCE void CHistoryView::Dump(CDumpContext& dc) const { CEditView::Dump(dc); } #endif #endif //_DEBUG // CHistoryView message handlers void CHistoryView::OnInitialUpdate() { CEditView::OnInitialUpdate(); // TODO: Add your specialized code here and/or call the base class GetEditCtrl().SetReadOnly(TRUE); } //! /*! */ void CHistoryView::AddRow(CString message) { CString temp; GetEditCtrl().GetWindowText(temp); if(temp.IsEmpty()) { GetEditCtrl().SetWindowText(message); } else { GetEditCtrl().SetWindowText(temp + "\r\n" + message); } GetEditCtrl().LineScroll(2, 0); //GetEditCtrl().UpdateWindow(); // no effect } ```
Turns out that a third-party UI toolkit was reconstructing the View (who knows why?) so my pointer to it was stale. Thus, I was actually refreshing a different view!
The problem seems to lie somewhere other than in the code you posted. I created a new MFC app with the view derived from CEditView, and the code you're using to add the text worked ok, although I did have to wrap the literal `"\r\n"` inside an explicit temporary `CString`, as in: ``` GetEditCtrl().SetWindowText(temp + CString("\r\n") + message); ```
CEditView not showing text
[ "", "c++", "mfc", "" ]
If i have an interface: ``` interface IFoo { int Offset {get;} } ``` can i have this: ``` interface IBar: IFoo { int Offset {set;} } ``` so consumers of IBar will be able to set or get?
No, you can't! (I was about to write "Yes", but after reading Anthony's post, and trying out a few tweaks, I found the answer to be NO!) ``` class FooBar : IFoo, IBar { public int Offset{get;set;} } ``` (Will generate a warning as Anthony points out, which can be fixed by adding the "new" keyword.) When trying out the code: ``` IBar a = new FooBar(); a.Offset = 2; int b = a.Offset; ``` The last line will generate a compile error, since you have hidden IBar's Offset setter. **EDIT:** Fixed the accesibillity modifier on the property in the class. Thx Anthony!
This is close but no banana. ``` interface IFoo { int Offset { get; } } interface IBar : IFoo { new int Offset { set; } } class Thing : IBar { public int Offset { get; set; } } ``` Note the `new` keyword in IBar, but this overrides the get accessor of IFoo so IBar doesn't have a get. Hence no you can't actually create IBar that simply adds a set whilst keeping the existing get.
Interface inheritance
[ "", "c#", "interface", "" ]
How do I Deserialize this XML document: ``` <?xml version="1.0" encoding="utf-8"?> <Cars> <Car> <StockNumber>1020</StockNumber> <Make>Nissan</Make> <Model>Sentra</Model> </Car> <Car> <StockNumber>1010</StockNumber> <Make>Toyota</Make> <Model>Corolla</Model> </Car> <Car> <StockNumber>1111</StockNumber> <Make>Honda</Make> <Model>Accord</Model> </Car> </Cars> ``` I have this: ``` [Serializable()] public class Car { [System.Xml.Serialization.XmlElementAttribute("StockNumber")] public string StockNumber{ get; set; } [System.Xml.Serialization.XmlElementAttribute("Make")] public string Make{ get; set; } [System.Xml.Serialization.XmlElementAttribute("Model")] public string Model{ get; set; } } ``` . ``` [System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)] public class Cars { [XmlArrayItem(typeof(Car))] public Car[] Car { get; set; } } ``` . ``` public class CarSerializer { public Cars Deserialize() { Cars[] cars = null; string path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data/") + "cars.xml"; XmlSerializer serializer = new XmlSerializer(typeof(Cars[])); StreamReader reader = new StreamReader(path); reader.ReadToEnd(); cars = (Cars[])serializer.Deserialize(reader); reader.Close(); return cars; } } ``` that don't seem to work :-(
Here's a working version. I changed the `XmlElementAttribute` labels to `XmlElement` because in the xml the StockNumber, Make and Model values are elements, not attributes. Also I removed the `reader.ReadToEnd();` (that [function](http://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend.aspx) reads the whole stream and returns a string, so the `Deserialize()` function couldn't use the reader anymore...the position was at the end of the stream). I also took a few liberties with the naming :). Here are the classes: ``` [Serializable()] public class Car { [System.Xml.Serialization.XmlElement("StockNumber")] public string StockNumber { get; set; } [System.Xml.Serialization.XmlElement("Make")] public string Make { get; set; } [System.Xml.Serialization.XmlElement("Model")] public string Model { get; set; } } [Serializable()] [System.Xml.Serialization.XmlRoot("CarCollection")] public class CarCollection { [XmlArray("Cars")] [XmlArrayItem("Car", typeof(Car))] public Car[] Car { get; set; } } ``` The Deserialize function: ``` CarCollection cars = null; string path = "cars.xml"; XmlSerializer serializer = new XmlSerializer(typeof(CarCollection)); StreamReader reader = new StreamReader(path); cars = (CarCollection)serializer.Deserialize(reader); reader.Close(); ``` And the slightly tweaked xml (I needed to add a new element to wrap <Cars>...Net is picky about deserializing arrays): ``` <?xml version="1.0" encoding="utf-8"?> <CarCollection> <Cars> <Car> <StockNumber>1020</StockNumber> <Make>Nissan</Make> <Model>Sentra</Model> </Car> <Car> <StockNumber>1010</StockNumber> <Make>Toyota</Make> <Model>Corolla</Model> </Car> <Car> <StockNumber>1111</StockNumber> <Make>Honda</Make> <Model>Accord</Model> </Car> </Cars> </CarCollection> ```
How about you just save the xml to a file, and use [xsd](http://msdn.microsoft.com/en-us/library/x6c1kb0s.aspx) to generate C# classes? 1. Write the file to disk (I named it foo.xml) 2. Generate the xsd: `xsd foo.xml` 3. Generate the C#: `xsd foo.xsd /classes` Et voila - and C# code file that should be able to read the data via `XmlSerializer`: ``` XmlSerializer ser = new XmlSerializer(typeof(Cars)); Cars cars; using (XmlReader reader = XmlReader.Create(path)) { cars = (Cars) ser.Deserialize(reader); } ``` (include the generated foo.cs in the project)
How to Deserialize XML document
[ "", "c#", "asp.net", "xml", "serialization", "xml-deserialization", "" ]
How can I implement the following in python? ``` #include <iostream> int main() { std::string a; std::cout << "What is your name? "; std::cin >> a; std::cout << std::endl << "You said: " << a << std::endl; } ``` Output: > What is your name? Nick > > You said: Nick
Call ``` name = raw_input('What is your name?') ``` and ``` print 'You said', name ```
Look at the `print` statement and the `raw_input()` function. Or look at `sys.stdin.read()` and `sys.stdout.write()`. When using `sys.stdout`, don't forget to flush.
How can the user communicate with my python script using the shell?
[ "", "python", "" ]
How do I convert a PIL `Image` back and forth to a NumPy array so that I can do faster pixel-wise transformations than PIL's `PixelAccess` allows? I can convert it to a NumPy array via: ``` pic = Image.open("foo.jpg") pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3) ``` But how do I load it back into the PIL `Image` after I've modified the array? `pic.putdata()` isn't working well.
You're not saying how exactly `putdata()` is not behaving. I'm assuming you're doing ``` >>> pic.putdata(a) Traceback (most recent call last): File "...blablabla.../PIL/Image.py", line 1185, in putdata self.im.putdata(data, scale, offset) SystemError: new style getargs format but argument is not a tuple ``` This is because `putdata` expects a sequence of tuples and you're giving it a numpy array. This ``` >>> data = list(tuple(pixel) for pixel in pix) >>> pic.putdata(data) ``` will work but it is very slow. As of PIL 1.1.6, the ["proper" way to convert between images and numpy arrays](https://web.archive.org/web/20081225061956/http://effbot.org/zone/pil-changes-116.htm) is simply ``` >>> pix = numpy.array(pic) ``` although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case). Then, after you make your changes to the array, you should be able to do either `pic.putdata(pix)` or create a new image with `Image.fromarray(pix)`.
Open `I` as an array: ``` >>> I = numpy.asarray(PIL.Image.open('test.jpg')) ``` Do some stuff to `I`, then, convert it back to an image: ``` >>> im = PIL.Image.fromarray(numpy.uint8(I)) ``` Source: [Filter numpy images with FFT, Python](http://barnesc.blogspot.com/2007/09/filter-numpy-images-with-fft-python.html) If you want to do it explicitly for some reason, there are pil2array() and array2pil() functions using getdata() on [this page](http://bradmontgomery.blogspot.com/2007/12/computing-correlation-coefficients-in.html) in correlation.zip.
How do I convert a PIL Image into a NumPy array?
[ "", "python", "image", "numpy", "python-imaging-library", "numpy-ndarray", "" ]
Suppose I have a database table that has a timedate column of the last time it was updated or inserted. Which would be preferable: 1. Have a trigger update the field. 2. Have the program that's doing the insertion/update set the field. The first option seems to be the easiest since I don't even have to recompile to do it, but that's not really a huge deal. Other than that, I'm having trouble thinking of any reasons to do one over the other. Any suggestions?
The first option can be more robust because the database will be maintaining the field. This comes with the possible overhead of using triggers. If you could have other apps writing to this table in the future, via their own interfaces, I'd go with a trigger so you're not repeating that logic anywhere else. If your app is pretty much it, or any other apps would access the database through the same datalayer, then I'd avoid that nightmare that triggers can induce and put the logic directly in your datalayer (SQL, ORM, stored procs, etc.). Of course you'd have to make sure your time-source (your app, your users' pcs, your SQL server) is accurate in either case. --- Regarding why I don't like triggers: Perhaps I was rash by calling them a nightmare. Like everything else, they are appropriate in moderation. If you use them for very simple things like this, I could get on board. It's when the trigger code gets complex (and expensive) that triggers start to cause lots of problems. They are a hidden tax on every insert/update/delete query you execute (depending on the type of trigger). If that tax is acceptable then they can be the right tool for the job.
You didn't mention **3. Use a stored procedure to update the table.** The procedure can set timestamps as desired. Perhaps that's not feasible for you, but I didn't see it mentioned.
What is the best way to maintain a LastUpdatedDate column in SQL?
[ "", "sql", "sql-server", "database", "sql-server-2005", "triggers", "" ]
We are just starting to migrate/reimplement an ERP system to Java with Hibernate, targeting a concurrent user count of 50-100 users using the system. We use MS SQL Server as database server, which is good enough for the load. The old system doesn't use transactions and relies for critical parts (e.g. stock changes) on setting manual locks (using flags) and releasing them. That's something like manual transaction management. But there are sometimes problems with data inconsistency. In the new system, we would like to use transactions to wipe out these problems. What would be a good/reasonable **default** transaction isolation level to use for an ERP system, given a usage of about 85% OLTP and 15% OLAP? Or should I always decide, on a per task basis, which transaction level to use? The four transaction isolation levels: * READ UNCOMMITTED * READ COMMITTED * REPEATABLE READ * SERIALIZABLE
99 times out of 100, read committed is the right answer. That ensures that you only see changes that have been committed by the other session (and, thus, results that are consistent, assuming you've designed your transactions correctly). But it doesn't impose the locking overhead (particularly in non-Oracle databases) that repeatable read or serializable impose. Very occasionally, you may want to run a report where you are willing to sacrifice accuracy for speed and set a read uncommitted isolation level. That's rarely a good idea, but it is occasionally a reasonably acceptable workaround to lock contention issues. Serializable and repeatable read are occasionally used when you have a process that needs to see a consistent set of data over the entire run regardless of what other transactions are doing at the time. It may be appropriate to set a month-end reconciliation process to serializable, for example, if there is a lot of procedureal code, a possibility that users are going to be making changes while the process is running and a requirement that the process needs to ensure that it is always seeing the data as it existed at the time the reconciliation started.
It really depends a lot on how you design your application, the easy answer is just run at READ\_COMMITTED. You can make an argument that if you design your system with it in mind that you could use READ\_UNCOMMITTED as the default and only increase the isolation level when you need it. The vast majority of your transactions are going to succeed anyway so reading uncommitted data won't be a big deal. The way isolation levels effect your queries depends on your target database. For instance databases like Sybase and MSSQL must lock more resources when you run READ\_COMMITTED, than databases like Oracle.
What is the best default transaction isolation level for an ERP, if any?
[ "", "sql", "database", "database-design", "transactions", "isolation-level", "" ]
Is there a recommended way to bounce an asp.net application besides touching web.config from inside the application? is `HttpRuntime.UnloadAppDomain()`; the preferred way to do this ? and if so where do you do this? In the unload of a page or some other place in the application?
If this is .NET 2.0 or greater, then you can add in an "App\_offline.htm" file, make a request to the server, remove it, and then make another request to the server. This sequence of events will force ASP.NET to unload the application for as long as the app\_offline.htm file exists in the folder. Scott Guthrie's blog entry on it: <http://weblogs.asp.net/scottgu/archive/2005/10/06/426755.aspx>
Touching web.config from inside an application is a bad idea, IMO. Also, the idea of having a file that you modify is a little hackney, IMO. The documentation specifically states that [`UnloadAppDomain`](http://msdn.microsoft.com/en-us/library/system.web.httpruntime.unloadappdomain.aspx) will shut the application down: > UnloadAppDomain allows programmatic shutdown of unused applications. You should be able to make this call anywhere in the application. Mind you, you might get a [`SecurityException`](http://msdn.microsoft.com/en-us/library/system.security.securityexception.aspx), so make sure that the runtime gives you the appropriate permissions (you might want to put this in a library and make a call and then set the library up in the GAC with evidence to give it full trust).
how to restart asp.net application besides modifying web.config
[ "", "c#", "asp.net", "restart", "" ]
I'm storing some additional per-user information using the [`AUTH_PROFILE_MODULE`](http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users). We can access the user in a Django template using `{{ request.user }}` but how do we access fields in the profile since the profile is only accessible via a function `user.get_profile()` ? Is it really required to explicitly pass the profile into the template every time?
Use `{{ request.user.get_profile.whatever }}`. Django's templating language automatically calls things that are callable - in this case, the `.get_profile()` method.
Not sure why it's different for me, but I need to use {{user}} rather than {{request.user}}.
How to access the user profile in a Django template?
[ "", "python", "django", "django-templates", "" ]
I'm currently learning the APIs related to Intel's parallelization libraries such as TBB, MKL and IPP. I was wondering, though, whether it's also worth looking at AMD's part of the puzzle. Or would that just be a waste of time? (I must confess, I have no clue about AMD's library support - at all - so would appreciate any advice you might have.) Just to clarify, the reason I'm going the Intel way is because 1) the APIs are very nice; and 2) Intel seems to be taking tool support as seriously as API support. (Once again, I have **no clue** how AMD is doing in this department.)
The MKL and IPP libraries will perform (nearly) as well on AMD machines. My guess is that TBB will also run just fine on AMD boxes. If I had to suggest a technology that would be beneficial and useful to both, it would be to master the OpenMP libraries. The Intel compiler with the OpenMP extensions is stunningly fast and works with AMD chips also.
Only worth it if you are specifically interested in building something like Video games, Operating systems, database servers, or virtualization software. In other words: if you have a segment where you care enough about performance to take the time to do it (and do it right) in assembler. The same is true for Intel.
Is it worth learning AMD-specific APIs?
[ "", "c++", "intel", "amd-processor", "" ]
Given two sets of values: ``` var subset = new[] { 2, 4, 6, 8 }; var superset = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; ``` how do I determine if `superset` contains all elements of `subset`? I have come up with this: ``` superset.Intersect(subset).Count() == subset.Count() ``` Is this the most logical and efficient method?
How about Not Any? ``` bool contained = !subset.Except(superset).Any(); ```
So, my other answer was pretty easy to use. But it's an O(n\*m) solution. Here's a slightly less friendly O(n+m) solution. This should be used if superset is HUGE. It avoids repeatedly enumerating superset. ``` HashSet<int> hashSet = new HashSet<int>(superset); bool contained = subset.All(i => hashSet.Contains(i)); ```
Determine if a sequence contains all elements of another sequence using Linq
[ "", "c#", "linq", "" ]
I need to use a priority queue in my Python code, and: * am looking for any **fast** implementations for priority queues * optimally, I'd like the queue to be **generic** (i.e. work well for any object with a specified comparison operator). Looking around for something efficient, I came upon [heapq](http://docs.python.org/library/heapq.html), but: * I'm looking for something faster than `heapq`, which is implemented in native Python, so it's not fast. * It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs. * Update: Re comparison in `heapq`, I can either use a `(priority, object)` as Charlie Martin suggests, or just implement `__cmp__` for my object.
You can use [Queue.PriorityQueue](http://docs.python.org/library/queue.html#Queue.PriorityQueue). Recall that Python isn't strongly typed, so you can save anything you like: just make a tuple of `(priority, thing)` and you're set.
When using a priority queue, decrease-key is a must-have operation for many algorithms (Dijkstra's Algorithm, A\*, OPTICS), I wonder why Python's built-in priority queue does not support it. None of the other answers supply a solution that supports this functionality. A priority queue which also supports decrease-key operation is [this](https://github.com/DanielStutzbach/heapdict) implementation by Daniel Stutzbach worked perfectly for me with Python 3.5. ``` from heapdict import heapdict hd = heapdict() hd["two"] = 2 hd["one"] = 1 obj = hd.popitem() print("object:",obj[0]) print("priority:",obj[1]) # object: one # priority: 1 ```
A generic priority queue for Python
[ "", "python", "queue", "" ]
I have a system-wide manual reset event that I create by doing the following: ``` EventWaitHandle notifyEvent = new EventWaitHandle(false, EventResetMode.ManualReset, notifyEventName, out createdEvent); ``` Several processes create this event (e.g. it is shared amongst them). It is used for notifying when something gets updated. I'd like to be able to set this event so that all of processes waiting on it are signaled and then immediately reset it so that subsequent Waits on the event are blocked. If I do a ``` notifyEvent.Set(); notifyEvent.Reset(); ``` It will sometimes notify all listening processes. If I do a ``` notifyEvent.Set(); Thread.Sleep(0); notifyEvent.Reset(); ``` More processes get notified (I assumed this would happen since the scheduler has a chance to run). And if I do ``` notifyEvent.Set(); Thread.Sleep(100); notifyEvent.Reset(); ``` Then everything seems to work out fine and all processes (e.g. ~8) get notified consistently. I don't like the use of a "magic number" for the Sleep call. Is there a better way to notify all listeners of an OS event in other processes that an event has occurred so that everyone listening to it at the time of notification receive the event signal and then immediately reset the event so that anyone else that goes to listen to the event will block? **UPDATE:** A Semaphore doesn't seem to be a good fit here since the number of listeners to the event can vary over time. It is not known in advance how many listeners there will be when an even needs to be notified.
You're using the EventWaitHandle class incorrectly. A reset event shouldn't be used to signal multiple threads. Instead, you need to create a reset event for each thread and then when you're ready loop through them all and use Set(). The master thread should not be calling the Reset() method. Each thread should be responsible for closing the gate behind them so to speak. Here's a basic example: ``` static class Program { static void Main() { List<ThreadState> states = new List<ThreadState>(); ThreadState myState; Thread myThread; string data = ""; for (int i = 0; i < 4; i++) { myThread = new Thread(Work); myState = new ThreadState(); myState.gate = new EventWaitHandle(false, EventResetMode.ManualReset); myState.running = true; myState.index = i + 1; states.Add(myState); myThread.Start(myState); } Console.WriteLine("Enter q to quit."); while (data != "q") { data = Console.ReadLine(); if (data != "q") foreach (ThreadState state in states) state.gate.Set(); } foreach (ThreadState state in states) { state.running = false; state.gate.Set(); } Console.WriteLine("Press any key to quit."); Console.ReadKey(); } static void Work(Object param) { ThreadState state = (ThreadState)param; while (state.running) { Console.WriteLine("Thread #" + state.index + " waiting..."); state.gate.WaitOne(); Console.WriteLine("Thread #" + state.index + " gate opened."); state.gate.Reset(); Console.WriteLine("Thread #" + state.index + " gate closed."); } Console.WriteLine("Thread #" + state.index + " terminating."); } private class ThreadState { public int index; public EventWaitHandle gate; public bool running; } } ```
I had the same problem and surprisingly couldn't find any good solution on the web for this loose-coupled / fire and forget / multiple listeners type of event, so here is what I came up with. Note the solution with the timeout between `Set()` and `Reset()` calls has also a race-condition issue (beyond the fact it relies on an arbitrary timeout value): if the publisher gets killed between these calls, then all the listeners will see the event as set forever (unless the publisher gets live again). So the requirement is: * there is one publisher (although it's not really enforced in the code) * there can be any number of listeners (in the same process or in other processes), between 0 and N (N is fixed once the binaries are compiled). * listeners can come and go as they want without disturbing the publisher * publisher can come and go as it wants without disturbing the listeners The trick is to use AutoReset events because they don't have race condition issues, but define one per listener. We don't know the number of listeners beforehand but we can fix a maximum number of listeners ('N' described above): ``` const int MAX_EVENT_LISTENERS = 10; const string EVENT_NAME = "myEvent_"; ``` Here is the publisher code to raise the event to all potential listeners: ``` public static void RaiseEvent() { for (int i = 0; i < MAX_EVENT_LISTENERS; i++) { EventWaitHandle evt; if (EventWaitHandle.TryOpenExisting(EVENT_NAME + i, out evt)) { evt.Set(); evt.Dispose(); } } } ``` Here is the listener code to get notified of the event: ``` ... EventWaitHandle evt = GetEvent(); do { bool b = evt.WaitOne(); // event was set! } while (true); .... // create our own event that no other listener has public static EventWaitHandle GetEvent() { for (int i = 0; i < MAX_EVENT_LISTENERS; i++) { bool createdNew; EventWaitHandle evt = new EventWaitHandle(false, EventResetMode.AutoReset, EVENT_NAME + i, out createdNew); if (createdNew) return evt; evt.Dispose(); } throw new Exception("Increase MAX_EVENT_LISTENERS"); } ```
Properly notifying all listeners of a system wide named manual reset event and then immediately resetting it
[ "", "c#", "windows", "multithreading", "events", "" ]
I've seen on the internet quite a few examples of binding a boolean to the Visibility property of a control in XAML. Most of the good examples use a BooleanToVisibiliy converter. I'd like to just set the Visible property on the control to bind to a System.Windows.Visibility property in the code-behind, but it doesn't seem to want to work. This is my XAML: ``` <Grid x:Name="actions" Visibility="{Binding Path=ActionsVisible, UpdateSourceTrigger=PropertyChanged}" /> ``` This is the code for the property: ``` private Visibility _actionsVisible; public Visibility ActionsVisible { get { return _actionsVisible; } set { _actionsVisible = value; } } ``` In the constructor of the Window, I also have this call: ``` base.DataContext = this; ``` When I update either ActionsVisible or this.actions.Visibility, the state doesn't transfer. Any ideas to what might be going wrong?
I think the problem is that WPF can't know that your ActionsVisible property has changed since you've not notified the fact. Your class will need to implement INotifyPropertyChanged, then in your set method for ActionsVisible you'll need to fire the PropertyChanged event with ActionsVisible as the property name that has changed. Hope this helps...
Change your property to be a DependencyProperty. This will handle the updating for you. ``` public Visibility ActionsVisible { get { return (Visibility)GetValue(ActionsVisibleProperty); } set { SetValue(ActionsVisibleProperty, value); } } // Using a DependencyProperty as the backing store for ActionsVisible. This enables animation, styling, binding, etc... public static readonly DependencyProperty ActionsVisibleProperty = DependencyProperty.Register("ActionsVisible", typeof(Visibility), typeof(FooForm)); ```
Binding Visibility in XAML to a Visibility property
[ "", "c#", "xaml", "binding", "visibility", "" ]
I'm fairly new to C# programming. I am making a program for fun that adds two numbers together, than displays the sum in a message box. I have two numericUpDowns and a button on my form. When the button is pushed I want it to display a message box with the answer. The problem is, I am unsure how to add the twp values from the numericUpDowns together. So far, I have this in my button event handler: ``` private void button1_Click(object sender, EventArgs e) { MessageBox.Show(this.numericUpDown1.Value + this.numericUpDown2.Value); } ``` But obviously, it does not work. It gives me 2 compiler errors: 1. The best overloaded method match for 'System.Windows.Forms.MessageBox.Show(string) has some invalid arguments 2. Argument '1': cannot convert decimal to 'string' Thanks!
`this.numericUpDown1.Value + this.numericUpDown2.Value` is actually evaluating properly to a number, so you're actually very close. The problem is that the `MessageBox.Show()` function, needs a string as an argument, and you're giving it a number. To convert the result to a string, add `.ToString()` to it. Like: ``` private void button1_Click(object sender, EventArgs e) { MessageBox.Show((this.numericUpDown1.Value + this.numericUpDown2.Value).ToString()); } ``` For reference, if you want to do more advanced formatting, you'd want to use `String.Format()` instead of `ToString()`. See [this page](http://msdn.microsoft.com/en-us/library/fht0f5be.aspx) for more info on how to use `String.Format()`.
This works. ``` decimal total = this.numericUpDown1.Value + this.numericUpDown2.Value; MessageBox.Show(total.ToString()); ``` MessageBox.Show expects a string as a parameter (that's the first error message).
New C# Programmer - Adding two numericUpDown values together?
[ "", "c#", "numericupdown", "" ]
What should a small team choose for their first game, when they are low on time but have big ambitions? I'm an experienced programmer, but haven't done any game programming before this. My designer is very talented and artistic, he has worked with 3D about an year ago but hasn't done it since so it could take him some time to learn it again, and i'm not sure if he'll be able to do a good job at it even though his graphic design skills are terrific otherwise. Our primary concern is to get the game finished as quickly as possible, and also to do it easily since this is my first game programming project. At the same time, we don't want to have any limitations that might hinder our progress later on, or otherwise make the game not fun in certain ways. For example, i learnt that certain animations aren't possible in 2D such as rotation etc. I would like the ability to have the player's character be able to morph into animals and there must be the ability to shoot at the monsters, (like shooting an arrow and seeing it fly through and hit the other person). Are these things possible in 2D? In the future, if we wanted to go from 3D to 2D, would it be possible without fully rewriting the game?
You don't have to use 3D to allow for a "3D look". Things like rotations, motions or transformations can be prerecorded or prerendered as animations or image sequences and seamlessly integrated into a 2D game. The only thing that is not possible in 2D is to navigate freely within your "game space" (like walking or flying freely, turning arbitrarily etc.) The main concern, however, when deciding for 2D or 3D should be the gameplay. There are games that absolutely need 3D (shooters, simulations), while others do perfectly without (adventures, puzzles, ...). So you don't actually have to decide but to choose the better fit for your game idea. Personally, I'd avoid using 3D in your first game attempt if possible to eliminate all the constraints and hassles that come with it. When using 3D you typically have to decide for a 3D framework which will heavily influence your software design, game look and feel and overall performance. Java3D for example brings a complicated class structure that you have to adjust to. And a lot of effort goes into making that 3D stuff work at all. Simple things like rotating a square evolve into matrix operations incorporating quaternions. Every effect has to be done in the complex 3D world, and in such a way that its 2D projected look turns out the way you intended it. Not to mention that 3D applications often suffer a very stereotypical look that is very hard to overcome. In 2D, you literally avoid one dimension of complexity. You do everything exactly the way it is supposed to look, you can use standard graphic applications and open file formats to simplify the workflow between the designer and the developer. And a lot of pseudo-3D effects like parallax motion, depth of field and prerendered artwork allow for astonishing looks in a 2D world.
You should go 2D. You have stated several reasons to take this approach: * You are a small team, and 3D takes more work. * It's your first game, so you need to keep it as simple as possible, or the project may fail (you are exposed to a lot of risk!) * The 3D artist needs to relearn the crafts! * You have a (seemingly self-imposed) deadline. * Etc. 3D takes a lot of time, and it will be best invested in improving the rest of the game. Think of all the awesome games that existed previous to the 3D era. Do not fear to accept restrictions: whilst 3D might give you lots of possibilities, 2D may result in more creative work!
Which to choose: 2D or 3D for a java game
[ "", "java", "3d", "2d", "" ]
I've got few files in resources (xsd files) that i use for validating received xml messages. The resource file i use is named **AppResources.resx** and it contains a file called **clientModels.xsd**. When i try to use the file like this: AppResources.clientModels, i get a string with the file's content. i would like to get a stream instead. i do not wish to use assembly.GetManifestResourceStream as i had bad experiences with it (using these streams to archive files with SharpZipLib didn't work for some reason). is there any other way to do it? i've heard about ResourceManager - is it anything that could help me?
Could you feed the string you get into a System.IO.StringReader, perhaps? That may do what you want. You may also want to check out MemoryStream.
here is the code from the link ``` //Namespace reference using System; using System.Resources; #region ReadResourceFile /// <summary> /// method for reading a value from a resource file /// (.resx file) /// </summary> /// <param name="file">file to read from</param> /// <param name="key">key to get the value for</param> /// <returns>a string value</returns> public string ReadResourceValue(string file, string key) { //value for our return value string resourceValue = string.Empty; try { // specify your resource file name string resourceFile = file; // get the path of your file string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString(); // create a resource manager for reading from //the resx file ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null); // retrieve the value of the specified key resourceValue = resourceManager.GetString(key); } catch (Exception ex) { Console.WriteLine(ex.Message); resourceValue = string.Empty; } return resourceValue; } #endregion ``` I did not write the code it came from <http://www.dreamincode.net/code/snippet1683.htm> HTH bones
how to get file from resources as a stream? (.net)
[ "", "c#", ".net", "resources", "" ]
First, to make my job explaining a bit easier, here's some of my code: ``` JSpinner spin = new JSpinner(); JFormattedTextField text = getTextField(spin); text.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { // Do stuff... } }); ``` ... ``` private JFormattedTextField getTextField(JSpinner spinner) { JComponent editor = spinner.getEditor(); if (editor instanceof JSpinner.DefaultEditor) { return ((JSpinner.DefaultEditor )editor).getTextField(); } else { System.err.println( "Unexpected editor type: " + spinner.getEditor().getClass() + " isn't a descendant of DefaultEditor" ); return null; } } ``` So as you can see, I got that far. And indeed, when I type in a value into the text field component of the spinner (`JFormattedTextField`), and THEN press ENTER, it works. What I want now is to be able to have the text field respond to ENTER without having to manually type in a new value (which sorta defeats the purpose of making a spinner out of it). How do I do that?
I know this is not the action listener...but maybe this can work for you? ``` text.addKeyListener( new KeyAdapter() { @Override public void keyReleased( final KeyEvent e ) { if ( e.getKeyCode() == KeyEvent.VK_ENTER ) { System.out.println( "enter pressed" ); } } } ); ```
I just ran into an issue relating to this, myself. In my case, I had a JSpinner with a `SpinnerNumberModel` setup so I could input numerical ID values, and then retrieve them from a remote database. This worked all well and good with a JButton as my trigger for the query, but I wanted to be able to switch focus to the field via Tab, and hit enter, and also be able to change the value by entering an ID with numerical keys, then hit enter. The one that was giving me the most issues was manually entering the ID with numerical keys, then pressing enter. When I would do this, the query would still happen, but it was querying the previous ID rather than the one I just entered, so I'd have to hit enter again to query the new ID (see code) ``` ((JSpinner.DefaultEditor) minRng.getEditor()).getTextField().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { queryData(); } } }); ``` and the query method: ``` private void queryData() { int minVal = Integer.parseInt(minRng.getValue().toString()); queryDataBase(minVal); } ``` In order to fix this, all I had to do was force the query to wait to run until the spinner updated its value, which was easily done by using `SwingUtilities.invokeLater()` to force it to the end of the EDT queue, like so: ``` ((JSpinner.DefaultEditor) minRng.getEditor()).getTextField().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { queryData(); } }); } } }); ``` Thanks to the `invokeLater()` the query now happens on the new value rather than the previous one, when pressing enter, as the JSpinner has then updated its value to the newly input one. I'm assuming the reason for this is that the value entered is not officially applied to the `JSpinner` until you hit enter, which also fires the key listener for the query. The `KeyEvent` for the custom [query] key listener appears to be the first one in the queue, so it runs its code first, and THEN the `KeyEvent` for applying the value to the `JSpinner` from the internal `JFormattedTextField`, which is why it queries the old value. `SwingUtilities.invokeLater()` just puts the query itself at the end of the queue, so it allows the other `KeyEvent` to finish its code before running the query. **Edit:** Another way to achieve this is to request the value directly from the `JFormattedTextField` rather than the `JSpinner`, as this should also return the newly entered value since the `JFormattedTextField` contains the value you typed in, but it hasn't yet been passed to the JSpinner, which appears to be where the issue lies. ``` private void queryData() { JFormattedTextField tf = ((JSpinner.DefaultEditor) minRng.getEditor()).getTextField(); int minVal = Integer.parseInt(tf.getText()); queryDataBase(minVal); } ``` The only problem with this method is that you then have to catch any `NumberFormatException`s, when parsing the value, where the `SwingUtilities.invokeLater()` approach allows the spinner model to remove any invalid characters, automatically, and continue with the query. Anyway, I'm still somewhat inexperienced with Java, so if my understanding of this is incorrect, please let me know in the comments.
Getting ENTER to work with a JSpinner the way it does with a JTextField
[ "", "java", "swing", "jtextfield", "listeners", "jspinner", "" ]
I'm making a script parser in python and I'm a little stuck. I am not quite sure how to parse a line for all its functions (or even just one function at a time) and then search for a function with that name, and if it exists, execute that function short of writing a massive list if elif else block.... *EDIT* This is for my own scripting language that i'm making. its nothing very complex, but i have a standard library of 8 functions or so that i need to be able to be run, how can i parse a line and run the function named in the line?
Once you get the name of the function, use a dispatch dict to run the function: ``` def mysum(...): ... def myotherstuff(...): ... # create dispatch dict: myfunctions = {'sum': mysum, 'stuff': myotherstuff} # run your parser: function_name, parameters = parse_result(line) # run the function: myfunctions[function_name](parameters) ``` Alternatively create a class with the commands: ``` class Commands(object): def do_sum(self, ...): ... def do_stuff(self, ...): ... def run(self, funcname, params): getattr(self, 'do_' + funcname)(params) cmd = Commands() function_name, parameters = parse_result(line) cmd.run(function_name, parameters) ``` You could also look at the [cmd module](http://docs.python.org/library/cmd) in the stdlib to do your class. It can provide you with a command-line interface for your language, with tab command completion, automatically.
Check out [PyParsing](http://pyparsing.wikispaces.com/), it allows for definition of the grammar directly in Python code: Assuming a function call is just `somename()`: ``` >>> from pyparsing import * >>> grammar = Word(alphas + "_", alphanums + "_")("func_name") + "()" + StringEnd() >>> grammar.parseString("ab()\n")["func_name"] "ab" ```
Parsing Functions
[ "", "python", "parsing", "" ]
Do you guys think internationalization should only done at the code level or should it be done in the database as well. Are there any design patterns or accepted practices for internationalizing databases? If you think it's a code problem then do you just use Resource files to look up a key returned from the database? Thanks
Internationalization extends to the database insofar as your columns will be able to hold the data. NText, NChar, NVarchar instead of Text, Char, Varchar. As far as your UI goes, for non-changing labels, resources files are a good method to use.
If you refer to making your app support multiple languages at the UI level, then there are more possibilities. If the labels never change, unless when you release a new version, then resource files that get embedded in the executable or assembly itself are your best bet, since they work faster. If your labels, on the other hand, need to be adjusted at runtime by the users, then storing the translations in the database is a good choice. As far as the code itself, the names of tables & fields in the database, we keep them in English as much as possible, since English is the "de facto" standard for IT people.
Internationalization in the database
[ "", "c#", "sql-server", "internationalization", "" ]
The typical ConfigParser generated file looks like: ``` [Section] bar=foo [Section 2] bar2= baz ``` Now, is there a way to index lists like, for instance: ``` [Section 3] barList={ item1, item2 } ``` Related question: [Python’s ConfigParser unique keys per section](https://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section)
There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like: ``` [Section 3] barList=item1,item2 ``` It's not pretty but it's functional for most simple lists.
I am using a combination of ConfigParser and JSON: ``` [Foo] fibs: [1,1,2,3,5,8,13] ``` just read it with: ``` >>> json.loads(config.get("Foo","fibs")) [1, 1, 2, 3, 5, 8, 13] ``` You can even break lines if your list is long (thanks @peter-smit): ``` [Bar] files_to_check = [ "/path/to/file1", "/path/to/file2", "/path/to/another file with space in the name" ] ``` Of course i could just use JSON, but i find config files much more readable, and the [DEFAULT] Section very handy.
Lists in ConfigParser
[ "", "python", "configparser", "" ]
I need to find a path or paths down a complicated graph structure. The graph is built using something similar to this: ``` class Node { public string Value { get; set;} public List<Node> Nodes { get; set;} public Node() { Nodes = new List<Node>(); } } ``` What makes this complicated is that the nodes can reference back to an earlier node. For example, > A -> C -> E -> A What I need to do is get a list of stacks which represent paths through the Nodes until I get to a Node with a specific value. Since its possible there can be some very large paths available we can have a maximum Nodes to try. ``` List<Stack<Node>> paths = FindPaths(string ValueToFind, int MaxNumberNodes); ``` Does anyone have a way to build this (or something similar)? I've done recursion in the past but I'm having a total brain fart thinking about this for some reason. My question specified a lambda expression but using a lambda is not necessarily required. I'd be grateful for any solution. Side note: I lifted the class from aku's excellent answer for [this recursion question](https://stackoverflow.com/questions/61143/recursive-lambda-expression-to-traverse-a-tree-in-c). While his elegant solution shown below traverses the tree structure it doesn't seem to allow enough flexibility to do what I need (for example, dismiss paths that are circular and track paths that are successful). ``` Action<Node> traverse = null; traverse = (n) => { Console.WriteLine(n.Value); n.Nodes.ForEach(traverse);}; traverse(root); // where root is the tree structure ``` **Edit**: Based on input from the comments and answers below I found an excellent solution over in CodeProject. It uses the A\* path finding algorithm. [Here is the link.](http://www.codeproject.com/KB/recipes/graphs_astar.aspx)
If you're issue is related to Pathfinding, you may want to google for "A star" or "A\*". Its a common and efficient pathfinding algorithm. See [this article](http://www.gamedev.net/reference/articles/article2003.asp) for an example directly related to your problem. You may also want to look at the [Dijsktra Algorithm](http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)
I'm not sure whether your intended output is *all* paths to the goal, the *best* path to the goal (by some metric, e.g. path length), or just *any* path to the goal. Assuming the latter, I'd start with the recursive strategy, including tracking of visited nodes as outlined by Brann, and make these changes: 1. Add parameters to represent the goal being sought, the collection of successful paths, and the current path from the start. 2. When entering a node that matches the goal, add the current path (plus the current node) to the list of successful paths. 3. Extend the current path with the current node to create the path passed on any recursive calls. 4. Invoke the initial `ExploreGraph` call with an empty path and an empty list of successful paths. Upon completion, your algorithm will have traversed the entire graph, and distinct paths to the goal will have been captured. That's just a quick sketch, but you should be able to flesh it out for your specific needs.
Recursive lambda expression to find the path(s) through a directed graph?
[ "", "c#", "recursion", "directed-graph", "" ]
This is a bit special: I'm loading some HTML in string form into the WebBrowser control via the DocumentText property. Now when I print the page with a PDF printer (Bullzip PDF Printer in my case) it always takes the URL as document name which is "about:blank". Is there any way to change this to another value by either changing the URL property (it's read-only) or by changing the print behaviour to use another text rather than the URL as filename?
There are a couple of options that I am aware of though my knowledge on this subject is a bit dated. The first is to change the computer settings in Internet Options. Regardless of whether this is done by hand or through a registry change script, it is simple for the developer, but obviously not the best approach from the deployment or compatibility angles. The next approach is to develop a custom print template. This is not fun, but is probably the most professional approach. As much as I would love to include all of the information needed on this approach in this post, it is too much to cover. [Here is a good overview](http://msdn.microsoft.com/en-us/library/aa753280(VS.85).aspx) and good luck Googling from there. My experience with this involved printing from the MS WebControl component used in a .NET 1.1 Winforms application to the Web Super Goo PDF converter component. Your mileage may vary.
You can change the header and footer such that the URL property is not printed.
WebBrowser control: How to overwrite URL property
[ "", "c#", ".net", "printing", "webbrowser-control", "" ]
I downloaded the Eclipse PDT 2.0 GA release (Eclipse 3.4), however, it doesn't look like the Ant tools are included in this package. How can I install the eclipse Ant tools (editor, executable, etc...)?
So I found the answer to my own question. You need to install the Eclipse Java Development Tools. These can be found under Ganymede > Java Development > Eclipse Java Development Tools in Help > Software Updates > Available Software.
This drove me crazy a couple days ago. In Galileo the update process is slightly different, which is bad forward design if you ask me (but I digress). Here's how you do it in Eclipse 3.5. Help > Install New Software From "Work with:" dropdown choose "Galileo - <http://download.eclipse.org/releases/galileo>" Then expand "Programming Languages" and choose "Eclipse Java Development Tools". You could install a different plugin, but this is the standard Eclipse Install.
Eclipse PDT Ant
[ "", "php", "eclipse", "development-environment", "eclipse-pdt", "" ]
I have used ValidatorEnable to disable a RequiredFieldValidator in javascript. However on postback the control being validated by the validator is still validated ... even though I disabled the validator on the client. I understand why this is happening since I've only disabled the client validation ... however is there a nice way to determine that I've disabled the client validation and to then disable the server validation on postback?
Peanut, I just encounted the same issue you are. On the client-side I have javascript that disables required field validators depending on their selections in the UI. However, the server side validation was still firing. During load, I added a method to disable my validators using the same rules I have on the javascript. In my case, it depended on the user's selection of a radio button: ``` this.requiredValidator.Enabled = this.myRadioButton.Checked; ``` This seems to work on the SECOND page load, but not the first. After debugging, I discovered that the wrong radio button is considered to be checked when this line was firing. The View State/Post Data wasn't applied to the control at the point when I was checking it to disable my validator. The reason I placed this during load was to make sure I disabled the validator before it fired. So, the solution seems to be to have something like the line above AFTER ViewState, but BEFORE validators. Overloading the Validate() method, as palehorse suggested, worked and allowed me to ensure the server side validators were enabled/disabled based on the current selections of the user.
You could, when you disable the client validation (presumably with JavasScript?), also set up values in a hidden input that you could query in page load method. This way you can examine the value of the hidden input (via the Request.Form{] array) to disable the validators on the server side prior to the validation event firing. Another option would be to override the pages Validate() method to disable the validators based on the same rules that hid them on the client side.
ASP.NET - how to stop unrequired server validation
[ "", "asp.net", "javascript", "validation", "" ]
Is there any work being done to create a C# compiler to produce native exe's? e.g. the output is a native exe and NOT a .NET assembly.
Why don't you try NGen. For exemple Paint.NET use nGen to create native images after installation.
If you want a standalone deployment (i.e. without needing the framework), there are a few options - see [here](http://www.yoda.arachsys.com/csharp/faq/#framework.required). However, I'm not aware of anything that will reliably produce purely unmanaged code. What is the use-case you have in mind? For embedded etc there is micro-framework, CF, etc.
Is there any work being done to create a C# compiler to produce native exe's?
[ "", "c#", "compiler-construction", "native", "exe", "" ]
Backdrop: There are two forms, the main application form and a form to edit various settings for the operations of main application. What would be the proper way to show the frmSettings form and how to dispose it once clicked OK or Cancel in the actual frmSettings form?
Perhaps a Dialog would be better suited to your Settings "form." There are subtle differences between a dialog and a form that would make the dialog easier to handle. A return code indicating the button that was clicked makes dialogs useful. Supposing that you used a dialog - a using statement could be used (off the top of my head): ``` using (DialogSettings dlgSettings = new DialogSettings) { if (dlgSettings.ShowDialog() == DialogResult.OK) { ``` } } If you insist on using a form then you would have to * Instance the form * show the form * record whether ok or cancel was clicked to a form level variable (from within the forms ok/cancel button click code) * hide the form * save the recorded value from the form * dispose of the form * make use of the saved ok/cancel value
fyi, using "frm" is not a recommended part of the C# coding guidelines. [Microsoft prefers you don't use hungarian notation in .NET at all.](http://blogs.msdn.com/brada/articles/361363.aspx)
C#: What is the proper way to show a form for "frmMainForm" settings and disposing?
[ "", "c#", "" ]
I'm in the process of trying to migrate my ASPNET site to Django. All my current data is tied up in MS SQL Server on a shared host that (helpfully) doesn't support python... I could use my existing code to export all the data but I've also stopped using Windows. The site is mainly compiled VB.NET so I'd need to install Windows and Visual Studio and then figure out what I'm trying to do... I don't like that plan. Rather than go through *that* headache, I'd like to use PHP to export the entire database (or a table at a time) to JSON. SimpleJSON in Python will make it ludicrously easy to import so it seems like a plan. So far, so good. In PHP I've managed to connect to the SQL Server and perform simple queries, but I need a list of tables so I know what data I need to copy. I want all the tables because there are legacy tables from when I rewrote the site about three years ago, and I'd like to keep that data somewhere... So first thing: **Does anybody know the SQL query for listing all tables?** I've tried `mssql_query('sp_tables');` but this returns a strange list: ``` mydatabasename mydatabasename dbo dbo syscolumns syscolumns SYSTEM TABLE SYSTEM TABLE ``` Secondly: In your opinion, would I be better off writing each table dump to its own .json file or should I keep it all together? Thirdly: Am I going about this the wrong way?
``` Select table_name from information_schema.tables ``` for any given table you can get the metadata with ``` sp_help tablename ```
You do query with : ``` SHOW TABLES; ``` (you need to select `DB` before this.)
List table names
[ "", "php", "sql-server", "" ]
In C++ you are able to compile files that are not included in the solution, with c# this is not the case. Is there a way to keep a file in a project but not have the standard SCCI provider attempt to keep checking in the file? Essentially what we are wanting to do is to create "by developer" code ability similar to how we code in c++, this allows for us to let our developers do nightly check-ins with pseudo code and by-developer utilities. ``` #ifdef (TOM) #include "Tom.h"; #endif ``` --- **EDIT** I don't want to create new configurations in the solution file either, I want these to be as machine specific as possible, without source control bindings to the user on the file/setting.
Well, it seems after working off the post here, and literally trying "wierd" things, I had an idea. Essentially I used the \*.csproj.user file, declared a UserConfig property, added a new Constant (for code checks), and did an ItemGroup with the condition of the UserConfig. All this fell under the DEBUG flag. The only issue is that the file does not show up in the solution explorer, but in c++ they didn't either. **My \*.csproj.user file** ``` <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <UserConfig>Tom</UserConfig> <DefineConstants>DEBUG;TRACE;TOM</DefineConstants> </PropertyGroup> <ItemGroup Condition=" '$(UserConfig)' == 'Tom'"> <Compile Include="Tom.cs" /> </ItemGroup> </Project> ``` **Resulting Code** ``` #if (TOM) Tom t = new Tom(); #endif ```
MSBuild has [Conditional Constructs](http://msdn.microsoft.com/en-us/library/ms164307.aspx). All you have to do is modify the Solution file to include what you want. The end result would look very similar to your example code. ``` <When Condition=" '$(Configuration)'=='TOM' "> <ItemGroup> <Compile Include="tomCode\*.cs" /> </ItemGroup> </When> ```
How do I create compiled user files in Visual Studio 2008?
[ "", "c#", ".net", "vb.net", "visual-studio-2008", "" ]
Is there a way in C# sytax for defining a new line? (Like in VB \_ ) Example: Instead of: ``` string myStr = "very long string" + "another long string"; ``` This: ``` string myStr = "very long string \something another long string" ``` Or; does compiler handles this and does something like; "string" + "string" -> "stringstring" in this example? Different cases are welcome like when these strings are constants, etc.
Compiler turns "ABC" + "DEF" into "ABCDEF" so there's no cost in using +
You can use ``` string myStr = @"very long string another long string"; ``` @" is the beginning of a string literal and this kind of string does not end until the next " character is found. There is not an exact syntax for c# which does the same thing as \_ character in vb. So if you want to avoid including a new line, you must manually connect your strings on different lines.
How to put a new line inside a string in C# source code?
[ "", "c#", "syntax", "" ]
I'd like to figure out (in runtime) whether or not two regular expressions intersect (i.e. if they do there exist one or more string the matches both regular expressions). Algorithm needs to be pretty fast as I need to loop through a database and check existing values. Found some theory on this but no implementations?
The obvious solution would be to convert the regexes to DFAs, compute the intersection of the DFAs (trivial) and see if there's anything the resulting DFA can accept (also trivial). The only hard part is converting the regexes to DFAs, which requires some work.
Here's an [implementation in Haskell](http://sulzmann.blogspot.com/2008/11/playing-with-regular-expressions.html) using partial derivatives of regexps. A comment to that post points out an issue with the approach in Chris Dodd's answer.
Algorithm: Intersection of two regexps
[ "", "c#", "algorithm", "" ]
I am wondering if there are any additional optimizations I can implement to improve the speed of reflective invocations in Java. Not that the performance is prohibitive, but I get the willies when thinking about some piece of code in a library I am writing being implemented in a tight loop somewhere. Consider a utility method to invoke reflectively: ``` public static Object invoke(Object targetObject, String methodName, Object[] arguments, Class<?>[] signature) ``` The basic operation is ``` return method.invoke(targetObject, arguments); ``` As a performance optimization, I cache the method using a hash of the target object's class, method name and signature (the code of which might use some improvement) but beyond that, is there anything else I can do ? I have heard references to some early implementations of **InvokeDynamic** that sound promising, but I just assumed that they were probably not applicable yet, and I discounted my own byte code manipulation as I would like to keep the utility simple (but fast). Cheers.
The comments below relate to Sun's implementation, in particular OpenJDK 6. Your mileage may vary with other Java platform implementations. `java.lang.Class` does some caching itself, so implementing your own cache may not improve things very much. Do timing tests with and without manual caching. The actual invocation mechanism is optimised too. The first 15 runs (by default) of your reflected method is called using JNI; after that, bytecode is generated and calling that reflected method would perform identically to calling that method directly in Java code.
I ran some tests around Chris Jester-Young's answer and using the **verbose** options, I definitely observed the compiler take some action around the 15th invocation. Hard to say if there's much performance differential without a more sophisticated test, but it is persuasive. Here's the output: ``` Test# 0 Test# 1 Test# 2 Test# 3 Test# 4 Test# 5 Test# 6 Test# 7 Test# 8 Test# 9 Test# 10 Test# 11 Test# 12 Test# 13 Test# 14 [Loaded sun.reflect.ClassFileConstants from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.AccessorGenerator from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.MethodAccessorGenerator from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.ByteVectorFactory from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.ByteVector from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.ByteVectorImpl from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.ClassFileAssembler from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.UTF8 from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded java.lang.Void from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.Label from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.Label$PatchInfo from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded java.util.AbstractList$Itr from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.MethodAccessorGenerator$1 from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.ClassDefiner from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.ClassDefiner$1 from C:\jdk1.5.0_06\jre\lib\rt.jar] [Loaded sun.reflect.GeneratedMethodAccessor1 from __JVM_DefineClass__] Test# 15 Test# 16 Test# 17 ``` I guess the **InvokeDynamic** business is not attracting too many developers on the basis of reflection speedup/elimination. Thanks Chris.
Any way to further optimize Java reflective method invocation?
[ "", "java", "performance", "reflection", "" ]
Say, for example, I have many web applications using the same class library compiled into a dll in C# and I want to update a specific method of a class for a particular application. I don't want to change the existing code because it will affect everyone, and I don't want to inherit from a class to create a new one. I just want to change an existing method of a class for an individual application. One way to achieve this would be to have the compiled classes as 'base' classes and have a separate file containing all the override classes inheriting the base classes. Then the applications will use the inherited classes. Then to change a class for an individual application you could just update the inherited classes. The only problem I see with this method is that every application would need 2 files, one of base classes and one of inherited (probably not compiled). Can anyone recommend a better way of doing this?
Polymorphism seems to be the best solution for this. This way base classes can be compiled and left alone and inherited classes can be changed for individual applications without changing the way the original is used (unless necessary). BaseClasses.cs ``` public class BaseUser { public BaseUser() {} public bool login() { return false; } } ``` Classes.cs ``` public class User : BaseUser {} ``` Application ``` User u = new User(); u.login(); ```
Maybe extension methods would work?
What's the best way to add custom functionality to existing code in C#?
[ "", "c#", "inheritance", "" ]
I've not used Unit Tests before other than a quick introduction in a Uni course. I'm currently writing an application though and would like to teach myself TDD in the process. The problem is, I've no idea what to test or really how. I'm writing a Django application, and so far have only created the models (and customised the admin application). This is how I've written the skeletons of my tests so far: ``` class ModelTests(TestCase): fixtures = ['initial_data.json',] def setUp(self): pass def testSSA(self): ssa = SSA.objects.create(name="sdfsdf", cost_center=1111, street_num=8, street_name="dfsdfsf Street", suburb="sdfsdfsdf", post_code=3333) def testResident(self): pass def testSSA_Client(self): pass ``` I planned to write a function to test each model within the ModelTests class. Is this a good way of writing tests? Also, what exactly should I be testing for? That creating a model with all of the fields completed works? That a half complete model fails? That any special cases are tested (like a null and is\_required=False)? I've trust in the ORM, which as far as I'm aware is heavily tested, so I shouldn't need to test all of the methods should I? What do I need to test for a web application written in Django/Python? Some examples would be nice.
**Is a function to test each model within the ModelTests class a good way of writing tests?** No. **What exactly should I be testing for?** * That creating a model with all of the fields completed works? * That a half complete model fails? * That any special cases are tested (like a null and is\_required=False)? * I've trust in the ORM, which as far as I'm aware is heavily tested, so I shouldn't need to test all of the methods should I? Not much of that. You might test validation rules, but that isn't meaningful until you've defined some Form objects. Then you have something to test -- does the form enforce all the rules. You'll need at least one TestCase class for each form. A function will be a scenario -- different combinations of inputs that are allowed or not allowed. For each Model class, you'll need at least one TestCase class definition. TestCases are cheap, define lots of them. Your model embodies your "business entity" definitions. Your models will have methods that implement business rules. Your methods will do things like summarize, filter, calculate, aggregate, reduce, all kinds of things. You'll have functions for each of these features of a model class. You're not testing Django. You're testing how your business rules actually work in Django. Later, when you have more stuff in your application (forms, views, urls, etc.) you'll want to use the Django unittest client to exercise each method for each url. Again, one TestCase per
I'm not exactly sure of the specifics of what you're trying to test here, I'd need more code snippets for this, but I can give you some general advice. First, read the unit testing chapter of "Dive into Python" (it's free online! <https://diveintopython3.net/unit-testing.html>), it's a great explanation of unit testing in general, what you need to do, and why. Second, with regards to TDD, it is a valuable practice, but be careful about growing too dependent on it as I've found it can lead to over-specifying software and further on to having software that can not be re-developed and adapted to new tasks. This is just my experience, mind. Also, providing you don't use it dogmatically TDD is valuable. Third, it strikes me that the best piece of advice for your specific situation is to *strive to test your logic, but not the logic of frameworks that you depend on*. That means that often testing half-complete models fail etc. etc. may not be appropriate, since that is not your logic, but django's, and so should already be tested. More valuable would be to test a few expected cases, instantiations that you expect, exceptions that you expect etc. to make sure your model specification is sound, and then move on to the more substantial logic of your application.
Writing unit tests in Django / Python
[ "", "python", "django", "unit-testing", "" ]
Im looing for a way to have a simple "on mouse over"-effect. (I want the page to show a dialogbox)
Use some Javascript. Jquery makes thoose things quite easy. Do you already have the information or is it something you want to pull from the server when the mouse is hovering? With Jquery you could do something like this ``` <script type="javascript"> $(document).ready( function(){ $("divToShow").hide(); $('#objectWithMouseOver').mouseover(onMouseOver()); }); function onMouseOver() { $('#divToShow').show(); } </script> <body> <div id="divToShow"> whatever info you want to show.... </div> <div id="objectWithMouseOver"> when you drag mouse over here the other will show </div> ``` I would use addclass removeclass instead of show/hide to get better control. Its not hard to extend it to call mvc controls and populate data using ajax. Add some parameters to the function and the use jquery.ajax functions.
I'd go for the [jQuery Tooltip plug-in](http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/) from Jörn Zaefferer
Ajax in ASP.NET MVC Framework
[ "", "javascript", "ajax", "asp.net-mvc", "" ]
I need to build an assembler for a CPU architecture that I've built. The architecture is similar to MIPS, but this is of no importance. I started using C#, although C++ would be more appropriate. (C# means faster development time for me). My only problem is that I can't come with a good design for this application. I am building a 2 pass assembler. I know what I need to do in each pass.\ I've implemented the first pass and I realised that if I have to lines assembly code on the same line ...no error is thrown.This means only one thing poor parsing techniques. So almighty programmers, fathers of assembler enlighten me how should I proceed. I just need to support symbols and data declaration. Instructions have fixed size. Please let me know if you need more information.
I've written three or four simple assemblers. Without using a parser generator, what I did was model the [S-C assembler](http://stjarnhimlen.se/apple2/) that I knew best for 6502. To do this, I used a simple syntax - a line was one of the following: ``` nothing [label] [instruction] [comment] [label] [directive] [comment] ``` A label was one letter followed by any number of letters or numbers. An instruction was <whitespace><mnemonic> [operands] A directive was <whitespace>.XX [operands] A comment was a \* up to end of line. Operands depended on the instruction and the directive. Directives included .EQ equate for defining constants .OR set origin address of code .HS hex string of bytes .AS ascii string of bytes - any delimiter except white space - whatever started it ended it .TF target file for output .BS n reserve block storage of n bytes When I wrote it, I wrote simple parsers for each component. Whenever I encountered a label, I put it in a table with its target address. Whenever I encountered a label I didn't know, I marked the instruction as incomplete and put the unknown label with a reference to the instruction that needed fixing. After all source lines had passed, I looked through the "to fix" table and tried to find an entry in the symbol table, if I did, I patched the instructions. If not, then it was an error. I kept a table of instruction names and all the valid addressing modes for operands. When I got an instruction, I tried to parse each addressing mode in turn until something worked. Given this structure, it should take a day maybe two to do the whole thing.
Look at this Assembler Development Kit from Randy Hyde's author of the famous "The Art of Assembly Language": [The Assembler Developer's Kit](http://www.plantation-productions.com/Webster/RollYourOwn/)
Building an assembler
[ "", "c#", "assembly", "" ]
Is it necessary to register a compiled DLL (written in C# .NET) on a target machine. The target machine will have .NET installed, is it enough to simply drop the DLL onto the target machine?
I think you're confusing things a little. Registering a dll has never been needed in order to use it. Using a dll requires only to load it (given a known location or if the library is in the system path) and get the address of the function you wanted to use. Registering the dll was used when distributing COM or ActiveX objects which need to add certain entries to the windows registry. In order to use a COM service (for example) you need to reference a GUID — that is, a unique identifier — which allows you to get a handle to the dll that implements the service (or provide access to it). Sometimes you can make reference to a fully-qualified name and get the same results. In order for all that to work the dll needed to be registered. This "registration" process just creates several entries in the registry, but mainly these two: one associating a GUID with the location of the dll (so that you can reference it through the GUID without knowing where is it exactly located) and a second one associating the full name with the GUID. But again, this is just for COM or ActiveX objects. When you develop an application in .NET, the libraries referenced on your project are automatically loaded when they're needed without you having to worry about locating or loading them. In order to to that, the framework checks two locations for the referenced libraries. * The first location is the application path. * The second location is the GAC. The GAC (Global Assembly Cache) allows you to effectively register a dll to be used throughout the system and works as an evolution of the old registering mechanism. So basically you just need to put the dll in the same folder of the application.
You need to "drop" it into a directory where the application needing it will find it. If there are multiple applications, or you want to "drop" the file somewhere other than the application directory, you generally need to either adjust the PATH variable, or register the assembly in the Global Assembly Cache (GAC).
In .NET, is there a need to register the DLL?
[ "", "c#", ".net", "dllregistration", "" ]
what is the best way to deploy a winforms app if you know you are going to be doing frequent releases
Click Once is your best bet.
Click Once is great if you know the customer base will always have access to an internet connection and they only ever need a single version installed. This is probably true for the majority of apps. But if that is not the case then I recommend you ensure that people can install different versions of your application side-by-side. Do not place your assemblies in the GAC or have them share a common resource. This way the customer can have multiple versions installed and they all continue to work. Xcopy deployment would be even better but hard to achieve in practice for non-trivial apps.
deployment of winforms applications
[ "", "c#", "deployment", "" ]
I am messing around with different PHP logging frameworks. I am currently trying PEAR::Log. I figured that I would use its `singleton` function to make sure there was only one instance of the class around. I have a small daemon-like script I wanted to add logging to because it was probably the simplest script in the system to test. This script has several functions. I will probably want to log things inside the functions. The question I have is how do I best manage this singleton? To me calling this: ``` &Log::singleton($handler, $name, $ident, $conf, $maxLevel); ``` in every function doesn't seem ideal especially since I already specified all of the options in the initial call. Pear::Log serializes this info, but from what it looks like you still have to provide all of those variables to get the instance. Another alternative is passing the instance into every function. Again, seems like it's less than ideal. I suppose you could make the instance a 'global' as well. What do you in this situation? Are there better solutions?
I don't know much about PEAR::Log, but why not create another singleton that wraps/simplifies logging. ``` class Logger { private static $log; private function __construct() { } public static function init(Log $log) { self::$log = $log; } public static function get() { return self::$log; } } ``` Once you initialize `Logger` with `Log` instance you can access it via `Logger::get`. Since dereference is possible in PHP you can then do ``` Logger::get()->doSomething($foo, $bar); ```
Better yet, if your end goal is to just be able to blindly call ``` Logger::Write("Something happened"); ``` wherever you need it, you can take Michal's solution one step further with ``` class Logger { private static $log = null; public static function init(Log $log) { self::$log = $log; } public static function Write(String $str) { if($log == null) init(Log::singleton(...)); $this->log->Write($str); } } ``` That way, your log will be initialized once, the first time it's used.
What's the best to way to manage a singleton?
[ "", "php", "design-patterns", "singleton", "" ]
It was hinted in a [comment to an answer to this question](https://stackoverflow.com/questions/433525/choosing-asp-net-over-php-or-perl#433610) that PHP can not reverse Unicode strings. > As for Unicode, it works in PHP > because most apps process it as > binary. Yes, PHP is 8-bit clean. Try > the equivalent of this in PHP: perl > -Mutf8 -e 'print scalar reverse("ほげほげ")' You will get garbage, > not "げほげほ". – jrockway And unfortunately it is correct that PHPs unicode support atm is at best "lacking". This will [hopefully change drastically with PHP6](http://74.125.77.132/search?q=cache:X3t6LgxXRa0J:derickrethans.nl/files/php6-unicode.pdf+php6+unicode). PHPs [MultiByte functions](https://www.php.net/manual/en/ref.mbstring.php) does provide the basic functionality you need to deal with unicode, but it is inconsistent and does lack a lot of functions. One of these is a function to reverse a string. I of course wanted to reverse this text for no other reason then to figure out if it was possible. And I made a function to accomplish this enormous complex task of reversing this Unicode text, so you can relax a bit longer until PHP6. Test code: ``` $enc = 'UTF-8'; $text = "ほげほげ"; $defaultEnc = mb_internal_encoding(); echo "Showing results with encoding $defaultEnc.\n\n"; $revNormal = strrev($text); $revInt = mb_strrev($text); $revEnc = mb_strrev($text, $enc); echo "Original text is: $text .\n"; echo "Normal strrev output: " . $revNormal . ".\n"; echo "mb_strrev without encoding output: $revInt.\n"; echo "mb_strrev with encoding $enc output: $revEnc.\n"; if (mb_internal_encoding($enc)) { echo "\nSetting internal encoding to $enc from $defaultEnc.\n\n"; $revNormal = strrev($text); $revInt = mb_strrev($text); $revEnc = mb_strrev($text, $enc); echo "Original text is: $text .\n"; echo "Normal strrev output: " . $revNormal . ".\n"; echo "mb_strrev without encoding output: $revInt.\n"; echo "mb_strrev with encoding $enc output: $revEnc.\n"; } else { echo "\nCould not set internal encoding to $enc!\n"; } ```
Grapheme functions handle UTF-8 string more correctly than mbstring and PCRE functions/ Mbstring and PCRE may break characters. You can see the defference between them by executing the following code. ``` function str_to_array($string) { $length = grapheme_strlen($string); $ret = []; for ($i = 0; $i < $length; $i += 1) { $ret[] = grapheme_substr($string, $i, 1); } return $ret; } function str_to_array2($string) { $length = mb_strlen($string, "UTF-8"); $ret = []; for ($i = 0; $i < $length; $i += 1) { $ret[] = mb_substr($string, $i, 1, "UTF-8"); } return $ret; } function str_to_array3($string) { return preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY); } function utf8_strrev($string) { return implode(array_reverse(str_to_array($string))); } function utf8_strrev2($string) { return implode(array_reverse(str_to_array2($string))); } function utf8_strrev3($string) { return implode(array_reverse(str_to_array3($string))); } // http://www.php.net/manual/en/function.grapheme-strlen.php $string = "a\xCC\x8A" // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) ."o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) var_dump(array_map(function($elem) { return strtoupper(bin2hex($elem)); }, [ 'should be' => "o\xCC\x88"."a\xCC\x8A", 'grapheme' => utf8_strrev($string), 'mbstring' => utf8_strrev2($string), 'pcre' => utf8_strrev3($string) ])); ``` The result is here. ``` array(4) { ["should be"]=> string(12) "6FCC8861CC8A" ["grapheme"]=> string(12) "6FCC8861CC8A" ["mbstring"]=> string(12) "CC886FCC8A61" ["pcre"]=> string(12) "CC886FCC8A61" } ``` IntlBreakIterator can be used since PHP 5.5 (intl 3.0); ``` function utf8_strrev($str) { $it = IntlBreakIterator::createCodePointInstance(); $it->setText($str); $ret = ''; $pos = 0; $prev = 0; foreach ($it as $pos) { $ret = substr($str, $prev, $pos - $prev) . $ret; $prev = $pos; } return $ret; } ```
here's another approach using regex: ``` function utf8_strrev($str){ preg_match_all('/./us', $str, $ar); return implode(array_reverse($ar[0])); } ```
How to reverse a Unicode string
[ "", "php", "string", "unicode", "reverse", "" ]
I am looking at some javascript code and it has this in a function: ``` $$('.CssClass').each(function(x) { .... } ) ``` I get that the intent is to apply the anonymous function to each element with a class of CssClass, but I can't work what the $$ refers to ... and can't google for $$! **Update**: thanks for the hints. The javascript comes from the iPhone look-alike library: [jPint](http://www.journyx.com/jpint/) which includes the [prototypejs](http://www.prototypejs.com/) library, and does define $$ as: ``` function $$() { return Selector.findChildElements(document, $A(arguments)); } ```
Probably [this](http://www.prototypejs.org/api/utility#method-%24%24) prototype function: ``` $$(cssRule...) -> [HTMLElement...] ``` > Takes an arbitrary number of CSS > selectors (strings) and returns a > document-order array of extended DOM > elements that match any of them. [http://www.prototypejs.org/api/utility#method-$$](http://www.prototypejs.org/api/utility#method-%24%24)
$ is an ordinary symbol character, thus "$", "$$", "$$$" are ordinary variables. the meaning of $ depends upon the libraries that are in use; in jQuery the $-function creates a jquery object from a css selector, e.g. $("DIV") is a collection of all DIVs in the current document.
What does $$ mean in Javascript?
[ "", "javascript", "prototypejs", "" ]
My problem is very similar to eight queens puzzle. I've got 2-dimensional array (N x N) that for example, looks like this: ``` 0,0,0,0,1 y 0,0,0,0,0 | 0,0,0,0,0 V 0,0,0,1,0 0,0,0,0,0 x-> ``` I'm checking horizontally, vertically and diagonally for occurrences of 1 ``` \,0,|,0,/ 0,\,|,/,0 -,-,1,-,- 0,/,|,\,0 /,0,|,0,\ ``` I'm thinking about storing only the (x,y) postions of "1"'s in a list ``` [[4,0],[3,3]] ``` and solving it mathematically, check every position of "1" with another (x1,y1)<->(x2,y2), if `x1 == x2` or `y1 == y2` `we have a collision!` if not check: ``` x2 == x1 + z; y2 == y1 + z; x2 == x1 - z; y2 == y1 - z; ``` (???) where z is +/- that `( x1+z in 0..N ) and ( y1+z in 0..N ) .......` ***My problem is checking for diagonal collision, is there a better way to do it???***
One possible solution: ``` def collision(x1, y1, x2, y2): return x1 == x2 or y1 == y2 or abs(x1-x2) == abs(y1-y2) ``` i.e. there is a collision if the two points are on the same horizontal row, same vertical row or same diagonal (vertical distance == horizontal distance).
Your description sounds like an instance of an exact cover problem, which can be solved using an algorithm Knuth calls [Algorithm X](http://en.wikipedia.org/wiki/Algorithm_X). I have implemented a [Sudoku solver in Javascript](http://hewgill.com/sudoku/) using this technique. You can probably find implementations in Python, too.
Checking 2-dimensional array (like eight queens puzzle)
[ "", "python", "arrays", "puzzle", "" ]
When writing destructive queries (e.g., DELETE or UPDATE) in SQL Server Management Studio I always find myself wishing I could preview the results of the query without actually running it. Access very conveniently allows you to do this, but I prefer to code my SQL by hand which, sadly, Access is very poor at. So my question is twofold: 1. Is there an add-on for SSMS, or a separate tool that is furnished with good SQL hand-coding facilities that can also preview the result of a destructive query, similar to Access? 2. Are there any techniques or best practices for doing previews "by hand"; e.g., somehow using transactions? It seems to me that doing this sort of thing is fundamentally important but yet I can't seem to find anything via Google (I'm probably just looking for the wrong thing - I am terribly ignorant on this matter). At present I'm taking a rather hairy belt and braces approach of commenting in and out select/delete/update lines and making sure I do backups. There's got to be a better way, surely? Can anyone help?
I would use the OUTPUT clause present in SQL SERVER 2008 onwards... [**OUTPUT Clause (Transact-SQL)**](http://msdn.microsoft.com/en-us/library/ms177564.aspx) Something like... ``` BEGIN TRANSACTION DELETE [table] OUTPUT deleted.* WHERE [woof] ROLLBACK TRANSACTION ``` INSERTs and UPDATEs can use the 'inserted' table too. The MSDN article covers it all. **EDIT:** This is just like other suggestions of SELECT then DELETE inside a transaction, except that it actually does both together. So you open a transaction, delete/insert/update with an OUTPUT clause, and the changes are made while ALSO outputting what was done. Then you can choose to rollback or commit.
I live in fear of someone doing this to my databases so I always ask my Team to do something like the following: ``` BEGIN TRAN   DELETE FROM X -- SELECT * FROM X FROM Table A as X JOIN Table B ON Blah blah blah WHERE blah blah blah   ROLLBACK TRAN COMMIT TRAN ``` In this way, if you accidentally hit F5 (done it!) you'll do no changes. You can highlight the SELECT part through the end of the SQL statement to see what records will be changed (and how many). Then, highlight the BEGIN TRAN and entire Delete statement and run it. If you delete the same number of records you expected, highlight the COMMIT TRAN and run it. If anything looks wonky, highlight the ROLLBACK TRAN and run it. I do this with any UPDATE or DELETE statement. It's saved me a couple times, but it ALWAYS provides peace of mind.
How do I preview a destructive SQL query?
[ "", "sql", "sql-server", "" ]
I have a custom object that implements INotifyPropertyChanged. I have a collection of these objects where the collection is based on BindingList I have created a binding source for the collection, and set the datasources of the bindingsource and datagridview. Everything works great, except I need to update properties on the custom object from background threads. when I do so, I get the following error : > BindingSource cannot be its own data source. Do not set the DataSource and DataMember properties to values that refere back to BindingSource I found the following post that seems to have my exact problem (and solution?) but I cannot quite figure it out. > <http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/3566f7c7-eb47-422e-ab09-9549a18da360/> I created and initialized the oper variables per the post in my business object, and then I put the two event functions into my collection class. This compiled correctly, but hangs without exception when run. I have seen many posts saying to use Invoke/Begin Invoke, but I am not calling any functions on the UI, just updating business objects, so I am not sure where I would put the invoke calls. One restriction : I want the business object to remain unaware of who is displaying it (as there are multiple consumers) so sending in GUI references into the business object so that I am later able to call invoke using those references is not an option.
I found this class in a forum that works. Just use this instead of BindingList ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Threading; namespace Utility { public class ThreadedBindingList<T> : BindingList<T> { SynchronizationContext ctx = SynchronizationContext.Current; protected override void OnAddingNew(AddingNewEventArgs e) { if (ctx == null) { BaseAddingNew(e); } else { ctx.Send(delegate { BaseAddingNew(e); }, null); } } void BaseAddingNew(AddingNewEventArgs e) { base.OnAddingNew(e); } protected override void OnListChanged(ListChangedEventArgs e) { // SynchronizationContext ctx = SynchronizationContext.Current; if (ctx == null) { BaseListChanged(e); } else { ctx.Send(delegate { BaseListChanged(e); }, null); } } void BaseListChanged(ListChangedEventArgs e) { base.OnListChanged(e); } } } ```
Since I took the time to format the sample for my needs I might as well post it here as a readable reference. Nothing changed except formatting. ``` using System.ComponentModel; using System.Threading; namespace Utility { public class ThreadedBindingList : BindingList { SynchronizationContext ctx = SynchronizationContext.Current; protected override void OnAddingNew(AddingNewEventArgs e) { if (ctx == null) { BaseAddingNew(e); } else { ctx.Send(delegate { BaseAddingNew(e); }, null); } } void BaseAddingNew(AddingNewEventArgs e) { base.OnAddingNew(e); } protected override void OnListChanged(ListChangedEventArgs e) { // SynchronizationContext ctx = SynchronizationContext.Current; if (ctx == null) { BaseListChanged(e); } else { ctx.Send(delegate { BaseListChanged(e); }, null); } } void BaseListChanged(ListChangedEventArgs e) { base.OnListChanged(e); } } } ```
How do you correctly update a databound datagridview from a background thread
[ "", "c#", "multithreading", "data-binding", "datagridview", "inotifypropertychanged", "" ]
I have a localization issue. One of my industrious coworkers has replaced all the strings throughout our application with constants that are contained in a dictionary. That dictionary gets various strings placed in it once the user selects a language (English by default, but target languages are German, Spanish, French, Portuguese, Mandarin, and Thai). For our test of this functionality, we wanted to change a button to include text which has a ñ character, which appears both in Spanish and in the Arial Unicode MS font (which we're using throughout the application). Problem is, the ñ is appearing as a square block, as if the program did not know how to display it. When I debug into that particular string being read from disk, the debugger reports that character as a square block as well. So where is the failure? I think it could be in a few places: 1) Notepad may not be unicode aware, so the ñ displayed there is not the same as what vs2008 expects, and so the program interprets the character as a square (EDIT: notepad shows the same characters as vs; ie, they both show the ñ. In the same place.). 2) vs2008 can't handle ñ. I find that very, very hard to believe. 3) The text is read in properly, but the default font for vs2008 can't display it, which is why the debugger shows a square. 4) The text is not read in properly, and I should use something other than a regular StreamReader to get strings. 5) The text is read in properly, but the default String class in C# doesn't handle ñ well. I find that very, very hard to believe. 6) The version of Arial Unicode MS I have doesn't have ñ, despite it being listed as one of the 50k characters by <http://www.fileinfo.info>. Anything else I could have left out? Thanks for any help!
I have a very short [guide to debugging Unicode problems](http://pobox.com/~skeet/csharp/debuggingunicode.html). It's targeted at fetching text from databases, but the same principles apply in general. The most important starting point IMO is to know what's actually in your string when it just shows a box. Dump the contents to the console, with code like this: ``` static void DumpString (string value) { foreach (char c in value) { Console.Write ("{0:x4} ", (int)c); } Console.WriteLine(); } ``` Then look up the character in the [code charts on unicode.org](http://www.unicode.org/charts/). I suspect you want U+00F1, but there may be another similar character with a different code point - I've been fooled by that before.
I would say that most certainly Notepad is the culprit. Notepad does not deal well with unicode characters. If you want to hand edit this file, use something like [Notepad++](http://notepad-plus.sourceforge.net/uk/site.htm) which can handle unicode, and make sure you save the file as UTF-8. You can probably just use VS to edit the file, and just forget about notepad or Notepad++ completely. .Net and Visual studio are actaully very good at handling accented characters. All strings are UTF-8 by default, so the problem almost certainly lies with Notepad.
Display ñ on a C# .NET application
[ "", "c#", "unicode", "localization", "character-encoding", "" ]
I have an enumeration: `ENUM( 'alpha', 'beta', 'gamma', 'delta', 'omega' )` If I sort my table by this column I get them in the correct order defined above. However, I can't find a way to select a subset of these, e.g. everything before delta. Using `WHERE status < 'delta'` only returns alpha and beta, not gamma. It seems MySQL uses a string comparison, not enum index comparison. I could use the index numbers - i.e. `WHERE status < 4` - but it's a bit of a code smell (magic numbers) and may break if I insert new values into the enumeration.
You're trying to use data-manipulation methods on metadata, and this is bound to be awkward. This is a good reason to replace the `ENUM` with a foreign key to a lookup table. Then you can use conventional data-manipulation techniques.
You can use `status+0` to return the index of the ENUM, starting from 1. Refer <http://serghei.net/docs/database/mysql/doc/E/N/ENUM.html>
Can I compare MySQL enums?
[ "", "sql", "mysql", "enums", "compare", "" ]
Suppose I have files `a.cpp` and `b.cpp` and I get warnings in `a.cpp` and an error in `b.cpp`. I fix the error in `b.cpp` and recompile -- since Visual Studio doesn't have to recompile `a.cpp`, it doesn't remind me of the warnings it found before. I'd like to somehow have the warnings persist; however, I **don't** want it to treat warnings as errors (I'd like it to still compile/run even with warnings). Is this possible?
Essentially, you're out of luck. The C++ compilation will discard all of the errors and warnings. Because it only recompiles .CPP files that have a missing .OBJ file (i.e. the ones that had errors and failed last time), you'll only see the errors. You have a few options. Off the top of my head: * Write a macro that responds to the build complete event. If it sees any warnings, it could delete the .OBJ file. The .CPP file would be compiled again next time. Unfortunately, this means that your program may not run without recompilation. * You could write a macro that works the other way: on build start, look to see if there are any warnings, and then delete the .OBJ file. * Write a VS addin that remembers warnings until the .CPP file is compiled again.
You could go into the project settings and set all warnings as errors in the C/C++ tab (category: General).
How to make warnings persist in visual studio
[ "", "c++", "visual-studio", "warnings", "" ]
How is it possible to programmatically select an item in a WPF `TreeView`? The `ItemsControl` model seems to prevent it.
It's a real pain for some strange reason, you have to use ContainerFromItem to get the container, then invoke the select method. ``` // selectedItemObject is not a TreeViewItem, but an item from the collection that // populated the TreeView. var tvi = treeView.ItemContainerGenerator.ContainerFromItem(selectedItemObject) as TreeViewItem; if (tvi != null) { tvi.IsSelected = true; } ``` There once was a blog entry on how to do it [here](http://askernest.com/archive/2008/01/23/how-to-programmatically-change-the-selecteditem-in-a-wpf-treeview.aspx), but the link is dead now.
For those who are still looking for the right solution to this problem here is the one below. I found this one in the comments to the Code Project article “WPF TreeView Selection” <http://www.codeproject.com/KB/WPF/TreeView_SelectionWPF.aspx> by DaWanderer. It was posted by Kenrae on Nov 25 2008. This worked great for me. Thanks Kenrae! ## Here is his post: Instead of walking the tree, have your own data object have the IsSelected property (and I recommend the IsExpanded property too). Define a style for the TreeViewItems of the tree using the ItemContainerStyle property on the TreeView that binds those properties from the TreeViewItem to your data objects. Something like this: ``` <Style x:Key="LibraryTreeViewItemStyle" TargetType="{x:Type TreeViewItem}"> <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" /> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" /> <Setter Property="FontWeight" Value="Normal" /> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="FontWeight" Value="Bold" /> </Trigger> </Style.Triggers> </Style> <TreeView ItemsSource="{Binding Path=YourCollection}" ItemContainerStyle="{StaticResource LibraryTreeViewItemStyle}" ItemTemplate={StaticResource YourHierarchicalDataTemplate}/> ```
How to programmatically select an item in a WPF TreeView?
[ "", "c#", ".net", "wpf", "treeview", "itemscontrol", "" ]
How would you implement a Plugin-system for your Java application? Is it possible to have an easy to use (for the developer) system which achieves the following: * Users put their plugins into a subdirectory of the app * The Plugin can provide a configuration screen * If you use a framework, is the license compatible with commercial developement?
First you need an interface that all plugins need to implement, e.g. ``` public interface Plugin { public void load(PluginConfiguration pluginConfiguration); public void run(); public void unload(); public JComponent getConfigurationPage(); } ``` Plugin authors should then bundle their plugins into JAR files. Your applications opens the JAR file and could then use an attribute from JAR manifest or the list of all files in the JAR file to find the class that implements your Plugin interface. Instantiate that class, the plugin is ready to go. Of course you may also want to implement some kind of sandboxing so that the plugin is restricted in what it can and can not do. I have created a small [test application](http://pterodactylus.net/download/security-test.tar.bz2) (and [blogged about it](http://blog.pterodactylus.net/2013/07/19/sandboxing/)) that consists of two plugins, one of which is denied access to local resources.
Use [OSGi](http://en.wikipedia.org/wiki/OSGi). It is the foundation of the Eclipse plug-in system. [Equinox](http://en.wikipedia.org/wiki/Equinox_OSGi) is Eclipse's implementation (licensed EPL) and [Felix](http://felix.apache.org/) is the Apache Project's implementation (licensed Apache Public License). Eclipse provides a concrete example that OSGi can cover the points you mentioned (or you could just build your application on top of [Eclipse RCP](http://wiki.eclipse.org/index.php/Rich_Client_Platform) if you want a full Eclipse/SWT/JFace stack).
Best way to build a Plugin system with Java
[ "", "java", "design-patterns", "plugins", "frameworks", "plugin-architecture", "" ]
I'm a student about to start my exam project, where I will be responsible for the server implementation of an online game targeting the flash player. I have a hard time to decide wether i should write my own lightweight server in Erlang or use the open source Red5. My experience is that java-developers tend to overcomplexify things making the APIs difficult to work with, is this true for Red5? And how does it perform under the heavy load that comes with synchronizing a game? Maybe my own Erlang server will be easier to work with and distribute on several machines? So the question is should i write my own Erlang flash server or use the existing Red5? Edit: I think i need to decide what my goals are: to just set up an online game or learn how to implement a multiuser server from scratch.
I'd say use Red5 if you are ok with programming java - it might feel trivial to implement your own server but I'd guess you probably will find out that there are some more things to it than you are thinking of now. However, if you want to program in erlang and think you'll have loads of fun developing your own server by all means go for it! Is also depends on the goal of your project - do you have to demonstrate you can get an online game going (go for Red5), or do you have to demonstrate you can program a distributed multiuser game server? (go for your own project progammed in Erlang) BTW: I'm using <http://www.smartfoxserver.com/> for one of my current projects
I think you need to estimate for yourself the effort for implementing your own, lightweight, server. Often ones own requirements are small and specific and implementing a server that meets them is the way to go. Also check out Blaze DS (Java flash server) and Juggernaut (ruby flash server). I think maybe Juggernaut is targeted for specific uses, beyond yours, but I'm not sure.
Should i write my own flash-server in Erlang or use Red5?
[ "", "java", "flash", "erlang", "red5", "online-game", "" ]
To be specific, I was trying this code: ``` package hello; public class Hello { Clock clock = new Clock(); public static void main(String args[]) { clock.sayTime(); } } ``` But it gave the error > Cannot access non-static field in static method main So I changed the declaration of `clock` to this: ``` static Clock clock = new Clock(); ``` And it worked. What does it mean to put that keyword before the declaration? What exactly will it do and/or restrict in terms of what can be done to that object?
`static` members belong to the class instead of a specific instance. It means that **only one instance of a `static` field exists**[1] even if you create a million instances of the class or you don't create any. It will be shared by all instances. Since `static` methods also do not belong to a specific instance, they can't refer to instance members. In the example given, `main` does not know which instance of the `Hello` class (and therefore which instance of the `Clock` class) it should refer to. `static` members can only refer to `static` members. Instance members can, of course access `static` members. *Side note:* Of course, `static` members can access instance members **through an object reference**. Example: ``` public class Example { private static boolean staticField; private boolean instanceField; public static void main(String[] args) { // a static method can access static fields staticField = true; // a static method can access instance fields through an object reference Example instance = new Example(); instance.instanceField = true; } ``` [1]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point.
It means that there is only one instance of "clock" in Hello, not one per each separate instance of the "Hello" class, or more-so, it means that there will be one commonly shared "clock" reference among all instances of the "Hello" class. So if you were to do a "new Hello" anywhere in your code: A- in the first scenario (before the change, without using "static"), it would make a new clock every time a "new Hello" is called, but B- in the second scenario (after the change, using "static"), every "new Hello" instance would still share and use the initial and same "clock" reference first created. Unless you needed "clock" somewhere outside of main, this would work just as well: ``` package hello; public class Hello { public static void main(String args[]) { Clock clock=new Clock(); clock.sayTime(); } } ```
What does the 'static' keyword do in a class?
[ "", "java", "static", "oop", "language-features", "restriction", "" ]
I have read that private variables in a base class are technically inherited by child classes, but are not accessible. If this is correct, why do we say they are inherited when presumably they can only be accessed by reflection?
Subclassing is about inheriting *implementation*; and fields are an implementation detail. The fields are indeed present, and are available via reflection. But ultimately, it is the base-classes job to manage the state of those fields via any public/protected/etc members. But ultimately - if a base-class declares a property (and field) for property `Foo`, then when you set that property the data has to go somewhere. The sub-class has to include all the fields from the base-class for it to make sense. This is also critical for field-based serialization frameworks (such as `BinaryFormatter`).
Private fields are inherited in the sense, that they take up space on the heap when allocated. However, the derived class cannot access them directly.
Are private static and instance variables inherited in C# and why?
[ "", "c#", "inheritance", "" ]
I would like to detect whether the OS I'm compiling on is Windows. Is there a simple macro I can check to verify that?
*[Edit: I assume you want to use compile-time macros to determine which environment you're on. Maybe you want to determine if you're running on Wine under Linux or something instead of Windows, but in general, your compiler targets a specific environment, and that is either Windows (DOS) or it isn't, but it's rarely (never?) both.]* Some compilers offer macros to indicate a Windows build environment. But these will vary from compiler to compiler, and even on the same compiler on Windows if the target environment is *not* exclusively windows. Usually it's `__WIN32__`, but not always. ``` #if defined (__WIN32__) // Windows stuff #endif ``` Sometimes it can be `_WIN32`, `__CYGWIN32__`, or possibly just the compiler indicator (`_MSC_VER`). If you know the environment you'll be building in (from the makefile) then you can usually pass in the `#define` on the command line, like "`g++ -D __WIN32__ yourfile.c`". [A little more info here](http://predef.sourceforge.net/)
There are a number of different ways to detect compilation, host, and runtime environments. All depending on exactly what you want to know. There are three broad types of environments: * **Build**: This is the environment in which the program is compiled. * **Host**: This is the environment in which the program is being run. * **Target**: In case of code-generation tools (such as compilers), this is where the generated code will run. If you are *cross-compiling*, the build and host environment can be completely different (this is common when building embedded applications, but not very common when building desktop/server apps), and you typically cannot run the compiled binary on the system used to compile it. Otherwise, the host environment must be compatible with the build environment: for example, building an application on XP which will run on Vista. C preprocessor macros can not be used to tell you the details of the host system (i.e. what you are running on); they can only tell you what the code was compiled for. In the windows case, the two most important macros are: * **\_WIN32** signifies that the Win32 API is available. It does **not** tell you which compiler you are using, in fact \_WIN32 is defined both when using Cygwin's GCC and MinGW's GCC. So, do not use \_WIN32 to figure out if you're being compiled with Visual Studio. * **`_MSC_VER`** tells you that you the the program is being compiled with Microsoft Visual C/C++. Well, almost. `_MSC_VER` is **also** defined when using Intel's C++ compiler which is intended to be a drop-in replacement for Visual C++. There are a bunch of other macros described in the Visual Studio documentation. If you want to know which exact version of Windows you are using, you'll have to use runtime functions such as GetVersion() (as described in other answers). You might get more specific answers if you told us exactly what you want to check for.
Are there any macros to determine if my code is being compiled to Windows?
[ "", "c++", "c", "operating-system", "c-preprocessor", "" ]
I need to work with array from several threads, so I use CRITICAL SECTION to give it an exclusive access to the data. Here is my template: ``` #include "stdafx.h" #ifndef SHAREDVECTOR_H #define SHAREDVECTOR_H #include <vector> #include <windows.h> template<class T> class SharedVector { std::vector<T> vect; CRITICAL_SECTION cs; SharedVector(const SharedVector<T>& rhs) {} public: SharedVector(); explicit SharedVector(const CRITICAL_SECTION& CS); void PushBack(const T& value); void PopBack(); unsigned int size() const; T& operator[](int index); virtual ~SharedVector(); }; template<class T> SharedVector<T>::SharedVector() { InitializeCriticalSection(&cs); } template<class T> SharedVector<T>::SharedVector(const CRITICAL_SECTION& r): cs(r) { InitializeCriticalSection(&cs); } template<class T> void SharedVector<T>::PushBack(const T& value) { EnterCriticalSection(&cs); vect.push_back(value); LeaveCriticalSection(&cs); } template<class T> void SharedVector<T>::PopBack() { EnterCriticalSection(&cs); vect.pop_back(); LeaveCriticalSection(&cs); } template<class T> unsigned int SharedVector<T>::size() const { EnterCriticalSection(&cs); unsigned int result = vect.size(); LeaveCriticalSection(&cs); return result; } template<class T> T& SharedVector<T>::operator[](int index) { EnterCriticalSection(&cs); T result = vect[index]; LeaveCriticalSection(&cs); return result; } template<class T> SharedVector<T>::~SharedVector() { DeleteCriticalSection(&cs); } ``` While compiling I have such a problem for calling `EnterCriticalSection(&cs)` and `LeaveCriticalSection(&cs)`: ``` 'EnterCriticalSection' : cannot convert parameter 1 from 'const CRITICAL_SECTION *' to 'LPCRITICAL_SECTION' ``` I do not know what is wrong. May be you can see. Just because I always used it this way and it was alright. `windows.h` is included
Just declare `cs` as: ``` mutable CRITICAL_SECTION cs; ``` or else remove the const clause on `size()` Entering a critical section modifies the `CRITICAL_SECTION`, and leaving modifies it again. Since entering and leaving a critical section doesn't make the `size()` method call logically non-`const`, I'd say leave it declared `const`, and make `cs` `mutable`. This is the type of situation `mutable` was introduced for. Also - take a look at [Martin York](https://stackoverflow.com/questions/384913/problems-using-entercriticalsection#385091)'s and [Joe Mucchiello](https://stackoverflow.com/questions/384913/problems-using-entercriticalsection#385091)'s suggestions - use RAII whenever possible to deal with any kind of resources that need to be cleaned up. This works just as well for critical sections as it does for pointers and file handles.
Also the code above is not Exception safe. There is no guarantee that push\_back() pop\_back() will not throw. If they do they will leave your critical section permanently locked. You should create a locker class that calls EnterCriticalSection() on construction and LeaveCriticalSection() on destruction. Also this makes your methods a lot easier to read. (see below) ``` class CriticalSectionLock { public: CriticalSectionLock(CRITICAL_SECTION& cs) : criticalSection(cs) { EnterCriticalSection(&criticalSection); } ~CriticalSectionLock() { LeaveCriticalSection(&criticalSection); } private: CRITICAL_SECTION& criticalSection; }; // Usage template unsigned int SharedVector::size() const { CriticalSectionLock lock(cs); return vect.size(); } ``` Another thing you should worry about. Is making sure that when you destroy the object you have ownership and that nobody else tries to take ownership during destruction. Hopefully your DestoryCriticalSection() takes care of this.
Problems using EnterCriticalSection
[ "", "c++", "winapi", "critical-section", "" ]
I want to know if the page is being accessed via http or https using JavaScript. Is there some sort of isSecure() method, or should I just parse it out of the URL somehow?
`location.protocol` should do it for you. (as in: ``` if (location.protocol === 'https:') { // page is secure } ``` )
You should be able to check `document.location.protocol` to see if it's "http:" or "https:"
How do I determine whether a page is secure via JavaScript?
[ "", "javascript", "https", "" ]
What is the equivalent of varchar(max) in Oracle? CLOB?
Varchars are limited to 4000 characters in Oracle. Other than that, you have to use a LONG or a CLOB. Prefer CLOBs. LONGs are the older equivalent. From [this Oracle documentation](http://www.cs.umbc.edu/help/oracle8/server.815/a68022/lob.htm): > **LOBs vs. LONG and LONG RAW** > > LOBs are different from the older LONG > and LONG RAW datatypes in many ways. > > * The maximum size of a LOB is 4 Gigabytes versus 2 Gigabytes for LONG > and LONG RAW. > * You can use random as well as sequential access methods on LOBs; you > can only use sequential access methods > on LONG and LONG RAW. > * LOBs (except NCLOBs) can be attributes of an object type that you > define. > * Tables can have multiple LOB columns, but can have only one LONG or > LONG RAW column. > > Migration of existing LONG and LONG > Raw attributes to LOBs is recommended > by Oracle. Oracle plans to end support > of LONG and LONG RAW in future > releases. See Oracle8 Migration for > more information on migration.
As I understand it, a VARCHAR(MAX) data type is a SQL Server 2005 specific way of specifying a text field that can either be small (up to 8000 characters in SQL Server) ***or*** big (up to 2GB in SQL Server). The database handles the change in storage *behind the scenes* as the content grows from the small range to the large range. There is no equivalent in Oracle. You either have a smallish bit of text in a VARCHAR2 - which is up to 32767 bytes in pl/sql and up to 4000 bytes in SQL (i.e. in a table definition) - or you have a potentially very big bit of text in a CLOB (which is a specialised BLOB).
What is the equivalent of varchar(max) in Oracle?
[ "", "sql", "sql-server", "oracle", "" ]
I need to batch create images with text. Requirements: 1. arbitrary size of bitmap 2. PNG format 3. transparent background 4. black text anti-aliased against transparency 5. adjustable character spacing 6. adjustable text position (x and y coordinates where text begins) 7. TrueType and/or Type1 support 8. Unix command line tool or Python library So far I've evaluated the following: * [Python Imaging Library](http://www.pythonware.com/library/pil/): fails 5. * [ImageMagick](http://www.imagemagick.org/) ("caption" option): hard to figure out 6. * [PyCairo](http://www.cairographics.org/documentation/pycairo/): fails 5. * [SVG](http://www.w3.org/Graphics/SVG/) + [ImageMagick convert](http://www.imagemagick.org/script/convert.php): most promising, although requires multiple tools The problem with PIL is that e.g. the default spacing for Verdana is way too sparse. I need the text to be a bit tighter, but there's no way to adjust it in PIL. In ImageMagick I haven't found an easy way to specify where in the image the text begins (I'm using -size WIDTHxHEIGHT and caption:'TEXT'). Adding a transparent border will move the text away from the corner it's achored to, but * image size needs to be adjusted accordingly since border adds to the extents * it's not possible to adjust horizontal and vertical offset independently Have I missed some obvious alternatives or failed to find necessary features from the above mentioned?
Here's the SVG + ImageMagick solution: Programmatically create SVG documents based on this template, replacing "TEXT HERE" with the desired text content: ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg version="1.0" width="152px" height="50px"> <text style="font-size: 22px; font-weight:bold; font-family: Verdana-Bold; letter-spacing: -1.3%;"> <tspan x="10" y="39">TEXT HERE</tspan> </text> </svg> ``` Convert the documents to background-transparent PNGs with ImageMagick's `convert`: ``` $ convert -background none input.svg output.png ```
(5) indeed looks tricky, short of inserting dummy narrow-spaces into the string (which will break kerning) or using something much higher-level like the SVG or HTML/CSS renderer. However, if you don't mind getting your hands dirty, it looks quite easy to hack PIL's freetype renderer into adding horizontal space. See [\_imagingft.c](http://svn.effbot.org/public/pil/_imagingft.c); after the following code in both font\_getsize and font\_render: ``` if (kerning && last_index && index) { FT_Vector delta; FT_Get_Kerning(self->face, last_index, index, ft_kerning_default, &delta); x += delta.x >> 6; } ``` Add: ``` if (last_index && index) { x += tracking; } ``` Try it with a plain integer for tracking (probably quite large judging by that '>>6') first; compile and see if it works. The next step would be to get the tracking value into the C function from Python, for which you would have to change the ParseTuple call in font\_render to: ``` long tracking; if (!PyArg_ParseTuple(args, "Ol|il:render", &string, &id, &mask, &tracking)) return NULL; ``` And in font\_getsize: ``` long tracking; if (!PyArg_ParseTuple(args, "O|l:getsize", &string, &tracking)) return NULL; ``` Then look at what Python interface you want. This is a trivial but quite tedious case of adding the extra 'tracking' argument through each level of the interface, for example: ``` def truetype(filename, size, index=0, encoding="", tracking= 0): # added optional tracking "Load a truetype font file." try: return FreeTypeFont(filename, size, index, encoding, tracking) # added tracking ... class FreeTypeFont: "FreeType font wrapper (requires _imagingft service)" def __init__(self, file, size, index=0, encoding="", tracking= 0): # added tracking import _imagingft self.font = _imagingft.getfont(file, size, index, encoding) self.tracking= tracking # add this line ... def getmask2(self, text, mode="", fill=Image.core.fill): size, offset = self.font.getsize(text, self.tracking) # use tracking im = fill("L", size, 0) self.font.render(text, im.id, mode=="1", self.tracking) # use tracking return im, offset ``` I haven't tested any of this! If it works, might be worth submitting as a patch.
Tools for creating text as bitmaps (anti-aliased text, custom spacing, transparent background)
[ "", "python", "fonts", "bitmap", "spacing", "unix", "" ]
So far I've found it impossible to produce usable tracebacks when Mako templates aren't coded correctly. Is there any way to debug templates besides iterating for every line of code?
Mako actually provides a [VERY nice way to track down errors in a template](http://docs.makotemplates.org/en/latest/usage.html#handling-exceptions): ``` from mako import exceptions try: template = lookup.get_template(uri) print template.render() except: print exceptions.html_error_template().render() ```
Looking at the [Flask-Mako](http://pythonhosted.org/Flask-Mako/) source, I found an undocumented configuration parameter called `MAKO_TRANSLATE_EXCEPTIONS`. Set this to `False` in your Flask app config and you'll get nice exceptions bubbling up from the template. This accomplishes the same thing as @Mariano suggested, without needing to edit the source. Apparently, this parameter was added after Mariano's answer.
How do you debug Mako templates?
[ "", "python", "debugging", "templates", "jinja2", "mako", "" ]
Is there any advantage to writing a PHP conditional like this: ``` if ($variable != NULL) { ``` versus ``` if (!empty($variable)) { ``` versus ``` if ($variable) { ``` Aren't they all same thing? It seems like the last is always the simplest if you are just trying to tell whether the variable exists or not. Thanks for helping me understand the difference here. I missed the first day of PHP 101.
I agree with Sean but I'll outline what each does in plain English: ``` if ($variable != NULL) { ``` `$variable` will be `NULL` if it hasn't been set. This is practically the same as `isset` and the same as the variable being undefined. ``` if (!empty($variable)) { ``` Generally, this checks whether `$variable` as a string (`(string) $variable`) has a `strlen` of 0. However `true` will make it return `false`, as will integers that aren't 0 and empty arrays. For some reason (which I believe to be wrong) `$variable = '0';` will return `true`. ``` if ($variable) { ``` This true/false check acts like `(boolean) $variable` - basically whether the variable returns true when converted to a boolean. One way to think about it is that it acts the same as empty, except returns the opposite value. For more information on what I mean by `(boolean) $variable` (type casting/juggling) see this [manual page](http://de3.php.net/manual/en/language.types.type-juggling.php). (PHP devs: this is mainly by memory, if I'm wrong here please correct me!)
Check out [this table](http://de3.php.net/types.comparisons) to get the skinny on PHP comparison operators. There's a number of subtle differences between false, 0, "", NULL and variables that are simply undefined.
Are these PHP conditionals the same or does one have an advantage
[ "", "php", "variables", "conditional-statements", "" ]
It seems like my code works to check for null if I do ``` if ($tx) ``` or ``` if (isset($tx)) ``` why would I do the second one when it's harder to write?
I want to point out that everyone's reponse I've read here should have one caveat added: **"isset() will return FALSE if testing a variable that has been set to NULL"** ([php.net/isset](http://php.net/isset)). This means that in *some* cases, like checking for a GET or POST parameter, using isset() is enough to tell if the variable is set (because it will either be a string, or it won't be set). However, in cases where NULL is a possible value for a variable, which is fairly common when you get into objects and more complex applications, isset() leaves you high and dry. For example (tested with PHP 5.2.6 with Suhosin-Patch 0.9.6.2 (cli) (built: Aug 17 2008 09:05:31)): ``` <?php $a = ''; $b = NULL; var_dump(isset($a)); var_dump(isset($b)); var_dump(isset($c)); ``` outputs: ``` bool(true) bool(false) bool(false) ``` Thanks, PHP!
``` if ($tx) ``` This code will evaluate to false for **any** of the following conditions: ``` unset($tx); // not set, will also produce E_WARNING $tx = null; $tx = 0; $tx = '0'; $tx = false; $tx = array(); ``` The code below will only evaluate to false under the following conditions: ``` if (isset($tx)) // False under following conditions: unset($tx); // not set, no warning produced $tx = null; ``` For some people, typing is very important. However, PHP by design is very flexible with variable types. That is why the [Variable Handling Functions](http://us.php.net/manual/en/ref.var.php) have been created.
Weak typing in PHP: why use isset at all?
[ "", "php", "syntax", "" ]
Simple idea: I have two images that I want to merge, one is 500x500 that is transparent in the middle the other one is 150x150. Basic idea is this: Create an empty canvas that is 500x500, position the 150x150 image in the middle of the empty canvas and then copy the 500x500 image over so that the transparent middle of it allows the 150x150 to shine through. I know how to do it in Java, PHP and Python... I just don't have any idea what objects/classes to use in C#, a quick example of copying an images into another would suffice.
basically i use this in one of our apps: we want to overlay a playicon over a frame of a video: ``` Image playbutton; try { playbutton = Image.FromFile(/*somekindofpath*/); } catch (Exception ex) { return; } Image frame; try { frame = Image.FromFile(/*somekindofpath*/); } catch (Exception ex) { return; } using (frame) { using (var bitmap = new Bitmap(width, height)) { using (var canvas = Graphics.FromImage(bitmap)) { canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; canvas.DrawImage(frame, new Rectangle(0, 0, width, height), new Rectangle(0, 0, frame.Width, frame.Height), GraphicsUnit.Pixel); canvas.DrawImage(playbutton, (bitmap.Width / 2) - (playbutton.Width / 2), (bitmap.Height / 2) - (playbutton.Height / 2)); canvas.Save(); } try { bitmap.Save(/*somekindofpath*/, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception ex) { } } } ```
This will add an image to another. ``` using (Graphics grfx = Graphics.FromImage(image)) { grfx.DrawImage(newImage, x, y) } ``` Graphics is in the namespace `System.Drawing`
Merging two images in C#/.NET
[ "", "c#", ".net", "image", "" ]
A while back, online apps used to say, "do not click submit more than once." That's gone now, right? How do you guard against that in, say, PHP? One solution I'm using involves putting a variable in the Session, so you cannot submit to a page more than once every 10 seconds. That way the database work will have completed so the normal checks can take place. Obviously, this feels like a hack and probably is. **Edit:** Thanks everybody for the Javascript solution. That's fine, but it is a bit of work. 1) It's an input type=image and 2) The submit has to keep firing until the [Spry stuff](http://labs.adobe.com/technologies/spry/) says it's okay. This edit is just me complaining, basically, since I imagine that after looking at the Spry stuff I'll be able to figure it out. **Edit:** Not that anyone will be integrating with the Spry stuff, but here's my final code using Prototype for the document.getElementByid. Comments welcome! ``` function onSubmitClick() { var allValid = true; var queue = Spry.Widget.Form.onSubmitWidgetQueue; for (var i=0;i<queue.length; i++) { if (!queue[i].validate()) { allValid = false; break; } } if (allValid) { $("theSubmitButton").disabled = true; $("form").submit(); } } ``` For some reason, the second form submit was necessary...
You should do both client- and server-side protections. **Client side** - disable button e.g. by jquery as cletus has described. **Server side** - put a token in the form. If there are two submissions with the same token, ignore the latter. Using this approach, you are protected against [CSRF](http://en.wikipedia.org/wiki/CSRF).
This is an excellent example of what jQuery is useful for (you can do it in any Javascript though). Add this code: ``` $("form").submit(function() { $(":submit",this).attr("disabled", "disabled"); }); ``` And it disables submit buttons once clicked once.
Avoid Race Conditions in PHP on Submit: Please do not click submit more than once!
[ "", "php", "" ]
Due to lack of capital and time we are having to do our game in 2D even though me (the developer) would prefer if it was done in 3D. I would hate for users to join the game, only to think the graphics look bad and leave. Though I suppose we just have to try and do our best. That being said, I would like to develop the game in such a way that, should the time come, we can port to 3D as easily as possible. I know of games that had to rewrite the entire thing from scratch. I'd hate to do that, so I'd like some tips / guidelines to use when programming the game so that, when we move to 3D, it will be as simple as changing the code of 1-5 graphics rendering classes (or close) and the 3D graphics would run. P.S It is a multiplayer roleplaying game (*Not* an MMORPG, much smaller in scope for now)
> Due to lack of capital and time we are > having to do our game in 2D even > though me (the developer) would prefer > if it was done in 3D. I would hate for > users to join the game, only to think > the graphics look bad and leave. > Though I suppose we just have to try > and do our best. I don't think everything has to be 3D to look good. Well done 2D can look many times better than some standard 3D graphics. To have great 3D graphics you have to invest some serious effort. If your budget doesn't allow for this, I would rather try to put a lot effort into gameplay development. Just think of (somewhat dated) Diablo II which is not 3D but still has some nice and good looking graphics. It is certainly possible to build an architecture which could make it easier to change the graphical representation, but I think it will almost never be as simple as you described. Of course, if you just want 3D for the sake of 3D it could be done (instead of bitmaps you now render 3D models) but this is somewhat pointless. If you want to use 3D the player should be able to make use of it (e.g. by moving the camera, having more degrees of freedom, ...) but this would have to be considered in the whole design of the game and thus seriously affects gameplay.
The simplest way to achieve this is to write the game in 3D, and render the views using a 3d to 2d projection, e.g. in plan or elevation. If the games internal mechanics are 2D and you try to move to a true 3d frame, you would probably better off with a rewrite. It also depends to an extent on what you mean by 3D, and whether you have an effective mapping option. For example, Microsofts Age of Empires is rendered in 3D, but would work perfectly well as a 2D plan. A first person shooter such as Half Life or Quake on the other hand would not.
Porting easily from 2D to 3D on a Java game
[ "", "java", "3d", "2d", "" ]
``` Response.Redirect(string.Format("myprofile.aspx?uid={0}&result=saved#main",user.UserID)); ``` said code translates to **IE7** - `myprofile.aspx?uid=933fdf8e-1be0-4bc2-a269-ac0b01ba4755&result=saved` **FF**- `myprofile.aspx?uid=933fdf8e-1be0-4bc2-a269-ac0b01ba4755&result=saved#main` why does IE7 drop my anchor? edit: I should mention I am using this in conjunction with jQuery UI's tab control. I want the postback to tab into a specific tab.
It would be quite the hack, but if IE isn't behaving, you could do this. pass a param as well, e.g. ``` uid=933fdf8e-1be0-4bc2-a269-ac0b01ba4755&result=saved&hash=main#main ``` Then on your page (before the body close tag, or as an onload event), only for IE, extract the parameter if present and set the hash manually. ``` <!--[if IE]> <script> if(document.location.href.indexOf('&hash=') != -1){ //extract value from url... document.location.hash = extractedValue; } </script> <![endif]--> ```
Maybe it is a regression issue from IE6? Did you try [working around it](http://blogs.vertigo.com/personal/tomphan/Blog/Lists/Posts/Post.aspx?ID=6) by prepending it with an &?
Response.Redirect with # anchor, does not work in IE7
[ "", "c#", "asp.net", "jquery-ui", "internet-explorer-7", "jquery-ui-tabs", "" ]
I am tying to make comments in a blog engine XSS-safe. Tried a lot of different approaches but find it very difficult. When I am displaying the comments I am first using [Microsoft AntiXss 3.0](http://www.codeplex.com/AntiXSS) to html encode the whole thing. Then I am trying to html decode the safe tags using a whitelist approach. Been looking at [Steve Downing's example](http://refactormycode.com/codes/333-sanitize-html#refactor_44440) in Atwood's "Sanitize HTML" thread at refactormycode. My problem is that the AntiXss library encodes the values to &#DECIMAL; notation and I don't know how to rewrite Steve's example, since my regex knowledge is limited. I tried the following code where I simply replaced entities to decimal form but it does not work properly. ``` &lt; with &#60; &gt; with &#62; ``` My rewrite: ``` class HtmlSanitizer { /// <summary> /// A regex that matches things that look like a HTML tag after HtmlEncoding. Splits the input so we can get discrete /// chunks that start with &lt; and ends with either end of line or &gt; /// </summary> private static Regex _tags = new Regex("&#60;(?!&#62;).+?(&#62;|$)", RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled); /// <summary> /// A regex that will match tags on the whitelist, so we can run them through /// HttpUtility.HtmlDecode /// FIXME - Could be improved, since this might decode &gt; etc in the middle of /// an a/link tag (i.e. in the text in between the opening and closing tag) /// </summary> private static Regex _whitelist = new Regex(@" ^&#60;/?(a|b(lockquote)?|code|em|h(1|2|3)|i|li|ol|p(re)?|s(ub|up|trong|trike)?|ul)&#62;$ |^&#60;(b|h)r\s?/?&#62;$ |^&#60;a(?!&#62;).+?&#62;$ |^&#60;img(?!&#62;).+?/?&#62;$", RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture | RegexOptions.Compiled); /// <summary> /// HtmlDecode any potentially safe HTML tags from the provided HtmlEncoded HTML input using /// a whitelist based approach, leaving the dangerous tags Encoded HTML tags /// </summary> public static string Sanitize(string html) { string tagname = ""; Match tag; MatchCollection tags = _tags.Matches(html); string safeHtml = ""; // iterate through all HTML tags in the input for (int i = tags.Count - 1; i > -1; i--) { tag = tags[i]; tagname = tag.Value.ToLowerInvariant(); if (_whitelist.IsMatch(tagname)) { // If we find a tag on the whitelist, run it through // HtmlDecode, and re-insert it into the text safeHtml = HttpUtility.HtmlDecode(tag.Value); html = html.Remove(tag.Index, tag.Length); html = html.Insert(tag.Index, safeHtml); } } return html; } } ``` My input testing html is: ``` <p><script language="javascript">alert('XSS')</script><b>bold should work</b></p> ``` After AntiXss it turns into: ``` &#60;p&#62;&#60;script language&#61;&#34;javascript&#34;&#62;alert&#40;&#39;XSS&#39;&#41;&#60;&#47;script&#62;&#60;b&#62;bold should work&#60;&#47;b&#62;&#60;&#47;p&#62; ``` When I run the version of Sanitize(string html) above it gives me: ``` <p><script language="javascript">alert&#40;&#39;XSS&#39;&#41;</script><b>bold should work</b></p> ``` The regex is matching script from the whitelist which I don't want. Any help with this would be highly appreciated.
Your problem is that C# is missinterpretating your regexp. You need to escape the #-sign. Without the escape it matches too much. ``` private static Regex _whitelist = new Regex(@" ^&\#60;(&\#47;)? (a|b(lockquote)?|code|em|h(1|2|3)|i|li|ol|p(re)?|s(ub|up|trong|trike)?|ul)&\#62;$ |^&\#60;(b|h)r\s?(&\#47;)?&\#62;$ |^&\#60;a(?!&\#62;).+?&\#62;$ |^&\#60;img(?!&\#62;).+?(&\#47;)?&\#62;$", RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture RegexOptions.Compiled ); ``` Update 2: You might be interested in this [xss](http://ha.ckers.org/xss.html) and [regexp](http://regexpal.com/) site.
Have you considered using Markdown or VBCode or some similar approaches for the users to mark their comments up with? Then you can disallow all HTML. If you must allow HTML then I would consider using a HTML parser (in the spirit of HTMLTidy) and do the white-listing there.
Sanitize html encoded text (#decimal notation) from AntiXSS v3 output
[ "", "c#", "html", "regex", "xss", "" ]
The following code prints 20, i.e. sizeof(z) is 20. ``` #include <iostream.h> class Base { public: int a; }; class X:virtual public Base { public: int x; }; class Y:virtual public Base { public: int y; }; class Z:public X,public Y { }; int main() { Z z; cout << sizeof(z) <<endl; } ``` Whereas if I don't use virtual base classes here, i.e. for the following code : sizeof(z) is 16. ``` #include <iostream.h> class Base { public: int a; }; class X:public Base { public: int x; }; class Y:public Base { public: int y; }; class Z:public X,public Y { }; int main() { Z z; cout << sizeof(z) <<endl; } ``` Why is sizeof(z) more(20) in the first case? Shouldn't it be 12, since Base will be included only once in Z?
Let's look at the class layout of the two cases. Without the virtual, you have two base classes ("X" and "Y") with an integer each, and each of those classes have integrated into them a "Base" base class which also has an integer. That is 4 integers, 32-bits each, totalling your 16 bytes. ``` Offset Size Type Scope Name 0 4 int Base a 4 4 int X x 8 4 int Base a 12 4 int Y y 16 size (Z members would come at the end) ``` (Edit: I've written a program in DJGPP to get the layout and tweaked the table to account for it.) Now let's talk about virtual base classes: they replace the actual instance of the class with a pointer to a shared instance. Your "Z" class has only one "Base" class, and both instances of "X" and "Y" point to it. Therefore, you have integers in X, Y, and Z, but you only have the one Z. That means you have three integers, or 12 bytes. But X and Y also have a pointer to the shared Z (otherwise they wouldn't know where to find it). On a 32-bit machine two pointers will add an additional 8 bytes. This totals the 20 that you see. The memory layout might look something like this (I haven't verified it... the ARM has an example where the ordering is X, Y, Z, then Base): ``` Offset Size Type Scope Name Value (sort of) 0 4 Base offset X ? 16 (or ptr to vtable) 4 4 int X x 8 4 Base offset Y ? 16 (or ptr to vtable) 12 4 int Y y 16 4 int Base a 20 size (Z members would come before the Base) ``` So the memory difference is a combination of two things: one less integer and two more pointers. Contrary to another answer, I don't believe vtables pay any (edit) direct (/edit) roll in this, since there are no virtual functions. Edit: ppinsider has provided more information on the gcc case, in which he demonstrates that gcc implements the pointer to the virtual base class by making use of an otherwise empty vtable (i.e., no virtual functions). That way, if there were virtual functions, it wouldn't require an additional pointer in the class instance, requiring more memory. I suspect the downside is an additional indirection to get to the base class. We might expect all compilers to do this, but perhaps not. The [ARM](http://www.research.att.com/~bs/arm.html) page 225 discusses virtual base classes without mentioning vtables. Page 235 specifically addresses "virtual base classes with virtual functions" and has a diagram indicating a memory layout where there are pointers from the X and Y parts that are separate from the pointers to the vtable. I would advise anyone not to take for granted that the pointer to Base will be implemented in terms of a table.
Mark Santesson's answer is pretty much on the money, but the assertation that there are no vtables is incorrect. You can use g++ -fdump-class-hierarchy to show what's going on. Here's the no virtuals case: ``` Class Base size=4 align=4 base size=4 base align=4 Base (0x19a8400) 0 Class X size=8 align=4 base size=8 base align=4 X (0x19a8440) 0 Base (0x19a8480) 0 Class Y size=8 align=4 base size=8 base align=4 Y (0x19a84c0) 0 Base (0x19a8500) 0 Class Z size=16 align=4 base size=16 base align=4 Z (0x19b1800) 0 X (0x19a8540) 0 Base (0x19a8580) 0 Y (0x19a85c0) 8 Base (0x19a8600) 8 ``` Pay particular attention to the "base size" argument. Now the virtuals case, and showing only Z: ``` Class Z size=20 align=4 base size=16 base align=4 Z (0x19b3000) 0 vptridx=0u vptr=((& Z::_ZTV1Z) + 12u) X (0x19a8840) 0 primary-for Z (0x19b3000) subvttidx=4u Base (0x19a8880) 16 virtual vbaseoffset=-0x0000000000000000c Y (0x19a88c0) 8 subvttidx=8u vptridx=12u vptr=((& Z::_ZTV1Z) + 24u) Base (0x19a8880) alternative-path ``` Note the "base size" is the same, but the "size" is one pointer more, and note that there is now a vtable pointer! This in turn contains the construction vtables for the parent classes, and all the inter-class magic (construction vtables, and virtual table table (VTT)), as described here: <http://www.cse.wustl.edu/~mdeters/seminar/fall2005/mi.html> Note that the actual function dispatch vtable will be empty.
Question on multiple inheritance, virtual base classes, and object size in C++
[ "", "c++", "multiple-inheritance", "sizeof", "" ]
I wonder if this is even possible. I have an application that adds a context menu when you right click a file. It all works fine but here is what I'd like to do: If the file is a PSD then I want the program to extract the image. Is this possible to do without having Photoshop installed? Basically I want the user to right click and click "image" which would save a .jpg of the file for them. edit: will be using c# Thanks
For people who are reading this now: the link from accepted answer doesn't seem to work anymore (at least for me). Would add a comment there, but not allowed to comment yet - hence I'm adding a new answer. The working link where you can find the psdplugin code for Paint.Net: <https://github.com/PsdPlugin/PsdPlugin>
The [ImageMagick](http://www.imagemagick.org) libraries (which provide [bindings for C#](http://midimick.com/magicknet/)) also support the PSD format. They might be easier to get started with than getting into the Paint.NET code and also come with a quite free (BSD-like) license. A simple sample (found at [http://midimick.com/magicknet/magickDoc.html)](http://midimick.com/magicknet/magickDoc.html) using MagickNet would look like this: ``` using System; static void Main(string[] args) { MagickNet.Magick.Init(); MagicNet.Image img = new MagicNet.Image("file.psd"); img.Resize(System.Drawing.Size(100,100)); img.Write("newFile.png"); MagickNet.Magick.Term(); } ``` Note: MagickNet has moved to <http://www.codeproject.com/KB/dotnet/ImageMagick_in_VBNET.aspx>
Reading PSD file format
[ "", "c#", "photoshop", "file-format", "" ]
I have the following SQL Statement. I need to select the latest record for each System.Id using the System.RevisedDate ``` SELECT [System.Id],[System.RevisedDate], [System.Title], [System.State], [System.Reason], [System.CreatedDate], [System.WorkItemType], [System.TeamProject], [Microsoft.VSTS.Scheduling.RemainingWork], [Microsoft.VSTS.Scheduling.CompletedWork], [Microsoft.VSTS.CMMI.Estimate] FROM WorkItems WHERE ([System.WorkItemType] = 'Change Request') AND ([System.CreatedDate] >= '09/30/2008') AND ([System.TeamProject] NOT LIKE '%Deleted%') AND ([System.TeamProject] NOT LIKE '%Sandbox%') ``` Can you please help?
Try this: ``` SELECT * FROM WorkItems w JOIN ( SELECT [System.Id],MAX([System.RevisedDate]) FROM WorkItems WHERE ([System.WorkItemType] = 'Change Request') AND ([System.CreatedDate] >= '09/30/2008') AND ([System.TeamProject] NOT LIKE '%Deleted%') AND ([System.TeamProject] NOT LIKE '%Sandbox%') GROUP BY {System.Id] ) x ON w.[System.Id] = x.[System.Id] AND w.[System.DateRevised] = x.[System.DateRevised] ```
In general it should go some thing like ``` SELECT ID,DATE_FIELD,FIELD1,FIELD2 FROM TBL1 AS A WHERE DATE_FIELD >= ALL ( SELECT DATE_FIELD FROM TBL1 AS B WHERE A.ID = B.ID ) ```
SQL Distinct by ID and Latest By Date
[ "", "sql", "tfs", "reporting-services", "" ]