Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
How can I make the following one liner print every file through Python? ``` python -c "import sys;print '>>',sys.argv[1:]" | dir *.* ``` Specifically would like to know how to pipe into a python -c. DOS or Cygwin responses accepted.
You can read data piped **into** a Python script by reading sys.stdin. For example: ``` ls -al | python -c "import sys; print sys.stdin.readlines()" ``` It is not entirely clear what you want to do (maybe I am stupid). The confusion comes from your example which is piping data out of a python script.
``` python -c "import os; print os.listdir('.')" ``` If you want to apply some formatting like you have in your question, ``` python -c "import os; print '\n'.join(['>>%s' % x for x in os.listdir('.')])" ``` If you want to use a pipe, use `xargs`: ``` ls | xargs python -c "import sys; print '>>', sys.argv[1:]" ``` or backticks: ``` python -c "import sys; print '>>', sys.argv[1:]" `ls` ```
Python one-liner to print every file in the current directory
[ "", "python", "cygwin", "cmd", "pipe", "" ]
I've the following class in *XmlSer.dll* ``` namespace xmlser { public class XmlSer { public Type test(string s) { return Type.GetType(s); } //...other code } } ``` and the following code in *MyApp.exe*, which links *XmlSer.dll* as a reference ``` namespace MyApp { public class TestClass { public int f1 = 1; public float f2 = 2.34f; public double f3 = 3.14; public string f4 = "ciao"; } class MainClass { public static void Main(string[] args) { TestClass tc = new TestClass(); XmlSer ser = new XmlSer(); Console.WriteLine(ser.test("MyApp.TestClass")!=null); } } ``` Running MyApp.exe I get *false*, that means that *ser* instance of *XmlSer* is not able to get the type of *Testclass* (result is *null*). Putting *XmlSer* class directly in *MyApp.exe* code I correctly get the type of *TestClass*. Checking on the net i've found that the problem is related to the assemblies. That means, the assembly of .exe is not visible to the *XmlSer.test* method so it can't resolve the type of *TestClass*. How can I resolve the problem maintaing *XmlSer* in *XmlSer.dll* and *MyApp.MainClass* in *MyApp.exe* ? Thanks. Alessandro
Since the two are not in the same assembly, you probably need to include the assembly name in the type string: ``` Console.WriteLine(ser.test("MyApp.TestClass, MyApp")!=null); ``` --- If all you want to do is serialize arbitrary objects, you can do the following: ``` public static class Serialization { public static void Serialize(object o, Stream output) { var serializer = new XmlSerializer(o.GetType()); serializer.Serialize(output, o); } } ```
Not sure, but maybe try ser.Test("MyApp.TestClass, MyApp")? EDIT: Obviously MyApp not XmlSer
c# : Type.GetType called from a dll on exe type string
[ "", "c#", ".net", "reflection", "" ]
I'm wondering if there are any reasons (apart from tidying up source code) why developers use the "Remove Unused `Usings`" feature in Visual Studio 2008?
There are a few reasons you'd want to take them out. * It's pointless. They add no value. * It's confusing. What is being used from that namespace? * If you don't, then you'll gradually accumulate pointless `using` statements as your code changes over time. * Static analysis is slower. * Code compilation is slower. On the other hand, there aren't many reasons to leave them in. I suppose you save yourself the effort of having to delete them. But if you're that lazy, you've got bigger problems!
I would say quite the contrary - it's extremely helpful to remove unneeded, unnecessary using statements. Imagine you have to go back to your code in 3, 6, 9 months - or someone else has to take over your code and maintain it. If you have a huge long laundry list of using statement that aren't really needed, looking at the code could be quite confusing. Why is that using in there, if nothing is used from that namespace?? I guess in terms of long-term maintainability in a professional environment, I'd strongly suggest to keep your code as clean as possible - and that includes dumping unnecessary stuff from it. Less clutter equals less confusion and thus higher maintainability. Marc
Why remove unused using directives in C#?
[ "", "c#", ".net", "using", "" ]
Using the tiny Diggit/Blog feature of StackOverflow described [here](https://stackoverflow.com/about): I would like to post the following Google tech talk video I have just saw and that I found quite interesting. I have always had problems understanding javascript "nature". Here, the [JavaScript good parts](http://www.youtube.com/watch?v=hQVTIJBZook) are described by Douglas Crockford I hope you find this link useful. Now the question part: What are your complaints about javascript? Do you use an IDE for javascript editting? Do you think this video helps to understand the "good parts"?
JavaScript: the bad parts. 1. The biggest mistake is late error detection. JavaScript will happily let you access a non-existant object member, or pass the wrong number of arguments to a function, and fill the gap with ‘undefined’ objects, which, unless you deliberately check for them (which is impractical to keep doing everywhere), will cause an exception or generate an unexpected value later on. Possibly much later on, resulting in subtle and difficult-to-debug errors appearing nowhere near the actual problem code. These conditions should have generated exceptions, except that JS didn't originally have exceptions to raise. ‘undefined’ was a quick and dirty hack we're now stuck with. 2. Undeclared variables defaulting to global scope. This is almost never what you want and can cause subtle and difficult-to-debug errors when two functions both forget ‘var’ and start diddling the same global. 3. The model of constructor functions is weird even for a prototype-based-OO language and confuses even experienced users. Forgetting ‘new’ can result in subtle and difficult-to-debug errors. Whilst you *can* make a passable class/instance system out of it, there's no standard, and most of the class systems proposed in the early tutorials that people are still using are both desperately inadequate, and obfuscate what JavaScript is actually doing. 4. Lack of bound methods. It's utterly unintuitive that accessing “object.method” when calling it makes a magic connection to ‘object’ in ‘this’, but passing “object.method” as a reference loses the connection; no other language works this way. When this happens, ‘this’ is set to an unexpected value, but it's not ‘undefined’ or something else that would raise an exception. Instead, all the property access ends up on ‘window’, causing subtle and difficult-to-debug errors later. 5. There is no integer type. Number looks like one but breaks down in various ways (eg. n+1==n for high enough n). Any time a NaN or Infinity sneaks in (quite unexpectedly if you think you are dealing with integers) you won't find out immediately; instead there will be subtle and difficult-to-debug errors down the line. 6. There is no associative array type. Object looks like one but breaks down under various unexpected keys. Arrays aren't pure lists. Any time you ever use ‘for...in’, you have probably fallen into a trap, and will experience... yes, subtle and difficult-to-debug errors. 7. Generally poor string handling, for a scripting language at least. String.split(, limit) and String.replace() don't do what you might think, causing... you know. The results of toString() are generally poor and not useful for debugging. Meanwhile we are stuck with a load of rubbish Netscape thought might be useful, like String.prototype.blink(), and the perpetually broken escape(). Yay. 8. And *then* there's all the browser differences (IE is still missing a lot of essential methods on the basic objects), and the DOM... 9. And finally, even when an exception does occur, it is hidden away from view, so the author won't even realise something is wrong. The result is that most sites are chock full of errors; turn on full JavaScript error reporting in IE and the result is unusable. It scares me to think a new generation of programmers are learning this tosh as a first language. What's worse, most of the tutorial material they're learning from (“My fiRST AEWsome R0LL0VERZ!”) invariably encourages the worst possible practice. ‘javascript:’ URLs, ‘eval()’ for everything, browser-specific DOM access... oy.
**The hard part about javascript**, in my opinion, is: 1. Cross browser development/debugging issues 2. Cross browser dom/model issues (event bubbling, etc...) 3. Lack of "classes" (subjective) 4. Lack of good solid debugging support in browsers Firebug helps a lot for FireFox, but I have not found anything that good for IE - and the mere fact that one has to is difficult. On the bright side, if you build a script from the ground up and understand each step, it can be really enjoyable and powerful.
Understanding JavaScript - Resource
[ "", "javascript", "video", "" ]
This is not working: ``` byte[] tgtBytes = ... Response.Write(tgtBytes); ```
You're probably looking for: ``` Response.BinaryWrite(tgtBytes); ``` MSDN documentation [here](http://msdn.microsoft.com/en-us/library/ms524318.aspx).
``` Response.OutputStream.Write(tgtBytes, 0, tgtBytes.Length); ```
how to response.write bytearray?
[ "", "c#", "asp.net", "" ]
``` <table> <tr id="parent_1"> <td>Parent 1</td> </tr> <tr class="child"> <td>Child 1</td> </tr> <tr class="child"> <td>Child 2</td> </tr> ... <tr id="parent_2"> <td>Parent2</td> </tr> ... </table> ``` How can I find the number of child rows between parent\_1 and parent\_2 using jQuery? Edit: Sorry, didn't make it clear that this is just an example, the table could contain any number of parent rows, and any number of child rows
This will get you what you want ``` var childCount = ($('#parent_2').get(0).rowIndex - $('#parent_1').get(0).rowIndex) - 1; ```
This: ``` $('#parent_1 ~ .child:not(#parent_2 ~ *)').size() ``` Translation: match all elements of class `child` that are a sibling of, and come *after*, `#parent_1`, but not those that are a sibling of and come after `#parent_2`.
Count number of table rows between two specific rows with jQuery
[ "", "javascript", "jquery", "html-table", "" ]
`std::string` provides [const char\* c\_str ( ) const](http://www.cplusplus.com/reference/string/string/c_str.html) which: > Get C string equivalent > > Generates a null-terminated sequence > of characters (c-string) with the same > content as the string object and > returns it as a pointer to an array of > characters. > > A terminating null character is > automatically appended. > > The returned array points to an > internal location with the required > storage space for this sequence of > characters plus its terminating > null-character, but the values in this > array should not be modified in the > program and are only granted to remain > unchanged until the next call to a > non-constant member function of the > string object. Why don't they just define `operator const char*() const {return c_str();}`?
From the C++ Programming Language 20.3.7 (emphasis mine): > Conversion to a C-style string could have been provided by an operator const char\*() rather than c\_str(). This would have provided the convenience of an implicit conversion **at the cost of surprises in cases in which such a conversion was unexpected**.
I see at least two problems with the implicit conversion: * Even the explicit conversion that `c_str()` provides is dangerous enough as is. I've seen a lot of cases where the pointer was stored to be used after the lifetime of the original string object had ended (or the object was modified thus invalidating the pointer). With the explicit call to `c_str()` you hopefully are aware of these issues. But with the implicit conversion it would be very easy to cause undefined behavior as in: ``` const char *filename = string("/tmp/") + name; ofstream tmpfile(filename); // UB ``` * The conversion would also happen in some cases where you wouldn't expect it and the semantics are surprising to say the least: ``` string name; if (name) // always true ; name-2; // pointer arithmetic + UB ``` These could be avoided by some means but why get into this trouble in the first place?
Why doesn't std::string provide implicit conversion to char*?
[ "", "c++", "string", "stl", "" ]
We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics. There are a few ways we could deal with this: * have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate `<script>` elements, * maintain a branch which we pull into before deploying to the production server, which we ensure includes the `<script>` elements, * do something with Google Analytics to block hits to 127.0.0.1 or localhost, or * something else. The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a `google_analytics` variable into all of our views? What are your thoughts?
First, create a way to have your development and production servers pull settings from different files, say dev.py and prod.py. There are lots of ways to do this. Then, create a setting, `GOOGLE_ANALYTICS_KEY`. In dev.py set it to the empty string. In prod.py, set it to your key, something like "UA-124465-1". Create a [context processor](http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors) to add this setting to all your template contexts, either as `GOOGLE_ANALYTICS_KEY`, or just go ahead and add your settings module. Then, in your template, use it to conditionally include your analytics code: ``` {% if settings.GOOGLE_ANALYTICS_KEY %} <script> blah blah {{settings.GOOGLE_ANALYTICS_KEY}} blah blah </script> {% endif %} ```
A little late to the party, but there's a reusable Django app called [django-google-analytics](http://github.com/montylounge/django-google-analytics). The easiest way to use it is: 1. Add the `google_analytics` application to your `INSTALLED_APPS` section of your `settings.py`. 2. In your base template, usually a `base.html`, insert this tag at the very top: `{% load analytics %}` 3. In the same template, insert the following code right before the closing body tag: `{% analytics "UA-xxxxxx-x" %}` the `UA-xxxxxx-x` is a unique Google Analytics code for your domain.
Deploying Google Analytics With Django
[ "", "python", "django", "deployment", "google-analytics", "" ]
I have a wysiwyg text area in a Java webapp. Users can input text and style it or paste some already HTML-formatted text. What I am trying to do is to *linkify* the text. This means, converting all possible URLs within text, to their "working counterpart", i.e. adding < a href="...">...< /a>. This solution **works** when all I have is plain text: ``` String r = "http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?"; Pattern pattern = Pattern.compile(r, Pattern.DOTALL | Pattern.UNIX_LINES | Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(comment); comment = matcher.replaceAll("<a href=\"$0\">$0</a>"); // group 0 is the whole expression ``` But the problem is when there is some already formatted text, i.e. that it *already* has the < a href="...">...< /a> tags. So I am looking for some way for the pattern *not to match* whenever it finds the text *between two HTML tags (< a>)*. I have read this can be achieved with [lookahead](http://www.regular-expressions.info/lookaround.html) or [lookbehind](http://www.lexemetech.com/2007/10/zero-width-negative-lookbehind.html) but I still can't make it work. I am sure I am doing it wrong because the regex still matches. And yes, I have been playing around/ debugging groups, changing $0 to $1 etc. Any ideas?
You are close. You can use a "negative lookbehind" like so: ``` (?<!href=")http:// etc ``` All results preceded by href will be ignored.
If you want to use regex, (though I think parsing to XML/HTML first is more robust) I think look-ahead or -behind makes sense. A first stab might be to add this at the end of your regex: ``` (?!</a>) ``` Meaning: don't match if there's a closing a tag just afterwards. (This could be tweaked forever, of course.) This doesn't work well, though, because given the string ``` <a href="...">http://example.com/</a> ``` This regex will try to match "<http://example.com/>", fail due to the lookahead (as we hope), and then *backtrack* the greedy qualifier to have on the end and match "<http://example.com>" instead, which doesn't have a after it. You can fix the latter problem by using a [possessive qualifier](http://www.regular-expressions.info/possessive.html) on your +, \* and ? operators - just stick a + after them. This prevents them from back-tracking. This is probably good for performance reasons, as well. This works for me (note the three extra +'s): ``` String r = "http(s)?://([\\w+?\\.\\w+])++([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*+)?+(?!</a>)"; ```
Linkify text with regular expressions in Java
[ "", "java", "regex", "" ]
Anyone know of an API (php preferable but I'd be interested in any language) for creating wiki-like data storage? How about any resources on rolling your own plaintext wiki? How do other plaintext wikis handle the format of the text file? I understand I can use Markdown or Textile for the formatting. But what I'm most interested in is how to approach the plaintext storage of multi-user edits. I'm writing a web application that is primarily database driven. I want at least one text field of this database to be in a wiki-like format. Specifically, this text can be edited by multiple users with the ability to roll back to any version. Think the wiki/bio section of [Last.FM](http://www.last.fm/music/Oingo+Boingo/) (almost the entire site is strictly structured by a database except for this one section per artist). So far, my approach of taking apart MediaWiki and wedging it into a database seems like overkill. I'm thinking it would be much easier to roll my own plaintext wiki, and store this file in the database's appropriate text field.
So, basically this is a "how do I version text information in my DB". Well, the simplest way is simply copying the data. Simply, create a "version" table that holds "old versions" of the data, and link it back to your main table. ``` create table docs { id integer primary key not null, version integer not null, create_date date, change_date date, create_user_id integer not null references users(id), change_user_id integer references users(id), text_data text } create table versions { id integer primary key not null, doc_id integer not null references docs(id), version integer, change_date date, change_user integer not null references users(id), text_data text } ``` Whenever you update your original document, you copy the old text value in to this table, copy the user and change date and bump the version. ``` select version, change_date, change_user, text_data into l_version, l_change_data, l_change_user, l_text_data from docs where id = l_doc_id; insert into versions values (newid, l_doc_id, l_version, l_change_date, l_change_user, l_text_data); update docs set version = version + 1, change_date = now, change_user = cur_user, text_data = l_new_text where id = l_doc_id; ``` You could even do this in a trigger if your DB supports those. Faults with this method are that its a full copy of the data (so if you have a large document, the version stay large). You can mitigate that by using something like diff(1) and patch(1). For example: ``` diff version2.txt version1.txt > difffile ``` Then you can store that difffile as "version 1". In order to recover version 1 from version 2, you grab the version 2 data, run patch on it using the diff file data, and that gives you v1. If you want to go from v3 to v1, you need to do this twice (once to get v2, and then again to get v1). This lowers your storage burden, but increases your processing (obviously), so you'll have to judge how you want to do this.
Will's huge answer is right on, but can be summed up, I think: you need to store the versions, and then you need to store the metadata (who what when of the data). But your question was about resources on Wiki-like versioning. I have none (well, one: [Will's answer above](https://stackoverflow.com/questions/613038/rolling-your-own-plaintext-wiki-wiki-inside-a-db/613165#613165)). However, about the storage of Wikis, I have one. Check out [the comparison matrix from DokuWiki](http://www.wikimatrix.org/show/DokuWiki). I know. You're thinking "what do I care what brand of DB different Wikis use?" Because DokuWiki uses plain text files. You can open them and they are indeed plain. So that's one approach, and they've got some interesting arguments as to why DBMS are not the best way to go. They don't even hold much metadata: most of the stuff is done through the flat files themselves. The point of the DokuWiki for you is that maybe it's a relatively simple problem (depending on how well you want to solve it :)
Rolling Your Own Plaintext Wiki (Wiki inside a DB)
[ "", "php", "database", "wiki", "wiki-engine", "" ]
I have two datetimes, one from a timestamp, and another I'm generating in code. I need to test their equality, and would love to do it without too many expressions. Here's an example of my two dates: ``` DateTime expireTimeStampUTC = DateTime.Parse(UTCValueFromDatabase)); DateTime expectedExpireTime = DateTime.UtcNow.AddHours(NumberOfExpectedHoursInConfig); ``` This is too high precision of a test: if (expireTimeStampUTC.Equals(expectedExpireTime)){} I don't care if they're exact to the second, just the hour. Could it possibly be the best solution to do something compound like this: ``` if (expireTimeStampUTC.Date.Equals(expectedExpireTime.Date)) { if (!expireTimeStampUTC.Hour.Equals(expectedExpireTime.Hour)) { pass = false; } } ``` I'm not the most experienced with C#... is there some elegent way to do this?
If the problem you are having is because of them is a database type, you could convert to that type and compare there, we lose/gain about a millisecond converting to SQLDateTimes on roughly 1/3 of DB saves. If not, compare the unit you actually care about: ``` DateTime dt1 = DateTime.UtcNow; DateTime dt2 = DateTime.UtcNow.AddMinutes(59); // or 1 or 61 for test values; // if the dates are in the same hour (12:10 == 12:50, 1:58 != 2:02) if(dt1.Hour == dt2.Hour) // result ``` or if you care that they are within an hour time span ``` // if the dates are within one hour of each other (1:58 == 2:02, 3:30 != 4:45) if((dt1 - dt2).Duration() < TimeSpan.FromHours(1)) // result ``` Here subtracting dates generates a time span, the duration is the 'absolute value' and then we create the limit explicitly from a unit we care about (FromHours) and compare. The last line is as clean as I can think to do equality within a particular time span.
How about finding the difference between the two hours, and seeing if it's below a certain threshold (say 3600 seconds for an hour)? ``` var diff = expireTimeStamp.Subtract(expectedExpireTime).TotalSeconds; pass = Math.Abs(diff) < 3600; ```
What's the best way to compare the equality of two DateTime's in C#... but only to a certain precision?
[ "", "c#", "datetime", "date", "" ]
I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop. Here is how I'm doing it in PHP: ``` while((name = raw_input("Name: ")) != ''): names.append(name) ``` What I'm trying to do is identical to this in functionality: ``` names = [] while(True): name = raw_input("Name: ") if (name == ''): break names.append(name) ``` Is there any way to do this in Python?
``` from functools import partial for name in iter(partial(raw_input, 'Name:'), ''): do_something_with(name) ``` or if you want a list: ``` >>> names = list(iter(partial(raw_input, 'Name: '), '')) Name: nosklo Name: Andreas Name: Aaron Name: Phil Name: >>> names ['nosklo', 'Andreas', 'Aaron', 'Phil'] ```
You can wrap `raw_input()` to turn it into a generator: ``` def wrapper(s): while True: result = raw_input(s) if result = '': break yield result names = wrapper('Name:') ``` which means we're back to square one but with more complex code. So if you need to wrap an existing method, you need to use [nosklo](https://stackoverflow.com/users/17160/nosklo)'s approach.
How to do variable assignment inside a while(expression) loop in Python?
[ "", "python", "syntax", "while-loop", "expression", "" ]
Today I needed a simple algorithm for checking if a number is a power of 2. The algorithm needs to be: 1. Simple 2. Correct for any `ulong` value. I came up with this simple algorithm: ``` private bool IsPowerOfTwo(ulong number) { if (number == 0) return false; for (ulong power = 1; power > 0; power = power << 1) { // This for loop used shifting for powers of 2, meaning // that the value will become 0 after the last shift // (from binary 1000...0000 to 0000...0000) then, the 'for' // loop will break out. if (power == number) return true; if (power > number) return false; } return false; } ``` But then I thought: How about checking if log2 x is an exactly a round number? When I checked for 2^63+1, `Math.Log()` returned exactly 63 because of rounding. So I checked if 2 to the power 63 is equal to the original number and it is, because the calculation is done in `double`s and not in exact numbers. ``` private bool IsPowerOfTwo_2(ulong number) { double log = Math.Log(number, 2); double pow = Math.Pow(2, Math.Round(log)); return pow == number; } ``` This returned `true` for the given wrong value: `9223372036854775809`. Is there a better algorithm?
There's a simple trick for this problem: ``` bool IsPowerOfTwo(ulong x) { return (x & (x - 1)) == 0; } ``` Note, this function will report `true` for `0`, which is not a power of `2`. If you want to exclude that, here's how: ``` bool IsPowerOfTwo(ulong x) { return (x != 0) && ((x & (x - 1)) == 0); } ``` ### Explanation First and foremost the bitwise binary & operator from MSDN definition: > Binary & operators are predefined for the integral types and bool. For > integral types, & computes the logical bitwise AND of its operands. > For bool operands, & computes the logical AND of its operands; that > is, the result is true if and only if both its operands are true. Now let's take a look at how this all plays out: The function returns boolean (true / false) and accepts one incoming parameter of type unsigned long (x, in this case). Let us for the sake of simplicity assume that someone has passed the value 4 and called the function like so: ``` bool b = IsPowerOfTwo(4) ``` Now we replace each occurrence of x with 4: ``` return (4 != 0) && ((4 & (4-1)) == 0); ``` Well we already know that 4 != 0 evals to true, so far so good. But what about: ``` ((4 & (4-1)) == 0) ``` This translates to this of course: ``` ((4 & 3) == 0) ``` But what exactly is `4&3`? The binary representation of 4 is 100 and the binary representation of 3 is 011 (remember the & takes the binary representation of these numbers). So we have: ``` 100 = 4 011 = 3 ``` Imagine these values being stacked up much like elementary addition. The `&` operator says that if both values are equal to 1 then the result is 1, otherwise it is 0. So `1 & 1 = 1`, `1 & 0 = 0`, `0 & 0 = 0`, and `0 & 1 = 0`. So we do the math: ``` 100 011 ---- 000 ``` The result is simply 0. So we go back and look at what our return statement now translates to: ``` return (4 != 0) && ((4 & 3) == 0); ``` Which translates now to: ``` return true && (0 == 0); ``` ``` return true && true; ``` We all know that `true && true` is simply `true`, and this shows that for our example, 4 is a power of 2.
Some sites that document and explain this and other bit twiddling hacks are: * <http://graphics.stanford.edu/~seander/bithacks.html> (<http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2>) * <http://bits.stephan-brumme.com/> (<http://bits.stephan-brumme.com/isPowerOfTwo.html>) And the grandaddy of them, [the book "Hacker's Delight" by Henry Warren, Jr.](https://rads.stackoverflow.com/amzn/click/com/0201914654): * <http://www.hackersdelight.org/> As [Sean Anderson's page](http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2) explains, the expression `((x & (x - 1)) == 0)` incorrectly indicates that 0 is a power of 2. He suggests to use: ``` (!(x & (x - 1)) && x) ``` to correct that problem.
How to check if a number is a power of 2
[ "", "c#", ".net", "algorithm", "math", ".net-core", "" ]
I have a Windows Forms C# application where I would like to use a tooltip on one of the text boxes. I initialize the tool-tip in the constructor of the Form class, and it works the first time. So when I hover over the text box with my mouse it works, but once the toolTip times out and it goes away, it does not re-appear when I move my mouse away and back onto the control. I would expect it to come back. What am I doing wrong? Here is how I initialize the tooltip: ``` myTip = new ToolTip(); myTip.ToolTipIcon = ToolTipIcon.Info; myTip.IsBalloon = true; myTip.ShowAlways = true; myTip.SetToolTip(txtMyTextBox,"My Tooltip Text"); ```
I had a similar problem today. Sometimes, the tooltip would not show. I had one ToolTip control for all the controls in my form. I also had a MouseEnter event on all the controls added automatically, so I modified the MouseEnter event to do: ``` _tooltip.Active = false; _tooltip.Active = true; ``` It fixed the bug, but I don't know why. Also, the bug always happened on Windows XP machines, but not on Windows Vista.
I guess you'll be happy to know that Microsoft knows about it...since about 5 years... * 2/21/2005 Bug acknowledged as reproducable * 3/29/2005 Hum we might fix it, but later... * 11/15/2005 Well actually it's not a big bug, and it doesn't happen much, so we won't fix it. Damn I love it when I stumble on bugs Microsoft doesn't want to solve! This time it's called a *corner case*, last time it was simply *too difficult to resolve*... <http://connect.microsoft.com/VisualStudio/feedback/details/115385/tooltip-stop-showing-after-autopopdelay> I'm off to tell my client that the bugs in my program are just corner cases and too difficult to resolve...
Windows Forms ToolTip will not re-appear after first use
[ "", "c#", ".net", "winforms", "tooltip", "" ]
I have a web service that's been running fine without modification for a couple of years now. Suddenly today it decides that it would not like to function, and throws a SQL timeout: System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. Interesting to note that this web service lives on the same server as the database, and also that if I pull the query out of a SQL trace and run it in management studio, it returns in under a second. But it's timing out after exactly 30 seconds when called from the web service without fail. I'm using the Enterprise Library to connect to the database, so I can't imagine that randomly started failing. I'm not quite sure what could suddenly make it stop working. I've recycled the app pool it's in, and even restarted the SQL process that I saw it was using. Same behavior. Any way I can troubleshoot this? **UPDATE:** Mitch *nailed* it. As soon as I added "WITH RECOMPILE" before the "AS" keyword in the sproc definition, it came back to life. Bravo!
The symptoms you describe are 99.9% certain of being due to an incorrectly cached query plan. Please see these answers: * [Big difference in execution time of stored proc between Managment Studio and TableAdapter](https://stackoverflow.com/questions/452467/big-difference-in-execution-time-of-stored-proc-between-managment-studio-and-tabl) * [Rule of thumb on when to use `WITH RECOMPILE` option](https://stackoverflow.com/questions/422632/rule-of-thumb-on-when-to-use-with-recompile-option) which include the advice to rebuild indexes and ensure statistics are up to date as a starting point. Do you have a regular index maintenance job scheduled and enabled? The canonical reference is: [Slow in the Application, Fast in SSMS?](http://www.sommarskog.se/query-plan-mysteries.html)
Rebuild any relevant indexes.
SQL Server Timeout troubleshooting
[ "", "c#", "sql-server", "" ]
I want to create a small windows application will go automatically every time period to my site and check if its running fine, if it found it down, not working or have an error "Examples: 404, network error, connection to db failed" it will show a message on my screen. How can i know that there is an error there programmaticly using any .NET language?
It's pretty easy to do with a `WebClient`. It would look something like this: ``` WebClient client = new WebClient(); try { string response = client.DownloadString("http://www.example.com/tester.cgi"); // We at least got the file back from the server // You could optionally look at the contents of the file // for additional error indicators if (response.Contains("ERROR: Something")) { // Handle } } catch (WebException ex) { // We couldn't get the file. // ... handle, depending on the ex // // For example, by looking at ex.Status: switch (ex.Status) { case WebExceptionStatus.NameResolutionFailure: // ... break; // ... } } ``` You could hook that up to a `Timer`'s `Tick` event or something to periodically make the check.
Why bother? You can get a much better solution for cheap from a provider like [RedAlert](http://www.redalert.com/) The nice thing about this is: 1) It tests your site from outside your firewall, so it can detect a wider variety of problems. 2) It is an impartial 3rd party so you can prove uptime if you need to for an SLA. 3) For a small premium you can have the thing try and diagnose the problems. 4) It can page or e-mail you when there is a problem. 5) You don't need to commission a new server. Geez, I sound like an ad for the guys, but I promise I don't work for them or get a kickback. I have just been happy with the service for our servers. BTW: I checked pricing and it is about $20 per site/month. So you could probably pay for a year of the service in less time than it will take to build it yourself.
Is My site down, not working or has an error?
[ "", "c#", ".net", "asp.net", "vb.net", "web", "" ]
So I am stuck with fixing/maintaining another programmers code (blech) I am a firm professor of the rule **"If it ain't broke dont fix it!"** so depsite wanting to change something every time I come across horrendous code, I am keeping myself limited to only changing the absolute minimum amount of code possible to make the required fixes. But in some cases I really need to understand something before trying to follow it/change it. I came across this little bit here: ``` region.LineSelected = (x) => { }; ``` And am wondering if it's the same as this: ``` region.LineSelected = null; ``` I want to be 100% positive of what the first line is doing before I go changing the method it's in.
**Edit based on my current opinion on the subject** They are not the same. The lambda version is adding an event handler to an empty anonymous method. This allows other code to freely raise LineSelected() without worrying about whether it is null (ie. having no listeners). Eg. ``` var lineSelected = this.LineSelected; if (lineSelected != null) { lineSelected(EventArgs.Empty); } ``` The above statement can throw a NullReferenceException if something unsubscribes from LineSelected in another thread after the if but before the event is raised. Assigning LineSelected to a temporary variable and then raising that can call an unsubscribed event listener. Assigning the event handler to a local variable is the recommended method of handling null delegates. By adding an empty delegate, other code is always able to call LineSelected without fear of a NullReferenceException. By assigning the multicast event delegates to a local variable, you can be sure that the value cannot be modified by another thread.
I can't think of any reason to have that first line of code. The only thing I can think of, is when raising the LineSelected event, if you have the first line of code in the class, you don't need to check if the LineSelected event is null. ie: ``` if (this.LineSelected != null) { LineSelected(this,new EventArgs()); } ``` Instead, you can just raise the event without null checks. However, with the second line of code, you will need to check for nulls.
Setting/Removing event handlers in .Net
[ "", "c#", ".net", "event-handling", "lambda", "" ]
This is a little C# specific. The default behaviour of a resizable dialog box is that a title bar click maximizes the dialog and a second double click restores the size. However, what I want is to have the Help button turned on, which means the minimize and maximize buttons are hidden, but I would still like the title bar double click behaviour. This might be achievable with some subclassing, but perhaps someone has some good ideas on this.
``` private const int WM_NCLBUTTONDBLCLK = 0xA3; protected override void WndProc(ref Message m) { switch (m.Msg) { case WM_NCLBUTTONDBLCLK: if (this.WindowState==System.Windows.Forms.FormWindowState.Maximized) this.WindowState=System.Windows.Forms.FormWindowState.Normal; else if (this.WindowState == System.Windows.Forms.FormWindowState.Normal) this.WindowState = System.Windows.Forms.FormWindowState.Maximized; return; } base.WndProc(ref m); } ```
You should be able to handle the WM\_NCHITTEST and look for HT\_CAPTION, see *[WM\_NCHITTEST message](http://msdn.microsoft.com/en-us/library/ms645618(VS.85).aspx)* for details. You'll need to override the WndProc to be able to handle these messages, this is demonstrated in *[Control.WndProc Method](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.wndproc(VS.71).aspx)*.
Allowing a title bar double click to maximize a dialog but without max-min buttons
[ "", "c#", ".net", "winforms", "" ]
Is there a straightforward way to run mysql\_query with an insert and get the ID of the new row, for example in the return? Or will I have to do another query with select to check it?
mysql\_insert\_id() or select last\_insert\_id()
Simply call [mysql\_insert\_id](https://www.php.net/mysql_insert_id) after running mysql\_query and you will get the ID.
PHP&MySQL: Is it possible after running mysql_query with an insert to get the ID of the new row?
[ "", "php", "mysql", "insert-query", "" ]
Per the title, do you find the default Java logging framework sufficient for your needs? Do you use alternative logging services such as [log4j](http://logging.apache.org/log4j/) or others? If so, why? I'd like to hear any advice you have regarding logging requirements in different types of projects, and when integrating frameworks is actually necessary and/or useful.
### Logging Dependencies with Third Party Libraries Java JDK logging in most cases is not insufficient by itself. However, if you have a large project that uses multiple open-source third party libraries, you will quickly discover that many of them have disparate logging dependencies. It is in these cases where the need to abstract your logging API from your logging implementation become important. I recommend using [slf4j](http://www.slf4j.org/) or [logback](http://logback.qos.ch/) (uses the slf4j API) as your API and if you want to stick with Java JDK logging, you still can! Slf4j can output to many different logger implementations with no problems. A concrete example of its usefulness happened during a recent project: we needed to use third-party libs that needed log4j, but we did not want to run two logging frameworks side by side, so we used the slf4j log4j api wrapper libs and the problem was solved. In summary, Java JDK logging is fine, but a standardized API that is used in my third party libraries will save you time in the long run. Just try to imagine refactoring every logging statement!
java.util.logging (jul) was unnecessary from the beginning. Just ignore it. jul in itself has the following downsides: * At the time that jul was introduced in Java 1.4 there was already a well established logging framework in wide use: LOG4J * the predefined log levels are: SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST. I won't tell you what I personally think about those predefined levels to keep this answer semi-objective. * Additional levels can be defined. jul supports up to 4G different log levels which is slightly overkill, IMHO. Less is sometimes more. * The most important point: **if you dare to define your own log level you are likely to run into a memory leak issue!** Feel free to read about this effect here: + [Classloader leaks: the dreaded "java.lang.OutOfMemoryError: PermGen space" exception](http://blogs.oracle.com/fkieviet/entry/classloader_leaks_the_dreaded_java) + [How to fix the dreaded "java.lang.OutOfMemoryError: PermGen space" exception (classloader leaks)](http://blogs.oracle.com/fkieviet/entry/how_to_fix_the_dreaded) It's a pretty interesting read even if you are not planning to use custom levels, btw, since the problem is a wide-spread one that doesn't just apply to jul at all. * it resides in the java.\* namespace so the implementation can't be exchanged at runtime. This effectively prevents bridging it to SLF4J the same way its possible in case of commons.logging and LOG4J. The way bridging is done for jul has a performance impact. This makes jul the most inflexible logging framework out there. * By introducing jul, Sun implicitly defined it to be the "standard java logging framework". This led to the common misconception that a "good Java citizen" should use jul in their libraries or applications. **The opposite is the case.** If you use either commons.logging or LOG4j you'll be able to exchange the actually used logging framework, if you ever need to, by bridging to SLF4J. This means that libraries using either commons.logging, LOG4J or SLF4J can all log to the same logging target, e.g. file. I'd personally suggest to use the [SLF4J](http://slf4j.org/)+[Logback](http://logback.qos.ch/) combo for all logging purposes. Both projects are coordinated by Ceki Gülcü, the guy behind LOG4J. SLF4J is a worthy (but unofficial since it's not from the same group) successor of commons.logging. It's less problematic than CL because it statically resolves the actually used logging backend. Additionally, it has a richer API than CL. Logback, on the other hand, is the (un)official successor of LOG4J. It implements SLF4J natively so there's no overhead caused by any wrapper. ***Now*** you may downvote me if you still think I deserve it. ;)
Do you find java.util.logging sufficient?
[ "", "java", "logging", "frameworks", "" ]
I start my application which spawns a number of Threads, each of which creates a NamedPipeServer (.net 3.5 added managed types for Named Pipe IPC) and waits for clients to connect (Blocks). The code functions as intended. ``` private void StartNamedPipeServer() { using (NamedPipeServerStream pipeStream = new NamedPipeServerStream(m_sPipeName, PipeDirection.InOut, m_iMaxInstancesToCreate, PipeTransmissionMode.Message, PipeOptions.None)) { m_pipeServers.Add(pipeStream); while (!m_bShutdownRequested) { pipeStream.WaitForConnection(); Console.WriteLine("Client connection received by {0}", Thread.CurrentThread.Name); .... ``` Now I also need a Shutdown method to bring this process down cleanly. I tried the usual bool flag isShutdownRequested trick. But the pipestream stays blocked on the WaitForConnection() call and the thread doesn't die. ``` public void Stop() { m_bShutdownRequested = true; for (int i = 0; i < m_iMaxInstancesToCreate; i++) { Thread t = m_serverThreads[i]; NamedPipeServerStream pipeStream = m_pipeServers[i]; if (pipeStream != null) { if (pipeStream.IsConnected) pipeStream.Disconnect(); pipeStream.Close(); pipeStream.Dispose(); } Console.Write("Shutting down {0} ...", t.Name); t.Join(); Console.WriteLine(" done!"); } } ``` Join never returns. An option that I didnt try but would possibly work is to call Thread.Abort and eat up the exception. But it doesn't feel right.. Any suggestions **Update 2009-12-22** Sorry for not posting this earlier.. This is what I received as a response from Kim Hamilton (BCL team) > The "right" way to do an interruptible > WaitForConnection is to call > BeginWaitForConnection, handle the new > connection in the callback, and close > the pipe stream to stop waiting for > connections. If the pipe is closed, > EndWaitForConnection will throw > ObjectDisposedException which the > callback thread can catch, clean up > any loose ends, and exit cleanly. > > We realize this must be a common > question, so someone on my team is > planning to blog about this soon.
Switch to the asynchronous version: `BeginWaitForConnection`. If it does ever complete, you'll need a flag so the completion handler can just call `EndWaitForConnection` absorbing any exceptions and exiting (call End... to ensure any resources are able to be cleaned up).
This is cheesy, but it is the only method I have gotten to work. Create a 'fake' client and connect to your named pipe to move past the WaitForConnection. Works every time. Also, even Thread.Abort() did not fix this issue for me. --- ``` _pipeserver.Dispose(); _pipeserver = null; using (NamedPipeClientStream npcs = new NamedPipeClientStream("pipename")) { npcs.Connect(100); } ```
What is a good way to shutdown Threads blocked on NamedPipeServer#WaitForConnection?
[ "", "c#", ".net-3.5", "named-pipes", "" ]
I need in a DLL to use a class, defined in an executable (DLL and executable are compiled by the same compiler). But I don't want the source code of this class definition to be available to DLL, only declaration. One possible way to do it is to make all the necessary class methods to be `virtual` (so that DLL linker will not need these methods' definitions). The disadvantages of this approach: 1. I cannot create objects of exported classes in DLL code using `new` (a have to create additional functions in executable's code). 2. I have to make all these methods `virtual`, even if otherwise they don't need to be `virtual`. There is a way to export a class from a DLL to an executable using Microsoft's `__declspec(dllexport)` storage-class extended attribute. Is there a way to export a class from executable to DLL using the same technique? My old Borland C 6 compiler does not allow me to create import library during the build of executable project. (So, when compiling the DLL, linker gives me unresolved external error messages for all imported non-virtual class methods.) Is it a limitation of this very compiler, or maybe I'm missing something important?
So far as I know, it is ok to use MS VS's dllexport to export a class or function from a exe and use it in a DLL. and it runs cool if your DLL and Exe execute **in one process**.
You could put the class in a second DLL if you really didn't want it in the first one. I'm having a hard time understanding your reasoning for not just putting the class in the DLL though. **ETA:** Did some more digging and found [this link](http://www.mail-archive.com/cmake@cmake.org/msg18672.html) that explains how to generate an import library from an EXE project in Visual Studio 2008. As for how to export them, it looks like you just use the regular \_\_declspec(dllexport).
Exporting class from executable to dll
[ "", "c++", "dllimport", "" ]
I am creating an object that has a constuctor like this... ``` public class BusinessLogic() { public BusinessLogic() { BusinessLogicSubClass blsc = new BusinessLogicSubClass(and I want to pass in BusinessLogic here) } } ``` I am doing this because I want BusinessLogicSubClass to call back to varying methods within BusinessLogic when it completes one method or another. BusinessLogicSubClass also uses Constructor Injection in order for my Unit Tests to work with NMock2. Any suggestions here would be helpful thank you in advance!
``` public BusinessLogic() { BusinessLogicSubClass blsc = new BusinessLogicSubClass(this); } ``` An alternative to this (to address Jon Skeet's comments) would be to have a constructor, and an initializer, which uses the "this" pointer: ``` public class BusinessLogic { private BusinessLogicSubClass blsc = null; public BusinessLogic() {} public void Initialize() { blsc = new BusinessLogicSubClass(this); } } public class Implementor { public void SomeFunction() { BusinessLogic bl = new BusinessLogic(); bl.Initialize(); } } ```
You can use `this` within a constructor. It's generally not a great idea though, as it means you've published a reference before the object has finished being constructed. It's not really clear why you're creating a subclass within the class itself though - I suspect your inheritance hierarchy might not be ideal. Could you give some more details, so we might be able to recommend better design patterns?
C# passing current object into another object?
[ "", "c#", "" ]
In PHP, if I create a string like this: ``` $str = "bla bla here is my string"; ``` Will I then be able to use the mbstring functions to operate on that string as UTF8? ``` // Will this work? $str = mb_strlen($str); ``` Further, if I then have another string that I *know* is UTF-8 (say it was a POSTed form value, or a UTF-8 string from a database), can I then concatenate these two and not have any problems? ``` // What about this, will this work? $str = $str . $utf8_string_from_database; ```
**First question: it depends on what exactly goes in the string.** In PHP (up to PHP5, anyway), strings are just sequences of bytes. There is no implied or explicit character set associated with them; that's something the programmer must keep track of. So, if you only put valid UTF-8 bytes between the quotes (fairly easy if the file itself is encoded as UTF-8), then the string will be UTF-8, and you can safely use mb\_strlen() on it. Also, if you're using mbstring functions, you need to explicitly tell it what character set your string is, either with [mbstring.internal\_encoding](http://php.net/manual/en/mbstring.configuration.php#ini.mbstring.internal-encoding) or as the last argument to any mbstring function. **Second question: yes, with caveats.** Two strings that are both independently valid UTF-8 can be safely byte-wise concatenated (like with PHP's `.` operator) and still be valid UTF-8. However, you can never be sure, without doing some work yourself, that a POSTed string is valid UTF-8. Database strings are a little easier, if you carefully set the connection character set, because most DBMSs will do any conversion for you.
If your source code is in UTF-8, then the string is in UTF-8, if not — it’s not. Since your example string is english-only, it is valid UTF-8. PHP doesn’t itself know about charsets. If you pass stuff to mb\* function, it treats it as an UTF-8 string. Concatenation must work fine no matter what, if I understand UTF-8 right :-) Just make sure *both* strings are UTF-8, otherwise you will get *strange* string as a result.
PHP UTF-8 questions - If I create a string in PHP... is it in UTF-8?
[ "", "php", "unicode", "utf-8", "" ]
I am looking for a package that is similar to [Net\_IPv4](http://pear.php.net/package/Net_IPv4) and [Net\_IPv6](http://pear.php.net/package/Net_IPv6) but written for Java. It needs to be able to do the following: * Verify an address is valid (e.g. 127.0.0.1 is valid, 127.0.0.257 is not) * Return if an address is contained within a subnet (e.g. 127.0.0.11 is in 127.0.0.0/28) * Return the broadcast address for a given subnet (e.g. for 127.0.0.0/28 it's 127.0.0.15) It would be awesome if it could also: * Return a list of addresses for a subnet in order * Sort a list of addresses I could probably write a package to do all this, but if someone has already gone through the trouble and most likely has done a better job, I'm all about using that. Anyone know of such a package or packages that could do all this? We are expanding into IPv6, so it needs to work for both IPv4 and IPv6 if possible. I appreciate any help.
It's only for IPv4, but the [SubnetUtils](http://commons.apache.org/net/apidocs/org/apache/commons/net/util/SubnetUtils.html) class that is part of [Commons Net](http://commons.apache.org/net/) has the functionality you are looking for. Based on that you could code up an IPv6 version and contribute it back to the project! :)
Maybe [CIDRUtils](https://github.com/edazdarevic/CIDRUtils) can help you. It enables you to convert CIDR notation to an IP range. Disclaimer: I am the author of CIDRUtils.
IPv4/IPv6 network calculations and validation for Java?
[ "", "java", "networking", "ip-address", "" ]
Could someone please tell me what I'm doing wrong with this code? It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). ``` import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: continue if count % x != 0: print count count += 1 ```
There are some problems: * Why do you print out count when it didn't divide by x? It doesn't mean it's prime, it means only that this particular x doesn't divide it * `continue` moves to the next loop iteration - but you really want to stop it using `break` Here's your code with a few fixes, it prints out only primes: ``` import math def main(): count = 3   while True: isprime = True   for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: isprime = False break   if isprime: print count   count += 1 ``` For much more efficient prime generation, see the Sieve of Eratosthenes, as others have suggested. Here's a nice, optimized implementation with many comments: ``` # Sieve of Eratosthenes # Code by David Eppstein, UC Irvine, 28 Feb 2002 # http://code.activestate.com/recipes/117119/ def gen_primes(): """ Generate an infinite sequence of prime numbers. """ # Maps composites to primes witnessing their compositeness. # This is memory efficient, as the sieve is not "run forward" # indefinitely, but only as long as required by the current # number being tested. # D = {}   # The running integer that's checked for primeness q = 2   while True: if q not in D: # q is a new prime. # Yield it and mark its first multiple that isn't # already marked in previous iterations # yield q D[q * q] = [q] else: # q is composite. D[q] is the list of primes that # divide it. Since we've reached q, we no longer # need it in the map, but we'll mark the next # multiples of its witnesses to prepare for larger # numbers # for p in D[q]: D.setdefault(p + q, []).append(p) del D[q]   q += 1 ``` Note that it returns a generator.
re is powerful: ``` import re def isprime(n): return re.compile(r'^1?$|^(11+)\1+$').match('1' * n) is None print [x for x in range(100) if isprime(x)] ###########Output############# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] ```
Simple prime number generator in Python
[ "", "python", "primes", "" ]
I'm trying to compute hmac using sha-512. The Perl code: ``` use Digest::SHA qw(hmac_sha512_hex); $key = "\x0b"x20; $data = "Hi There"; $hash = hmac_sha512_hex($data, $key); print "$hash\n"; ``` and gives the correct hash of ``` 87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 ``` Python version: ``` import hashlib, hmac print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() ``` which gives the incorrect hash of ``` 9656975ee5de55e75f2976ecce9a04501060b9dc22a6eda2eaef638966280182 477fe09f080b2bf564649cad42af8607a2bd8d02979df3a980f15e2326a0a22a ``` any ideas why the Python version is giving me the wrong hash? Edit: version is Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
yes indeed -- it seems the Leopard version of python2.5 is the one that is broken. below run on a Penryn-based MBP... ``` $ **uname -a** Darwin lizard-wifi 9.6.0 Darwin Kernel Version 9.6.0: Mon Nov 24 17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386 i386 dpc@lizard-wifi:~$ **which python** /usr/bin/python ``` Running this version installed in Leopard OS ``` dpc@lizard-wifi:~$ python Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import hashlib, hmac >>> print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() 9656975ee5de55e75f2976ecce9a04501060b9dc22a6eda2eaef638966280182477fe09f080b2bf564649cad42af8607a2bd8d02979df3a980f15e2326a0a22a >>> ``` And then the MacPorts version of `python2.5` ``` $ /opt/local/bin/python2.5 Python 2.5.4 (r254:67916, Feb 3 2009, 21:40:31) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import hashlib, hmac >>> print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() 87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 >>> ```
I am unable to replicate your results here. In IDLE using Python 2.5: ``` Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. ... IDLE 1.2.2 >>> import hashlib, hmac >>> print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() 87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 ```
Why do I get wrong results for hmac in Python but not Perl?
[ "", "python", "perl", "hash", "hmac", "" ]
Random.nextGaussian() is supposed to give random no.s with mean 0 and std deviation 1. Many no.s it generated are outside range of [-1,+1]. how can i set so that it gives normally distributed random no.s only in the range -1 to 1.
A Gaussian distribution with a mean 0 and standard deviation one means that the average of the distribution is 0 and about 70% of the population lies in the range [-1, 1]. Ignore the numbers that are outside your range -- they form the fringe 16% approx on either side. Maybe a better solution is to generate a distribution with `mean=0` and `std.dev=0.5`. This will give you a distribution with about 96% of the values in the range [-1, 1]. An even better solution is to work backward as above and use the idea that approx. 99.7% of the values lie in the 3-sigma range: use a `std.dev = 1/3`. That will almost nullify the amount of not-so-useful values that you are getting. When you do get one, omit it. Of course, if you are working on a math intensive product, all of this bears no value.
Doesn't the normal distribution include numbers arbitrarily far from the mean, but with increasingly small probabilities? It might be that your desires (normal and limited to a specific range) are incompatible.
problem with Random.nextGaussian()
[ "", "java", "random", "" ]
Is there a way to write binary literals in C#, like prefixing hexadecimal with 0x? 0b doesn't work. If not, what is an easy way to do it? Some kind of string conversion?
C# [7.0](https://github.com/dotnet/roslyn/issues/2136) supports [binary literals](https://github.com/dotnet/roslyn/issues/215) (and optional digit separators via underscore characters). An example: ``` int myValue = 0b0010_0110_0000_0011; ``` You can also find more information on the [Roslyn GitHub page](https://github.com/dotnet/roslyn).
### Update C# 7.0 now has binary literals, which is awesome. ``` [Flags] enum Days { None = 0, Sunday = 0b0000001, Monday = 0b0000010, // 2 Tuesday = 0b0000100, // 4 Wednesday = 0b0001000, // 8 Thursday = 0b0010000, // 16 Friday = 0b0100000, // etc. Saturday = 0b1000000, Weekend = Saturday | Sunday, Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday } ``` ### Original Post Since the topic seems to have turned to declaring bit-based flag values in enums, I thought it would be worth pointing out a handy trick for this sort of thing. The left-shift operator (`<<`) will allow you to push a bit to a specific binary position. Combine that with the ability to declare enum values in terms of other values in the same class, and you have a very easy-to-read declarative syntax for bit flag enums. ``` [Flags] enum Days { None = 0, Sunday = 1, Monday = 1 << 1, // 2 Tuesday = 1 << 2, // 4 Wednesday = 1 << 3, // 8 Thursday = 1 << 4, // 16 Friday = 1 << 5, // etc. Saturday = 1 << 6, Weekend = Saturday | Sunday, Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday } ```
C# binary literals
[ "", "c#", "syntax", "binary", "" ]
I've searched the IIS7 MSDN database but can't find any *concrete* material on how to create custom C#.NET extensions for IIS7, I know that previously in IIS6 you had to write an ISAPI extension in C++ if you wanted to say plug in your own scripting language for websites (this is sort of what I want to do) but in IIS7 you're supposed to be able to write it using C#.NET and utilizing the new plugable architecture of IIS7... but I can't find any sodding docs on how to do it. Anyone care to point me in the right direction?
A good place to start is this [article](http://mvolo.com/blogs/serverside/archive/2007/08/15/Developing-IIS7-web-server-features-with-the-.NET-framework.aspx). It has links in the beginning to sample modules.
In IIS7 Integrated mode, HTTP Modules are equivalent to ISAPI filters and HTTP Handlers are equivalent to ISAPI extensions.
Creating what is equivalent to an ISAPI extension for IIS7
[ "", "c#", ".net", "asp.net", "iis", "iis-7", "" ]
What is the most efficient Java Collections library? A few years ago, I did a lot of Java and had the impression back then that [trove](http://trove4j.sourceforge.net/) is the best (most efficient) Java Collections implementation. But when I read the answers to the question "[Most useful free Java libraries?](https://stackoverflow.com/questions/130095/most-useful-free-java-libraries)" I noticed that [trove](http://trove4j.sourceforge.net/) is hardly mentioned. So which Java Collections library is best now? **UPDATE:** To clarify, I mostly want to know what library to use when I have to store millions of entries in a hash table etc. (need a small runtime and memory footprint).
From inspection, it looks like Trove is just a library of collections for primitive types - it's not like it's meant to be adding a lot of functionality over the normal collections in the JDK. Personally (and I'm biased) I love [Guava](https://github.com/google/guava) (including the former Google Java Collections project). It makes various tasks (including collections) a lot easier, in a way which is at least reasonably efficient. Given that collection operations rarely form a bottleneck in my code (in my experience) this is "better" than a collections API which may be more efficient but doesn't make my code as readable. Given that the overlap between Trove and the Guava is pretty much nil, perhaps you could clarify what you're actually looking for from a collections library.
The question is (now) about storing lots of data, which can be represented using primitive types like `int`, in a Map. Some of the answers here are very misleading in my opinion. Let's see why. I modified the benchmark from [trove](http://trove4j.sourceforge.net/index.html) to measure both runtime and memory consumption. I also added [PCJ](http://pcj.sourceforge.net/) to this benchmark, which is another collections library for primitive types (I use that one extensively). The 'official' trove benchmark does not compare IntIntMaps to Java Collection's `Map<Integer, Integer>`, probably storing `Integers` and storing `ints` is not the same from a technical point of view. But a user might not care about this technical detail, he wants to store data representable with `ints` efficiently. First the relevant part of the code: ``` new Operation() { private long usedMem() { System.gc(); return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); } // trove public void ours() { long mem = usedMem(); TIntIntHashMap ours = new TIntIntHashMap(SET_SIZE); for ( int i = dataset.size(); i-- > 0; ) { ours.put(i, i); } mem = usedMem() - mem; System.err.println("trove " + mem + " bytes"); ours.clear(); } public void pcj() { long mem = usedMem(); IntKeyIntMap map = new IntKeyIntOpenHashMap(SET_SIZE); for ( int i = dataset.size(); i-- > 0; ) { map.put(i, i); } mem = usedMem() - mem; System.err.println("pcj " + mem + " bytes"); map.clear(); } // java collections public void theirs() { long mem = usedMem(); Map<Integer, Integer> map = new HashMap<Integer, Integer>(SET_SIZE); for ( int i = dataset.size(); i-- > 0; ) { map.put(i, i); } mem = usedMem() - mem; System.err.println("java " + mem + " bytes"); map.clear(); } ``` I assume the data comes as primitive `ints`, which seems sane. But this implies a runtime penalty for java util, because of the auto-boxing, which is not neccessary for the primitive collections frameworks. The runtime results (without `gc()` calls, of course) on WinXP, jdk1.6.0\_10: ``` 100000 put operations 100000 contains operations java collections 1938 ms 203 ms trove 234 ms 125 ms pcj 516 ms 94 ms ``` While this might already seem drastic, this is not the reason to use such a framework. The reason is memory performance. The results for a Map containing 100000 `int` entries: ``` java collections oscillates between 6644536 and 7168840 bytes trove 1853296 bytes pcj 1866112 bytes ``` Java Collections needs **more than three times** the memory compared to the primitive collection frameworks. I.e. you can keep three times as much data in memory, without resorting to disk IO which lowers runtime performance by magnitudes. And this matters. Read [highscalability](http://highscalability.com/) to find out why. In my experience high memory consumption is the biggest performance issue with Java, which of course results in worse runtime performance as well. Primitive collection frameworks can really help here. So: No, java.util is not the answer. And "adding functionality" to Java collections is not the point when asking about efficiency. Also the modern JDK collections do **not** "out-perform even the specialized Trove collections". Disclaimer: The benchmark here is far from complete, nor is it perfect. It is meant to drive home the point, which I have experienced in many projects. Primitive collections are useful enough to tolerate fishy API - **if** you work with lots of data.
What is the most efficient Java Collections library?
[ "", "java", "collections", "" ]
I wrote a multi-threaded program which does some CPU heavy computation with a lot of floating point operations. More specifically, it's a program which compares animation sequences frame by frame. I.e. it compares frame data from animation A with all the frames in animation B, for all frames in animation A. I carry out this intensive operation for different animations in parallel, so the program can be working on A-B pair, B-C pair and C-A pair in parallel. The program is using QtConcurrent and a "map" function which maps a container with motions onto a function. QtConcurrent manages thread pool for me, I am working on Intel Quad Core processor so it spawns 4 threads. Now, the problem is that my process destroys my CPU. The usage is 100% constant and I actually get a Blue Screen of Death if I run my program on a big enough set of motions (Page fault in non-paged area). I suspect that this is because my computer is overclocked. However, could this be because of the way I coded my program? Some very intensive benchamrking tools I used to test my machine's stability never crashed my PC. Is there any way to control how my program uses my CPU to reduce the load? Or perhaps I am misunderstanding my problem?
There are some excellent answers here. I would only add, from the perspective of having done lots of performance tuning, unless each thread has been optimized aggressively, chances are it has lots of room for cycle-reduction. To make an analogy with a long-distance auto race, there are two ways to try to win: 1. Make the car go faster 2. Make fewer stops and side-trips In my experience, most software as first written is quite far from taking the most direct route, *especially* as the software gets large. To find wasted cycles in your program, as Kenneth Cochran said, never guess. If you fix something without having proved that it is a problem, you are investng in a guess. The popular way to find performance problems is to use profilers. However, I do this a lot, and my method is this: <http://www.wikihow.com/Optimize-Your-Program%27s-Performance>
Overclocking PCs can lead to all sorts of strange problems. If you suspect that to be the root cause of your problem, try to clock it in reasonable ranges and retry your tests. It could also be some sort of quite strange memory-bug where you corrupt your RAM in a way where Windows (I guess that OS, because of BSOD) cannot recover anymore (very unlikely, but who knows). Another possibility I can think of is, that you've got some error in your threading-implementation which kills windows. But at first, I'd look at the overclocking-issue...
How to reduce CPU usage of a program?
[ "", "c++", "performance", "parallel-processing", "qtconcurrent", "" ]
Say you've got some IEnumerable called S of length N. I would like to select all continuous subsequences of length n <= N from S. If S were, say, a string, this'd be pretty easy. There are (S.Length - n + 1) subsequences of length n. For example, "abcdefg" is length (7), so that means it has (5) substrings of length (3): "abc", "bcd", "cde", "def", "efg". But S could be any IEnumerable, so this route isn't open. How do I use extension methods to solve this?
F# has a library function called Seq.windowed for this. <http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Collections.Seq.html> ``` // windowed : int -> seq<'a> -> seq<array<'a>> let windowed n (s: seq<_>) = if n <= 0 then Helpers.invalid_arg2 "n" "the window size must be positive" { let arr = Array.zero_create n let r = ref (n-1) let i = ref 0 use e = s.GetEnumerator() while e.MoveNext() do do arr.[!i] <- e.Current do i := (!i + 1) % n if !r = 0 then yield Array.init n (fun j -> arr.[(!i+j) % n]) else do r := (!r - 1) } ```
Actually, you can use LINQ to solve this problem, e.g. ``` var subList = list.Skip(x).Take(y); ``` where list is an `IEnumerable`
Select the next N elements of an IEnumerable<T>
[ "", "c#", "extension-methods", "" ]
When I try to save a BitmapSource that I loaded earlier, a `System.IO.IOException` is thrown stating another process is accessing that file and the filestream cannot be opened. If I only save whithout loading earlier, everything works fine. The loading code: ``` BitmapImage image = new BitmapImage(); image.BeginInit(); image.UriSource = uri; if (decodePixelWidth > 0) image.DecodePixelWidth = decodePixelWidth; image.EndInit(); ``` the saving code: ``` using (FileStream fileStream = new FileStream(Directory + "\\" + FileName + ".jpg", FileMode.Create)) { JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create((BitmapImage)image)); encoder.QualityLevel = 100; encoder.Save(fileStream); } ``` It seems like after loading the image data, the file is still locked an can never be overwritten while the application who opened it is still running. Any ideas how to solve this? Thanks alot for any solutions.
Inspired by the comments I got on this issue, I solved the problem by reading all bytes into a memorystream and using it as the BitmapImage's Sreamsource. This one works perfectly: ``` if (File.Exists(filePath)) { MemoryStream memoryStream = new MemoryStream(); byte[] fileBytes = File.ReadAllBytes(filePath); memoryStream.Write(fileBytes, 0, fileBytes.Length); memoryStream.Position = 0; image.BeginInit(); image.StreamSource = memoryStream; if (decodePixelWidth > 0) image.DecodePixelWidth = decodePixelWidth; image.EndInit(); } ```
Here is another solution, based upon the original loading code: ``` var image = new BitmapImage(); image.BeginInit(); // overwrite cache if already exists, to refresh image image.CreateOptions = BitmapCreateOptions.IgnoreImageCache; // load into memory and unlock file image.CacheOption = BitmapCacheOption.OnLoad; image.UriSource = uri; if (decodePixelWidth > 0) image.DecodePixelWidth = decodePixelWidth; image.EndInit(); ```
Load a BitmapSource and save using the same name in WPF -> IOException
[ "", "c#", "wpf", "load", "bitmap", "save", "" ]
So I am utilizing CollectionBase as an inherited class for custom collections. I am utilizing CollectionBase through an abstract class so that I don't repeated knowledge (following the DRY principle). The abstract class is defined as a generic class also. Here is how I am implementing my class: ``` public abstract class GenericCollectionBase<T,C> : CollectionBase { //Indexders, virtual methods for Add, Contains, IndexOf, etc } ``` I utilize this so I don't have to implement these base methods in 10+ classes. My question is am I taking this too far when I override the Equals method like this: ``` public override bool Equals(object obj) { if (obj is C) { GenericCollectionBase<T, C> collB = obj as GenericCollectionBase<T, C>; if (this.Count == collB.Count) { for (int i = 0; i < this.Count; ++i) { if (!this[i].Equals(collB[i])) return false; } return true; } } return false; } ``` Am I trying to accomplish too much with my abstract, or doing this the correct way? EDIT: This is written for .Net 2.0 and do not have access to 3.5 to utilize things like LINQ
I don't believe you are trying to accomplish too much. If an abstract class was meant to not have any implementation at all, or other methods which define functionality, then they would be interfaces. The only thing I would change is to use `EqualityComparer<T>` instead of equals for the comparison of `this[i]` and `collB[i]`.
Well, first, this is weird : ``` if (obj is C) { GenericCollectionBase<T, C> collB = obj as GenericCollectionBase<T, C>; ``` I'll assume you meant that : ``` GenericCollectionBase<T, C> collB = obj as GenericCollectionBase<T, C>; if (collB != null) { ... ``` I think you're over-thinking this, except if you really, really need two *different* collections with the same content to be considered as equal. I'd put this logic in another method to be called explicitly or in an equality comparer.
Abstract Class - Am I over-thinking this or doing it right?
[ "", "c#", "generics", "abstract-class", "" ]
I'm developing a website, and due to user-input or by other reason, I need to show some error messages. For this, I have a page named *error.php*, and I get the error number using $\_GET. All error messages are stored in a array. Example: ``` header( 'Location: error.php?n=11' ); ``` But I don't want the users to the enter the error code in the URL and see all the other error messages. For preventing that, I thought I could whitelist the referer page, and only show the error message if the referer is found in my whitelist. It should be fair similar to this (haven't tested yet ;) ) ``` $accept = false; $allowedReferer = array (0=>'page1.php', 'page2.php'); if (in_array($_SERVER['HTTP_REFERER'], $allowedReferer )) {$accept = true;} if ($accept) { $n=$_GET['n'];echo "Error: " . $errorList[$n];} ``` Is this method good enough to avoid the *spy-users*? I'm doing this with PHP5 Thanks
Rather than redirect, you could simply display the error "in place" - e.g. something as simple as adapting your present code with something like ``` if ($error_condition) { $_GET['n']=11; include "/path/to/error.php"; exit; } ``` In practice it might be a little more sophisticated, but the idea is the same - the user is presented with an error message without redirecting. Make sure you output some kind of error header, e.g. header("HTTP/1.0 401 Bad Request") to tell the browser that it's not really seeing the requested page. If you do want to redirect, then you could create a "tamperproof" URL by including a hash of the error number with a salt known only to your code, e.g. ``` $n=11; $secret="foobar"; $hash=md5($n.$secret); $url="http://{$_SERVER['HTTP_HOST']}/error.php?n={$n}&hash={$hash}"; ``` Now your error.php can check whether the supplied hash was correctly created. If it was, then in all likelihood it was created by your code, and not the user.
No, it isn't remotely secure: the `HTTP` `Referer` header is trivial to spoof, and is not a required header either. I suggest you read [this article](http://www.mustap.com/phpzone_post_62_how-to-bypass-the-referer-se) for an example of exploiting code (written in PHP), or download [this add-on](http://refspoof.mozdev.org/) for Firefox to do it yourself from the comfort of your own browser. In addition, your `$allowedReferer` array should contain **full** URL's, not just the script name, otherwise the code will also be exploitable from remote referrals, e.g. from ``` http://www.example.org/page1.php ``` To summarise: you cannot restrict access to any *public* network resource without requiring authentication.
Is this method good/secure enough for showing errors to users? - PHP
[ "", "php", "error-handling", "http-referer", "" ]
I'm cleaning an incoming text in my Java code. The text includes a lot of "\n", but not as in a new line, but literally "\n". I was using replaceAll() from the String class, but haven't been able to delete the "\n". This doesn't seem to work: ``` String string; string = string.replaceAll("\\n", ""); ``` Neither does this: ``` String string; string = string.replaceAll("\n", ""); ``` I guess this last one is identified as an actual new line, so all the new lines from the text would be removed. Also, what would be an effective way to remove different patterns of wrong text from a String. I'm using regular expressions to detect them, stuff like HTML reserved characters, etc. and replaceAll, but everytime I use replaceAll, the whole String is read, right? **UPDATE**: Thanks for your great answers. I' ve extended this question here: [Text replacement efficiency](https://stackoverflow.com/questions/542770/text-replacement-efficiency) I'm asking specifically about efficiency :D
Hooknc is right. I'd just like to post a little explanation: "\\n" translates to "\n" after the compiler is done (since you escape the backslash). So the regex engine sees "\n" and thinks new line, and would remove those (and not the literal "\n" you have). "\n" translates to a real new line by the compiler. So the new line character is send to the regex engine. "\\\\n" is ugly, but right. The compiler removes the escape sequences, so the regex engine sees "\\n". The regex engine sees the two backslashes and knows that the first one escapes it so that translates to checking for the literal characters '\' and 'n', giving you the desired result. Java is nice (it's the language I work in) but having to think to basically double-escape regexes can be a real challenge. For extra fun, it seems StackOverflow likes to try to translate backslashes too.
I think you need to add a couple more slashies... ``` String string; string = string.replaceAll("\\\\n", ""); ``` Explanation: The number of slashies has to do with the fact that "\n" by itself is a controlled character in Java. So to get the real characters of "\n" somewhere we need to use "\n". Which if printed out with give us: "\" You're looking to replace all "\n" in your file. But you're not looking to replace the control "\n". So you tried "\n" which will be converted into the characters "\n". Great, but maybe not so much. My guess is that the replaceAll method will actually create a Regular Expression now using the "\n" characters which will be misread as the control character "\n". Whew, almost done. Using replaceAll("\\n", "") will first convert "\\n" -> "\n" which will be used by the Regular Expression. The "\n" will then be used in the Regular Expression and actually represents your text of "\n". Which is what you're looking to replace.
Text cleaning and replacement: delete \n from a text in Java
[ "", "java", "string", "" ]
I have Subclipse installed for Java and just installed TortoiseSVN for #develop, as suggested by someone answering another question of mine. When I try to edit a C# class, it says "client is too old to work with working copy" - but the Subversion version of TortoiseSVN (1.5) seems to be newer than that of Subclipse (1.4?). What is going on - the message seems a bit backwards! Can I downgrade the version level of TortoiseSVN to match Subclipse, or upgrade Subclipse?! Suggestions would be appreciated!
Turns out my problem was due to the fact that #develop 2.2 forces TortoiseSVN 1.4 - it does not work with TortoiseSVN 1.5. Oh well! Thanks for your feedback anyway!
Straight from the [FAQ](http://tortoisesvn.tigris.org/faq.html#clientold): > The full error message is: This client is too old to work with working copy '.'; please get a newer Subversion client. You will get this error message once you have used a Subversion client linked with a higher Subversion version, and then try to execute a command with a Subversion client linked with an older version, e.g., you used an 1.4.x client on your working copy, and now you try an svn 1.3.x client on the same working copy. The reason for this is that Subversion 1.4 and 1.5 upgrade the working copies transparently on every command. But once the working copy format is upgraded, older clients can't access the working copy anymore because they don't know the new format. The only solution to 'fix' this is to upgrade whatever client you use and that gave you this error message. Or do a fresh checkout with the older client.
Version problems running Subclipse and TortoiseSVN
[ "", "c#", "tortoisesvn", "subclipse", "" ]
I have a class, lets call it A, and within that class definition I have the following: ``` static QPainterPath *path; ``` Which is to say, I'm declaring a static (class-wide) pointer to a path object; all instances of this class will now have the same shared data member. I would like to be able to build upon this class, subclassing it into more specialised forms, layering behaviour, and with each class having its own unique path object (but not having to repeat the boring bits like calculating bounding boxes or calling the painting routines). If I subclass it to create a class F (for example), I want F to use the inherited drawing routines from A, but to use the static (class-wide) path object declared in F. I have tried having the declaration above in the private section (and repeating it in the derived class F), and tried having it in the protected section, all with no joy. I can sort of see why this is happening: ``` void A::paint() { this->path... ``` is referring to A::path instead of F::path, even when the object is of class F. Is there an elegant way to get round this, and allow each class to maintain a static path object, while still using drawing code defined in the base class, and having all classes (except perhaps the base class) be real and instantiatable?
Use a virtual method to get a reference to the static variable. ``` class Base { private: static A *a; public: A* GetA() { return a; } }; class Derived: public Base { private: static B *b; public: A* GetA() { return b; } }; ``` Notice that B derives from A here. Then: ``` void Derived::paint() { this->GetA() ... } ```
You might be able to do a variant on a mix in or [Curiously recurring template pattern](http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern) ``` #include <stdio.h> typedef const char QPainterPath; class Base { public: virtual void paint() { printf( "test: %s\n", getPath() ); } virtual QPainterPath* getPath() = 0; }; template <class TYPE> class Holder : public Base { protected: static QPainterPath* path; virtual QPainterPath* getPath() { return path; } }; class Data1 : public Holder<Data1> { }; class Data2 : public Holder<Data2> { }; template <> QPainterPath* Holder<Data1>::path = "Data1"; template <> QPainterPath* Holder<Data2>::path = "Data2"; int main( int argc, char* argv[] ) { Base* data = new Data1; data->paint(); delete data; data = new Data2; data->paint(); delete data; } ``` I have just run this code in CodeBlocks and got the following: ``` test: Data1 test: Data2 Process returned 0 (0x0) execution time : 0.029 s Press any key to continue. ```
Overriding static variables when subclassing
[ "", "c++", "inheritance", "static", "overriding", "" ]
I want to perform a global replace of string using String.replace in Javascript. In the documentation I read that I can do this with /g, i.e. for example; ``` var mystring = mystring.replace(/test/g, mystring); ``` and this will replace all occurrences inside mystring. No quotes for the expression. But if I have a variable to find, how can I do this without quotes? I've tried something like this: ``` var stringToFind = "test"; ``` //first try ``` mystring = mystring.replace('/' + stringToFind + '/g', mystring); ``` //second try, not much sense at all ``` mystring = mystring.replace(/stringToFind/g, mystring); ``` but they don't work. Any ideas?
Can you use prototype.js? If so you could use String.gsub, like ``` var myStr = "a day in a life of a thing"; var replace = "a"; var resultString = myStr.gsub(replace, "g"); // resultString will be "g day in g life of g thing" ``` It will also take regular expressions. To me this is one of the more elegant ways to solve it. [prototypejs gsub documentation](http://www.prototypejs.org/api/string/gsub)
``` var mystring = "hello world test world"; var find = "world"; var regex = new RegExp(find, "g"); alert(mystring.replace(regex, "yay")); // alerts "hello yay test yay" ``` In case you need this into a function ``` replaceGlobally(original, searchTxt, replaceTxt) { const regex = new RegExp(searchTxt, 'g'); return original.replace(regex, replaceTxt) ; } ```
In Javascript, how can I perform a global replace on string with a variable inside '/' and '/g'?
[ "", "javascript", "regex", "string", "" ]
I want to create some heat-map style tiles to overlay over our base maps using Open Layers. Basically, I want to divide some some bounding box into a grid, and display each square of the grid using a different color based on how many points of a sample fall within that grid square. The technologies involved are C#, OpenLayers, SQL Server 2008 and GeoServer. My question is basically one of general approach, I'm not really sure where to put the tip of the chisel on this one. My ultimate goal is to be able to take any arbitrary bounding box, calculate an x-mile by x-mile grid that fits within that bounding box, the iterate over a collection of individual points and assign them to one grid square or another so I can calculate point density per grid square, then color the grid according to the densities, then overlay that on a CloudMade base map using Open Layers. Any help at all would be greatly appreciated, on the whole thing or any piece of it.
If your bounding box is axis aligned, this is fairly simple. Just make your image, and create a world file for it by hand. The world file is just 6 lines of text, and you already know everything needed (x & y pixel size, coordinate of your upper left corner). Just make sure that you use the CENTER of the upper left corner pixel, not the corner of the box. ------ Here's how you'd make the world file ------- Say your bounding box's upper left corner is at 203732x598374, and you want an image that has rectangles that are 200m wide east<->west and 300m tall north<->south. You'd make an image that was the appropriate number of pixels, then a world file that had the following 6 lines: ``` 200 0 0 -300 203632 598524 ``` This corresponds to: ``` 200 == size of one pixel in X 0 == shear1 0 == shear2 -300 == size of one pixel in Y (from top down) 203632 == left edge - 1/2 pixel size (to center on pixel instead of edge of box) 598524 == top edge - 1/2 pixel size (to center on pixel instead of edge of box) ``` If you use a .png image, you'll want to save this with the same name, but as .pgw. If you use a .jpg, it'd be .jgw, etc. For complete details, see: [Wiki on World Files](http://en.wikipedia.org/wiki/World_file)
"Dividing some some bounding box into a grid, and displaying each square of the grid using a different color based on how many points of a sample fall within that grid square." This is a **raster** and there are [features](https://web.archive.org/web/20110203142517/http://geoserver.org/display/GEOSDOC/RasterSymbolizer) in GeoServer for displaying these with colour shading, legends and so on. I think it will be more flexible to use these features than to create image tiles in C#. From the GeoServer documentation: > Raster data is not merely a picture, > rather it can be thought of as a grid > of georeferenced information, much > like a graphic is a grid of visual > information (with combination of reds, > greens, and blues). Unlike graphics, > which only contain visual data, each > point/pixel in a raster grid can have > lots of different attributes, with > possibly none of them having an > inherently visual component. This is also called thematic mapping or contour plots or heatmaps or 2.5D plots in other GIS packages. You could use a free GIS like [Grass](https://grass.osgeo.org/) to [create](http://grass.osgeo.org/gdp/html_grass63/r.resamp.interp.html) the raster grids, but from your description you don't need to interpolate (because every cell contains at least one point) so it might be just as easy to roll your own code. EDIT: there is an open source library [GDAL](https://gdal.org/) which you can use to write raster files in [various formats](https://gdal.org/formats_list.html). There are C# bindings.
Generating Geo-Referenced Images in C#
[ "", "c#", "geospatial", "openlayers", "heatmap", "geoserver", "" ]
Basically the child process runs indefinitely until killed in the background, and I want to clean it up when my program terminates for any reason, i.e. via the Taskmanager. Currently I have a while (Process.GetProcessesByName("ParentProcess").Count() > 0) loop and exit if the parent process isn't running, but it seems pretty brittle, and if I wanted it to work under debugger in Visual Studio I'd have to add "ParentProcess.vshost" or something. Is there any way to make sure that the child process end without requiring the child process to know about the parent process? I'd prefer a solution in managed code, but if there isn't one I can PInvoke. Edit: Passing the PID seems like a more robust solution, but for curiosity's sake, what if the child process was not my code but some exe that I have no control over? Is there a way to safeguard against possibly creating orphaned child processes?
If the child process is your own code, you could pass it the PID of the parent process when you launch it. The child process could then fetch the process with [`Process.GetProcessById`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessbyid.aspx) and subscribe to its [`Exited`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx) event with a handler which shuts down the rest of the (child) process gracefully. Note that you need to set the [`EnableRaisingEvents`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.enableraisingevents.aspx) property on the process to `true`.
If the child process is not your own code you can use this code to find and kill all child processes: ``` using System; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; namespace Util { public static class ProcessExtensions { public static void KillDescendants(this Process processToNotKillYet) { foreach (var eachProcess in Process.GetProcesses()) { if (eachProcess.ParentPid() == processToNotKillYet.Id) { eachProcess.KillTree(); } } } public static void KillTree(this Process processToKill) { processToKill.KillDescendants(); processToKill.Kill(); } public static PROCESS_BASIC_INFORMATION Info(this Process process) { var processInfo = new PROCESS_BASIC_INFORMATION(); try { uint bytesWritten; NtQueryInformationProcess(process.Handle, 0, ref processInfo, (uint)Marshal.SizeOf(processInfo), out bytesWritten); // == 0 is OK } catch (Win32Exception e) { if (!e.Message.Equals("Access is denied")) throw; } return processInfo; } public static int ParentPid(this Process process) { return process.Info().ParentPid; } [DllImport("ntdll.dll")] private static extern int NtQueryInformationProcess( IntPtr hProcess, int processInformationClass /* 0 */, ref PROCESS_BASIC_INFORMATION processBasicInformation, uint processInformationLength, out uint returnLength); [StructLayout(LayoutKind.Sequential)] public struct PROCESS_BASIC_INFORMATION { public int ExitStatus; public int PebBaseAddress; public int AffinityMask; public int BasePriority; public int Pid; public int ParentPid; } } } ```
Is there a way to make sure a background process spawned by my program is killed when my process terminates?
[ "", "c#", "child-process", "" ]
I have a module that I want to keep up to date, and I'm wondering if this is a bad idea: > Have a module (mod1.py) in the > site-packages directory that copies a > different module from some other > location into the site-packages > directory, and then imports \* from > that module. ``` import shutil from distutils.sysconfig import get_python_lib p_source = r'\\SourceSafeServer\mod1_current.py' p_local = get_python_lib() + r'\mod1_current.py' shutil.copyfile(p_source, p_local) from mod1_current import * ``` Now I can do this in any module, and it will always be the latest version: ``` from mod1 import function1 ``` This works.... but is there a better way of doing this? **Update** Here is the current process... there is a project under source-control that has a single module: `mod1.py` There is also a `setup.py` Running `setup.py` copies `mod1.py` to the site-packages directory. Developers that use the module must run `setup.py` to update the module. Sometimes, they don't and not having the latest version causes problems. I want to be able to just check-in the a new version, and any code that imports that module will automatically grab the latest version every time, without anyone having to run `setup.py`
In some cases, we put `.pth` files in the Python site-packages directory. The `.pth` files name our various SVN checkout directories. No install. No copy. `.pth` files are described [here](http://docs.python.org/library/site.html#module-site).
Do you *really* want to do this? This means you could very easily roll code to a production app simply by committing to source control. I would consider this a nasty side-effect for someone who isn't aware of your setup. That being said this seems like a pretty good solution - you may want to add some exception-handling around the network file calls as those are prone to failure.
Automatically fetching latest version of a file on import
[ "", "python", "version-control", "visual-sourcesafe", "" ]
We need to add a wiki to an already existing website, however we want only logged in users to be able to edit the wiki and we would prefer to use our own method of authentication. Has anyone got any experiences with something similar or any suggestions of a good wiki engine for the job? UPDATE: Thanks everyone, the general seems to be consensus is that ScrewTurn is one of the best Wiki's, however does anyone have any experience of integrating it into your own website? Imagine you have the website with the basic layout done and you have an authentication system already. How can you bring the engine into the middle of that so that your layout and menus surround the wiki and it uses your own authentication system?
I did a bit of evaluation of ASP.NET wikis recently, and the best one in my opinion is [ScrewTurn Wiki](https://stw.codeplex.com/). You could try comparing some on [WikiMatrix](http://www.wikimatrix.org) if you want to see alternatives.
[Screwturn Wiki](http://www.screwturn.eu/Wiki.ashx) is what Chuck Norris would use if he needed a Wiki
What is the best c# wiki to integrate into an already existing website?
[ "", "c#", ".net", "asp.net", "wiki", "wiki-engine", "" ]
Im breaking my head against the table right now. I have a flash batch uploader, which puts every file through upload.php which thumbnails the images, and moves them to appropriate directories. When I upload in IE, it functions perfectly (never thought I'd say this), but in Firefox, when flash executes upload.php it has its own session variable, thats different from the one that is used to browse the rest of the site, so a logged in user is no longer logged in, so their userid isnt read nor inserted into the DB, and ever a simple piece of code like this: ``` $_SESSION["uploaded_ids"][] = $inserted_id; ``` Overwrites the entire array with just the last ID, since it cannot read it to append it. What can I do? the uploader in question is this: [MultiPowUpload](http://www.element-it.com/MultiPowUpload.aspx)
If the php file is being executed via some form of ajax, and not directly from the browser, I believe the session is not persistant. IICRC Firefox treats ajax calls as new browser sessions. If this sounds like it could be the case, I usually fix these problems by manually attaching the PHPSESSID to the end of the ajax call. Hopefully this helps.
Flash DOES have access to your cookies normally, but FileReference is a strange exception in MSIE, and as you've obviously noticed will not send the current session cookie. I have got around this problem by passing the session id into flash (either with flashvars, or a separate remote service) then passing the session id in the query string when you post the FileReference upload. You can then start the session in PHP with the forced id.
Flash uploader has its own session id..... why?
[ "", "php", "flash", "" ]
I would be interested in knowing what the StackOverflow community thinks are the important language features (idioms) of Python. Features that would define a programmer as Pythonic. Python (pythonic) idiom - "code expression" that is natural or characteristic to the language Python. **Plus, Which idioms should all Python programmers learn early on?** Thanks in advance Related: * [Code Like a Pythonista: Idiomatic Python](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html) * [Python: Am I missing something?](https://stackoverflow.com/questions/566865/python-am-i-missing-something)
Python is a language that can be described as: > "rules you can fit in the > palm of your hand with a huge bag of > hooks". Nearly everything in python follows the same simple standards. Everything is accessible, changeable, and tweakable. There are very few language level elements. Take for example, the len(data) builtin function. `len(data)` works by simply checking for a `data.__len__()` method, and then calls it and returns the value. That way, `len()` can work on any object that implements a `__len__()` method. --- Start by learning about the types and basic syntax: 1. Dynamic Strongly Typed Languages 2. bool, int, float, string, list, tuple, dict, set 3. statements, indenting, "everything is an object" 4. basic function definitions Then move on to learning about how python works: 1. imports and modules (really simple) 2. the python path (sys.path) 3. the `dir()` function 4. `__builtins__` Once you have an understanding of how to fit pieces together, go back and cover some of the more advanced language features: 1. iterators 2. overrides like `__len__` (there are tons of these) 3. list comprehensions and generators 4. classes and objects (again, really simple once you know a couple rules) 5. python inheritance rules And once you have a comfort level with these items (with a focus on what makes them pythonic), look at more specific items: 1. Threading in python (note the Global Interpreter Lock) 2. context managers 3. database access 4. file IO 5. sockets 6. etc... --- And never forget **The Zen of Python** (by Tim Peters) ``` Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ```
This page covers all the major python idioms: <http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html>
What are the important language features (idioms) of Python to learn early on
[ "", "python", "idioms", "" ]
I want to build a dlinq query that checks to see if a title has any number of items in it. I know you can do `.Contains()` with a list, but I need to check if the title contains any of the items, not if the items contain part of the title. For example: I have three items in the list *"bacon, chicken, pork"*. I need the title of *"chicken house"* to match. ``` var results = (from l in db.Sites where list.Contains(l.site_title) select l.ToBusiness(l.SiteReviews)).ToList(); ``` If I try the first 2 answers, I get an error `"Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator."` The third solution gives me > Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL."
I finally figured it out. Thanks to my good buddy Cory for the help. There are two ways you can do it. ``` var resultSets = (from k in list select (from b in db.Sites where b.site_title.Contains(k) select b.ToBusiness()).ToList<Business>()).ToList(); List<Business> all = new List<Business>(); for (int i = 0; i < resultSets.Count; ++i) { all.AddRange(resultSets[i]); } ``` This is a linq query that will successfuly do what is stated. As well, you can also just build the sql query in plain text by hand.
Try the following. You can use a combination of Where and Any to search for substring matches. ``` var results = (from l in db.Sites where list.Where(x => 0 != x.IndexOf(l)).Any() select l.ToBusiness(l.SiteReviews)).ToList(); ```
How do I do a Contains() in DLINQ with a list of items?
[ "", "c#", "dynamic-linq", "" ]
Is there a way to make the default access modifier public for variable/method/class declarations? I think by default, class declarations are private yes?
You can't change the defaults. They default to the most restrictive. The default accessibility (for the type) for a top-level type is `internal`. The default accessibility (for the type) for a nested type is `private`. The default accessibility for members is private. The only time it isn't the most restrictive is for the explicit part of an automatically implemented property, where you can make it *more* restrictive by adding a modifier: ``` public int Foo {get;private set;} ```
The general rule is that the default is the most private access level which you could specify. The only *slight* variation on this is when you make one part of a property (usually the setter) more private than the rest of the property. Being able to change the default would be extraordinarily confusing to people maintaining your code. There are many who argue that you should never use the defaults anyway always explicitly specifying the visibility.
Variable/Type declaration private by default
[ "", "c#", "declaration", "" ]
Why does the following code: ``` <%= Html.ActionLink("[Click Here For More +]", "Work", "Home", new { @class = "more" }) %> ``` render as: ``` <a class="more" href="/Home/Work?Length=4">[Click Here For More +]</a> ``` Where is that "Length=4" coming from? Update If I remove the `new { @class = "more" }`, I don't get that Length=4 parameter.
I've had this happen before. If you look at the overload you're actually using it's probably not the one you want. Try... ``` <%= Html.ActionLink("[Click Here For More +]", "Work", "Home", null, new { @class = "more" }) %> ```
I look at the overloads for ActionLink and changed the code to look like: ``` <%= Html.ActionLink("[Click Here For More +]", "Work", "Home", null, new { @class = "more" }) %> ``` Added a "null" for the route values. This seems to work. Not sure though what this might affect.
Puzzling ... why do most of my links, in ASP.NET MVC, have Length=4 appended to them?
[ "", "c#", "html", "asp.net-mvc", "" ]
I've been trying to follow the principles of Dependency Injection, but [after reading this article, I know I'm doing something wrong.](http://misko.hevery.com/2008/10/21/dependency-injection-myth-reference-passing/) Here's my situation: My application receives different types of physical mail. All the incoming mail passes through my `MailFunnel` object. While it's running, `MailFunnel` receives different types of messages from the outside: Box, Postcard and Magazine. Each mail type needs to be handled differently. For example, if a Box comes in, I may need to record the weight before delivering it. Consequently, I have `BoxHandler`, `PostcardHandler` and `MagazineHandler` objects. Each time a new message comes into my `MailFunnel`, I instantiate a **new** corresponding `MailHandler` object. For example: ``` class MailFunnel { void NewMailArrived( Mail mail ) { switch (mail.type) { case BOX: BoxHandler * bob = new BoxHandler(shreddingPolicy, maxWeightPolicy); bob->get_to_work(); break; case POSTCARD: PostcardHandler * frank = new PostcardHandler(coolPicturePolicy); frank->get_to_work(); break; case MAGAZINE: MagazineHandler * nancy = new MagazineHandler(censorPolicy); nancy->get_to_work(); break; } } private: MaxWeightPolcy & maxWeightPolicy; ShreddingPolicy & shreddingPolicy; CoolPicturePolicy & coolPicturePolicy; CensorPolicy & censorPolicy; } ``` On one hand, this is great because it means that if I get five different pieces of mail in, I immediately have five different `MailHandlers` working concurrently to take care of business. However, this also means that [I'm mixing object creation with application logic](http://misko.hevery.com/2008/09/10/where-have-all-the-new-operators-gone/) - a big no-no when it comes to Dependency Injection. Also, I have all these policy references hanging around in my `MailFunnel` object that `MailFunnel` really doesn't need. The only reason that `MailFunnel` has these objects is to pass them to the `MailHandler` constructors. Again, [this is another thing I want to avoid](http://misko.hevery.com/2008/10/21/dependency-injection-myth-reference-passing/). All recommendations welcome. Thanks!
This looks more like a factory to me. Move the invocation of the get\_to\_work() method out of the invocation and return the handler. The pattern works pretty well for a factory. ``` class MailHandlerFactory { IMailHandler* GetHandler( Mail mail ) { switch (mail.type) { case BOX: return new BoxHandler(shreddingPolicy, maxWeightPolicy); break; case POSTCARD: return new PostcardHandler(coolPicturePolicy); break; case MAGAZINE: return new MagazineHandler(censorPolicy); break; } } private: MaxWeightPolcy & maxWeightPolicy; ShreddingPolicy & shreddingPolicy; CoolPicturePolicy & coolPicturePolicy; CensorPolicy & censorPolicy; } class MailFunnel { MailHandlerFactory* handlerFactory; MailFunnel( MailHandlerFactory* factory ) { handlerFactory = factory; } void NewMailArrived( Mail mail ) { IMailHandler handler = handlerFactory.GetHandler(mail); handler.get_to_work(); } } ```
Why can't you just have three methods that are overloaded which take the different types of mail, and then do the appropriate thing? Or have each type handle itself. In fact, if you have something like type, chances are you should in fact have different types. Basically do the following: 1) Make the Mail class abstract. 2) Create a three sub classes of mail, Box, PostCard, and Magazine 3) Give each subclass a method to handle mail, or centralize it in a separate HandlerFactory 4) When passed to the mail funnel, simply have it call the handle mail method, or have the HandlerFactory pass it the mail, and get the appropriate handler back. Again, rather than having awkward switch statements everywhere, use the language, this is what types and method overloading is for. If your mail handling becomes complex and you want to take it out, you can eventually make a mail handler class and extract those policies into that. You can also consider using a template method, because the only real difference between each of those seems to be the handler you instance, maybe you could simplify it, such that the mail type determines the handler, the rest of the code is basically the same.
Dependency Injection and Runtime Object Creation
[ "", "c++", "dependency-injection", "" ]
I'm trying to build an efficient string matching algorithm. This will execute in a high-volume environment, so performance is critical. Here are my requirements: * Given a domain name, i.e. www.example.com, determine if it "matches" one in a list of entries. * Entries may be absolute matches, i.e. www.example.com. * Entries may include wildcards, i.e. \*.example.com. * Wildcard entries match from the most-defined level and up. For example, \*.example.com would match www.example.com, example.com, and sub.www.example.com. * Wildcard entries are not embedded, i.e. sub.\*.example.com will not be an entry. Language/environment: C# (.Net Framework 3.5) I've considered splitting the entries (and domain lookup) into arrays, reversing the order, then iterating through the arrays. While accurate, it feels slow. I've considered Regex, but am concerned about accurately representing the list of entries as regular expressions. My question: what's an efficient way of finding if a string, in the form of a domain name, matches any one in a list of strings, given the description listed above?
If you're looking to roll your own, I would store the entries in a tree structure. See [my answer to another SO question](https://stackoverflow.com/questions/346757/how-do-spell-checkers-work/346818#346818) about spell checkers to see what I mean. Rather than tokenize the structure by "." characters, I would just treat each entry as a full string. Any tokenized implementation would still have to do string matching on the full set of characters anyway, so you may as well do it all in one shot. The only differences between this and a regular spell-checking tree are: 1. The matching needs to be done in reverse- You have to take into account the wildcards To address point #2, you would simply check for the "\*" character at the end of a test. A quick example: Entries: ``` *.fark.com www.cnn.com ``` Tree: ``` m -> o -> c -> . -> k -> r -> a -> f -> . -> * \ -> n -> n -> c -> . -> w -> w -> w ``` Checking www.blog.fark.com would involve tracing through the tree up to the first `"*"`. Because the traversal ended on a `"*"`, there is a match. Checking www.cern.com would fail on the second "n" of n,n,c,... Checking dev.www.cnn.com would also fail, since the traversal ends on a character other than `"*"`.
I would use Regex, just make sure to have it the expression compiled once (instead of it being calculated again and again).
Efficient string matching algorithm
[ "", "c#", "algorithm", "" ]
Most projects have some sort of data that are essentially static between releases and well-suited for use as an enum, like statuses, transaction types, error codes, etc. For example's sake, I'll just use a common status enum: ``` public enum Status { ACTIVE(10, "Active"); EXPIRED(11, "Expired"); /* other statuses... */ /* constructors, getters, etc. */ } ``` I'd like to know what others do in terms of persistence regarding data like these. I see a few options, each of which have some obvious advantages and disadvantages: * Persist the possible statuses in a status table and keep all of the possible status domain objects cached for use throughout the application * Only use an enum and don't persist the list of available statuses, creating a data consistency holy war between me and my DBA * Persist the statuses and maintain an enum in the code, but don't tie them together, creating duplicated data My preference is the second option, although my DBA claims that our end users might want to access the raw data to generate reports, and not persisting the statuses would lead to an incomplete data model (counter-argument: this could be solved with documentation). Is there a convention that most people use here? What are peoples' experiences with each and are there other alternatives? **Edit:** After thinking about it for a while, my real persistence struggle comes with handling the id values that are tied to the statuses in the database. These values would be inserted as default data when installing the application. At this point they'd have ids that are usable as foreign keys in other tables. I feel like my code needs to know about these ids so that I can easily retrieve the status objects and assign them to other objects. What do I do about this? I could add another field, like "code", to look stuff up by, or just look up statuses by name, which is icky.
We store enum values using some explicit string or character value in the database. Then to go from database value back to enum we write a static method on the enum class to iterate and find the right one. If you expect a lot of enum values, you could create a static mapping `HashMap<String,MyEnum>` to translate quickly. Don't store the actual enum name (i.e. "ACTIVE" in your example) because that's easily refactored by developers.
I'm using a blend of the three approaches you have documented... Use the database as the authoritative source for the Enum values. Store the values in a 'code' table of some sort. Each time you build, generate a class file for the Enum to be included in your project. This way, if the enum changes value in the database, your code will be properly invalidated and you will receive appropriate compile errors from your Continuous Integration server. You have a strongly typed binding to your enumerated values in the database, and you don't have to worry about manually syncing the values between code and the data.
Persisting data suited for enums
[ "", "java", "types", "enums", "persistence", "" ]
if you have an entity which is reference in the client and a webservice like this ``` public class Post { public int ID {get; set;} string Data {get; set;} } public class MyService: System.Web.Services.WebService { [WebMethod] public int Write (Post post) { //Do stuff } } ``` on the client in order to use the entity you to instantiate from the proxy class ``` public void ClientMethod() { var post = new proxyclass.Post(); //fill post new ProxyClass.Myservice().Write(post) } ``` how can i use my domain entity to call the webservice? ``` public void ClientMethod() { var post = new Post(); //fill post new ProxyClass.Myservice().Write(post) } ```
Basically, you can't - with regular web-services, at least... the proxy class is completely separate. However, the above *is* possible with WCF, where you don't actually need proxy classes *at all* (however, for SOA purity it is a good idea to use them). You could use reflection (etc) to copy the properties *between* your domain entities and the proxies, but it is quite hard to get this 100% right (although xml serialization should work [in theory] as an intermediate language). --- So; if you want to use assembly sharing; consider using WCF, which supports this ;-p To get hold of a service without using a proxy layer, you can do tricks like: ``` public class WcfClient<T> : ClientBase<T> where T : class { public T Service { get { return base.Channel; } } } ``` (this will access the default configuration from the app.config; for more control you need to add a few constructor overloads matching to the base constructor overloads) Then: ``` interface IFoo {void Bar();} ... using(WcfClient<IFoo> client = new WcfClient<IFoo>()) { client.Service.Bar(); } ```
You should use WCF for new development whenever possible. However, you should reconsider your reasons for wanting to use your domain class on the client. It does violate the principles of SOA by exposing to the client some details of the implementation of the service. Why should the client know anything about your entity classes, beyond the data that they contain? For instance, your entity classes may contain methods to save the entity to the database. Why does your client need access to that method? Also, one of the principals of SOA is to interoperate with different platforms. As soon as you require your client to use your (.NET) entity, you prevent a Java or PHP client from being written to use your service. You may have good enough reasons to overcome such objections, but I recommend that you think it through and make sure your reasons are good enough.
how to use your same Domain entities throug a .Net webservice?
[ "", "c#", ".net", "web-services", "casting", "" ]
I'm working on a search function for an MVC C# app that will place a (possibly large) chunk of text through a filter, and given the search query, will place an html `<span>` with a highlighted style before and after each search term. I've got a simple algorithm working, but I've got a feeling it will be slow, probably because of the amount of strings that will need to be created (2 \* the number of matches). ``` public static string Surround(string original, string head, string tail, string match, StringComparison comparer) { var ret = original; if (ret.IndexOf(match, 0, comparer) != -1) { var lastIndex = 0; while ((lastIndex = ret.IndexOf(match, lastIndex, comparer)) != -1) { ret = ret.Insert(lastIndex, head); var tailIndex = lastIndex + match.Length + head.Length; lastIndex = tailIndex; ret = ret.Insert(tailIndex, tail); } } return ret; } ``` I'm wondering if anyone can give some hints for a better algorithm that would perform better for large chunks of text? I was thinking of using a stringbuilder, but it's also occurred to me that I could be approaching this from entirely the wrong way. Any insight would be greatly appreciated.
A regular expression will do the job, and the code should be a lot simpler. However you'd need to test to determine if it actually delivers better performance. Something like this: ``` public static string Surround( string original, string head, string tail, string match) { return Regex.Replace( original, match, head + "$0" + tail, RegexOptions.IgnoreCase); } ``` Even better if you can pass in the replacer whole as you save 2N string concats: ``` public static string Surround(string original, string replacer, string match) { return Regex.Replace(original, match, replacer, RegexOptions.IgnoreCase); } Surround("foo bar baz", "<span>$&</span>", "bar"); //call like so ```
A StringBuilder will of course be much faster, but never the less when you do an .Insert you will be moving around a whole lot of data each time. So it would be better to build up the result in the StringBuilder using only .Append. Not .Insert. However, you should also be able to use a RegularExpression for this, although I don't know the syntax by heart (I use a wonderful tool called RegEx Buddy to build my regular expressions when I have the need.). EDIT: Very few people in this world have the ability to distinguish a regular expression from tranismission line noise. :-)
Best algorithm for inserting text before and after a token in C#?
[ "", "c#", "search", "highlight", "" ]
I have a Java program consisting of about 15 methods. And, these methods get invoked very frequently during the exeuction of the program. At the moment, I am creating a new connection in every method and invoking statements on them (Database is setup on another machine on the network). What I would like to know is: Should I create only one connection in the main method and pass it as an argument to all the methods that require a connection object since it would significantly reduce the number of connections object in the program, instead of creating and closing connections very frequently in every method. I suspect I am not using the resources very efficiently with the current design, and there is a lot of scope for improvement, considering that this program might grow a lot in the future.
Yes, you should consider re-using connections rather than creating a new one each time. The usual procedure is: * make some guess as to how many simultaneous connections your database can sensibly handle (e.g. start with 2 or 3 per CPU on the database machine until you find out that this is too few or too many-- it'll tend to depend on how disk-bound your queries are) * create a **pool** of this many connections: essentially a class that you can ask for "the next free connection" at the beginning of each method and then "pass back" to the pool at the end of each method * your getFreeConnection() method needs to return a free connection if one is available, else either (1) create a new one, up to the maximum number of connections you've decided to permit, or (2) if the maximum are already created, wait for one to become free * I'd recommend the Semaphore class to manage the connections; I actually have a short article on my web site on [managing a resource pool with a Semaphore](http://www.javamex.com/tutorials/synchronization_concurrency_semaphore2.shtml) with an example I think you could adapt to your purpose A couple of practical considerations: * For optimum performance, you need to be careful **not to "hog" a connection while you're not actually using it to run a query**. If you take a connection from the pool once and then pass it to various methods, you need to make sure you're not accidentally doing this. * Don't forget to return your connections to the pool! (try/finally is your friend here...) * On many systems, you **can't keep connections open 'forever'**: the O/S will close them after some maximum time. So in your 'return a connection to the pool' method, you'll need to think about **'retiring' connections that have been around for a long time** (build in some mechanism for remembering, e.g. by having a **wrapper object** around an actual JDBC Connection object that you can use to store metrics such as this) * You may want to consider using prepared statements. * Over time, you'll probably need to **tweak the connection pool size**
You can either pass in the connection or better yet use something like Jakarta Database Connection Pooling. <http://commons.apache.org/dbcp/>
How many JDBC connections in Java?
[ "", "java", "performance", "jdbc", "database-connection", "" ]
In Java, is there any way to use the JDK libraries to discover the private classes implemented within another class? Or do I need so use something like asm?
[`Class.getDeclaredClasses()`](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getDeclaredClasses()) is the answer.
I think this is what you're after: [`Class.getClasses()`](https://java.sun.com/javase/6/docs/api/java/lang/Class.html#getClasses())
Can I discover a Java class' declared inner classes using reflection?
[ "", "java", "reflection", "" ]
I need to select the rows of a table where a column value is numeric, any Help? EDIT: I have a varchar column and I need to select the ones that are numbers and the ones that are not. EDIT 2: Integer.TryParse cannot be use because it cannot be translate to SQL.
I don't know if there is a mapping for int.TryParse() in LinqToSQL, but you could probably do it in two steps by performing the query, casting to a List, then selecting out of the list with LinqToObjects. ``` int i; var query = context.Table.ToList(); var intQuery = query.Where( t => int.TryParse( t.Column, out i ) ); ``` You might want to look at [Dynamic LINQ](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx), too. That would allow you to do something like: ``` var query = context.Table.Where( "IsNumeric(Column)" ); ``` **EDIT** Dynamic LINQ is available in the VS2008 Code Samples, linked to from Scott Guthrie's blog, which I've linked above.
Open up your DBML (LINQ-to-SQL) file in an XML editor, go down to the end of the file and paste this just before the '</Database>' node: ``` <Function Name="ISNUMERIC" IsComposable="true"> <Parameter Name="Expression" Parameter="Expression" Type="System.String" DbType="NVarChar(4000)" /> <Return Type="System.Boolean" DbType="BIT NOT NULL"/> </Function> ``` Now, you can use the *already-in-SQL* function called "ISNUMERIC". Here's how: ``` var blah = myDataContext.Accounts.Where(account=> myDataContext.ISNUMERIC(account.ID) == true); ``` There you go :) You may also find these functions useful to copy: ``` <Function Name="RAND" IsComposable="true"> <Return Type="System.Double" DbType="Float NOT NULL" /> </Function> <Function Name="NEWID" IsComposable="true"> <Return Type="System.Guid" DbType="UniqueIdentifier NOT NULL" /> </Function> ```
How to know if a field is numeric in Linq To SQL
[ "", "c#", "sql-server", "linq-to-sql", "" ]
How can a C# program running as LocalSystem impersonate the login identity of another user temporarily? Roughly speaking I have a Windows Service that I'd like to run as LocalSystem but at times impersonate user XYZ (when connecting to a db using windows integrated security). Most important of all: Is there a way to do this without knowing the other user's password? Note: if a password is mandatory is there a recommended strategy for storing a password securely (c# and/or vbscript).
It's possible, although it requires you to do a lot of code. See [NtCreateToken](http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/NT%20Objects/Token/NtCreateToken.html) and [CreateToken](https://msdn.microsoft.com/en-us/library/windows/desktop/aa374780(v=vs.85).aspx). You need SeCreateTokenPrivilege, although that won't be a problem since you're running under NT AUTHORITY\SYSTEM. You can then use the created token to impersonate inside a thread.
Short answer: you can't without the user password or the user calling your service through COM. To impersonate another user in your process, you have to call [`ImpersonateLoggedOnUser`](http://msdn.microsoft.com/en-us/library/aa378612.aspx). `ImpersonateLoggedOnUser` requires a token handle. There are several ways you can obtain token handle: * by logging on as the user with [`LogonUser`](http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx). This however requires you to know the user password. * by duplicating an existing token with [`CreateRestrictedToken`](http://msdn.microsoft.com/en-us/library/aa446583(VS.85).aspx), [`DuplicateToken`](http://msdn.microsoft.com/en-us/library/aa446616(VS.85).aspx), or [`DuplicateTokenEx`](http://msdn.microsoft.com/en-us/library/aa446617(VS.85).aspx). * by opening the token from another process or thread, that already is loggen on as the user, with [`OpenProcessToken`](http://msdn.microsoft.com/en-us/library/aa379295(VS.85).aspx) or [`OpenThreadToken`](http://msdn.microsoft.com/en-us/library/aa379296(VS.85).aspx)
Windows Impersonation from C#
[ "", "c#", "windows", "impersonation", "" ]
I am trying to search employees based on their code and department. I triggered a query using IN operator which has 1200 employee codes. When i executed the query I got an exception ("Maximum 1000 records allowed in IN "). Can anyone help me out with this issue.
Many DBMS don't allow a query like ``` SELECT * FROM table WHERE col IN (...) ``` with more than 1,000 values in the list. Maybe it is possible to split it up using chunks of less than 1,000 values: ``` SELECT * FROM table WHERE col IN (...) OR col IN (...) ``` or ``` SELECT * FROM table WHERE col IN (...) UNION SELECT * FROM table WHERE col IN (...) ``` (Although it would not make sense and is unlikely to work). Otherwise, you should store your values in a temporary table and use a JOIN instead. Where do you get your 1,200 codes from -- they don't happen to be in the same database? :)
Uploading those records to a temporary table and using a join is almost certainly going to be much faster. As it is, the parser has to build a huge condition tree for the IN. Note: I don't know if MYSQL supports the transaction-level temporary tables of Oracle or SQLServer, but even a "real" table should be faster, particularly if created once and reused. There are, of course, many variables such as the ability to batch inserts to that table, cost of writing transactions logs, &c. Rereading your question: where do you get those employee codes? Can you get them from a table or join?
Problem with "IN" while executing query
[ "", "sql", "mysql", "" ]
I have a servlet based application that is serving images from files stored locally. I have added logic that will allow the application to load the image file to a BufferedImage and then resize the image, add watermark text over the top of the image, or both. I would like to set the content length before writing out the image. Apart from writing the image to a temporary file or byte array, is there a way to find the size of the BufferedImage? All files are being written as jpg if that helps in calculating the size.
No, you must write the file in memory or to a temporary file. The reason is that it's impossible to predict how the JPEG encoding will affect file size. Also, it's not good enough to "guess" at the file size; the `Content-Length` header has to be spot-on.
``` BufferedImage img = = new BufferedImage(500, 300, BufferedImage.TYPE_INT_RGB); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); ImageIO.write(img, "png", tmp); tmp.close(); Integer contentLength = tmp.size(); response.setContentType("image/png"); response.setHeader("Content-Length",contentLength.toString()); OutputStream out = response.getOutputStream(); out.write(tmp.toByteArray()); out.close(); ```
How to calculate java BufferedImage filesize
[ "", "java", "bufferedimage", "" ]
Can you call a vb.net api function using reflection from javascript code? I just started playing around with reflection, I have this snippet of code that works, I want to change it to a javascript page. ``` Dim RawPlugin As Reflection.Assembly RawPlugin = Reflection.Assembly.LoadFrom("C:\Inetpub\wwwroot\demo\MasterApplication\getSession\bin\Debug\getSession.dll") Dim Instance As Object Instance = RawPlugin.CreateInstance("getSession.class1", True, _ Reflection.BindingFlags.Default, Nothing, Nothing, Nothing, Nothing) theValue = Instance.getSessionValue(Session).ToString ``` Does anyone know if this is possible?
Client side code doesn't speak directly to server side code. If the information you are looking for is unaffected in between page requests by the user, then you have two options: output the server side value to the client with the page request (so it's value is inside a JavaScript variable on the page), or make it an ajax call. If the information could possibly be stale in between page requests, then you're only option is to return the value from an ajax call.
In ASP.Net, the .Net code runs on your web server. Javascript runs on the user's computer, in their browser. That user might not even have *Windows*, let alone the .Net runtime. For that matter, your user might not even have javascript enabled.
JavaScript triggering - reflection of vb.net api calls?
[ "", "asp.net", "javascript", "reflection", "system.reflection", "" ]
I am trying to build Python 2.6 for [QGIS](http://en.wikipedia.org/wiki/Quantum_GIS) on [RHEL](http://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux) 5. During the making of QGIS I get the following error: ``` Linking CXX shared library libqgispython.so /usr/bin/ld: /usr/local/lib/python2.6/config/libpython2.6.a(abstract.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC /usr/local/lib/python2.6/config/libpython2.6.a: could not read symbols: Bad value collect2: ld returned 1 exit status make[2]: *** [src/python/libqgispython.so.1.0] Error 1 make[1]: *** [src/python/CMakeFiles/qgispython.dir/all] Error 2 make: *** [all] Error 2 ``` What I figure out from this error is that I need to build Python 2.6 with some flag, `-fPIC`. OK, so I found it in the `configure.in` file but it checks several conditions and on the basis of those conditions it assigns `-fPIC` to the `CCSHARED` flag. What I did was that after all conditions were checked I added the following line to deliberately use `CCSHARED` as `-fPIC`. ``` CCSHARED="-fPIC"; ``` But it did not work.. How to specify while configuring that I want to set `CCSHARED` as `-fPIC`?
Run configure with `--enable-shared`. Then `-fPIC` will be included as part of the shared flags.
The following worked for me when I ran into this error: ``` make clean ./configure CFLAGS=-fPIC CXXFLAGS=-fPIC ```
How can I set ccshared=-fPIC while executing ./configure?
[ "", "c++", "makefile", "g++", "" ]
Can you pass a standard c# enum as a parameter? For example: ``` enum e1 { //... } enum e2 { //... } public void test() { myFunc( e1 ); myFunc( e2 ); } public void myFunc( Enum e ) { // Iterate through all the values in e } ``` By doing this I hope to retrieve all the names within any given enum. What would the Iteration code look like?
This! ``` public void Foo(Enum e) { var names = Enum.GetNames(e.GetType()); foreach (var name in names) { // do something! } } ``` EDIT: My bad, you *did* say *iterate*. Note: I know I could just do the GetNames() call in my foreach statement, but I prefer to assign that type of thing to a method call first, as it's handy for debugging.
Use the Enum.GetNames( typeof(e) ) method, this will return an array of strings with the names. You can also use Enum.GetValues to obtain the counterpart values. Edit -Whoops - if you are passing the parameter as Enum, you will need to use e.GetType() instead of typeof() which you would use if you had passed the parameter in as the actual Enum type name.
C# enums as function parameters?
[ "", "c#", "enums", "loops", "function-parameter", "" ]
We are using a custom sitemap provider to populate an ASP.Net application's menu control from a recursive database table and therefore do not use the static xml web.sitemap file: ``` <?xml version="1.0" encoding="utf-8" ?> <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode url="" title="" description=""> <siteMapNode url="" title="" description="" /> <siteMapNode url="" title="" description="" /> </siteMapNode> </siteMap> ``` For SEO optimization reasons would it be useful to export the customsitemap provider's items into the web.sitemap file even though the app doesn't even use the web.sitemap file? If it does impact positively on SEO, what approach to use to get the sitemapprovider items into the xml file in the correct format? How would you go about doing that?
I'm not sure anything particularly cares about asp.net's sitemap beyond asp.net itself. As far as converting into the infinitely more SEO happy [(Google) Sitemap schema](http://www.sitemaps.org/protocol.php) - this is the kind of job XSLT is designed for.
I'll second annakata there. Google is not going to care about your asp.net sitemap file. You'll need to create one that conforms to the [sitemap spec](http://www.sitemaps.org/protocol.php). XSLT would be a great solution for creating that from your existing sitemap. Also, keep in mind that if you have lots of links (over 50,000 URLs or more than a 10MB sitemap) you'll need to use a special sitemap index with multiple sitemaps. To make sure your sitemap is found by search engines, put a reference to it in your robots.txt file as well: ``` Sitemap: <sitemap_location> ``` You can also use [Google's webmaster tools](http://www.google.com/webmasters/) to let them know about your sitemap. This will generally help your site get indexed more quickly, and also provides lots of great info about your site (broken sitemap links, pagerank stats, etc). Yahoo has a similar tool called [site explorer](https://siteexplorer.search.yahoo.com/) as well.
SEO: Custom sitemap provider versus static web.sitemap file
[ "", "c#", "asp.net", "seo", "sitemap", "" ]
I'm trying to implement a Facebook like toolbar on the bottom of the screen for a website I'm currently working on. Currently, I have it 100% of the width of the screen but I'd like to have it look almost exactly like Facebook's toolbar, centered, bottom justified on top, around 80% of the current screen's width. Here is the current CSS for the toolbar I have that is 100% of the screen's width. Thanks in advance. CSS: ``` <style type="text/css"> #toolbar { background:url('/_assets/img/toolbar.gif') repeat-x; height:25px; position:fixed; bottom:0px; width:100%; left:0px; border-left:1px solid #000000; border-right:1px solid #000000; z-index:100; font-size:0.8em; } </style> ```
use: ``` left:10%; right:10%; ```
``` width: 80%; left: 10%; right: 10%; ``` How's that?
Floating toolbar on bottom, centered, 80% of current screen width
[ "", "javascript", "html", "css", "" ]
I want to run a cron job that does cleanup that takes a lot of CPU and Mysql resources. I want it to run only if the server is not relatively busy. What is the simplest way to determine that from PHP? (for example, is there a query that returns how many queries were done in the last minute? ...)
``` if (function_exists('sys_getloadavg')) { $load = sys_getloadavg(); if ($load[0] > 80) { header('HTTP/1.1 503 Too busy, try again later'); die('Server too busy. Please try again later.'); } } ``` Try to update this function to your needs
If this is a Unix system, parse the output of `uptime`. This shows the CPU load which is generally considered to be a good measure of "busy." Anything near or over `1.0` means "completely busy." There are three CPU "load" times in that output giving the load average over 1, 5, and 15 minutes. Pick whichever makes sense for your script. Definition of "load" [is here](http://www.usenet-forums.com/linux-general/88308-what-does-uptimes-load-average-mean.html).
How can my PHP script tell whether the server is busy?
[ "", "php", "mysql", "load", "" ]
I'm trying to create a program to clone multiple bugs at a time through the web interface of our defect tracking system. How can I wait before a page is completely loaded before I continue? ``` //This is pseudo code, but this should give you an idea of what I'm trying to do. The //actual code uses multi-threading and all that good stuff :). foreach (string bug in bugs) { webBrowser.Navigate(new Uri(url)); webBrowser.Document.GetElementById("product").SetAttribute("value", product); webBrowser.Document.GetElementById("version").SetAttribute("value", version); webBrowser.Document.GetElementById("commit").InvokeMember("click"); //Need code to wait for page to load before continuing. } ```
Try the `DocumentCompleted` Event: ``` webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted); void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { webBrowser.Document.GetElementById("product").SetAttribute("value", product); webBrowser.Document.GetElementById("version").SetAttribute("value", version); webBrowser.Document.GetElementById("commit").InvokeMember("click"); } ```
This code was very helpful for me. Maybe it could be for you also ``` wb.Navigate(url); while(wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } MessageBox.Show("Loaded"); ```
C# how to wait for a webpage to finish loading before continuing
[ "", "c#", "webbrowser-control", "" ]
We have a SQL server that has a database for each client, and we have hundreds of clients. So imagine the following: database001, database002, database003, ..., database999. We want to combine all of these databases into one database. Our thoughts are to add a siteId column, 001, 002, 003, ..., 999. We are exploring options to make this transition as smoothly as possible. And we would LOVE to hear any ideas you have. It's proving to be a VERY challenging problem. I've heard of a technique that would create a view that would match and then filter. Any ideas guys?
Create a client database id for each of the client databases. You will use this id to keep the data logically separated. This is the "site id" concept, but you can use a derived key (identity field) instead of manually creating these numbers. Create a table that has database name and id, with any other metadata you need. The next step would be to create an SSIS package that gets the ID for the database in question and adds it to the tables that have to have their data separated out logically. You then can run that same package over each database with the lookup for ID for the database in question. After you have a unique id for the data that is unique, and have imported the data, you will have to alter your apps to fit the new schema (actually before, or you are pretty much screwed). If you want to do this in steps, you can create views or functions in the different "databases" so the old client can still hit the client's data, even though it has been moved. This step may not be necessary if you deploy with some downtime. The method I propose is fairly flexible and can be applied to one client at a time, depending on your client application deployment methodology.
Why do you want to do that? You can read about [Multi-Tenant Data Architecture](http://msdn.microsoft.com/en-us/library/aa479086.aspx) and also listen to [SO #19 (around 40-50 min)](https://blog.stackoverflow.com/2008/08/podcast-19/) about this design.
Ideas for Combining Thousand Databases into One Database
[ "", "sql", "sql-server", "" ]
For a website I'm doing we're using LINQ to Entities. I have been charged with adding search functionality to the site. I'm trying to figure out the most elegant way to search for multiple keywords (user entered) on a single field in the database. Allow me to give an example. Table columns: ``` Name, Description ``` Example row: ``` "Cookie monster", "Fluffy, likes cookies and blue" ``` User search (delimiter doesn't matter): ``` "blue fluffy" ``` Currently I am using the following: ``` public List<SesameCharacters> SearchByKeywords(string keywords) { List<SesameCharacters> output = new List<SesameCharacters>(); string[] k = keywords.ToLower().Split(' '); using (SesameStreet_Entities entities = new SesameStreet_Entities()) { IQueryable<SesameCharacters> filter = entities.SesameCharacters; foreach (string keyword in k) filter = ForceFilter(filter, keyword); output = filter.ToList(); } return output; } private IQueryable<SesameCharacters> ForceFilter(IQueryable<SesameCharacters> filter, string keyword) { return filter.Where(p => p.Description.ToLower().Contains(keyword)); } ``` This currently works as expected but I imagine it is not the best solution to the problem. Am I missing something glaringly obvious? *NOTE:* This is `AND` matching.
Looks like Linq to Entities doesn't support contains: <http://msdn.microsoft.com/en-us/library/bb738638.aspx> I'd roll my own query for this one. Your probably going to want full control over the text search queries if you find out these types of searches become performance issues.
I found this worked for me - this is using VB.Net with Entity Framework 4.0, but I'm sure the principle translates. This one does the "OR" style query: ``` Function Search(ByVal query As String) As IQueryable(Of Product) Dim queryWords As String() = query.Split() Dim entities As New Entities() Return entities.Products.Where(Function(p) queryWords.Any(Function(w) p.Description.Contains(w))) End Function ``` And this one does "AND" style queries: ``` Function Search(ByVal query As String) As IQueryable(Of product) Dim queryWords As String() = query.Split() Dim entities As New Entities() Return entities.Products.Where(Function(p) queryWords.All(Function(w) p.Description.Contains(w))) End Function ```
LINQ to Entities Searching text properties for multiple keywords
[ "", "c#", "search", "linq-to-entities", "" ]
I'm currently using a PHPBB2 forum for a section of one of my sites, and I would like to extend this site (add new pages, scripts, etc). I would like to restrict access to these pages to the users already logged in the PHPBB2 Forum. In fact, if only members of a certain MemberGroup could access these pages, that would be great. Is there a way to use the same login credentials on the rest of my site, and to check out which groups the members are from? Thanks (by the way, these pages are in PHP)
If a user is logged into PHPBB, there's a good chance, though not always likely, that they will then have a cookie that you can read and help with checking who's who against the database. In this case, you'll want to break the crumbs of the cookie below: ``` $_COOKIE["phpbb2mysql_data"] ``` Let's use an example and blow it out to find the data we need to query against the database. Below is the chunk found in the above cookie: ``` a:2:{s:11:"autologinid";s:0:"";s:6:"userid";s:1:"3";} ``` For this, you'll want to go in and extract that "3" which happens to correspond to the logged in PHPBB user. [Unserialize that data](http://au.php.net/unserialize) to yank that user\_id out: ``` $goo = unserialize($_COOKIE["phpbb2mysql_data"]); $extracted_id = $goo["userid"]; ``` (Thanks to [epochwolf](https://stackoverflow.com/users/16204/epochwolf) on pointing out the above serialized form of that cookie) That number will be good to run against the database to check out which group the member belongs to. And you would run the check against the `phpbb_user_group` table (if you had phpbb\_ as the prefix of your forum tables.) If you didn't want to keep track of the group IDs from the database, then you will need to do some kind of join and test against the name. Maybe something like this: ``` SELECT pug.user_id FROM phpbb_user_group pug LEFT JOIN phpbb_groups g ON pug.group_id=g.group_id WHERE pug.user_id='$extracted_id' AND g.group_name='Foo'; ``` If you can pull a row out of that, then you've found yourself a logged in user who belongs to that Foo group.
Use PHPBB2's user table and it's login and permissions code in the other pages. It's dirty but it works. By using PHPBB2's code, I mean: Dig into PHPBB2's code, figure out how PHPBB2 authenticates users, and copy the relevant chunks of code. If PHPBB2 is decently structured, you may be able to just include a couple of files from within PHPBB2 and use them without a major hack job. If it's not nicely structured, it's going to be dirty and ugly. Don't forgot to test your new secured additions to your website! Make sure that you get the hacks right.
Use PHPBB2 Login Credentials in my site
[ "", "php", "authentication", "credentials", "phpbb", "" ]
I have to encode the 5 XML reserved chars (& < > " and ') properly as follows: ``` "&", "&amp;" "<", "&lt;" ">", "&gt;" "\"", "&quot;" "\'", "&apos;" ``` I can do them one by one, but is it possible in regexp something like ("[&|<|>|\"|\']", "&|<"); ... etc so that it will not be executed in 5 operations one after another but alltogether simultaneously? by the way, Possibly in Java using `String.replaceAll(regexpString, string);`
``` protected static void escapeXMLSpecialCharactersAndWrite(Writer writer, String str) throws IOException { int len = str.length(); for (int i = 0; i < len; i++) { char c = str.charAt(i); switch (c) { case '&': writer.write("&amp;"); break; case '<': writer.write("&lt;"); break; case '>': writer.write("&gt;"); break; case '\"': writer.write("&quot;"); break; case '\'': writer.write("&apos;"); break; default: writer.write(c); break; } } } ```
Use StringEscapeUtils.escapeXml in commons-lang library. BTW, I never start a Java progress without adding almost all of the commons library to my dependencies. They save loooooooots of time.. ``` <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.4</version> </dependency> ```
replace a set of characters with another set of chars (in pair): "&", "&amp;" "<", "<" etc. in regex
[ "", "java", "xml", "regex", "" ]
Currently it seems that I can only use effects in their most basic form when using the Dialog widget. For example, the following will use the drop effect for both showing and hiding the dialog box: ``` $('#dialog').dialog({show:'drop', hide:'drop'}); ``` However, the default for the drop method always drops to the left. What I really want is for it to drop to the right. Something like this: ``` $('#dialog').dialog({ show:{effect:'drop', direction:'right'}, hide:{effect:'drop', direction:'right'} }); ``` Is this possible? I'm currently using 1.6rc6. I've also tried it 1.5.3 (stable) without any luck. --- After digging into the source a bit, I don't think this is supported in both version 1.5.3 and 1.6rc\*. It'll probably require a change to the API before the functionality above can be supported. Steerpike has found a [version](http://labs.cloudream.name/jquery/dialog/dialog.html) that probably should be in the mainline. If anyone knows otherwise, do correct me.
This is currently not Possible with 1.6 and 1.7.1.
Actually, you can use any of the jQuery UI effects; e.g. pulsate: ``` $("#dialog").dialog({ show: "pulsate" }); ``` There are plenty to be found here: <http://docs.jquery.com/UI/Effects/> Note that there is a dependency on effects.core.js. I tried passing an option (like you did) into 'show', it didn't work. I also tried to make 'show' a function, no luck avail. What works however is: ``` $("a").click(function() { $("#dialog").hide("drop", { direction: "right" }, 1000); }); ```
Is possible to have more granular control over jQuery UI Dialog Widget's show/hide method?
[ "", "javascript", "jquery", "jquery-ui", "dialog", "effects", "" ]
I dont think this is quite possible, but its worth a shot to see what you guys say. I am trying to create a half-elliptical button in C# (not XAML, that might through another curve ball). If I wanted a pre-determined size for the buttons, I would just use images or something like that, but thats not the case since the size changes. Here is more detail: 1. I have an ellipse with x-radius and y-radius (or width and height, respectfully multiplied by 2). 2. I want two button to fill the entire ellipse, each taking up one half of the ellipse. 3. I dont want rectangular button that extend beyond the ellipse and get clipped to the parent, I want actual elliptical buttons, except only one-half of an ellipse per button. 4. If this cant be accomplished using buttons, but using some other control, then I'd like that control to be able to act like a button. Any help or advice or pointers would greatly help.
Before I answer this, I'd love to know WHY you have to avoid XAML, in a WPF application? You would almost certainly be indirectly using XAML anyway, so why not use it - making your button should then be a piece of cake! That's exactly what it's for ! This is like trying to make a house with sticky-tape when you are standing next to bricks and mortar! :)
Use XAML, seriously XAML may look daunting at first but it's nothing like the headache you're creating for yourself by trying to do this purely in code behind. [Custom WPF Button Style](http://mark-dot-net.blogspot.com/2007/07/creating-custom-wpf-button-template-in.html) [Step-by-Step Introduction to styling with Blend](http://expression.microsoft.com/en-us/dd279541.aspx) [XAML Level 100](http://www.danielmoth.com/Blog/2008/05/xaml-level-100.html)
WPF: Create half elliptical button
[ "", "c#", "wpf", "button", "ellipse", "" ]
What i am doing is a new image uploader, i want to put the input file in the iframe and show the uploaded images in the parent page. So how can i access the parent elements from the inner iframe? or if some one have an example, that will be nice as well.
Frame object .parent will allow you to access the outer, or even document.top. If the two pages are not on the same domain your browser will likely block the script execution as an XSS attack.
You have limited options since iframes are **not compatible** browser-wide. If you really stick to it, you can have it done only via server-side. JavaScript handles iframes incorrectly in many contexts, it is insecure, uncertain and doubtedly. If you are open-minded enough, check out **Ajax** frameworks to change your uploading iframe into a smooth and effective uploader. If you're interested in the latter, examples might be available on the air.
how to access iframe parent elements?
[ "", ".net", "asp.net", "javascript", "html", "ajax", "" ]
We have a flex application that works with ASP.NET. (through weborb). And we use several data at the .NET Side to load data, ex: UserId, ChannelId, ... For now only userid is stored in the name of the HttpContext.Current.Identity. So the flex side doesn't need to push the user id all the time, but now we want to disable the "push" of the channelid too. I was wondering where we should "store" these data. Is a Session save enough or do we need to use a cookie? or are there any other methods for this "problem".
I'd recommend to use `Session` because the values are then stored on the server (cookies are stored on the client). Also use a static class and wrap the session there. Instead of ``` Session["channelid"] = ChannelId ``` use ``` SessionManager.ChannelId = ChannelId ``` and you can declare `SessionManager` as a static class with static properties that use the session. I believe this is a general Microsoft practice as well. Cheers
Session sounds like a good choice for this. Whilst there is much aversion to it unless you really do need to scale to a very large number concurrent users there is no reason to avoid it for such a small amount of data per session. Cookies is an option however it means the data is held client-side which may not be desirable and bulks up every request being sent to the server.
How can I store session data in ASP.NET?
[ "", "c#", "asp.net", "session", "" ]
A file has been encrypted by Perl. Initial decrypt attempts failed and I am now trying to ascertain whether there is any hoojoo going on (some other settings required) **Duff Perl Code:** ``` use strict; use Crypt::Rijndael; my $key ='...'; my $rcipher = Crypt::Rijndael->new ($key, Crypt::Rijndael::MODE_CBC()); undef $/; my $encrypted = <>; print $rcipher->decrypt($encrypted); ``` **C# Decryption Implementation** ``` CryptoStream decryptor = null; StreamReader srDecrypt = null; FileStream fsIn = null; RijndaelManaged rijndaelCipher = null; string fileContents; try { rijndaelCipher = new RijndaelManaged(); rijndaelCipher.Mode = CipherMode.CBC; rijndaelCipher.Key = Encoding.UTF8.GetBytes(Password); rijndaelCipher.IV = Encoding.UTF8.GetBytes(Password); rijndaelCipher.Padding = PaddingMode.None; fsIn = new FileStream(FilePath, FileMode.Open); decryptor = new CryptoStream(fsIn, rijndaelCipher.CreateDecryptor(), CryptoStreamMode.Read); srDecrypt = new StreamReader(decryptor); fileContents = srDecrypt.ReadToEnd(); } finally { if (decryptor != null) decryptor.Close(); if (fsIn != null) fsIn.Close(); if (srDecrypt != null) srDecrypt.Close(); if (rijndaelCipher != null) rijndaelCipher.Clear(); } ``` **How Perl Code should read** ``` binmode OUTF; my $key ="..."; # Your secret key my $rcipher = Crypt::Rijndael->new ($key, Crypt::Rijndael::MODE_CBC()); $rcipher->set_iv($key); # You may wish this IV to be something different from the Secret Key my $plaintext = "Please encrypt me"; # Your string to be encrypted if(length($plaintext) % 16 != 0 ) { $plaintext .= ' ' x (16 - (length($plaintext) % 16)); } my $rencrypted = $rcipher->encrypt($plaintext); ```
I'm the maintainer of Perl's [Crypt::Rijndael](http://search.cpan.org/dist/Crypt-Rijndael). I didn't write the original code, but I try to make it work when it fails for other people. I received another report like this as [RT #27632](https://rt.cpan.org/Ticket/Display.html?id=27632). The problem in the module was a signed int that should have been an unsigned int. The latest version of [Crypt::Rijndael](http://search.cpan.org/dist/Crypt-Rijndael), 1.07, should have the fix. Which version are you using? Also, some of these problems are platform dependent. If you look in the rijndael.h code in the distribution, you'll see the hoops I have to jump through to get the right type sizes for various platforms. I figure you're on Windows (but not Cygwin). Which version of Windows are you using? As noted in the RT ticket, the first step is to encrypt the same messages with the same initialization vectors using both [Crypt::Rijndael](http://search.cpan.org/dist/Crypt-Rijndael) and the C# implementation. You should get the same output. If you don't get the same crypttext, there is a problem. Let me know how this works out for you so I can track it as a [Crypt::Rijndael](http://search.cpan.org/dist/Crypt-Rijndael) bug if I need to.
I'm assuming you run this on Windows. You're dealing with binary data, so you need to take that into account. In Perl, you have to use [binmode](http://perldoc.perl.org/functions/binmode.html). I think you need to use BinaryReader in C# (but I'm no C# programmer, so I'm not sure).
Why can't C# decrypt the output from Perl's Crypt::Rijndael?
[ "", "c#", "perl", "aes", "encryption", "rijndaelmanaged", "" ]
I have a query to a database on a seperate thread and on the return I invoke a threadsafe call. But an exception is created - what am I doing wrong? Note I also populate the list view but have left it out for clarity ``` private void ThreadSafeListView() { if (this.listView1.InvokeRequired) { try { ThreadSafe Operation d = new ThreadSafeOperation(ThreadSafeListView); this.Invoke(d ); } catch { } } else { listView1.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); listView1.Columns[1].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); listView1.Columns[2].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); listView1.Columns[3].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize); listView1.Columns[4].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize); } } ``` Exception Details= InvalidOperationException : "Cross-thread operation not valid: Control 'listView1' accessed from a thread other than the thread it was created on."
What exception is thrown? If it's still a thread-safe exception, then it may be because you're not invoking from the item that requires invocation. Try: ``` listView1.Invoke(d) ``` rather than ``` this.Invoke(d) ``` In theory this is the form, so it should work, but without more information about the exception this is my only guess.
I give up...I'm just spinning my wheels so instead I... ``` void listView1_Resize(object sender, EventArgs e) { listView1.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); listView1.Columns[1].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); listView1.Columns[2].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); listView1.Columns[3].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize); } ```
How do I resize Listview columns in a threadsafe manner - C#
[ "", "c#", "" ]
After following [this](https://stackoverflow.com/questions/20856/how-do-you-recommend-implementing-tags-or-tagging/20871#20871) recommendation regarding tags tables structure, I've implemented the following design: ``` Table: Item Columns: ItemID, Title, Content Table: Tag Columns: TagID, Title Table: ItemTag Columns: ItemID, TagID ``` I'm facing another problem, I wanna display the number each tag appears in the system. What's the best way to do this in terms of search query / php code that will not cause a severe performance impact (tags count will appear for each item). Thanks, Roy
> ``` > select count(*) > from ItemTag > where TagId = X > ``` is mySQL that will get it dynamically. If you're worried about the performance hit, you should store a count in the tag table, and increment/decrement it when you tag or untag an item.
Pretty sure the following (SQL) will get all the tag titles and associated counts of how often they appear on items. ``` select tag.title, count(itemtag.tagid) from tag, itemtag where itemtag.tagid = tag.tagid group by tag.title ```
What's the best way to display the number of items related to tags?
[ "", "php", "mysql", "" ]
I have a library I'm writing unit tests for. The library is used by two applications: one a Windows service, the other a command-line application that does some registry read-writes. Each has a slightly different App.config file that is loaded from the library at start-up. For example: ``` public RetentionService() { SettingHive = new Hive(); TimingService = new RetentionTimingService(SettingHive); AppSettingsReader asr = new AppSettingsReader(); object appsListObj = asr.GetValue(@"blocking-process-list", Type.GetType(@"System.String")); string appsList = appsListObj.ToString(); _BlockingAppNames = RetentionService.ListFromList(appsList); string targetList = asr.GetValue(@"target-files", Type.GetType(@"System.String")).ToString(); _TargetLogs = RetentionService.ListFromList(targetList); } ``` When I try to use this library from a unit test, it fails to load because the application loading the library (presumably nunit) doesn't have a \*.exe.config file with the appropriate keys. What's a better way to do this? I'd like the library to load the settings from each application's \*.exe.config in production, but from a third location if running a unit test.
If your unit tests are designed to test the code, then don't depend on the config file at all. Extract your dependency out of your classes and use dependency injection to inject the data in. That way, you can stub your configuration class. If you *are* actually just testing your configuration file, you should be able to load it explicitly using [ConfigurationManager](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx), although I wouldn't suggest unit testing configuration data. It's a better candidate for smoke testing.
Alternatively, just add an app.config file to your unit testing project that contains the relevant information.
How do I configure my settings file to work with unit tests?
[ "", "c#", ".net", "nunit", "app-config", "" ]
I have a C++ class that overloads `operator[]`, the array subscript/brackets operator. This is awfully convenient outside of my class, where I can write `foo[bar`]. However, I can't figure out how to use this notation when I'm implementing methods *inside* my class. I know I can write `operator[](bar)` or `this->operator[](bar)` but those are fairly unwieldy and take away a lot of the convenience of the operator in the first place. (I also know I can just add a new method that calls the operator.) Is there a way I can write `this[bar]` or `this->[bar]` or something similarly nice?
``` (*this)[bar]; ``` works fine for me.
Use ``` (*this)[bar] ``` to call the `operator[]` of the instance object. Assuming `bar` is an integer (or can be auto-converted to one), `this[bar]` treats the `this` pointer as an array and indexes the `bar`-th element of that array. Unless `this` is in an array, this will result in undefined behavior. If `bar` isn't integer-like, expect a compile-time error.
C++: Convenient way to access operator[] from within class?
[ "", "c++", "operator-overloading", "" ]
Is there a (standalone!) java api which wraps the XML-RPC interface to bugzilla? I don't want to program my own api for it, and I can't actually find a library which does this (and only this). **Update:** I'm looking for something like this <http://oss.dbc.dk/bugzproxy/> only written in Java
I know this is a bit old thread but as it is quite possible that people with the same question could land up here I thought of sharing a blog post I wrote about four Java client libraries that I found for accessing Bugzilla: J2Bugzilla, B4J (Bugzilla for Java), Bugzilla Library, LightingBugAPI. <http://www.dzone.com/links/r/bugzilla_web_service_and_java_client_libraries.html> Best Regards, Nandana
There's [Apache WS XML-RPC](http://ws.apache.org/xmlrpc/) *(now that's a mouthful!)* which is a full XML-RPC implementation that you could use. I don't know BugZilla that well but assuming it supports XML-RPC, there shouldn't be any issues using the monstrous mouthful I just linked.
Is there a java api to access bugzilla?
[ "", "java", "api", "xml-rpc", "bugzilla", "" ]
I have created a online examination web application. I want the users to avoid using browsers (for checking answers in Google). How should I achieve this? Shall we have the full screen mode, even though I want to restrict minimizing the window or using Ctrl+Tab? Is it possible?
There is a very simple solution: Set a time limit. Any student who has to browse the web for an answer will lose a lot of time compared to the ones who know the answer immediately. Another solution: Don't care. It's not your job to make sure that students don't know about the Internet. Your job is to make sure they know their stuff when they start a job. So if a student is not able to memorize something but can look it up on Google? Why not? I'd award her extra points for working smarter rather than harder.
Speaking as a browser user, I hope it's not possible, since it implies that any web site could do the same thing, thus taking control of my computer away from me, against my will.
How can I restrict the use of other applications during an online exam?
[ "", "javascript", "html", "" ]
I have in input box that can only contain numerical values (with use of [this](http://itgroup.com.ph/alphanumeric/) plugin). Now I want the input to be below, say 90. If a value is entered that exceeds this max cap or cannot be parsed, the previous value should be inserted. By default, the box will contain "1". ``` <input id="targetQuantity" name="targetQuantity" type="text" value="1" /> ``` I imagine I should catch the current value somehow. Try to parse the new value. If it is an allowed value, continue with this value, if not, put the old one back. As my JS skills are really limited I don't even know what events are available to me and I find the documentation I found on the intarwebz rather confusing. --EDIT-- I ended up using [Sergei's](https://stackoverflow.com/questions/630129/keep-value-in-html-input-box-below-set-amount/630228#630228) code and using [Aaron's](https://stackoverflow.com/questions/630129/keep-value-in-html-input-box-below-set-amount/630192#630192) usability advice. All I'm looking for now is to enable/disable a whole form's submit. Just disabling a submit button is not enough.
``` <input id="targetQuantity" name="targetQuantity" type="text" value="1" onkeyup="check(this)" /> ``` ... JavaScript: ``` var v=1; function check(i) { if(i.value > 100) { i.value=v; alert("< 100"); } else v=i.value; } ```
This should help: [JavaScript Madness: Keyboard Events](http://unixpapa.com/js/key.html) Now a word on usability: Never ever change the value as the user types. If you want to know why, try it. Instead, turn the field red (set the background color). When the form is submitted, run the validation again to make sure the user has fixed the mistake. If not, display an *inline* error message ("value must be < 90") somewhere near the field and set the focus to the field. **Do not use alert()**. alert() is for debugging only and has no use in a real web application since it a) interrupts the work flow of the user and b) doesn't work when the user is typing: Eventually, the user will hit space and the dialog will close, possibly with the user ever noticing that there was a dialog or what it said. You may want to check out a library like [jQuery](http://jquery.com/) or [Prototype](http://www.prototypejs.org/) because they already contain all the building blocks you need and they fix a lot of the browser bugs for you.
Keep value in html input box below set amount
[ "", "javascript", "validation", "" ]
Is it possible to get Java 6 running on a Mac PowerPC with Mac OS X 10.4? AFAIK [SoyLatte](http://landonf.bikemonkey.org/static/soylatte/) is only available for Intel processors.
Note that in addition to not working on PPC, Apple's Java6 [does not work on 32 bit Intel](http://support.apple.com/kb/HT1856) either. And there are other restrictions for the new Java6, leading to opinions such as [this](http://java.dzone.com/news/java-6-mac-worsest-release-eve).
As of December 2009, a beta of OpenJDK 7 for OS X 10.5 PPC is available at <http://landonf.bikemonkey.org/static/soylatte/> -- haven't tried it, and it's not quite what you were after, but it's the first I've seen so far of Java >=6 on any PPC OS X version! More details at <http://landonf.bikemonkey.org/2009/12/index.html> .
Java 6 on Mac PowerPC with Mac OS X 10.4
[ "", "java", "macos", "" ]
I'm learning some Fluent NHibernate and I've run across the semi-awesome PersistenceSpecification class. I've set it up in a unit test to verify my mappings and it works great. However, it leaves the record in the database when done. I tried throwing it in a transaction so I can rollback the changes but I get an error: System.ObjectDisposedException: Cannot access a disposed object. Object name: 'AdoTransaction'.. Without a transaction I have to figure out the ID's of the record, retrieve them and delete them and that doesn't seem very elegant. Any thoughts? EDIT: Here is the code snippet: ``` var factory = GetSessionFactory(); using (var session = factory.OpenSession()) using (var transaction = session.BeginTransaction()) { new PersistenceSpecification<TimePeriod>(session) .CheckProperty(x => x.EndDate, DateTime.Today) .VerifyTheMappings(); transaction.Rollback(); } ```
Try setting the IsolationLevel on the transaction. This snippet worked for me: ``` using (var trans = _session.BeginTransaction(IsolationLevel.ReadUncommitted)) { new PersistenceSpecification<Event>(_session) .CheckProperty(p => p.StartTime, new DateTime(2010, 1, 1)) .VerifyTheMappings(); trans.Rollback(); } ```
The `PersistenceSpecification` is usually used with an in-memory database like SQLite, that's why it doesn't roll anything back. I believe there's a constructor overload that takes an `ISession` instance, have you tried getting a transaction from there then rolling that back after?
Rolling back records created by PersistenceSpecifications in Fluent NHibernate
[ "", "c#", "fluent-nhibernate", "" ]
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question here *[How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899)* and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution to sort either in ascending or descending order.
### Python 3.7+ or CPython 3.6 Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but [it's an implementation detail](https://stackoverflow.com/q/39980323/4518341). ``` >>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} >>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])} {0: 0, 2: 1, 1: 2, 4: 3, 3: 4} ``` or ``` >>> dict(sorted(x.items(), key=lambda item: item[1])) {0: 0, 2: 1, 1: 2, 4: 3, 3: 4} ``` ### Older Python It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples. For instance, ``` import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(1)) ``` `sorted_x` will be a list of tuples sorted by the second element in each tuple. `dict(sorted_x) == x`. And for those wishing to sort on keys instead of values: ``` import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(0)) ``` In Python3 since [unpacking is not allowed](https://stackoverflow.com/a/15712231/4293057) we can use ``` x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=lambda kv: kv[1]) ``` If you want the output as a dict, you can use [`collections.OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict): ``` import collections sorted_dict = collections.OrderedDict(sorted_x) ```
## As simple as: `sorted(dict1, key=dict1.get)` Well, it is actually possible to do a "sort by dictionary values". Recently I had to do that in a Code Golf (Stack Overflow question *[Code golf: Word frequency chart](https://stackoverflow.com/questions/3169051/code-golf-word-frequency-chart#3170549)*). Abridged, the problem was of the kind: given a text, count how often each word is encountered and display a list of the top words, sorted by decreasing frequency. If you construct a dictionary with the words as keys and the number of occurrences of each word as value, simplified here as: ``` from collections import defaultdict d = defaultdict(int) for w in text.split(): d[w] += 1 ``` then you can get a list of the words, ordered by frequency of use with [`sorted(d, key=d.get)`](https://docs.python.org/library/functions.html#sorted) - the sort iterates over the dictionary keys, using the number of word occurrences as a sort key . ``` for w in sorted(d, key=d.get, reverse=True): print(w, d[w]) ``` I am writing this detailed explanation to illustrate what people often mean by "I can easily sort a dictionary by key, but how do I sort by value" - and I think the original post was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above.
How do I sort a dictionary by value?
[ "", "python", "sorting", "dictionary", "" ]
When a user creates an account on my website, I want the input username to be checked against all the current usernames in my database(MySQL) and confirmed if it is available. Does anyone know any good libraries I could use, or a plug-in for jQuery perhaps?
Exactly what you want is given in example form [here](http://jqueryfordesigners.com/using-ajax-to-validate-forms/). it uses jQuery as the JavaScript library
And this is untested code that is the server-side ``` <?php // check_username_available.php?name=(name they supplied) // this stuff is normally in config.inc.php $username = "..."; // Mysql username $password = "..."; // Mysql password $db_name = "..."; // Database name // get name supplied from querystring $name = $_GET('name'); // Connect to server and select database. // mysql_connect("localhost", $username, $password) or die("cannot connect to db"); mysql_select_db($db_name) or die("cannot select $db_name DB"); $query = "SELECT COUNT(*) FROM 'users' WHERE user_name = '$name'"; $result = mysql_query($query) or die("cannot count rows: " . mysql_error()); header("Content-Type: text/plain"); echo ( 0 < mysql_result($result, 0) ? "false" : "true" ); ```
AJAX live email validation (PHP)
[ "", "php", "jquery", "ajax", "validation", "" ]
Does anyone know of a class in Java that has a list of elements, so that the elements are sortable by any of the elements members? The idea is basically to have some database table-like implementation, where you can just add fields to sort by. To illustrate: ``` SomeTable table = new SomeTable(); table.addField("name", String); table.addField("age", int); table.addField("hair color", String); table.add(new Object[]{"Thomas", 32, "brown"}); table.add(new Object[]{"Jack", 34, "black"}); ``` `table.sort("age")` would sort the table so that Thomas is the first element, while `table.sort("name")` would sort the table so that Jack is the first element. I can code something like this myself (actually I have done that once), but I'm just curious to see if there's a ready library to do such things (without a database). PS: I know that `int` is not a class, but that's not the point here. This example code is just here to show the kind of functionality I expect. ---
The closest thing I can think of myself is the Apache Commons [BeanUtils](http://commons.apache.org/beanutils/) API. For example for a "student" table. ``` DynaProperty[] props = new DynaProperty[]{ new DynaProperty("firstName", String.class), new DynaProperty("lastName", String.class), new DynaProperty("address", java.util.Map.class) }; BasicDynaClass dynaClass = new BasicDynaClass("student", null, props); ``` Given a collection *table* of these student objects. We define a BeanComparator ``` BeanComparator surnameComparator = new BeanComparator("lastname"); Collections.sort(table, surnameComparator); ``` Not sure if this is what you're looking for, but it seems pretty close.
You must consider the `Collection.sort()` function, with the `Comparator` interface. There is a very good example [here](http://mindprod.com/jgloss/sort.html#EXAMPLE)
Sortable table-like Java class
[ "", "java", "sorting", "" ]
I'm connecting to a hardware device via telnet. That device is pretty simple in terms of I/O. So I submit a command to it, and after that the device pumps out data one line at a time, once per second. Each line just contains a number. So my question is this: if I connect to this device using python's telnetlib, how can I fetch data for a fixed period of time (or a fixed number of lines of data)? I've tried using all the various read\_ commands, but they all seem to block indefinitely, apart from read\_until, which I can't use as the output can't be used to determine when to stop. (I'm running python 2.5 under Cygwin, btw). Edit: Maybe the real question is, should I be using telnetlib at all for this, or should I just use the socket module?
From your description I'm not clear if you're using telnetlib because the device you're connecting to *requires terminal setup provided by telnet* or because it seemed like the right thing to do. If the device is as simple as you describe--i.e. not negotiating terminal options on connection--have you considered the [asynchat](http://docs.python.org/library/asynchat.html) module? It would be appropriate for the "send command, read lines" sort of IO pattern you are describing. Alternatively, for something lower-level, you could use the [socket](http://docs.python.org/library/socket.html) module to open the connection to the device and then sit in a timed loop and `read()` the incoming data. If the lines are newline-terminated it should be simple for you to identify each individual number. If you are concerned with blocking, stick this loop in its own thread.
In my experience, most such devices use some prompt, in which case [`Telnet.read_until()`](http://docs.python.org/library/telnetlib.html#telnetlib.Telnet.read_until) is appropriate: > `Telnet.read_until(expected[, timeout])` > > Read until a given string, expected, is encountered or until timeout seconds have passed. > When no match is found, return whatever is available instead, possibly the empty string. Raise EOFError if the connection is closed and no cooked data is available. If no usable (repetitive) prompt is presented by the device, try [`Telnet.read_very_eager()`](http://docs.python.org/library/telnetlib.html#telnetlib.Telnet.read_very_eager), or `Telnet.read_very_lazy()`: > `Telnet.read_very_eager()` > > Read everything that can be without blocking in I/O (eager). > > Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Do not block unless in the midst of an IAC sequence.
How can I use python's telnetlib to fetch data from a device for a fixed period of time?
[ "", "python", "telnet", "" ]
I have an asp page containing a form with two fields where the client is supposed to write his/her information. ``` <td><%=Html.TextBox("Date")%></td> <td><%=Html.TextBox("City")%></td> ``` My action's signature looks (at the moment) like this: ``` public ActionResult XXX(string Date, string City) {...} ``` The problem is that I want to propagate a simple integral number from my view to the action. Is it possible to have a hidden textbox or something similar? I want my action signature to look something like this: ``` public ActionResult CreateCourseDate(string Date, string City, int id) ```
There are two ways to do this. Either use the hidden field method (I wouldn't recommend this) or add it to the url (route value). The latter fits better with the REST-like urls that MVC prefers. So, if you are using an new form, then your url would look like: ``` http://example.com/course/newcoursedate/1 ``` This would edit the `course` with id `1`. You'd have a corresponding `create` action that your new form would POST to. The example below assumes that your view is strongly typed with a `Course` model. You could also pull the id out of ViewData if necessary. ``` <% using (Html.BeginForm( "CreateCourseDate", "Course", new { id = ViewData.Model.CourseID }, ... ... <td><%=Html.TextBox("Date")%></td> <td><%=Html.TextBox("City")%></td> <% } %> ``` I didn't look at the order of the parameters, but I believe that at least one signature has the route values after the controller name. Consult the source (or intellisense) to be sure.
You can pass additional values like this: ``` <% using (Html.BeginForm("YourActionName", "YourControllerName", new { id = yourid })) { %> ... <td><%=Html.TextBox("Date")%></td> <td><%=Html.TextBox("City")%></td> ... <input type="submit" value="Submit" /> <% } %> ```
asp.net mvc framework information propagation
[ "", "c#", "asp.net", "html", "asp.net-mvc", "" ]
I'm writing one of my first C# programs. Here's what I'm trying to do: * Open an XML document * Navigate to a part of the XML tree and select all child elements of type `<myType>` * For each `<myType>` element, change an attribute (so `<myType id="oldValue">` would become `<myType id="newValue">` * Write this modified XML document to a file. I found the `XmlDocument.SelectNodes` method, which takes an XPath expression as its argument. However, it returns an `XmlNodeList`. I read a little bit about the difference between an XML node and an XML element, and this seems to explain why there is no `XmlNode.SetAttribute` method. But is there a way I can use my XPath expression to retrieve a list of `XmlElement` objects, so that I can loop through this list and set the `id` attributes for each? (If there's some other easier way, please do let me know.)
Simply - it doesn't know if you are reading an element or attribute. Quite possibly, all you need is a cast here: ``` foreach(XmlElement el in doc.SelectNodes(...)) { el.SetAttribute(...); } ``` The SelectNodes returns an XmlNodeList, but the above treats each as an XmlElement.
I am a big fan of System.Xml.Linq.XDocument and the features it provides. ``` XDocument xDoc = XDocument.Load("FILENAME.xml"); // assuming you types is the parent and mytype is a bunch of nodes underneath IEnumerable<XElement> elements = xdoc.Element("types").Elements("myType"); foreach (XElement type in elements) { // option 1 type.Attribute("id").Value = NEWVALUE; // option 2 type.SetAttributeValue("id", NEWVALUE); } ``` Option 1 or 2 works but I prefer 2 because if the attribute doesn't exist this'll create it.
Setting attributes in an XML document
[ "", "c#", "xml", "" ]
Is there a built in linq method thing I can use to find out if two sequences contains the same items, not taking the order into account? For example: ``` {1, 2, 3} == {2, 1, 3} {1, 2, 3} != {2, 1, 3, 4} {1, 2, 3} != {1, 2, 4} ``` You have the SequenceEquals, but then I would have to Order both sequences first, wouldn't I?
There are quite a few ways. Assume A and B is IEnumerable. ``` !A.Except(B).Any() && !B.Except(A).Any() A.Count() == B.Count() && A.Intersect(B).Count() == B.Count() etc ```
If you don't care about duplicates (i.e. you'd consider `{1, 2, 3}` to be equal to `{1, 2, 3, 2}`) then: ``` new HashSet<int>(A).SetEquals(B) ``` (Or whatever type is the element type instead of `int`). Otherwise: ``` public static bool SequenceEqualUnordered<T>(IEnumerable<T> first, IEnumerable<T> second) { if (first == null) return second == null; // or throw if that's more appropriate to your use. if (second == null) return false; // likewise. var dict = new Dictionary<T, int>(); // You could provide a IEqualityComparer<T> here if desired. foreach(T element in first) { int count; dict.TryGetValue(element, out count); dict[element] = count + 1; } foreach(T element in second) { int count; if (!dict.TryGetValue(element, out count)) return false; else if (--count == 0) dict.Remove(element); else dict[element] = count; } return dict.Count == 0; } ``` Keep a tally of each element in the first sequence, then check the second against it. The moment you have one too many in the second sequence you can return false, otherwise if you have nothing left in the dictionary of tallies they are equal, or false if there's any elements left. Rather than the two O(n log n) sorts of using `OrderBy()` followed by the O(n) comparison, you've an O(n) operation building the set of tallies, and an O(n) check against it.
C#: Compare contents of two IEnumerables
[ "", "c#", "linq", "" ]
I want to create an OpenOffice.org plug-in that adds a sidebar. I have successfully installed OpenOffice.org, OpenOffice.org SDK and NetBeans OpenOffice plug-in. I am familiar with Java, AWT and Swing, so no need to explain these concepts to me. Now, I want to create a sidebar Panel(or JPanel) in OpenOffice.org Writer application. How can I do this? It would be in the left and fill all available height(while using a fixed width). Any idea on how to implement this? I have no OpenOffice.org plug-in past experience. Thank you in advance.
This is currently not possible through the OpenOffice.org API. You can create menus, toolbars and dialogs. You cannot create dockable windows or panels via UNO. See: [GUI Chapter in the Dev Guide](http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/GUI/Graphical_User_Interfaces). Exposing this capability through the API is under active development and I suggest you join the api-dev@openoffice.org mailing list to stay on top of things. The specific feature you asked for was already discussed there and it was suggested that it would be made available with a future update to OpenOffice 3.0. See [post in the list archive](http://api.openoffice.org/servlets/ReadMsg?list=dev&msgNo=20716).
I don't know if there's an easy answer for this. OO.o provides [their dev guide here](http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/OpenOffice.org_Developers_Guide). It appears once you create an UNO component to their spec you can use: > Arbitrary objects written in Java or > C++ [and then] can be called from the user > interface, display their own GUI, and > work with the entire application. That sounds like what you want to do. Hope this helps!
How to create a sidebar panel in OpenOffice?
[ "", "java", "user-interface", "sdk", "panel", "openoffice.org", "" ]
I have this following data source binding: ``` MembershipProvider provider = new MembershipProvider(); UserUpdateLogs userUpdateLogs = provider.GetUserUpdateLogs(username); dgUserUpdateLog.DataSource = userUpdateLogs.Logs; dgUserUpdateLog.DataBind(); ``` **Logs** is a collection of **UserUpdateLogEntry**. This class owns the **UserData** Property, and UserData contains other properties. My aspx: ``` <Columns> <asp:BoundColumn DataField="ChangeDate" Visible="true" HeaderText="Date"/> <asp:BoundColumn DataField="UserData.Sex" HeaderText="Sex" /> <asp:BoundColumn DataField="UserData.Phone" HeaderText="Phone" /> </Columns> ``` The first row (**ChangeDate**) seems to work well. But when rendering the second BoundColumn, the following error is shown: > A field or property with the name > 'UserData.Sex' was not found on the > selected data source. Why does it happen? Can't Aspx recognize a concatenation of properties like PropertyA.PropertyB? I've checked the object and all properties have valid data.
You can not bind to properties of sub-objects in that way. As an alternative, you can use a template column and use Eval to display the properties of the sub-object, e.g. something like this: ``` <asp:TemplateColumn HeaderText="Sex" Visible="true"> <ItemTemplate> <asp:Literal runat="server" Text='<%# Eval("UserData.Sex") %>' /> </ItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn HeaderText="Phone" Visible="true"> <ItemTemplate> <asp:Literal runat="server" Text='<%# Eval("UserData.Phone") %>' /> </ItemTemplate> </asp:TemplateColumn> ```
One thing that you can do is create an accessor property: ``` public string UserSex { get { return userUpdateLogs.Logs.UserData.Sex; } } ```
Why this data binding in aspx does not work?
[ "", "c#", ".net", "asp.net", "data-binding", ".net-2.0", "" ]
I have created a small Java application to automatically test some expressions for a true/false condition. I am getting two compiler errors in both jGRASP and with the javac command. The code follows: ``` public class MathTest { public static void main(String[] args) { int x = 10; int y = 20; int z = 30; String string1 = "six"; String string2 = "six"; if (x < 10 || x > 10) System.out.print("True"); else System.out.print("False"); if (z - y == x && Math.abs(y - z) == z) System.out.print("True"); else System.out.print("False"); if (x < 10 && x < 10) System.out.print("True"); else System.out.print("False"); if (string1.equals(string2)) System.out.print("True"); else System.out.print("False"); if (x > y || y > x) System.out.print("True"); else System.out.print("False"); if (!(x < y + z) || !(x + 10 <= 20)) System.out.print("True"); else System.out.print("False"); if (string1 == string2) System.out.print("True"); else System.out.print("False"); } } ``` The error message is: ``` MathTest.java:14: cannot find symbol symbol : method abs(int) location: class Math if(z - y == x && Math.abs(y - z) == z) ^ ./Math.java:13: cannot find symbol symbol : method abs(int) location: class Math if(z - y == x && Math.abs(y - z) == z) ^ 2 errors ``` What am I doing wrong? In the unlikely event that my instructor or any administrator from Salt Lake Community College ever comes across this question, let me make my intentions clear. This question is posted in the greatest spirit of academic honesty. I ask this question to seek general advice and help in understanding the proper way to use the Java programming language. I in no way use the work of others and represent it as my own work. I use the answers provided here as a general aid in my understanding. I do all my own work and do not copy work provided by people answering my question.
If you want your program to use Java's Math.abs (instead of an abs() method in the Math class you wrote), you can say: ``` if(z - y == x && java.lang.Math.abs(y - z) == z) ``` ...which isn't very pretty. In general, try not to name your classes the same as the ones in java.lang (or java.anything, really).
You have a Math class, and you're attempting to use the abs() method. The question is: Is it your intention to provide this function or are you trying to use the one in java.lang.Math? For the first, you have to make sure you're declaring that function. For the second you have to make sure you're using the correct parameters types; see [Math](http://java.sun.com/javase/6/docs/api/java/lang/Math.html). Does your Math class have the abs method? It seems like your Math class is shadowing the Math class that comes in the core of the language. Your Math class is loaded and the abs method could not be found (hence the "Cannot find symbol" message)
Cannot Find Symbol
[ "", "java", "" ]
I created a class called Colors. I am setting certain properties on the Colors object and setting it in a Session variable. When I access the Session variable on another page, I am noticing that if I change properties on objColors below, it changes the Session and does not keep the original properties which is what I want it to do. Here is an example: ``` Session["Colors"] = Colors; Colors objColors = Session["Colors"]; //If I change objColors, it changes the Session. I don't want this to happen. ``` Is there a better way to keep retain the original properties? Why does it do this?
Create a copy constructor for Colors. Then, do this. ``` Colors objColors = new Colors((Colors)Session["Colors"]); ``` In your new constructor, just copy the values that you need to and do your other constructor-related things. What's happening in your code is that you are getting a ***pointer*** to a Colors object. Session["Colors"] and objColors point to the same object in memory, so when you modify one, changes are reflected in both. You want a brand spankin' new Colors object, with values initialized from objColors or Session["Colors"]. edit: A copy constructor might look like this: ``` public Colors(Colors otherColors) { this.privateVar1 = otherColors.privateVar1; this.publicVar2 = otherColors.publicVar2; this.Init(); } ```
You can implement your own cloning methods to make a "copy" of an object. The reason this is happening is because the assignment of `Colors objColors = Session["Colors"];` is a reference assignment, this is by design. All you are doing is making a local scope reference to an object that already exists. Take a look at [IClonable](http://msdn.microsoft.com/en-us/library/system.icloneable.aspx) for actual object cloning. This isn't necessary either you can implement your own copy methods. You may also want to take a look at [MemberwiseClone](http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx) depending on how deep your object goes.
How do you make a copy of an object?
[ "", "c#", "asp.net", "" ]
Does Mono miss any functionality from .NET? If not, when will we see official MS recognition for it, like including Mono platforms in the Platforms section on MSDN? It seems like they are seen as separate things.
They *are* separate things - Mono is a competitor to .NET. I doubt very much that we'll ever see it being advertised on MSDN. Would you expect Microsoft to have an advert for a Linux distribution there? ;) (And no, Mono [doesn't contain everything from .NET](http://mono-project.com/Guidelines:Application_Portability#Missing_Functionality).)
[MoMA](http://www.mono-project.com/MoMA) is a useful tool for examining your assemblies and reporting on any potential issues (e.g., not implemented methods). There are a couple of things to be aware of with Mono. Despite a good report from MoMA, we've run into bugs (including regressions in the new 2.2 release) as you would expect. You do have the source and I really recommend being able to build Mono (in particular the managed part which compiles the libraries). Be sure to push bug reports via the public bugzilla for Mono. Also, be aware of dependencies on third party libraries. Thorough testing is a must. For example, we tried using xUnit.net with mono and it mostly worked well. However, it uses an ugly reflection hack to set the value of a private member variable (in the Exception class). Of course, something like this is bound to cause runtime issues. Once again, source code to the rescue as xUnit.net is OpenSource.
Mono feature complete
[ "", "c#", ".net", "mono", "" ]
In C# Is there way to specify a class to be inherited only by a class present in the same assembly and for other assemblies should behave like a public sealed type.
I think Eric Lippert gets the defining quotes here: * [Preventing third-party derivation part one](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/preventing-third-party-derivation-part-one) * [Preventing third-party derivation part two](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/preventing-third-party-derivation-part-two)
The language itself doesn't have anything that makes this easy, but you should be able to do this by making your constructors internal. If you do this, however, you won't be able to new it up from external assemblies, so you'll have to add a factory method. ``` public class Foo { internal Foo() { } public Foo Create() { return new Foo(); } } ``` Here's an alternative that lets you new up the class in external assemblies ``` public sealed class Foo : FooBase { } public class FooBase { internal FooBase() { } } ``` One question you might ask yourself, however, is exactly *why* you want the class to be sealed. Sometimes it's inevitable, but I have seen the `sealed` keyword get abused so often that I thought I'd bring it up. Often, developers will seal classes because they are overprotective of their code. *Most of the time*, if a class is well designed, it doesn't need to be sealed.
Inheritable only inside assembly in C#
[ "", "c#", "oop", "inheritance", "" ]
The following works fine on IE6, IE7, and chrome. Not working on ff 3.0.7. ``` <html><head> <script src="prototype.js" type="text/javascript" ></script> <script type="text/javascript"> Event.observe(window, 'load', function(){ Event.observe(document.body, 'keydown', myEventHandler); alert('window load'); }); function myEventHandler(evt) { alert(evt); } </script> </head> <body > <input type="text" /><br><br> </body></html> ``` EDIT: By "not working" I mean myEventHandler is not firing in firefox. EDIT2: Furthermore, it works fine when focus is on the input element. I want it fire for all keydowns.
~~I have no idea why your code doesn't work, but it's overly complicated~~ - this should do the trick: ``` document.observe('keydown', myEventHandler); ``` There's no need to wait for `load` as `document` is available immediately. --- Your code doesn't work because not all key events originate within a document's body element. Opera has issues similar to the ones in Firefox, but the originating element seems to additionally depend on the placement of the mouse cursor. Anyway, the fix is to just catch the events at `document` level, because as long as no one stops them from doing so, all DOM events will bubble up to `document` eventually.
I also found that my keydown events weren't firing in Firefox for similar code. In my case, I don't need to use anything other than Safari and Firefox, so I have not tested this on IE. Nevertheless, observing 'document' rather than 'document.body' seemed to work: ``` document.observe('dom:loaded', function() { Event.observe(document, 'keypress', function(evt) { alert("In Keypress Function"); }); }); ``` Now, I realize this is observing keypress, not keydown. AFAIK, keypress is generated right after keydown.
prototype/javascript - firefox not firing keypress/keydown event unless focus is in textbox
[ "", "javascript", "events", "prototypejs", "" ]
I figured I could pass an `IList<ChildClass>` as an `IEnumerable<ParentClass>`, since obviously each object in a ChildType list is also an instance of ParentType. But I'm gettin no love from the compiler. What am I missing? EDIT: Added function Foo3 which does what I want. Thanks! ``` namespace StackOverflow { public class ParentClass { } public class ChildClass : ParentClass { } public class Test { // works static void Foo(ParentClass bar2) { } // fails static void Foo2(IEnumerable<ParentClass> bar) { } // EDIT: here's the right answer, obtained from the // Charlie Calvert blog post static void Foo3<T>(IEnumerable<T> bar) where T : ParentClass { } public static void Main() { var childClassList = new List<ChildClass>(); // this works as expected foreach (var obj in childClassList) Foo(obj); // this won't compile // Argument '1': cannot convert from // 'System.Collections.Generic.List<ChildClass>' // to 'System.Collections.Generic.IEnumerable<ParentClass>' Foo2(childClassList); // EDIT: this works and is what I wanted Foo3(childClassList); } } } ```
Because generics aren't co/contra variant: [Eric Lippert's blog](http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx) has a great post on this. Another article from [Charlie Calvert is here](http://blogs.msdn.com/charlie/archive/2008/10/28/linq-farm-covariance-and-contravariance-in-visual-studio-2010.aspx).
You're missing generic variance, which doesn't exist in C# *at the moment*. Your code would work in C# 4.0, I believe. This is a duplicate of other questions though... See: * [Why can't a `List<string>` be stored in a `List<object>` variable](https://stackoverflow.com/questions/6557/in-c-why-cant-a-liststring-object-be-stored-in-a-listobject-variable) * [How does C# 4.0 Generic Covariance and Contra-Variance implemented](https://stackoverflow.com/questions/245607/how-does-c-4-0-generic-covariance-contra-variance-implmeneted) * [Is there a way to cast generic lists to lists of interface/base class types](https://stackoverflow.com/questions/188769/is-there-a-way-to-cast-generic-lists-to-lists-of-interface-base-class-types) * [C# .NET passing a collection of InterfaceImplementingClass objects to a routine that takes a collection of Interface objects](https://stackoverflow.com/questions/584319) * [Casting from `IEnumerable<Object>` to `IEnumerable<String>`](https://stackoverflow.com/questions/609608)
Why can't I pass IList<ChildType> to F(IEnumerable<ParentType>)?
[ "", "c#", "" ]