Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
For a project of mine, I'm trying to implement a small part of the BitTorrent protocol, which can be found [here](http://www.bittorrent.org/beps/bep_0003.html). Specifically, I want to use the "Bencoding" part of it, which is a way to safely encode data for transfer over a socket. The format is as follows: ``` 8:a string => "a string" i1234e => 1234 l1:a1:be => ['a', 'b'] d1:a1:b3:one3:twoe => {'a':'b', 'one':two} ``` The encoding part was easy enough, but decoding is become quite a hassle. For example, if I have a list of strings, I have no way to separate them into individual strings. I've tried several different solutions, including [PyParsing](http://pyparsing.wikispaces.com/) and a custom token parser. I'm currently attempting to use regexes, and it seems to be going fairly well, but I'm still hung up on the string problem. My current regex is: ``` (?P<length>\d+):(?P<contents>.{\1}) ``` However, i can't seem to use the first group as the length of the second group. Is there any good way to do this? Or am I approaching this all wrong, and the answer is sitting right in front of me?
Any parser you use for this is going to need to be stateful (i.e. remember stuff), and regexes are, by and large, not stateful. They're the wrong tool for this job. If those are the only data types you have to worry about, I think I'd just write custom parsers for each data type, passing control to the appropriate parser after reading the first character. I'd actually implement one now, but it's late. **Alright I decided to write an implementation:** ``` from StringIO import StringIO import string inputs = ["10:a stringly", "i1234e" , "l1:a1:be", "d1:a1:b3:one3:twoe"] # Constants DICT_TYPE = 'd' LIST_TYPE = 'l' INT_TYPE = 'i' TOKEN_EOF = '' TOKEN_END = 'e' COLON = ':' class BadTypeIndicatorException(Exception):pass def read_int(stream): s = "" while True: ch = stream.read(1) if ch not in [TOKEN_EOF, TOKEN_END, COLON]: s += ch else: break return s def tokenize(stream): s = "" while True: ch = stream.read(1) if ch == TOKEN_END or ch == TOKEN_EOF: return if ch == COLON: length = int(s) yield stream.read(length) s = "" else: s += ch def parse(stream): TYPE = stream.read(1) if TYPE in string.digits: length = int( TYPE + read_int(stream) ) return stream.read(length) elif TYPE is INT_TYPE: return int( read_int(stream) ) elif TYPE is LIST_TYPE: return list(tokenize(stream)) elif TYPE is DICT_TYPE: tokens = list(tokenize(stream)) return dict(zip(tokens[0::2], tokens[1::2])) else: raise BadTypeIndicatorException for input in inputs: stream = StringIO(input) print parse(stream) ```
You can do it if you parse the string twice. Apply the first regex to get the length. Concatenate the length in your second regex to form a valid expression. Not sure how that can be done in python, but a sample in C# would be: ``` string regex = "^[A-Za-z0-9_]{1," + length + "}$" ``` To match 1 to length no of chars which can be alpanumeric or \_ where length is determined from a previous regex that retrieves only the length. Hope this helps :)
How to match a string of a certain length with a regex
[ "", "python", "regex", "" ]
I'm attempting to write a junit test to guard against a piece of code getting stuck in a endless iteration which will eventually cause a StackOverflow. so i'm looking for a way to decrease the stack size at runtime so the Junittest will fail faster. setting the max stack as a jvm argument is not possible because the test is part of a much larger test suite.
You could run a recursive method which will run itself a given number of times and then execute a given action. Sounds pretty flaky though :( Something like: ``` public void eatStackThenExecute(int depth, Runnable action) { // Maybe put some locals here (and use them) to eat more stack per iteration? if (depth == 0) { action(); } else { eatStackThenExecute(depth - 1, action); } } ``` EDIT: It's possible that smart JVMs will optimise the tail call here, so it may be that we'd need to do "something" after the recursive call to stop that from happening... Ick 'n stuff :(
It's not possible to set the stack size at runtime, but perhaps you can: * invoke that piece of code inside a different thread - retaining the reference to it; * periodically poll `thread.getStackTrace()` and fail if its size is larger than x; * cancel the check if execution terminates correctly. --- not-compiled proof of concept code ( does not properly check all edge conditions ): ``` AtomicBoolean success = new AtomicBoolean(false); Thread t= new Thread(new Runnable() { public void run() { codeToTest(); success.set(true); } }); t.start(); while ( t.isAlive() ) { if ( t.getStackTrace().length > 50 ) fail("Stack trace too large"); Thread.sleep(50); } assertTrue(sucess.get()); ```
Decrease max stacksize at runtime in Java
[ "", "java", "stack-overflow", "runtime", "" ]
I was reviewing some code for log4net and I came across this. ``` private static readonly ILog logger = LogManager.GetLogger(typeof(AdminClient)); ``` I am wondering why would you need to have private static readonly. From my understanding private would mean that the variable cannot not be used outside the class unless there is a accessor method or get property. static would mean that the variable is scoped only in this file only. readonly would mean that you can only read from the value and cannot assign it. So, I am thinking that the person who wrote this code. declared it private as they don't want it used outside the class and static so that don't want it used outside the file. However, if there is a get property would static prevent this form happening. I think I can understand readonly and the value is only to be read from and not set. Many thanks for any advice,
* **private** No one should use the logger field outside the class (even in subclasses), if you don't set this any other class could use your logger for log in your class' name. * **static** The attribute is *attached* to the class so it won't *repeat* with each instance of the class. If you don't set this the logger attribute will occupy extra space in memory with every instance the system makes of the object (you misunderstood this). * **readonly** The logger field shouldn't be modified.
I think you're misunderstanding static. Static doesn't mean "can't be used outside the file." Static means: there's one per class. What this declaration does is creates a logger that is only allocated once (static), only available in the class (not in derived classes either) (private), and cannot be written to past its initialization (readonly). Good question though!
C# private, static, and readonly
[ "", "c#", "log4net", "access-modifiers", "" ]
Can anyone give me an idea or perhaps some references on how to create custom markups for django using textile or Markdown(or am I thinking wrong here)? For example: I'd like to convert the following markups(the outer bracket mean they are grouped as one tag: [ [Contacts] \* Contact #1 \* Contact #2 \* Contact #3 [Friend Requests] \* Jose ] to have them converted to: ``` <div class="tabs"> <ul> <li class="tab">Contacts</li> <li>Contact #1</li> (etc.. etc..) </ul> </div> ``` or is regex more recommended for my needs?
Well it seems the best way is still use a regex and create my own filter. here are some links that helped me out: <http://showmedo.com/videos/video?name=1100010&fromSeriesID=110> <http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/> hope this helps someone who had the same problem as me!
The built in [markup](http://docs.djangoproject.com/en/dev/ref/contrib/#markup) app uses a filter template tag to render textile, markdown and restructuredtext. If that is not what your looking for, another option is to use a 'markup' field. e.g., ``` class TownHallUpdate(models.Model): content = models.TextField() content_html = models.TextField(editable=False) def save(self, **kwargs): self.content_html = textile.textile(sanitize_html(self.content)) super(TownHallUpdate, self).save(**kwargs) ``` *Example from James Tauber's (and Brian Rosner's) [django patterns](http://eldarion.com/talks/2009/05/eurodjangocon_djangopatterns.pdf) talk.*
Custom Markup in Django
[ "", "python", "django", "markdown", "" ]
I have an eclipse plugin, which connects to a COM component using Jacob. But after I close the plugin entirely, the .exe file stays hanging in Windows processes. I use `ComThread.InitMTA(true)` for initialization and make sure that `SafeRelease()` is called for every COM object I created before closing the app and I call `ComThread.Release()` at the very end. Do I leave something undone?
Had the same problem with TD2JIRA converter. Eventually had to patch one of the Jacob files to release the objects. After that all went smooth. The code in my client logout() method now looks like this: ``` try { Class rot = ROT.class; Method clear = rot.getDeclaredMethod("clearObjects", new Class[]{}); clear.setAccessible(true); clear.invoke(null, new Object[]{}); } catch( Exception ex ) { ex.printStackTrace(); } ``` The ROT class wasn't accessible initially, AFAIR. **Update** The correct way to release resources in Jacob is to call ``` ComThread.InitSTA(); // or ComThread.InitMTA() ... ComThread.Release(); ``` Bad thing though is that sometimes it doesn't help. Despite Jacob calls native method release(), the memory (not even Java memory, but JVM process memory) grows uncontrollably.
Some further suggestions: 1. Move the call to `ComThread.Release()` into a `finally` block, otherwise the thread will remain attached if an exception is thrown. 2. Check that you are calling `ComThread.InitMTA` and `ComThread.Release` in every thread that uses a COM object. If you forget to do this in a worker thread then that thread will be attached automatically and never detached. 3. Avoid `InitSTA` and stick to `InitMTA`. Even when there is only one thread using COM, I have found `InitSTA` to be flaky. I don't know how JACOB's internal marshalling mechanism works but I have ended up with "ghost" objects that appear to be valid but do nothing when their methods are invoked. Fortunately I have never yet needed to modify any code in the JACOB library.
JACOB doesn't release the objects properly
[ "", "java", "com", "jacob", "" ]
I find the table layout panel in c# (.net 2.0) to be very primitive. I wanted to allow my users to resize the columns in a table layout panel but there are no ready made options to do so. Is there a way atleast to find out whether the cursor is directly over any borders of a cell and if so, which cell is beneath it ?? May be having this information, we can atleast try resizing that row/column thru' code. Help me finding, * whether the cursor is directly over any borders of a cell * which cell is beneath it (applicable only if the first question has an answer) Many Thanks, Sudarsan Srinivasan
If your layout is not overly complex, maybe you can achieve what you want by using [SplitContainer](http://msdn.microsoft.com/en-us/library/system.windows.forms.splitcontainer.aspx) controls? Unfortunately, each SplitContainer will have only two "cells", but you can embed a SplitContainer in another SplitContiner panel to get more resizable cells: ``` β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚ β”‚β”‚ β”‚ β”‚β”‚ β”‚β”‚ β”‚ β”‚β”‚ β”‚β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”β”‚ β”‚β”‚ β”‚ β”‚β”‚ β”‚β”‚ β”‚ β”‚β”‚ β”‚β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` OK, so ASCII art was never one of my stronger skills, but I think you get the point ;o)
Building on top of [@Fredrik MΓΆrk's solution](https://stackoverflow.com/a/980515/198797): After embedding another SplitContainer(s), the only drawback is that they don't automatically resize together, so you quickly lose the tabular view. A solution could be to set up a `SplitterMoved` event handler for every applicable SplitContainer: ``` private void mySplitContainer_SplitterMoved(object sender, SplitterEventArgs e) { mOtherySplitContainer.SplitterDistance = e.SplitX; } ``` If your SplitContainer is horizontal use `e.SplitX`, if it's vertical use `e.SplitY`.
Resizable table layout panel in c#
[ "", "c#", "winforms", "user-controls", ".net-2.0", "tablelayoutpanel", "" ]
With reference to [this question](https://stackoverflow.com/questions/980206/c-when-why-if-ever-should-i-think-about-doing-generic-programming-meta-pr), could anybody please explain and post example code of metaprogramming? I googled the term up, but I found no examples to convince me that it can be of any practical use. On the same note, is [Qt's Meta Object System](https://doc.qt.io/qt-5/metaobjects.html) a form of metaprogramming?
Most of the examples so far have operated on values (computing digits of pi, the factorial of N or similar), and those are pretty much textbook examples, but they're not generally very useful. It's just hard to imagine a situation where you really need the compiler to comput the 17th digit of pi. Either you hardcode it yourself, or you compute it at runtime. An example that might be more relevant to the real world could be this: Let's say we have an array class where the size is a template parameter(so this would declare an array of 10 integers: `array<int, 10>`) Now we might want to concatenate two arrays, and we can use a bit of metaprogramming to compute the resulting array size. ``` template <typename T, int lhs_size, int rhs_size> array<T, lhs_size + rhs_size> concat(const array<T, lhs_size>& lhs, const array<T, rhs_size>& rhs){ array<T, lhs_size + rhs_size> result; // copy values from lhs and rhs to result return result; } ``` A very simple example, but at least the types have some kind of real-world relevance. This function generates an array of the correct size, it does so at compile-time, and with full type safety. And it is computing something that we couldn't easily have done either by hardcoding the values (we might want to concatenate a lot of arrays with different sizes), or at runtime (because then we'd lose the type information) More commonly, though, you tend to use metaprogramming for types, rather than values. A good example might be found in the standard library. Each container type defines its own iterator type, but plain old pointers can *also* be used as iterators. Technically an iterator is required to expose a number of typedef members, such as `value_type`, and pointers obviously don't do that. So we use a bit of metaprogramming to say "oh, but if the iterator type turns out to be a pointer, its `value_type` should use this definition instead." There are two things to note about this. The first is that we're manipulating types, not values We're not saying "the factorial of N is so and so", but rather, "the `value_type` of a type T is defined as..." The second thing is that it is used to facilitate generic programming. (Iterators wouldn't be a very generic concept if it didn't work for the simplest of all examples, a pointer into an array. So we use a bit of metaprogramming to fill in the details required for a pointer to be considered a valid iterator). This is a fairly common use case for metaprogramming. Sure, you can use it for a wide range of other purposes (Expression templates are another commonly used example, intended to optimize expensive calculations, and Boost.Spirit is an example of going completely overboard and allowing you to define your own parser at compile-time), but probably the most common use is to smooth over these little bumps and corner cases that would otherwise require special handling and make generic programming impossible.
The concept comes entirely from the name [Meta-](http://en.wikipedia.org/wiki/Meta) means to abstract from the thing it is prefixed on. In more 'conversational style' to do something with the thing rather than the thing itself. In this regard metaprogramming is essentially writing code, which writes (or causes to be written) more code. The C++ template system is meta programming since it doesn't simply do textual substitution (as the c preprocessor does) but has a (complex and inefficient) means of interacting with the code structure it parses to output code that is far more complex. In this regard the template preprocessing in C++ is Turing complete. This is not a *requirement* to say that something is metaprogramming but is almost certainly *sufficient* to be counted as such. Code generation tools which are parametrizable may be considered metaprogramming if their template logic is sufficiently complex. The closer a system gets to working with the abstract syntax tree that represents the language (as opposed to the textual form we represent it in) the more likely it is to be considered metaprogramming. From looking at the QT MetaObjects code I would not (from a cursory inspection) call it meta programming in the sense usually reserved for things like the C++ template system or Lisp macros. It appears to simply be a form of code generation which injects some functionality into existing classes at the compile stage (it can be viewed as a precursor to the sort of Aspect Oriented Programming style currently in vogue or the prototype based object systems in languages like JavaScripts As example of the sort of extreme lengths you can take this in C++ there is [Boost MPL](http://www.boost.org/doc/libs/1_39_0/libs/mpl/doc/index.html) whose [tutorial](http://www.boost.org/doc/libs/1_39_0/libs/mpl/doc/tutorial/tutorial-metafunctions.html) shows you how to get: [Dimensioned types](http://www.boost.org/doc/libs/1_39_0/libs/mpl/doc/tutorial/dimensional-analysis.html) (Units of Measure) ``` quantity<float,length> l( 1.0f ); quantity<float,mass> m( 2.0f ); m = l; // compile-time type error ``` [Higher Order Metafunctions](http://www.boost.org/doc/libs/1_39_0/libs/mpl/doc/tutorial/higher-order.html) > twice(f, x) := f(f(x)) ``` template <class F, class X> struct twice : apply1<F, typename apply1<F,X>::type> {}; struct add_pointer_f { template <class T> struct apply : boost::add_pointer<T> {}; }; ``` > Now we can use twice with add\_pointer\_f to build pointers-to-pointers: ``` BOOST_STATIC_ASSERT(( boost::is_same< twice<add_pointer_f, int>::type , int** >::value )); ```
What is metaprogramming?
[ "", "c++", "qt", "metaprogramming", "" ]
I usually store dates as integers using PHP's `time()` function in a MySQL database rather than using MySQL's date format simply because it's easier to manipulate when I pull it back out, but are there any disadvantages to this?
**Range:** There's always the obvious disadvantage: The range that you can store is limited frΓ₯n 1970 to 2038. If you need to store dates outside of this range, you'll generally need to use another format. The most common case I've found where this apply is to birthdates. **Readability:** I think that the most important reason that people chose to use one of the built-in date-types it that the data is easier to interpret. You can do a simple select, and understand the values without having to format the response further. **Indexes:** A good technical reason to use the date types is that it allows for indexed query in some cases that unix timestamps doesn't. Consider the following query: ``` SELECT * FROM tbl WHERE year(mydate_field) = 2009; ``` If mydate\_field is of a native date type, and there's an index on the field, this query will actually use an index, despite the function call. This is pretty much the only time that mysql can optimize function calls on fields like this. The corresponding query on a timestamp field won't be able to use indices: ``` SELECT * FROM tbl WHERE year(from_unixtime(mytimestamp_field)) = 2009; ``` If you think about it for a bit, there's a way around it, though. This query does the same thing, and *will* be able to use index optimizations: ``` SELECT * FROM tbl WHERE mytimestamp_field > unix_timestamp("2009-01-01") AND mytimestamp_field < unix_timestamp("2010-01-01"); ``` **Calculations:** Generally, I store dates as unix time, despite the disadvantages. This isn't really based on it's merits, but rather it's because I'm used to it. I've found that this simplifies some calculations, but complicate others. For example, it's very hard to add a month to a unix timestamp since the number of seconds per month varies. This is very easy using the mysql DATE\_ADD() function. However, I think that in most cases it actually simplifies calculations. For example, it's quite common that you want to select the posts from, say, the last two days. If the field contains a unix timestamp this can be done easily by simply doing: ``` SELECT * FROM tbl WHERE mytimestamp_field > time() - 2*24*3600; ``` It's probably a matter of taste, but I personally find this faster and easier than having to rember the syntax of a function such as DATE\_SUB(). **Timezones:** Unix timestamps can't store time zone data. I live in sweden which has a single timezone, so this isn't really a problem for me. However, it can be a major pain if you live in a country that spans multiple timezones.
One disadvantage is that you won't be able to manipulate and query those dates using SQL functions.
MySQL date or PHP time?
[ "", "php", "mysql", "" ]
I need to display a grid on a webpage. The data will come from SQL Server 2008 through a stored procedure. As the sproc returns thousands of records, I decided to go for a paging option which works fine. In the stored procedure, I do something like this: ``` declare @RowIdMin int=10 declare @RowIdMax int=25 select * from (select Col1, Col2, ROW_NUMBER() over (order by Col1 desc) as RowId from MyTable ) dt where RowId BETWEEN @RowIdMin AND @RowIdMax ``` This works fine as long as the user is happy to get the data sorted by Col1. How could I rewrite this if I don't know in advance which column the recordset has to be sorted by? This doesn't work: ``` declare @RowIdMin int=10 declare @RowIdMax int=25 ``` **declare @ColSort varchar(100)='MyColumn'** ``` select * from (select Col1, Col2, ROW_NUMBER() over (order by <b>@ColSort</b> desc) as RowId from MyTable) dt where RowId BETWEEN @RowIdMin AND @RowIdMax ```
FROM MyTable ORDER BY CASE WHEN @ColSort = 'ABC' THEN ABC .... More thorough explanation <http://www.extremeexperts.com/sql/articles/CASEinORDER.aspx>
Dynamic SQL is probably your best bet; swap out the sort options in your row\_number() function. You can parameterize the options in the executesql too see [msdn](http://msdn.microsoft.com/en-us/library/aa933299(SQL.80).aspx) ``` declare @SQLScript nVarchar(4000) declare @RowIdMin int=10 declare @RowIdMax int=25 declare @ColSort varchar(100)='MyColumn' Select @SQLScript = 'select * from (select Col1, Col2, ROW_NUMBER() over (order by ' + @ColSort + 'desc) as RowId from MyTable dt where RowId BETWEEN ' + cast(@RowIdMin as nvarchar(100))+ ' AND ' + cast(@RowIdMax as nvarchar(100)) exec sp_executesql @SQLScript ```
SQL paging sorting
[ "", "sql", "sorting", "paging", "" ]
Is there a way to reference a namespace globally across the whole solution? So instead of having these lines in every code file: ``` using System; using MyNamespace; ``` having to declare them only once, and every code file would use them. Btw I am using Visual Studio.
No, C# doesn't have this concept. Each source file is independent in this respect. (And if the using directives are in a namespace declaration, those are independent from other using directives in peer namespace declarations, too. That's a pretty rare case though in my experience.) You don't need ReSharper to change what gets included in a new class though. You can use the [Visual Studio templates](https://stackoverflow.com/questions/651055/default-using-directives-in-new-c-files). EDIT: Just to clarify the point about using directives within namespaces, suppose we had (all in one file): ``` using Foo; namespace X { using Bar; // Foo and Bar are searched for code in here, but not Baz } namespace Y { using Baz; // Foo and Baz are searched for code in here, but not Bar } ``` Usually I only have one namespace declaration in a file, and put all the using directives before it.
No, this is not possible. If you're using [ReSharper](http://www.jetbrains.com/resharper/index.html), you can set an option to include specific using directives in every new file you create though.
Referencing namespaces globally?
[ "", "c#", ".net", "namespaces", "" ]
Say I have a function like this: ``` inline int shift( int what, int bitCount ) { return what >> bitCount; } ``` It will be called from different sites each time `bitCount` will be non-negative and within the number of bits in `int`. I'm particularly concerned about call with `bitCount` equal to zero - will it work correctly then? Also is there a chance that a compiler seeing the whole code of the function when compiling its call site will reduce calls with `bitCount` equal to zero to a no-op?
It is *certain* that at least one C++ compiler will recognize the situation (when the 0 is known at compile time) and make it a no-op: **Source** ``` inline int shift( int what, int bitcount) { return what >> bitcount ; } int f() { return shift(42,0); } ``` **Compiler switches** ``` icpc -S -O3 -mssse3 -fp-model fast=2 bitsh.C ``` **Intel C++ 11.0 assembly** ``` # -- Begin _Z1fv # mark_begin; .align 16,0x90 .globl _Z1fv _Z1fv: ..B1.1: # Preds ..B1.0 movl $42, %eax #7.10 ret #7.10 .align 16,0x90 # LOE # mark_end; .type _Z1fv,@function .size _Z1fv,.-_Z1fv .data # -- End _Z1fv .data .section .note.GNU-stack, "" # End ``` As you can see at ..B1.1, Intel compiles "return shift(42,0)" to "return 42." Intel 11 also culls the shift for these two variations: ``` int g() { int a = 5; int b = 5; return shift(42,a-b); } int h(int k) { return shift(42,k*0); } ``` For the case when the shift value is unknowable at compile time ... ``` int egad(int m, int n) { return shift(42,m-n); } ``` ... the shift cannot be avoided ... ``` # -- Begin _Z4egadii # mark_begin; .align 16,0x90 .globl _Z4egadii _Z4egadii: # parameter 1: 4 + %esp # parameter 2: 8 + %esp ..B1.1: # Preds ..B1.0 movl 4(%esp), %ecx #20.5 subl 8(%esp), %ecx #21.21 movl $42, %eax #21.10 shrl %cl, %eax #21.10 ret #21.10 .align 16,0x90 # LOE # mark_end; ``` ... but at least it's inlined so there's no call overhead. Bonus assembly: volatile is expensive. The source ... ``` int g() { int a = 5; volatile int b = 5; return shift(42,a-b); } ``` ... instead of a no-op, compiles to ... ``` ..B3.1: # Preds ..B3.0 pushl %esi #10.9 movl $5, (%esp) #12.18 movl (%esp), %ecx #13.21 negl %ecx #13.21 addl $5, %ecx #13.21 movl $42, %eax #13.10 shrl %cl, %eax #13.10 popl %ecx #13.10 ret #13.10 .align 16,0x90 # LOE # mark_end; ``` ... so if you're working on a machine where values you push on the stack might not be the same when you pop them, well, this missed optimization is likely the least of your troubles.
[According to K&R](http://net.pku.edu.cn/~course/cs101/2008/resource/The_C_Programming_Language.pdf) "The result is undefined if the right operand is negative, or greater than or equal to the number of bits in the left expression's type." (A.7.8) Therefore `>> 0` is the identity right shift and perfectly legal.
Will bit-shift by zero bits work correctly?
[ "", "c++", "bit-manipulation", "bit-shift", "" ]
Is there a compiler that has good support for the new C++0x? I use GCC but unfortunately the current version 4.4 has a poor support for the new features.
The only compiler that has an implementation of concepts is conceptgcc (and even that is incomplete - but it is good enough to get a good feel for the feature). Visual C++ 2010 Beta has some useful C++0x support - you can play with lambdas, rvalue references, auto, decltype. Comeau C++ or the EDG based compilers are surprisingly not as advanced I would have expected them to be in their implementation of C++0x. GCC 4.4 (variadic templates, initializer lists, inline namespaces, autor, decltype) probably has the most features implemented out of any of the other compilers, but is lagging in concepts and lambdas (separate branch development is ongoing).
The Apache Standard C++ Library project maintains [a wiki page of major compilers' C++0x support](http://wiki.apache.org/stdcxx/C++0xCompilerSupport). Here are links to the vendors' pages describing their C++0x support: * [GCC](https://gcc.gnu.org/projects/cxx0x.html) * [CodeGear C++Builder 2009](https://web.archive.org/web/20120715135311/http://docs.codegear.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/whatsnewtiburon_xml.html#432B2B4275696C6465722032303039) * [Intel C++ Compiler](http://www.intel.com/software/products/compilers/docs/clin/main_cls/copts/ccpp_options/option_std.htm) * Visual C++ 2009 and 2010 - see [here](https://stackoverflow.com/questions/146381/visual-studio-support-for-new-c-c-standards), [here](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/dd465215%28v=vs.100%29?redirectedfrom=MSDN), or [here](https://web.archive.org/web/20160127230241/http://blogs.msdn.com/b/vcblog/archive/2010/04/06/c-0x-core-language-features-in-vc10-the-table.aspx) * [Comeau C++](https://web.archive.org/web/20190108062108/http://www.comeaucomputing.com:80/43101features.html)
Compiler support for upcoming C++0x
[ "", "c++", "c++11", "" ]
I need to write a circular file in c++. The program has to write lines in a file and when the code reaches a maximum number of lines, it must overwrite the lines in the beginning of the file. Anyone have any idea?
Unfortunately you can't truncate/overwrite lines at the beginning of a file without rewriting the entire thing. ## New Suggestion I've just thought of a new approach that might do the trick for you... You could include a small header to your file that has the following structure. *Edit:* Rubbish, I've just described a variant of a [circular buffer](http://en.wikipedia.org/wiki/Circular_buffer)! **Header Fields** * `Bytes 00 - 07 (long)` - Total (current) number of lines written to the file. * `Bytes 08 - 15 (long)` - Pointer to the start of the "actual" first line of your file. This will initially be the byte after the header ends, but will change later when data gets overridden.` * `Bytes 16 - 23 (long)` - Length of the "end section" of the file. Again, this will initially be zero, but will change later when data gets overridden. **Read Algorithm (Pseudocode)** *Reads the entire file.* ``` Read the header field that points to the start of the "actual" first line Read the header field that specifies the length of the "end section" Read every line until the end of the file Seek to the byte just after the end of the header Read every line until the "end section" has been fully read ``` **Write Algorithm (Pseudocode)** *Writes an arbitrary number of new lines to the file.* ``` Read the header field that contains the total no. of lines in the file If (line count) + (no. of new lines) <= (maximum no. of lines) Then Append new lines to end of file Increment header field for line count by (no. of ne lines) Else Append as many lines as possible (up to maximum) to end of file Beginning at pointer to first line (in header field), read as many lines as still need to be written Find the total byte count of the lines just read Set the header field that points to the first line to the next byte in the stream Keep writing the new lines to the end of the file, each at a time, until the byte count of the remaining lines is less than the byte count of the lines at the beginning of the file (it may be that this condition is true immediately, in which case you don't need to write any more) Write the remaining new lines to the start of the file (starting at the byte after the header) Set the header field that contains the length of the "end section" of the file to the number of bytes just written after the header. ``` Not a terribly simple algorithm, I fully admit! I nonetheless think it's quite elegant in a way. Let me know if any of that isn't clear, of course. Hopefully it should do precisely what you want now. ## Original Suggestion Now, if you're lines are guaranteed to be of constant length (in bytes), you could easily enough just seek back to the appropiate point and overwrite existing data. This would seem like a rather unlikely situation however. If you don't mind imposing the restriction that your lines must have a maximum length, and additionally padding each of the lines you write to this maximum length, then that could make matters easy for you. Still, it has its disadvantages such as greatly increasing file size under certain circumstances (i.e. most lines are much shorted than the maximum length.) It all depends on the situation whether this is acceptable or not... Finally, you may instead want to look at utilising an existing logging system, depending on your exact purpose.
The usual way to handle logging that doesn't explode in size is to use rolling log files, and roll them once a day or similar, and only keep the N latest files. For instance, every day you create a new logfile with the filename `application\_2009\_05\_20.log', and start writing to it, always appending. Once you have 14 days worth of logfiles, you start deleting the oldest.
Write a circular file in c++
[ "", "c++", "file-io", "ofstream", "" ]
Recently I had to deal with a problem that I imagined would be pretty common: given a database table with a large (million+) number of rows to be processed, and various processors running in various machines / threads, how to safely allow each processor instance to get a chunk of work (say 100 items) without interfering with one another? The reason I am getting a chunk at a time is for performance reasons - I don't want to go to the database for each item.
There are a few approaches - you could associate each processor a token, and have a SPROC that sets that token against the next [n] available items; perhaps something like: (note - needs suitable isolation-level; perhaps serializable: `SET TRANSACTION ISOLATION LEVEL SERIALIZABLE`) (edited to fix TSQL) ``` UPDATE TOP (1000) WORK SET [Owner] = @processor, Expiry = @expiry OUTPUT INSERTED.Id -- etc WHERE [Owner] IS NULL ``` You'd also want a timeout (`@expiry`) on this, so that when a processor goes down you don't lose work. You'd also need a task to clear the owner on things that are past their `Expiry`.
You can have a special table to queue work up, where the consumers delete (or mark) work as being handled, or use a middleware queuing solution, like MSMQ or ActiveMQ. Middleware comes with its own set of problems so, if possible, I'd stick with a special table (keep it as small as possible, hopefully just with an id so the workers can fetch the rest of the information by themselves on the rest of the database and not lock the queue table up for too long). You'd fill this table up at regular intervals and let processors grab what they need from the top. Related questions on SQL table queues: [Queue using table](https://stackoverflow.com/questions/280515/queue-using-table) [Working out the SQL to query a priority queue table](https://stackoverflow.com/questions/465692/working-out-the-sql-to-query-a-priority-queue-table) Related questions on queuing middleware: [Building a high performance and automatically backupped queue](https://stackoverflow.com/questions/798748/building-a-high-performance-and-automatically-backupped-queue) [Messaging platform](https://stackoverflow.com/questions/960630/messaging-platform)
Getting a Chunk of Work
[ "", "sql", "concurrent-processing", "" ]
When would I write a UoW implementation on top of what is already provided by NHibernate? Any real world examples?
The Unit Of Work you are describing is already provided by NHibernate so there is no reason to do such a unit of work. What we have in our WCF Service is a higher level unit of work that contains information important in our application for the current unit of work. This includes abstracting the NHibernate ISession for us. When you break it down you have code that fits into three categories 1. Code that needs to deal with a Unit Of Work. It doesn't matter who backs the unit of work. It could be NHibernate, iBatis or a custom ORM. All the code needs to do is Load, Rollback, Save, etc. It doesn't nor should it care about the mechanism used to do so. 2. Code that needs to deal with an ISession directly because it's doing NHibernate specific things. Usually this has to do with complex queries that need to be created. 3. Doesn't need to know that it's running in a Unit Of Work or access the ISession. We can completely ignore this as part of this discussion. While code in 1. could just work against an ISession our preference is to try to abstract away things in the code that we do not directly control or that could change. This has value for two reasons. * When we started we weren't 100% sold on NHibernate. We were considering iBatis or something custom. Obviously this is no longer an issue. * The entire team are not experts in NHibernate nor do we want them to be. For the most part people write code that fits into category 1. and all they know about is our Unit Of Work. When code in category 2. has to get written it gets written by the people on the team that understand NHibernate well. So to close I would say that the type of Unit Of Work you are talking about is not needed I would suggest that a higher level Unit of Work can provide a lot of value.
My basic unit of work interface contains the following methods - Initialize - Commit - Rollback - IDisposable.Dispose I use it for both session and transaction management. It is useful because I don't have to write that code again and again for different session scopes. (unit of work per request, per series of requests, per thread, etc)
Why would I use the Unit of Work pattern on top of an NHibernate session?
[ "", "c#", "nhibernate", "unit-of-work", "" ]
Can someone please tell me the point of the STL heap function templates like `std::make_heap`? Why would anyone ever use them? Is there a practical use?
If you want to make a [priority queue](http://www.cplusplus.com/reference/algorithm/make_heap/) out from a list, well, you can use make\_heap: > Internally, a heap is a tree where > each node links to values not greater > than its own value. In heaps generated > by make\_heap, the specific position of > an element in the tree rather than > being determined by memory-consuming > links is determined by its absolute > position in the sequence, with \*first > being always the highest value in the > heap. > > Heaps allow to add or remove elements > from it in logarithmic time by using > functions push\_heap and pop\_heap, > which preserve its heap properties.
Your direct question would be well-answered by a class in algorithms and data structures. Heaps are used all over the place in algorithms in computer science. To quote from the make\_heap function linked below, "a heap is a tree where each node links to values not greater than its own value." While there are lots of applications for a heap, the one that I use most frequently is in search problems when you want to keep track of a sorted list of N values efficiently. I had similar confusion to yours when I first encountered the STL heap functions. My question was a little bit different though. I wondered "Why isn't the STL heap in the same class of data structures as std::vector?" I thought that it should work like this: ``` std::heap< int > my_heap; my_heap.heap_insert( 7 ); my_heap.heap_insert( 3 ); ``` The idea behind the STL heap functions though is that they allow you to make a heap data structure out of several different underlying STL containers, including std::vector. This can be really useful if you want to pass around the container for use elsewhere in your programs. It's also a little bit nice, because you can choose the underlying container of your heap if you so choose to use a something other than std::vector. All you really need are the following: ``` template <class RandomAccessIterator> void make_heap ( RandomAccessIterator first, RandomAccessIterator last ); ``` This means that you can make lots of different containers into a heap A comparator is also optional in the method signature, you can read more about the different things that you can try in the STL pages for the make\_heap function. Links: * [Heap Data Structure](http://en.wikipedia.org/wiki/Heap_(data_structure)) * [make\_heap function](http://en.cppreference.com/w/cpp/algorithm/make_heap)
What is the point of make_heap?
[ "", "c++", "stl", "language-design", "" ]
I'm using Django forms in my website and would like to control the order of the fields. Here's how I define my forms: ``` class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): name = forms.CharField() ``` The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create\_form and loose the inheritance but I'd like to know if this is possible. **Why?** Imagine you've got 100 fields in edit\_form and have to add 10 fields on the top in create\_form - copying and maintaining the two forms wouldn't look so sexy then. (This is *not* my case, I'm just making up an example) So, how can I override this behavior? **Edit:** Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations. In short the code would become something like this: ``` class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): def __init__(self,*args,**kwargs): forms.Form.__init__(self,*args,**kwargs) self.fields.insert(0,'name',forms.CharField()) ``` That shut me up :)
### From Django 1.9+ Django 1.9 adds a new `Form` attribute, `field_order`, allowing to order the field regardless their order of declaration in the class. ``` class MyForm(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) author = forms.CharField() notes = form.CharField() field_order = ['author', 'summary'] ``` Missing fields in `field_order` keep their order in the class and are appended after the ones specified in the list. The example above will produce the fields in this order: `['author', 'summary', 'description', 'notes']` See the documentation: <https://docs.djangoproject.com/en/stable/ref/forms/api/#notes-on-field-ordering> ### Up to Django 1.6 I had this same problem and I found another technique for reordering fields in the [Django CookBook](http://code.djangoproject.com/wiki/CookBookNewFormsFieldOrdering): ``` class EditForm(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class CreateForm(EditForm): name = forms.CharField() def __init__(self, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) self.fields.keyOrder = ['name', 'summary', 'description'] ```
From Django 1.9: <https://docs.djangoproject.com/en/1.10/ref/forms/api/#notes-on-field-ordering> --- **Original answer:** Django 1.9 will support this by default on the form with `field_order`: ``` class MyForm(forms.Form): ... field_order = ['field_1', 'field_2'] ... ``` <https://github.com/django/django/commit/28986da4ca167ae257abcaf7caea230eca2bcd80>
Django forms, inheritance and order of form fields
[ "", "python", "django", "django-forms", "" ]
This is a fairly straightforward question, I'm basically looking for a 'best practice' approach to what I'm trying to do. I have a Win32 GUI application which starts up a worker thread to do a bunch of blocking calls. I want this thread to send string messages back to the GUI so they can be displayed to the user. Currently I'm thinking the use of SendMessage would be a good approach, using WM\_COPYDATA? Is this on the right track? I did originally have a thread safe queue class which sent simple notification messages back to the GUI thread, which then popped the string off the queue. However I soon took a step back and realised I didn't need the queue; I could just send the string directly. Any tips? Thanks! Edit: And for completeness, I'm using C++.
WM\_COPYDATA would work fine, but I think it's better to simply define your own private window message. Allocate the string on the worker thread and free it on the GUI thread when you're done. Use PostMessage instead of SendMessage so that you don't block your worker unnecessarily.
As several others have pointed out a custom window message may be the best approach here. Another thing to consider is the actual memory being used. By passing the string between threads, I'm guessing that you are also passing ownership of the string between threads. This can cause a few issues you should be aware of including * Memory leaks: What happens if Thread A posts the messages and hence gives away ownership but the window is destroyed before Thread B processes the message * Can the memory manager backing your string safely allocate and free memory on different threads. The first issue is probably the one that has the biggest chance of impacting your application. I think this is a good reason to re-consider your original approach. As long as the queue itself is properly managed you can eliminate the memory leak as the queue can serve as a temporary owner of the memory.
Sending string data between threads (Win32)
[ "", "c++", "multithreading", "winapi", "sendmessage", "" ]
I've got a number of classes that inherit from `Item<T>`. Each class has a Create() method that I would like to move up into `Item<T>`. Yet the following code gets the error "**Cannot create an instance of the variable type 'T' because it does not have the new() constraint**": ``` T item = new T(loadCode); ``` What is the **correction syntax** to do this? ``` public abstract class Item<T> : ItemBase { public static T Create(string loadCode) { T item = new T(loadCode); if (!item.IsEmpty()) { return item; } else { throw new CannotInstantiateException(); } } ```
It's not possible. You can only use `new()` constraint to force existence of a constructor. A workaround is to take a `Func<InputType, T>` (`Func<string,T>` in your example) delegate as input parameter that'll create the object for us. ``` public static T Create(string loadCode, Func<string,T> construct) { T item = construct(loadCode); if (!item.IsEmpty()) { return item; } else { throw new CannotInstantiateException(); } } ``` and call it with: `Item<T>.Create("test", s => new T(s));`
**Correction**: I made a slight mistake, you need another constraint on T for this solution, see code below. You can only put a constraint on for parameterless constructor, but maybe something like this could work: ``` public interface ILoadable { void Load(string loadCode); } public abstract class Item<T> : ItemBase where T : ILoadable, new() { public static T Create(string loadCode) { T item = new T(); item.Load(loadCode); if (!item.IsEmpty()) { return item; } else { throw new CannotInstantiateException(); } } } ``` And then you implement the constructor code that depends on the `loadCode` in the override to `Load(...)` in the descendant classes.
What is the syntax to use C# generics as a constructor name?
[ "", "c#", "generics", "inheritance", "" ]
I can't be the only one getting tired of defining and naming a delegate for just a single call to something that requires a delegate. For example, I wanted to call .Refresh() in a form from possibly other threads, so I wrote this code: ``` private void RefreshForm() { if (InvokeRequired) Invoke(new InvokeDelegate(Refresh)); else Refresh(); } ``` I'm not even sure I have to, I just read enough to be scared that it won't work at some later stage. InvokeDelegate is actually declared in another file, but do I *really* need an entire delegate dedicated just for this? aren't there any generic delegates at all? I mean, for example, there's a Pen class, but there's also Pens.*pen-of-choice* so you don't have to remake the whole thing. It's not the same, but I hope you understand what I mean.
Yes. In .NET 3.5 you can use [Func](http://msdn.microsoft.com/en-us/library/bb534960.aspx) and [Action](http://msdn.microsoft.com/en-us/library/018hxwa8.aspx) delegates. The Func delegates return a value, while Action delegates return void. Here is what the type names would look like: ``` System.Func<TReturn> // (no arg, with return value) System.Func<T, TReturn> // (1 arg, with return value) System.Func<T1, T2, TReturn> // (2 arg, with return value) System.Func<T1, T2, T3, TReturn> // (3 arg, with return value) System.Func<T1, T2, T3, T4, TReturn> // (4 arg, with return value) System.Action // (no arg, no return value) System.Action<T> // (1 arg, no return value) System.Action<T1, T2> // (2 arg, no return value) System.Action<T1, T2, T3> // (3 arg, no return value) System.Action<T1, T2, T3, T4> // (4 arg, no return value) ``` I don't know why they stopped at 4 args each, but it has always been enough for me.
There's the Action delegate you could use, like so: ``` private void RefreshForm() { if (InvokeRequired) Invoke(new Action(Refresh)); else Refresh(); } ``` Or, with lambda syntax: ``` private void RefreshForm() { if (InvokeRequired) Invoke((Action)(() => Refresh())); else Refresh(); } ``` Finally there's anonymous delegate syntax: ``` private void RefreshForm() { if (InvokeRequired) Invoke((Action)(delegate { Refresh(); })); else Refresh(); } ```
anonymous delegates in C#
[ "", "c#", "delegates", "anonymous-methods", "" ]
I have a page with a jqueryui tabset on it. I'd like to be able to open the page with tab other than the first tab selected. If I have four tabs on the page I need to be able to select any of the four to be the 'open' tab. This maybe a link from another page or a link from a page in the same frameset. Under the covers everything is PHP.
You'll want to select a tab on the initial load of the page through JavaScript. Here's an example of how to select a tab: <http://docs.jquery.com/UI/API/1.7/Tabs#method-select> ``` <script type="text/javascript"> $(function() { $("#tabs").tabs( 'select' , index ) }); </script> ``` Where the index variable is the integer of the tab you want to have selected. It is 0 based, so if you want the third tab selected, you'll want to specify 2 for index. You'll want to do this once the page is ready: <http://www.learningjquery.com/2006/09/introducing-document-ready>
The answers above are no longer valid with the current version of jQuery UI v1.10.0. As per the jQuery UI API, the option is now **active** and no longer *select*. Here's a link to the API: <http://api.jqueryui.com/tabs/#option-active> > Initialize the tabs with the active option specified: ``` $(".selector").tabs({ active: 1 }); ```
Opening page with tab preselected that's not the first tab
[ "", "php", "jquery", "jquery-ui", "" ]
I'm a reasonably experienced Java programmer but relatively new to Java2D. I'm trying to scale an image but I'm getting poor quality results. The image is a preview of a panel so contains things like text and textfields. I'll always be scaling down, never up. Currently I'm using the following code:- ``` g.drawImage(panelImage, 0, 0, scaledWidth, scaledHeight, null); ``` Where panelImage is the full sized preview (BufferedImage) and scaledWidth and scaledHeight are the respective target dimensions. I seem to lose a lot of detail in the text and edges of things like textfields etc. Is there a better call I should be using to scale the image? Thanks, John
A suggestion I can make is to first resize the image onto a separate [`BufferedImage`](http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html). The reason being, a [`Graphics2D`](http://java.sun.com/javase/6/docs/api/java/awt/Graphics2D.html) object of the `BufferedImage` can be obtained in order to produce a better quality scaled image. `Graphics2D` can accept "rendering hints" which instruct the way image processing should be performed by the `Graphics2D` object. The [`setRenderingHint`](http://java.sun.com/javase/6/docs/api/java/awt/Graphics2D.html#setRenderingHint(java.awt.RenderingHints.Key,%20java.lang.Object)) method is one of the methods which can be used to set those rendering hints. The rendering hints from the [`RenderingHints`](http://java.sun.com/javase/6/docs/api/java/awt/RenderingHints.html) class can be used. Then, using that `Graphics2D` object, an image can be drawn to the `BufferedImage` using the rendering hints specified earlier. A rough (untested) code would work as the following: ``` BufferedImage scaledImage = new BufferedImage( scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB ); Graphics2D g = scaledImage.createGraphics(); g.setRenderingHints( RenderingHints.Key.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC ); g.drawImage(panelImage, 0, 0, scaledWidth, scaledHeight, null); g.dispose(); ``` Other rendering hints of interest may include: * [`KEY_ANTIALIASING`](http://java.sun.com/javase/6/docs/api/java/awt/RenderingHints.html#KEY_ANTIALIASING) * [`KEY_RENDERING`](http://java.sun.com/javase/6/docs/api/java/awt/RenderingHints.html#KEY_RENDERING) The [Controlling Rendering Quality](http://java.sun.com/docs/books/tutorial/2d/advanced/quality.html) section of The Java Tutorials also has more information on how to control the rendering quality of `Graphics2D` objects. And for a very good source of information on dealing with graphical interfaces in general, [Filthy Rich Clients](http://filthyrichclients.org/) by Chet Haase and Romain Guy is highly recommended. There is one section of the book that deals with the issue of scaling images, which seems quite relevant.
May be you should call: ``` g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); ``` and ``` g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ```
Java2D: scaling issues
[ "", "java", "scaling", "java-2d", "" ]
I have a list of items which I want the user to be able to tick which are appropriate to them. Currently I have a `<ul>` generated by a `Repeater` with checkbox and label controls placed in side, all working fine. However, the `<ul>` is taking up too much space on the screen and I need to condense it. I think the best approach would be a table that expands based on the number of items, 9 resultining a 3x3 grid, 12 a 3x4 grid, 16 a 4x4 grid etc up to a maximum width of 6 rows. Any suggestions for where to start?
Use an asp.net CheckBoxList control. You can control the way it displays e.g. the number of rows/columns it uses.
I think you can achieve this by using a CheckBoxList control. It has a RepeatColumns property that can be used to specify the number of columns.
ASP.NET Generate a table from list with dynamic number of rows and columns
[ "", "c#", "asp.net", "" ]
Consider this code: ``` try { ISomeObject pObj(__uuidof(SomeClass)); ISomeObject pObj2(__uuidof(SomeOtherClass)); } catch ( _com_error& e ) { // Log what failed } ``` I.e. I have a block of code which instanciates my objects. Sometimes (a bad install) it failes because some class wasn't properly registered. (I don't have a particular problem, rather general discussion here.) Is there some way to, from the caught exception or otherwise, realize what class failed? A have pondered to make a wrapper of my own which stores a variable like *gLastCreateAttemptUuid*, but it feel cumbersome. Also, suppose that SomeClass in turn attempt to instanciate something else, which isn't registered. Can one then figure out the underlying issue?
It's the duty of CoCreateInstance() caller to provide enough information about what it was trying to instantiate - both ATL and Native COM Support have no built-in features for that. Instead of calling a smart pointer constructor parameterized with a class id you can call its CreateInstance() method - it has exactly the same set of parameters but doesn't throw exceptions. Then you could check the HRESULT and handle the error and provide the class id you just used to the error handler. However it will not help ypu if the problem happens in the code you don't control. In extreme cases you can use [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) to monitor registry queries and detect which class id is causing the problem.
Neither [`CComPtr::CreateInstance`](http://msdn.microsoft.com/en-us/library/fz0akhxa(VS.71).aspx) nor [`_com_ptr_t::CreateInstance`](http://msdn.microsoft.com/en-us/library/k2cy7zfz(VS.80).aspx) should throw an exception from what I can tell from the documentation. Both return an HRESULT value. But if you check the `HRESULT` return value from each call, you should be able to determine which of the two classes are not registered (if that is the problem). ``` try { ISomeObject pObj, pObj2; HRESULT hr1 = pObj.CreateInstance(__uuidof(SomeClass)); HRESULT hr2 = pObj2.CreateInstance(__uuidof(SomeOtherClass)); } catch ( _com_error& e ) { // Log what failed } ``` Check out the documentation for [CoCreateInstance](http://msdn.microsoft.com/en-us/library/ms686615(VS.85).aspx) for return values. **Update:** If you are catching an exception, then please show us any information it has. If this is the case, then my guess is that one of the classes you are trying to instantiate is throwing the error. Debugging over those lines or separating the code into two try/catch blocks would help you narrow down which one if the exception does not have any information.
"class not registered" which class?
[ "", "c++", "com", "atl", "" ]
I am looking for a way to display TIF documents on a web page. It basically needs to render a Multi-page TIF in some form of container on a web page. Do I need a control or is there a simple way to build something like this? Is there any free stuff that we could simply implement? I have looked at the [Telerik reporting](http://www.telerik.com/products/reporting.aspx) product which apparently contains a Tif viewer. I haven't looked into the licensing for this though. (If I only need the TIF Viewer, do I need to purchase the entire reporting solution? Our biggest issue at the moment (like always) is that we have a very tight deadline with very little available resource. This product will be installed at a client so ActiveX controls that request user permission to install are less than ideal. Any suggestions and/or comments would be welcome. Thanks
If you want to try and roll your own (this would be a lot of work), you can use the System.Drawing namespace to convert TIF images to a browser-supported format, like PNG or JPG, or a third party library like [AbcPdf](http://www.websupergoo.com/abcpdf-1.htm) to go to PDF as Lazarus suggested. The problem here is that you would have to create and code-behind a toolset for magnification, cropping, and multi-page support, along with whatever else you would want, which could be quite a bit of coding (unless you went to PDF and relied on Adobe Reader). Also, the server-side conversion can be prohibitive for speed if you're dealing with large TIF files or with formats that aren't supported. As far as vendor solutions are concerned, I don't know of any good free viewing plugins off-hand. R Ubben is right; Snowbound's viewer is nice, but if I recall, the AJAX version requires it's own website that you pass the image to, which then gets rendered to the client, which may bring up some security issues (and leaves a bad taste in my mouth anyway). [Atalasoft](http://www.atalasoft.com/products/dotimage/documentimaging/default.aspx) has an excellent AJAX image viewer and a very powerful imaging SDK, but it does cost a bit. My current company has settled on an ActiveX plugin from Pegasus Imaging (recently merged with Accusoft) called [Prizm Viewer](http://www.accusoft.com/prizmviewer.htm). The viewer itself is quite powerful, can handle many image formats, and is scriptable. It does have drawbacks (beyond being an ActiveX control). We've had some trouble with our desktop deployments as the default install will only push for the current user as opposed to the local machine, but we've fixed that with a post-install registry hack. I would say that, if you have the cash and want a robust imaging solution, go with Atalasoft. Otherwise, Pegasus is fairly cheap and works just fine, unless you have severe aversions to ActiveX. There are lots of other options out there, it's just a matter of how much money you have and how much coding you want to do.
Use a library server-side to convert the TIF to a PDF (assuming that it's a common plug-in that most people have) which will eliminate the need to install another, convert each page of the TIF into a GIF or JPG and present those, again fully supported by browsers eliminating the need for an additional plug-in. You could probably do this conversion on-the-fly and then cache the output to reduce subsequent loading times.
Previewing TIF documents on the Web (.Net C#)
[ "", "c#", "asp.net", "" ]
If I have a method that does something with multiple Subsonic ActiveRecords and doesn know what type exactly it is easy thanks to interfaces. ``` public void DoSomething(IActiveRecord item) { // Do something } ``` But what if you have a method and you don't know what Collection (e.g. ProductCollection) you get? How do I have to declare my Parameter? There is no IActiveList interface. I tried it with an generic approach, but that doesn't compile. ``` public void Add<Titem, Tlist>(ActiveList<Titem, Tlist> list) { foreach(IActiveRecord item in list) { // Do something } } ```
You could limit the parameter to be a BindingListEx (the base class for AbstractList) and which would would give you an enumerable list: ``` public void <T>(T list) where T : BindingListEx<IActiveRecord> { foreach(IActiveRecord item in list) { } } ```
Maybe this will help you? <http://msdn.microsoft.com/en-us/library/d5x73970> ``` public void Add<Titem, Tlist>(ActiveList<Titem, Tlist> list) where Titem : IActiveRecord ``` Dunno, I don't know anything about SubSonic. But I'm guess generic class constraints would do the trick :)
Need a method that accepts all kind of Subsonic Collections as a parameter
[ "", "c#", "subsonic", "" ]
I would like to be able to detect a clapping sound. Being pretty new to any form of sound recognition, is there simple any way to do this? If not, any good resources for C# sound recognition/detection? My goal is to automate a clients media center with some basic clap-based controls.
There was a similar question asked in the past: [Given an audio stream, find when a door slams (sound pressure level calculation?)](https://stackoverflow.com/questions/499795/given-an-audio-stream-find-when-a-door-slams-sound-pressure-level-calculation) Although the question was not specific to C#, it does have some ideas for algorithms to use. (Disclosure: Yes, I did answer that question.)
I wouldnt focus on the language as such, but on the algorithm. What characteristics of a sound allow you to identify it as a clap? Duration? Intensity? Variation of intensity over time? Once you've got an algorithm, *then* decide the best way to implement it.
Clap sound detection in C#
[ "", "c#", "audio", "sound-recognition", "" ]
Here's a query I'm working on: ``` SELECT TBL_SUB_KEY AS port , poe.[TBL_COMPANY] , poe.[TBL_DIVISION_1] FROM dbo.TMVKTAB AS poe WHERE ( TBL_NUMBER = '8A' ) AND ( TBL_SUB_KEY <> '' ) AND ( poe.[TBL_COMPANY] <> '011' AND poe.[TBL_DIVISION_1] <> '11' ) ``` What I want returned are all the records that are **not** in Company = '011'/Division\_1' = '11'. I thought combining the company/division in the () would achieve this, but it does not. It eliminates all the company '011' records and it eliminates all division '11' records. However, when I do this: ``` SELECT TBL_SUB_KEY AS port , poe.[TBL_COMPANY] , poe.[TBL_DIVISION_1] FROM dbo.TMVKTAB AS poe WHERE ( TBL_NUMBER = '8A' ) AND ( TBL_SUB_KEY <> '' ) AND NOT ( poe.[TBL_COMPANY] = '011' AND poe.[TBL_DIVISION_1] = '11' ) ``` it seems to pull the correct results. Why is this?
It's a boolean logic issue: ``` NOT (A and B) <=> NOT A OR NOT B ``` i.e.: ``` NOT ( poe.[TBL_COMPANY] = '011' AND poe.[TBL_DIVISION_1] = '11') ``` Is equivalent to: ``` ( poe.[TBL_COMPANY] <> '011' OR poe.[TBL_DIVISION_1] <> '11') ``` Read: <http://en.wikipedia.org/wiki/Boolean_logic>
I think the equivalent to the NOT would use OR as shown below: ``` SELECT TBL_SUB_KEY AS port , poe.[TBL_COMPANY] , poe.[TBL_DIVISION_1] FROM dbo.TMVKTAB AS poe WHERE ( TBL_NUMBER = '8A' ) AND ( TBL_SUB_KEY <> '' ) AND ( poe.[TBL_COMPANY] <> '011' OR poe.[TBL_DIVISION_1] <> '11' ) ```
SQL WHERE excluding records using AND and NOT
[ "", "sql", "syntax", "" ]
How do I flush the keyboard buffer in C# using Windows Forms? I have a barcode scanner which acts like a keyboard. If a really long barcode is scanned and the cancel button is hit on the form, I need the keyboard buffer to be cleared. So I need to flush and ignore all pending input. I need the buffer cleared because if the barcode contains spaces, the spaces are processed as button clicks which is unecessary.
I'm not sure you can do this. The keystrokes go into the event queue for the main event loop. Any action you take to cancel these keystrokes will be placed in the queue after the keystrokes. The event loop will only get to your cancel action after the keystrokes have been processed. You can only cancel the keystrokes based on some event that happens in the middle of the keystroke sequence.
``` while (Console.KeyAvailable) { Console.ReadKey(true); } ```
C# or .NET Flushing Keyboard Buffer
[ "", "c#", "keyboard", "buffer", "flush", "" ]
I have two tables, like this: ``` #Articles: ID | Title 1 "Article title" 2 "2nd article title" #Comments: ID | ParentID | Comment 1 1 "This is my comment" 2 1 "This is my other comment" ``` I've always wanted to know, what is the most elegant way to get the following result: ``` ID | Title | NumComments 1 "Article title" 2 2 "2nd article title" 0 ``` This is for SQL Server.
This will normally be faster than the subquery approach, but as always you have to profile your system to be sure: ``` SELECT a.ID, a.Title, COUNT(c.ID) AS NumComments FROM Articles a LEFT JOIN Comments c ON c.ParentID = a.ID GROUP BY a.ID, a.Title ```
``` select title, NumComments = (select count(*) from comments where parentID = id) from Articles ```
SQL Query to get a row, and the count of associated rows
[ "", "sql", "sql-server", "" ]
I need to count the number of occurrences of a character in a string. For example, suppose my string contains: ``` var mainStr = "str1,str2,str3,str4"; ``` I want to find the count of comma `,` character, which is 3. And the count of individual strings after the split along comma, which is 4. I also need to validate that each of the strings i.e str1 or str2 or str3 or str4 should not exceed, say, 15 characters.
I have updated this answer. I like the idea of using a match better, but it is slower: ``` console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3 console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4 ``` Use a regular expression literal if you know what you are searching for beforehand, if not you can use the `RegExp` constructor, and pass in the `g` flag as an argument. `match` returns `null` with no results thus the `|| []` The original answer I made in 2009 is below. It creates an array unnecessarily, but **using a split is faster** (as of September 2014). I'm ambivalent, if I really needed the speed there would be no question that I would use a split, but I would prefer to use match. Old answer (from 2009): If you're looking for the commas: ``` (mainStr.split(",").length - 1) //3 ``` If you're looking for the str ``` (mainStr.split("str").length - 1) //4 ``` Both in @Lo's answer and in my own silly [performance test](https://parsebox.io/dthree/fgrsjqmknxzs) split comes ahead in speed, at least in Chrome, but again creating the extra array just doesn't seem sane.
There are at least five ways. The best option, which should also be the fastest (owing to the native RegEx engine) is placed at the top. ### Method 1 ``` ("this is foo bar".match(/o/g)||[]).length; // returns 2 ``` ### Method 2 ``` "this is foo bar".split("o").length - 1; // returns 2 ``` Split not recommended as it is resource hungry. It allocates new instances of 'Array' for each match. Don't try it for a >100MB file via FileReader. You can observe the exact resource usage using **Chrome's profiler** option. ### Method 3 ``` var stringsearch = "o" ,str = "this is foo bar"; for(var count=-1,index=-2; index != -1; count++,index=str.indexOf(stringsearch,index+1) ); // returns 2 ``` ### Method 4 Searching for a single character ``` var stringsearch = "o" ,str = "this is foo bar"; for(var i=count=0; i<str.length; count+=+(stringsearch===str[i++])); // returns 2 ``` ### Method 5 Element mapping and filtering. This is not recommended due to its overall resource preallocation rather than using Pythonian 'generators': ``` var str = "this is foo bar" str.split('').map( function(e,i){ if(e === 'o') return i;} ) .filter(Boolean) //>[9, 10] [9, 10].length // returns 2 ``` **Share:** I made this *[gist](https://gist.github.com/2757250)*, with currently 8 methods of character-counting, so we can directly pool and share our ideas - just for fun, and perhaps some interesting benchmarks :)
Count the number of occurrences of a character in a string in Javascript
[ "", "javascript", "string", "" ]
I have a page with an anchor tag. In my JavaScript I am setting the `HREF` attribute of the anchor tag dynamically based on some if-else conditions. Now I want to invoke the click event of the anchor tag programmatically. I used the below code, but was not successful. ``` var proxyImgSrc="CostMetrics.aspx?Model=" + model +"&KeepThis=true&TB_iframe=true&height=410&width=650"; document.getElementById("proxyAnchor").href=proxyImgSrc; document.getElementById("proxyAnchor").onclick; ``` Can any one tell me how to go ahead? I have a jQuery light box implementation(thickbox) on this link. Kindly advise. Thanks in advance.
If you have jQuery installed then why not just do this: ``` $('#proxyAnchor')[0].click(); ``` Note that we use [0] to specify the first element. The jQuery selector returns a jQuery instance, and calling click() on that only calls click javascript handler, not the href. Calling click() on the actual element (returned by [0]) will follow the link in an href etc. See here for an example to illustrate the difference: <http://jsfiddle.net/8hyU9/> As to why your original code is not working - it is probably because you are calling `onclick`, and not `onclick()`. Without the parenthesis JavaScript will return whatever is assigned to the `onclick` property, not try to execute it. Try the following simple example to see what I mean: ``` var f = function() { return "Hello"; }; alert(f); alert(f()); ``` The first will display the actual text of the function, while the second will display the word "Hello" as expected.
You should call click event like this: ``` document.getElementById("proxyAnchor").click(); // $('#proxyAnchor').click(); ``` but in your case you should set the window's location to a redirect page, if you want that.
JavaScript: Invoking click-event of an anchor tag from javascript
[ "", "javascript", "jquery", "click", "onclick", "" ]
I'm sending a jquery get request like so: ``` $.get($(this).attr("href"), $(this).serialize(), null, "script"); ``` The response I expect to receive will be wrapped in script tags. I understand the browser doesn't execute the response unless its returned without the script tags. Normally I would remove the tags from the response but in this situation I don't have access to the code running on the remote machine so cannot strip out the tags at the source. Is there a way I can strip out the script tags from the response client side and execute the javascript?
You should be able to do the following: ``` $.get($(this).attr("href"), $(this).serialize(), function(data){ var script = $(data).text(); eval(script); }); ```
Or: ``` var myScript = new Function($('script#myscript',responseText).text()); myScript(); ```
How to execute javascript inside a script tag returned by an ajax response
[ "", "javascript", "ajax", "jquery", "" ]
Say you have 3 layers: UI, Business, Data. Is that a sign of poor design if Business layer needs to access Sessions? Something about it doesn't feel right. Are there any guidelines to follow specifically tailored to web app? I use c# 2.0 .net
My feeling is that the business layer is the only place to put the session data access because it really is part of your logic. If you bake it into the presentation layer, then if you change where that data is stored (lets says, you no longer want to use session state), then making a change is more difficult. What I would do is for all the data that is is session state, I'd create a class to encapsulate the retrieval of that data. This will allow for future changes. Edit: The UI should only be used to do the following: 1. Call to the business layer. 2. Interact with the user (messages and events). 3. Manipulate visual object on the screen. I have heard people consider the session data access as part of the data layer, and this is semantic, and depends on what you consider the data layer.
No. If you had a "Controller" layer, you should access it there. Get what you need from the Session and hand it off to your business layer.
Should Business layer of the application be able to access Session object?
[ "", "c#", "session", "business-logic", "" ]
I have a table which has a column labeled 'sortorder' which is used to allow customer to manually change the order of each item. The table also has a column labeled 'CategoryId'. I was curious, if I was bulk importing a set of data in which I knew all data, including CategoryId, how I could specify the incrimenting value for 'SortOrder' inside the query, so that it went from 1 to X within each unique CategoryId. Thanks everyone.
I'm not sure I understand your question but I *think* what you're asking is how to synthesize an appropriate SortOrder during an insert into the table. You should use ROW\_NUMBER() with partitioning by CategoryId. Of course you will need to define a sorting criteria that gives the propert order of '1 to X': ``` INSERT INTO myTable (SortOrder, CategoryId, <other columns> ...) SELECT ROW_NUMBER() OVER (PARTITION BY CategoryId ORDER BY mySortCriteria) , CategoryId , <other columns> ... FROM SourceTable; ```
Sounds like you're needing to use the row\_number function in your import. ``` INSERT MyTable(SortOrder, ...) SELECT SortOrder = row_number() over (partition by CatgoryID order by SomeOtherField), ... FROM MyTable ```
Incrementing value based on criteria in a single database query
[ "", "sql", "sql-server-2005", "" ]
I'm having a debate with another programmer I work with. For a database return type, are there any significant memory usage or performance differences, or other cons which should make someone avoid using the DataSets and DataTables and favour types which implement `IEnumerable<T>`... or vice versa I prefer returning types which implement`IEnumerable<T>` (`List<T>, T[] etc`) because it's more lightweight, strongly typed to the object when accessing properties, allows richer information about the underlying type etc. They do take more time to set up though when manually using the data reader. Is the only reason to use DataTables these day just lazyness?
DataTables are definitely much heavier than Lists, both in memory requirements, and in processor time spent creating them / filling them up. Using a DataReader is considerable faster (although more verbose) than using DataTables (I'm assuming you're using a DataAdapter to fill them). That said... Unless this is in some place where it **really** matters, you're probably fine either way, and both methods will be fast enough, so just go with whatever is more comfortable in each case. (Sometimes you want to fill them up with little code, sometimes you want to read them with little code) I myself tend to only use DataTables when I'm binding to a GridView, or when I need more than one resultset active at the same time.
Another advantage to using the System.Collections classes is that you get better sorting and searching options. I don't know of any reasonable way to alter the way a DataTable sorts or searches; with the collection classes you just have your class implement IComparable or IEquatable and you can completely customize how List.Sort and List.Contains work. Also with lists you don't have to worry about DBNull, which has tripped me up on more than one occasion because I was expecting null and got DBNull.
DataTables vs IEnumerable<T>
[ "", "c#", "list", "datatable", "ienumerable", "" ]
I'm currently trying to extract data from a table, and am using this: ``` $online = mysqli_fetch_field(mysqli_query($db, "SELECT `online` FROM `tbl_system` WHERE `property` = 'extranet'")); ``` However, it's not working as echoing `$online` give "Array". Here's a var\_dump from $online ``` object(stdClass)#3 (11) { ["name"]=> string(6) "online" ["orgname"]=> string(6) "online" ["table"]=> string(10) "tbl_system" ["orgtable"]=> string(10) "tbl_system" ["def"]=> string(0) "" ["max_length"]=> int(1) ["length"]=> int(11) ["charsetnr"]=> int(63) ["flags"]=> int(36865) ["type"]=> int(3) ["decimals"]=> int(0) } ```
You want: ``` $query = mysqli_query($db, "SELECT online FROM tbl_system WHERE property = 'extranet'"); $row = mysqli_fetch_array($query); $online = $row[0]; ``` [`mysqli_fetch_field()`](http://www.php.net/mysqli_fetch_field) is for retrieving *column definitions*, not data, and it's working perfectly well: giving you back a column definition object. [`mysqli_fetch_array()`](http://www.php.net/mysqli_fetch_array), [`mysqli_fetch_assoc()`](http://www.php.net/mysqli_fetch_assoc), and [`mysqli_fetch_object()`](http://www.php.net/mysqli_fetch_object) are for data retrieval.
Try one of the following functions: * [`mysqli_fetch_array`](http://docs.php.net/mysqli_fetch_array) β€” Fetch a result row as an associative, a numeric array, or both ``` $row = mysqli_fetch_array($result); echo $row[0]; // or echo $row['online']; ``` * [`mysqli_fetch_assoc`](http://docs.php.net/mysqli_fetch_assoc) β€” Fetch a result row as an associative array ``` $row = mysqli_fetch_assoc($result); echo $row['online']; ``` * [`mysqli_fetch_object`](http://docs.php.net/mysqli_fetch_object) β€” Returns the current row of a result set as an object ``` $row = mysqli_fetch_object($result); echo $row->online; ``` * [`mysqli_fetch_row`](http://docs.php.net/mysqli_fetch_row) β€” Get a result row as an enumerated array ``` $row = mysqli_fetch_row($result); echo $row[0]; ``` With `$result` being: ``` $result = mysqli_query($db, "SELECT `online` FROM `tbl_system` WHERE `property` = 'extranet'"); ```
What mysqli function should I use?
[ "", "php", "arrays", "mysqli", "fetch", "" ]
In JavaScript there is the idea of truthy and falsy values. e.g. * 0 : Always false * 1 : Always true * '0' : Always true * '1' : Always true Is there an equivalent list of truthy and falsey values in the C# language on the .NET framework? The reason I would like to know this is that I find myself doing the following ``` if(obj != null) { // Do something with the object } ``` When I could write the following ``` if(obj) { // Do something with the object } ```
C# only has literal `true` and `false` values. C# requires you to be very explicit in your declarations. This behaves like other popular strongly-typed languages, as opposed to JavaScript which can do implicit conversions when needed. It should be noted for clarity that "strong typing" is not the reason why C# doesn't implicitly convert to "truthy/falsy" values. The language intentionally is trying to avoid the pitfalls of some other compiled languages like C where certain values can be truthy, like '`0`' or '`1`' which could allow you to make a syntactical mistake you might not notice until runtime when your code behaves unexpectedly.
By default, C# only provides `true` and `false`. However, you can have your own custom types becomes "truthy" and "falsey" by implementing the `true` operator. When a type implements the `true` operator, instances of that type can be used as a boolean expression. From section 7.19 of the [C# Language Specification](http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/csharp%20language%20specification.doc): > When a boolean expression is of a type that cannot be implicitly converted to bool but does implement operator true, then following evaluation of the expression, the operator true implementation provided by that type is invoked to produce a bool value. > > The `DBBool` struct type in Β§11.4.2 provides an example of a type that implements operator true and operator false. Here is a code snippet of a declaration of the `true` operator (which will probably accomplish what you wanted to do in your question): ``` public static bool operator true(MyType myInstance) { return myInstance != null; } ``` If you implement the `true` operator, then you must implement the `false` operator too.
c# truthy and falsy values
[ "", "c#", ".net", "" ]
I need a simple program that given a string, returns to me the next one in the alphanumeric ordering (or just the alphabetic ordering). ``` f("aaa")="aab" f("aaZ")="aba" ``` And so on. Is there a function for this in one of the modules already?
I don't think there's a built-in function to do this. The following should work: ``` def next_string(s): strip_zs = s.rstrip('z') if strip_zs: return strip_zs[:-1] + chr(ord(strip_zs[-1]) + 1) + 'a' * (len(s) - len(strip_zs)) else: return 'a' * (len(s) + 1) ``` Explanation: you find the last character which is not a `z`, increment it, and replace all of the characters after it with `a`'s. If the entire string is `z`'s, then return a string of all `a`'s that is one longer.
Are the answers at [How would you translate this from Perl to Python?](https://stackoverflow.com/questions/604721/how-would-you-translate-this-from-perl-to-python/604777) sufficient? Not 100% what you're asking, but close...
How can I get the next string, in alphanumeric ordering, in Python?
[ "", "python", "string", "" ]
I've been investigating [frame breaking](http://www.bloggingtips.com/2009/04/07/how-to-remove-the-digg-bar-from-your-blog/) code recently and have come across some really bizarre behavior related to the [same origins policy](https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript) that I am having trouble understanding. Suppose I've got a page Breaker.html on domain A, and a page Container.html on domain B. The example frame breaker code would go into Breaker.html, like below: ``` if (top !== self) top.location.href = self.location.href; ``` This will successfully break Breaker.html out of Container.html, but I don't understand why it should. From my reading of the same origins policy, `top.location` shouldn't be accessible *at all*, since Container.html is on a different domain than Breaker.html. Even weirder, it appears that top.location **write-only**: ``` // Fails if Container.html is on a different domain than Breaker.html alert(top.location); ``` This is problematic to me because I'm trying to write code that allows my page to be in an iframe, but only if it's on the same domain as its parent (or is on a configured allowable domain) . However, it seems to be impossible to determine this, since the same origins policy denies me access to the parent's location. So I've got two questions, basically: 1. Why does the above frame breaker code work at all? 2. Is there any way to break frames conditionally, or is the only check one can do is whether `top !== self`? (In particular, I want to be able to read the domain, so that I can provide a list of allowable domains; simply checking whether I'm in the same domain or not would not be ideal.)
FOr your answer to number 1: In terms of security, there is a big difference between read access and write access. Being able to read top.location.href is a security problem. Being able to *write* to top.location.href is not. As for the answer to your question, I don't know javascript well enough to be sure, but one idea would be to assumine that if reading top.location fails (check for exceptions), it is on a different domain.
The answer to question 1 is that the equality operator can be used against top.location.href for legacy reasons. Breaker.html cannot read top.location.href but it can compare it with another value. The answer to question 2 then becomes no, you must use the !== to part because you won't be able to do a substring on top.location.href from a cross domain breaker.html. I could be wrong but that's my understand of the current iframe world.
Why do frame breakers work cross-domain, and can you conditionally use frame breakers?
[ "", "javascript", "iframe", "same-origin-policy", "" ]
I have a pointer to an int. ``` int index = 3; int * index_ptr = &index; ``` `index_ptr` is a member variable of a class `IndexHandler`. class A has a std::vector of IndexHandlers, Avector. class B has a std::vector of pointers to IndexHandlers, Bvector, which I set to point to the items in class A's vector, thusly: ``` Bvector.push_back(Avector[i].GetPtr()) ``` With me so far? I want to check that when I resolve the pointers in Bvector, and retreive the internal IndexHandlers `index_ptr`, that they point to the same `index_ptr` as class A's... How can I check they are pointing to the same memory address?... How do i print the address of the value pointed to by both sets of pointers?
the non-iterator method to print them out side-by-side: ``` for (size_t i = 0; i < Avector.size(); i++) { std::cout << "Avector ptr:" << Avector[i].GetPtr() << ", Bvector ptr:" << Bvector[i] << std::endl; } ``` This will print out the pointer values of each one. One thing you should be aware of though. If the pointer in the IndexHandler is pointing to a value within the IndexHandler then it can become invalidated if the vector is resized, and pointers to anything above an index WILL be invalidated if an item is inserted or deleted at that index. Because of this, it's generally a bad idea to keep pointers to items in a vector and if you want to do this then it's better practice to use a std::list container instead (which doesn't invalidate pointers to items in the list when you insert or delete new values)
To print the address of an int pointer and the int value an int pointer points to, use ``` printf("%p %i\n", ptr, *ptr); ```
How to get the address of a value, pointed to by a pointer
[ "", "c++", "pointers", "" ]
I am using Two SQL Server connection object in my C# console application project. I need to do this in single transaction So I used Transactionscope (Distributed Transaction) I am not able to use the connection within the transactionscope It is displaying the error MSDTC on server is unavailable. How can I solve.... Both the one sql connection is remote server and another one is local server. Note:- The msdtc service is already started. The server started on both the machines. Still I am facing the issue. Do I need to turn off the firewall in my local intranet machines.
Whenever you do a distributed transaction, the Microsoft Distributed Transaction Coordinator needs to be running on your local machine and on all servers which participate in the transaction. If you have firewalls in place you will also need to make sure that you have limited the ports on which MSDTC communicates and added the appropriate rules to your firewall configuration to allow the connections -- I believe it needs portmapper access as well as the specific port range you've chosen for RPC. There are also various security settings for MSDTC that need to be synchronized that control how authentication is done between the servers. Here are some links that may be helpful: 1. [MSDTC at MSDN](http://msdn.microsoft.com/en-us/library/ms684146.aspx) 2. [MSDTC Troubleshooting](http://msdn.microsoft.com/en-us/library/aa561924.aspx) 3. [MSDTC and Firewall Issues](http://support.microsoft.com/kb/306843)
Start MSDTC Service. On the command prompt: ``` net start msdtc ``` Or from Services MMC. Find "Distributed Transaction Coordinator" and click start.
Transactionscope not working when two remote sql connections
[ "", "c#", "ado.net", "transactions", "mstdc", "" ]
I am looking into using a producer\consumer threading pattern to run through a list of strings that i retrieve from a database and then am going to run powershell commands against. As the powershell commands can be quite intensive i only want to spawn 3 threads at a time and then wait for one thread to finish before doing anymore. I looked into the treadpool but it looks like it is used for more lightweight processing. I am new to threading and have seen a few producer\consumer examples on the internet but am not sure how to handle the 3 thread loop situation using waithandles (if thats the way to do it). I think i have to use the waithandle.waitany to achieve the above but am not sure how to implement this. If someone could point me in the right direction i would be most appreciative Thanks
Use a queue where you add the work items. Then spawn as many threads as you want to run concurrently, and have them run a loop, trying to get items from the work item queue (make sure that this is happening in a properly synchronized fashion). If the queue is filled before you start processing, you can use the empty queue as condition to end the loop in the thread. In this case you can wait for all threads to stop so you know when all items have finished processing.
If you could use .NET 4.0, you could investigate using the `Task` class and a `TaskScheduler` instance with a limited `MaximumConcurrencyLevel` set.
Custom multithreading loop
[ "", "c#", "vb.net", "multithreading", "" ]
I don't really want to call the Zend filter in my code after every getRequest->getParam('x') if I don't have to. Is there a lazy way of filtering everything inside getRequest magically? **Edit:** *When I say filter, I mean, escapting tags, cleaning out the XSS, and escaping any sql escape characters.* i.e: ``` $myVar = $this->getRequest()->getParam('x'); filter the variable, escape sql stuf... etc ``` What's the standard? How are you doing it?
There are a few ways to deal with your situation. First of all, you can get all params at once: ``` $params = $this->_request->getParams(); //_request is equivalent to getRequest() ``` So a lazy way to filter all your params would be to use the \*\*\*\*\* when declaring your filters, which means all fields, and would look something like: ``` $filters = array('*' => array('StringTrim','HtmlEntities','StripTags')); $input = new Zend_Filter_Input($filters,$validators,$params); if($input->isValid()) { //blah blah blah } ``` You should read more about the [request](http://framework.zend.com/manual/en/zend.controller.request.html) object, as well as [filters](http://framework.zend.com/manual/en/zend.filter.html), [input filters](http://framework.zend.com/manual/en/zend.filter.input.html) and [validators](http://framework.zend.com/manual/en/zend.validate.html).
The only way is to do it every way. * use `Zend_Filter_Input` (as noted above by karim79) to filter things to how they should be stored or looked up by (stripping tags with `StripTags`, casting to `Int`, `StringTrim`, etc), validating where validation needed - but not htmlentities since that should probably be done on output to avoid complications in db search, etc. Fields should be individually flitered/validated in most cases. * use parameterized queries (`Zend_Db_Select` with ? placeholders) always, or at least use the db escape functions * escape all output (`Zend_View_Helper_Escape` -> `$this->escape()`) as necessary.
Is there a way to auto filter the getRequest() params in Zend?
[ "", "php", "zend-framework", "" ]
Currently if I supply no extensions to the class it allows no extensions. I would like to allow all extensions. Is there any way to do this without hacking the core?
In Codeigniter 2, you simply need to define allowed types like this : ``` $config['allowed_types'] = '*'; ```
The answer to your direct question: No, there's no way to do this without overriding the core To good news is you can avoid hacking the core, [per the manual](http://codeigniter.com/user_guide/general/creating_libraries.html) > As an added bonus, CodeIgniter permits your libraries to extend > native classes if you simply need to add some functionality to > an existing library. Or you can even replace native libraries just > by placing identically named versions in your application/libraries folder. So, to have a drop in replacement for your library, you could copy Upload.php to your ``` application/libraries ``` folder, and then add your custom logic to that Upload.php file. Code Igniter will include this file instead whenever you load the upload library. Alternately, you could create your OWN custom uploader class that extends the original, and only refines the is\_allowed\_filetype function. ``` application/libraries/MY_Upload.php class MY_Upload Extends CI_Upload{ function is_allowed_filetype(){ //my custom code here } } ``` You'll want to read over [the changelog](http://codeigniter.com/user_guide/changelog.html) whenever you're upgrading, but this will allow you to keep your code and the core code in separate universes.
How to make CodeIgniter file upload class accept all extensions?
[ "", "php", "codeigniter", "" ]
I am developing a survey invitation that can be embedded in many sites. To present the invitation I am using [Modalbox](http://www.wildbit.com/labs/modalbox/), a javascript library that shows an animated modal box over a semi-transparent overlay. This Modalbox library depends on Prototype and script.aculo.us/effects libraries. The invitation will be dynamically embedded in sites that I don't own and can't statically modify their markup. At the load time I check (in JS) if Prototype is loaded like: ``` if (typeof Prototype == "undefined") { document.write('<script type="text/javascript" src="http://mysite.com/lib/prototype.js"><\/script>'); } if (typeof Effect == "undefined") { document.write('<script type="text/javascript" src="http://mysite.com/lib/scriptaculous.js?load=effects"><\/script>'); } ``` All works well with the majority of sites since they usually don't load Prototype.js nor script.aculo.us. There are some site which load them and I don't have to load them and again it works. HOWEVER... there are sites that already loads them but have OLDER versions (Modalbox requires Prototype 1.6.0 and script.aculo.us 1.8.0) such as 1.4.0 / 1.5.1 **How can I dynamically unload/replace prototype and/or script.aculo.us in Javascript? Is it possible?**
You may be able to do this technically, but are you willing to risk breaking the rest of the page just so that your plugin works? There could be good reasons why these sites haven't upgraded -- such as compatibility with other plugins that don't work with newer versions. I'd suggest that you either require the sites that use your code to have the minimum version of Prototype (by examining Prototype.Version) or including it, as you are, when it is not found. Do the same with Scriptaculous. This will allow the user of your code to make decisions on how best to proceed. Either they can upgrade their page (most likely, since the older version is probably being used due to inertia) or drop your plugin.
In response to tvanfosson, if you can figure out how to dynamically update the to the required prototype, then you should also be able to utilize something like the [WTFFramework](http://blog.olicio.us/2008/11/08/wtframework-bookmarklet/) to determine the original version. Then before you show the popup, load your prototype, and when you popup is closed reload the original prototype.
Dynamically upgrade/replace prototype library
[ "", "javascript", "prototypejs", "upgrade", "scriptaculous", "" ]
I want to declare a nested enum like: ``` \\pseudocode public enum Animal { dog = 0, cat = 1 } private enum dog { bulldog = 0, greyhound = 1, husky = 3 } private enum cat { persian = 0, siamese = 1, burmese = 2 } Animal patient1 = Animal.dog.husky; ``` Can it be done?
I was looking for something similar as a way to create lightweight, hierarchical channel ID's for a logging system. I'm not quite sure this was worth the effort, but I had fun putting it together, and I learned something new about operator overloading and lizards in the process. I've built a mechanism that supports this notation: ``` public static class Animal { public static readonly ID dog = 1; public static class dogs { public static readonly ID bulldog = dog[0]; public static readonly ID greyhound = dog[1]; public static readonly ID husky = dog[3]; } public static readonly ID cat = 2; public static class cats { public static readonly ID persian = cat[0]; public static readonly ID siamese = cat[1]; public static readonly ID burmese = cat[2]; } public static readonly ID reptile = 3; public static class reptiles { public static readonly ID snake = reptile[0]; public static class snakes { public static readonly ID adder = snake[0]; public static readonly ID boa = snake[1]; public static readonly ID cobra = snake[2]; } public static readonly ID lizard = reptile[1]; public static class lizards { public static readonly ID gecko = lizard[0]; public static readonly ID komodo = lizard[1]; public static readonly ID iguana = lizard[2]; public static readonly ID chameleon = lizard[3]; } } } ``` And which you can use like so: ``` void Animalize() { ID rover = Animal.dogs.bulldog; ID rhoda = Animal.dogs.greyhound; ID rafter = Animal.dogs.greyhound; ID felix = Animal.cats.persian; ID zorro = Animal.cats.burmese; ID rango = Animal.reptiles.lizards.chameleon; if (rover.isa(Animal.dog)) Console.WriteLine("rover is a dog"); else Console.WriteLine("rover is not a dog?!"); if (rover == rhoda) Console.WriteLine("rover and rhoda are the same"); if (rover.super == rhoda.super) Console.WriteLine("rover and rhoda are related"); if (rhoda == rafter) Console.WriteLine("rhoda and rafter are the same"); if (felix.isa(zorro)) Console.WriteLine("er, wut?"); if (rango.isa(Animal.reptile)) Console.WriteLine("rango is a reptile"); Console.WriteLine("rango is an {0}", rango.ToString<Animal>()); } ``` That code compiles and produces the following output: ``` rover is a dog rover and rhoda are related rhoda and rafter are the same rango is a reptile rango is an Animal.reptiles.lizards.chameleon ``` Here's the ID struct that makes it work: ``` public struct ID { public static ID none; public ID this[int childID] { get { return new ID((mID << 8) | (uint)childID); } } public ID super { get { return new ID(mID >> 8); } } public bool isa(ID super) { return (this != none) && ((this.super == super) || this.super.isa(super)); } public static implicit operator ID(int id) { if (id == 0) { throw new System.InvalidCastException("top level id cannot be 0"); } return new ID((uint)id); } public static bool operator ==(ID a, ID b) { return a.mID == b.mID; } public static bool operator !=(ID a, ID b) { return a.mID != b.mID; } public override bool Equals(object obj) { if (obj is ID) return ((ID)obj).mID == mID; else return false; } public override int GetHashCode() { return (int)mID; } private ID(uint id) { mID = id; } private readonly uint mID; } ``` This makes use of: * a 32-bit uint as the underlying type * multiple small numbers stuffed into an integer with bit shifts (you get maximum four levels of nested ID's with 256 entries at each level -- you could convert to ulong for more levels or more bits per level) * ID 0 as the special root of all ID's (possibly ID.none should be called ID.root, and any id.isa(ID.root) should be true) * [implicit type conversion](http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx) to convert an int into an ID * an [indexer](http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx) to chain ID's together * [overloaded equality operators](http://msdn.microsoft.com/en-us/library/53k8ybth.aspx) to support comparisons Up to now everything's pretty efficient, but I had to resort to reflection and recursion for ToString, so I cordoned it off in an [extension method](http://msdn.microsoft.com/en-ca/library/bb383977.aspx), as follows: ``` using System; using System.Reflection; public static class IDExtensions { public static string ToString<T>(this ID id) { return ToString(id, typeof(T)); } public static string ToString(this ID id, Type type) { foreach (var field in type.GetFields(BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static)) { if ((field.FieldType == typeof(ID)) && id.Equals(field.GetValue(null))) { return string.Format("{0}.{1}", type.ToString().Replace('+', '.'), field.Name); } } foreach (var nestedType in type.GetNestedTypes()) { string asNestedType = ToString(id, nestedType); if (asNestedType != null) { return asNestedType; } } return null; } } ``` Note that for this to work Animal could no longer be a static class, because [static classes can't be used as type parameters](https://stackoverflow.com/questions/5858591/c-sharp-static-types-cannot-be-used-as-type-arguments), so I made it sealed with a private constructor instead: ``` public /*static*/ sealed class Animal { // Or else: error CS0718: 'Animal': static types cannot be used as type arguments private Animal() { } .... ``` Phew! Thanks for reading. :-)
I would probably use a combination of enumerated bit fields and extension methods to achieve this. For example: ``` public enum Animal { None = 0x00000000, AnimalTypeMask = 0xFFFF0000, Dog = 0x00010000, Cat = 0x00020000, Alsation = Dog | 0x00000001, Greyhound = Dog | 0x00000002, Siamese = Cat | 0x00000001 } public static class AnimalExtensions { public bool IsAKindOf(this Animal animal, Animal type) { return (((int)animal) & AnimalTypeMask) == (int)type); } } ``` **Update** In .NET 4, you can use the `Enum.HasFlag` method rather than roll your own extension.
How do I declare a nested enum?
[ "", "c#", "enums", "" ]
**I am seeing the weirdest bug with the following code.** I have a `PathGeometry` to which I added a `PathFigure` so that I can add `LineSegment`s to it. **This is what I do:** ``` _pathGeometry.Figures.Add(_pathFigure); _pathFigure.StartPoint = new Point(4, 0); LineSegment lineSegment1 = new LineSegment(new Point(4, -10), true); LineSegment lineSegment2 = new LineSegment(new Point(4, 0), true); _pathFigure.Segments.Add(lineSegment1); _pathFigure.Segments.Add(lineSegment2); ``` **I then draw it:** ``` using (DrawingContext drawingContext = RenderOpen()) drawingContext.DrawGeometry(null, _pen, _pathGeometry); ``` **What I should see:** WPF should draw a vertical line that goes from 0 to -10 and back to 0. The last part (back to 0) cannot be seen because it's drawn on the same x pixel. But the last part causes the following: **What I see:** WPF draws a line that goes from 0 to -15. It makes no sense to me. This 5 pixel difference happens whenever I draw a vertical line on top of another vertical line as in the previous example. **Please someone tell me I made a mistake and this is not a WPF bug.**
I think the issue has to do with how WPF renders "corners" in your Path. As the angle between two line segments becomes more acute, the corner rendering becomes more apparent. In your case, you have a zero degree angle (a line segment folding back on itself), which is the most problematic case. Not all is lost -- there several possible solutions: * Split the PathFigure into two PathFigures (which is your workaround). By doing this, you remove the corner, and thus the issue. * Set the Path's StrokeLineJoin property to Bevel instead of the Miter (the default). This will bevel corner appearance. * Lower the Path's StrokeMiterLimit. This will make the corner less "pointy", as the scientists say. * Tell the LineSegment to explicitly remove it's "corner-ness". You can do this by setting the IsSmoothJoin property to true. For more information regarding StrokeLineJoin, see [here](http://msdn.microsoft.com/en-us/library/system.windows.shapes.shape.strokelinejoin.aspx). For an interesting post about how WPF renders Mitered corners, see [here](http://blogs.msdn.com/mswanson/archive/2006/03/23/559698.aspx).
If it is anything like `GraphicsPath`, you will need to set the end point too.
WPF bug or am I going crazy?
[ "", "c#", ".net", "wpf", "drawing", "line", "" ]
Can you please help me to understand where is the problem? ``` SELECT mz_t_NaznExec.p_Services FROM mz_t_NaznExec ``` Above script returns recordset where record with p\_Services = 200000000000115 not exists ``` SELECT mz_t_Services.p_ID from mz_t_Services ``` Above script returns recordset where record with id = 200000000000115 exists But this query returns no record ``` SELECT mz_t_Services.p_ID from mz_t_Services where mz_t_Services.p_ID not in(SELECT mz_t_NaznExec.p_Services FROM mz_t_NaznExec) ``` I am using MSSQL EDIT: Both p\_ID and p\_Services data types ara bigint
Are there any NULLs in mz\_t\_NaznExec.p\_Services? "NOT IN" will always fail if there is even one NULL in the resultset.
``` SELECT mz_t_Services.p_ID from mz_t_Services where mz_t_Services.p_ID not in(SELECT ISNULL(mz_t_NaznExec.p_Services,0) FROM mz_t_NaznExec) ``` or better ``` SELECT mz_t_Services.p_ID from mz_t_Services where mz_t_Services.p_ID not in(SELECT mz_t_NaznExec.p_Services FROM mz_t_NaznExec WHERE mz_t_NaznExec.p_Services is not null) ```
Problem with using IN in sql
[ "", "sql", "t-sql", "" ]
I am creating a Javascript object that contains a function that executes a jQuery `each` method like the following: ``` function MyClass { Method1 = function(obj) { // Does something here } Method2 = function() { $(".SomeClass").each(function() { // 1 2 this.Method1(this); }); } } ``` Which object is each `THIS` referring to? jQuery is referring to the item returned from the `each` iteration. However, I would like `This[1]` to refer to the containing class... How can I refer to the containing class from within the jQuery loop?
I guess you could do something like this: ``` function MyClass { Method1 = function(obj) { //do something here } Method2 = function () { var containingClass = this; $(".SomeClass").each(function () { containingClass.Method1(this); }); } } } ```
From <http://docs.jquery.com/Core/each>: > This means that every time the > passed-in function is executed (which > is once for every element matched) the > 'this' keyword points to the specific > DOM element. Note that 'this' does not > point to a jQuery object. Personally, I prefer using explicit parameters. This way, it is more easily readable: ``` $('#rotfl').each(function(index, domObject) { var jQueryObject = $(domObject); // code }); ``` To answer your question: JavaScript has dynamic static scope. You can do the following: ``` var that = this; $('#rotfl').each(function(index, domObject) { var jQueryObject = $(domObject); that.DoSomething(); // code }); ```
Jquery $().each method obscures 'this' keyword
[ "", "javascript", "jquery", "" ]
I'm presently refactoring a `JTable` which displays a multitude of different types of data. The primary reason for this refactoring is that there a few `ClassCastExceptions` (the author/friend who wrote the code is off on hiatus), and I can't seem to find where these are originating from. Due to the large codebase, I'm at a loss as to where to start. Does anyone have any suggestions? I realize and apologize for the ambiguity of this question! I've included the stack trace below. Thanks!! ``` Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean at javax.swing.JTable$BooleanRenderer.getTableCellRendererComponent(Unknown Source) at javax.swing.JTable.prepareRenderer(Unknown Source) at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source) at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source) at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source) at javax.swing.plaf.ComponentUI.update(Unknown Source) at javax.swing.JComponent.paintComponent(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JComponent.paintToOffscreen(Unknown Source) at javax.swing.BufferStrategyPaintManager.paint(Unknown Source) at javax.swing.RepaintManager.paint(Unknown Source) at javax.swing.JComponent._paintImmediately(Unknown Source) at javax.swing.JComponent.paintImmediately(Unknown Source) at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source) at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source) at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source) at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) ```
This error which is occurring in `BooleanRenderer` is because it is expecting that the value that is from the table's model is of type `Boolean` and tries to cast to it (akf's answer has the exact line of code where it occurs). My guess is that initially it was expected that the model would return `Boolean` values for the given column but at one point it is returning strings instead. Therefore, I would concentrate on what model is being used for this given table (is it a custom model? Is it the default model where it is adding values to it?) and see where it may be getting a String instead of a `Boolean`.
Probably the table contains a checkbox (when the column model states that the column contains type Boolean) and the renderer tries to convert the contents into a boolean. But probably the contents are just strings. The solution is to change the data in the table or to create your own renderer.
Unknown source of ClassCastException (in JTables)
[ "", "java", "swing", "jtable", "classcastexception", "" ]
Are there any standard protocols with witch you could make games with (like http, ftp), as i had problems when I tested a connection on a random port (1024-65300) out (I had to forward ports on my router and it only works with one computer at a time). There should be, im programs use something and there is no need to set up any ports... Do you have any idea what I could use? i use c++ p.s. I would be interested in something similar to http, someone sends a request and the other sends response. I saw in html you have to send to ip/index.html or something like that which I don't really understand how to use...
IM Programs don't require any open ports because they are client programs. As a general rule (watch out for outbound firewalls) all ports are open for outgoing connections on a client. In order to actually *accept* connections, the port has to allow incoming traffic. Most servers, for example, can accept incoming traffic on all ports. Network communications and protocols are designed with this in mind: the client (your browser) always initiates the connection to the server (the website), not the other way around. As for a protocol, you should use either TCP/IP or UDP, depending on what you need to do. UDP is great if you plan to have your client for the game account for missing information by using approximation (most FPS games do this, as well as just about any game that requires very quick reflexes) where TCP/IP is simpler, will greatly reduce errors in transmission, and be more prone to lag. The main difference between the two is that UDP is "fire and forget," meaning that it doesn't bother to check to see if the message actually arrived at its destination. As for the protocol on top of that, you mentioned http and ftp. I would greatly advice using neither. When you're using direct socket communication on a custom port, you have all the freedom of crafting your own protocol for the game to use. So long as it gets its job done by sending packets back and forth, everything else about it is completely up to you, and should be. After all, a game protocol needs to be *fast*, you don't want all this extra header garbage from http clogging up your network transmissions unless you really need it. Just remember: network connections require two parts, a client and a server. This means that you either have a central server set up for the game, or you have one player "host" the game (acting as a server, he will need his ports open). The other players (all players, in a central server setup) connect to the central guy, and pass communication through him. This means that your game protocol needs two parts, a server end and a client end. The client in most games sort of runs blind, in that it sends off player information about the user, and then relies on server updates to tell it where everything else in the game is. The server should be in charge of collecting player information from all clients, and then distributing that information to everyone else. This can include validation (most do) to prevent "illegal" things from happening within the game, but that's up to you.
The problem is a little more complex than just using a specific port or protocol to get through a NAT. You can get [more information here.](https://www.rfc-editor.org/rfc/rfc5128.txt)
Gaming protocol
[ "", "c++", "networking", "" ]
I am getting following exception while parsing the xml. ``` Fatal error at line -1 Invalid character '&#x0' encountered. No stack trace ``` I have Xml data in string format and I am parsing it using DOM parser. I am parsing data which is a response from Java server to a Blackberry client. I also tried parsing with SAX parser,but problem is not resolved. Please help.
I got the solution, I just trimmed it with trim() and it worked perfectly fine with me.
You have a null character in your character stream, i.e. char(0) which is not valid in an XML-document. If this is not present in the original string, then it is most likely a character decoding issue.
Invalid character '&#x0' encountered
[ "", "java", "xml", "blackberry", "java-me", "" ]
By looking at the source code for LinkedHashMaps from Sun, I see that there is a private class called KeyIterator, I would like to use this. How can I gain access?
You get it by calling ``` myMap.keySet().iterator(); ``` You shouldn't even need to know it exists; it's just an artifact of the implementation. For all you know, they could be using flying monkeys to iterate the keys; as long as they're iterated according to the spec, it doesn't matter how they do it. By the way, did you know that `HashMap` has a private class called `KeyIterator` (as do `ConcurrentHashMap`, `ConcurrentSkipListMap`, `EnumMap`, `IdentityHashMap`, `TreeMap`, and `WeakHashMap`)? Does that make a difference in how you iterate through the keys of a `HashMap`? --- **Edit:** In reponse to your comment, be aware that if you are trying to iterate over all *key-value pairs* in a `Map`, there is a better way than iterating over the keys and calling `get` for each. The [`entrySet()`](http://java.sun.com/javase/6/docs/api/java/util/Map.html#entrySet()) method gets a `Set` of all key-value pairs which you can then iterate over. So instead of writing: ``` for (Key key : myMap.keySet()) { Value val = myMap.get(key); ... } ``` you should write: ``` for (Map.Entry<Key, Value> entry : myMap.entrySet()) { doSomethingWithKey(entry.getKey()); doSomethingWithValue(entry.getValue()); ... } ``` You could also iterate over the values with [`values()`](http://java.sun.com/javase/6/docs/api/java/util/Map.html#values()) if you want. Note that since `keySet`, `entrySet`, and `values` are defined in the [`Map` interface](http://java.sun.com/javase/6/docs/api/java/util/Map.html), they will work for any `Map`, not just `LinkedHashMap`.
It's a private class, so you can't directly use it. ``` private class KeyIterator extends LinkedHashIterator<K> { ``` An instance of it is returned when you use the normal Iterator. ``` myMap.keySet().iterator() ```
How do I get a keyIterator for a LinkedHashMap?
[ "", "java", "iterator", "linkedhashmap", "" ]
I was searching Google for a page offering some simple OpenMp algorithms. Probably there is an example to calculate min, max, median, average from a huge data array but I am not capable to find it. At least I would normally try to divide the array into one chunk for each core and do some boundary calculation afterwards to get the result for the complete array. I just didn't want to reinvent the wheel. --- Additional Remark: I know that there are thousands of examples that work with simple reduction. e.g. Calculating PI. ``` const int num_steps = 100000; double x, sum = 0.0; const double step = 1.0/double(num_steps); #pragma omp parallel for reduction(+:sum) private(x) for (int i=1;i<= num_steps; i++){ x = double(i-0.5)*step; sum += 4.0/(1.0+x*x); } const double pi = step * sum; ``` but when these kind of algorithms aren't usable there are almost no examples left for reducing algorithms.
OpenMP (at least 2.0) supports reduction for some simple operations, but not for max and min. In the following example the `reduction` clause is used to make a sum and a `critical` section is used to update a shared variable using a thread-local one without conflicts. ``` #include <iostream> #include <cmath> int main() { double sum = 0; uint64_t ii; uint64_t maxii = 0; uint64_t maxii_shared = 0; #pragma omp parallel shared(maxii_shared) private(ii) firstprivate(maxii) { #pragma omp for reduction(+:sum) nowait for(ii=0; ii<10000000000; ++ii) { sum += std::pow((double)ii, 2.0); if(ii > maxii) maxii = ii; } #pragma omp critical { if(maxii > maxii_shared) maxii_shared = maxii; } } std::cerr << "Sum: " << sum << " (" << maxii_shared << ")" << std::endl; } ``` EDIT: a cleaner implementation: ``` #include <cmath> #include <limits> #include <vector> #include <iostream> #include <algorithm> #include <tr1/random> // sum the elements of v double sum(const std::vector<double>& v) { double sum = 0.0; #pragma omp parallel for reduction(+:sum) for(size_t ii=0; ii< v.size(); ++ii) { sum += v[ii]; } return sum; } // extract the minimum of v double min(const std::vector<double>& v) { double shared_min; #pragma omp parallel { double min = std::numeric_limits<double>::max(); #pragma omp for nowait for(size_t ii=0; ii<v.size(); ++ii) { min = std::min(v[ii], min); } #pragma omp critical { shared_min = std::min(shared_min, min); } } return shared_min; } // generate a random vector and use sum and min functions. int main() { using namespace std; using namespace std::tr1; std::tr1::mt19937 engine(time(0)); std::tr1::uniform_real<> unigen(-1000.0,1000.0); std::tr1::variate_generator<std::tr1::mt19937, std::tr1::uniform_real<> >gen(engine, unigen); std::vector<double> random(1000000); std::generate(random.begin(), random.end(), gen); cout << "Sum: " << sum(random) << " Mean:" << sum(random)/random.size() << " Min:" << min(random) << endl; } ```
in OpenMP 3.1 onwards one can implement for min, max through reduction clause, you can have a look at detailed example covering this in [this link](http://www.techdarting.com/2013/06/openmp-min-max-reduction-code.html).
OpenMp C++ algorithms for min, max, median, average
[ "", "c++", "algorithm", "multithreading", "openmp", "" ]
The UI for an application I work on was recently redone with Ext.js and I have noticed the memory usage of IE seems very large when viewing it. Are there known memory issues with Ext.js when using IE?
The first thing that jumps out at me in your question is that you are seeing this in IE. My team recently went through the same issue (Extjs on IE). It turns out Ext is not the culprit but rather IE is likely the cause. A quick Google for 'IE closure memory leak' will find you plenty of explanations, but the basic gist is as follows: IE uses two separate engines to manage the DOM and JavaScript. When JavaScript makes a call to create a DOM element, the Javascript engine reaches across to the other to create it. If you attach JavaScript to an event on a DOM element, a link is created back from the DOM side to JavaScript side. The problem lies in the fact that each engine has its own garbage collection and can't see across to the other engine. So circular references are REALLY easy to come across that can eat of large quantities of memory very quickly.
I think that it's quite easy to create memory leaks when programming with ExtJS for non-experienced programmers. This is not ExtJS problem on itself. It's ExtJS programming paradigm which lets programmers to easily make such mistakes. From my experience I've created memory leak when tried to make a straighforward AJAX chat using ExtJS. When some objects are constantly created within AJAX callbacks (such as datastores, grid manipulations), then these objects are not released and destroyed. There must be special and very clever techniques used to avoid memory leaks with ExtJS, and it's not only related to AJAX or callbacks. All in all, ExtJS is great library, but it must be used carefully.
Are There Memory Issues with Ext.js
[ "", "javascript", "memory-leaks", "extjs", "" ]
Is there a good way to enumerate through only a subset of a Collection in C#? That is, I have a collection of a large number of objects (say, 1000), but I'd like to enumerate through only elements 250 - 340. Is there a good way to get an Enumerator for a subset of the collection, without using another Collection? Edit: should have mentioned that this is using .NET Framework 2.0.
Try the following ``` var col = GetTheCollection(); var subset = col.Skip(250).Take(90); ``` Or more generally ``` public static IEnumerable<T> GetRange(this IEnumerable<T> source, int start, int end) { // Error checking removed return source.Skip(start).Take(end - start); } ``` **EDIT** 2.0 Solution ``` public static IEnumerable<T> GetRange<T>(IEnumerable<T> source, int start, int end ) { using ( var e = source.GetEnumerator() ){ var i = 0; while ( i < start && e.MoveNext() ) { i++; } while ( i < end && e.MoveNext() ) { yield return e.Current; i++; } } } IEnumerable<Foo> col = GetTheCollection(); IEnumerable<Foo> range = GetRange(col, 250, 340); ```
I like to keep it simple (if you don't necessarily need the enumerator): ``` for (int i = 249; i < Math.Min(340, list.Count); i++) { // do something with list[i] } ```
Enumerate through a subset of a Collection in C#?
[ "", "c#", "collections", ".net-2.0", "enumeration", "subset", "" ]
I have found when using NHibernate and creating a one to many relationship on an object that when the many grows very large it can slow down dramatically. Now I do have methods in my repository for collecting a paged IList of that type, however I would prefer to have these methods on the model as well because that is often where other developers will look first to gather the list of child objects. e.g. RecipientList.Recipients will return every recipient in the list. I would like to implement a way to add paging on all of my oen to many relationships in my models using preferably an interface but really anything that won't force a typed relationship onto the model. For example it would be nice to have the following interface: ``` public interface IPagedList<T> : IList<T> { int Count { get; } IList<T> GetPagedList(int pageNo, int pageSize); IList<T> GetAll(); } ``` Then being able to use it in code... ``` IList<Recipient> recipients = RecipientList.Recipients.GetPagedList(1, 400); ``` I have been trying to think of ways to do this without giving the model any awareness of the paging but I'm hitting my head against a brick wall at the moment. Is there anyway I can implement the interface in a similar way that NHibernate does for IList and lazyloading currently? I don't have enough knowledge of NHibernate to know. Is implementing this even a good idea? Your thoughts would be appreciated as being the only .NET developer in house I have no-one to bounce ideas off. *UPDATE* The post below has pointed me to the custom-collection attribute of NHibernate, which would work nicely. However I am unsure what the best way is to go around this, I have tried to inherit from PersistentGenericBag so that it has the same basic functionality of IList without much work, however I am unsure how to gather a list of objects based on the ISessionImplementor. I need to know how to either: * Get some sort of ICriteria detail for the current IList that I am to be populating * Get the mapping details for the particular property associated with the IList so I can create my own ICriteria. However I am unsure if I can do either of the above? Thanks
Ok I'm going to post this as an answer because it is doing mostly what I wanted. However I would like some feedback and also possibly the answer to my one caveat of the solution so far: I've created an interface called IPagedList. ``` public interface IPagedList<T> : IList<T>, ICollection { IList<T> GetPagedList(int pageNo, int pageSize); } ``` Then created a base class which it inherits from IPagedList: ``` public class PagedList<T> : IPagedList<T> { private List<T> _collection = new List<T>(); public IList<T> GetPagedList(int pageNo, int pageSize) { return _collection.Take(pageSize).Skip((pageNo - 1) * pageSize).ToList(); } public int IndexOf(T item) { return _collection.IndexOf(item); } public void Insert(int index, T item) { _collection.Insert(index, item); } public void RemoveAt(int index) { _collection.RemoveAt(index); } public T this[int index] { get { return _collection[index]; } set { _collection[index] = value; } } public void Add(T item) { _collection.Add(item); } public void Clear() { _collection.Clear(); } public bool Contains(T item) { return _collection.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { _collection.CopyTo(array, arrayIndex); } int Count { get { return _collection.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(T item) { return _collection.Remove(item); } public IEnumerator<T> GetEnumerator() { return _collection.GetEnumerator(); } int ICollection<T>.Count { get { return _collection.Count; } } IEnumerator IEnumerable.GetEnumerator() { return _collection.GetEnumerator(); } public void CopyTo(Array array, int index) { T[] arr = new T[array.Length]; for (int i = 0; i < array.Length ; i++) { arr[i] = (T)array.GetValue(i); } _collection.CopyTo(arr, index); } int ICollection.Count { get { return _collection.Count; } } // The IsSynchronized Boolean property returns True if the // collection is designed to be thread safe; otherwise, it returns False. public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return this; } } } ``` I then create an IUserCollectionType for NHibernate to use as the custom collection type and NHPagedList which inherits from PersistentGenericBag, IPagedList as the actual collection itself. I created two seperate classes for them because it seemed like the use of IUserCollectionType had no impact on the actual collection to be used at all, so I kept the two pieces of logic seperate. Code below for both of the above: ``` public class PagedListFactory<T> : IUserCollectionType { public PagedListFactory() { } #region IUserCollectionType Members public bool Contains(object collection, object entity) { return ((IList<T>)collection).Contains((T)entity); } public IEnumerable GetElements(object collection) { return (IEnumerable)collection; } public object IndexOf(object collection, object entity) { return ((IList<T>)collection).IndexOf((T)entity); } public object Instantiate(int anticipatedSize) { return new PagedList<T>(); } public IPersistentCollection Instantiate(ISessionImplementor session, ICollectionPersister persister) { return new NHPagedList<T>(session); } public object ReplaceElements(object original, object target, ICollectionPersister persister, object owner, IDictionary copyCache, ISessionImplementor session) { IList<T> result = (IList<T>)target; result.Clear(); foreach (object item in ((IEnumerable)original)) { result.Add((T)item); } return result; } public IPersistentCollection Wrap(ISessionImplementor session, object collection) { return new NHPagedList<T>(session, (IList<T>)collection); } #endregion } ``` NHPagedList next: ``` public class NHPagedList<T> : PersistentGenericBag<T>, IPagedList<T> { public NHPagedList(ISessionImplementor session) : base(session) { _sessionImplementor = session; } public NHPagedList(ISessionImplementor session, IList<T> collection) : base(session, collection) { _sessionImplementor = session; } private ICollectionPersister _collectionPersister = null; public NHPagedList<T> CollectionPersister(ICollectionPersister collectionPersister) { _collectionPersister = collectionPersister; return this; } protected ISessionImplementor _sessionImplementor = null; public virtual IList<T> GetPagedList(int pageNo, int pageSize) { if (!this.WasInitialized) { IQuery pagedList = _sessionImplementor .GetSession() .CreateFilter(this, "") .SetMaxResults(pageSize) .SetFirstResult((pageNo - 1) * pageSize); return pagedList.List<T>(); } return this .Skip((pageNo - 1) * pageSize) .Take(pageSize) .ToList<T>(); } public new int Count { get { if (!this.WasInitialized) { return Convert.ToInt32(_sessionImplementor.GetSession().CreateFilter(this, "select count(*)").List()[0].ToString()); } return base.Count; } } } ``` You will notice that it will check to see if the collection has been initialized or not so that we know when to check the database for a paged list or when to just use the current in memory objects. Now you're ready to go, simply change your current IList references on your models to be IPagedList and then map NHibernate to the new custom collection, using fluent NHibernate is the below, and you are ready to go. ``` .CollectionType<PagedListFactory<Recipient>>() ``` This is the first itteration of this code so it will need some refactoring and modifications to get it perfect. My only problem at the moment is that it won't get the paged items in the order that the mapping file suggests for the parent to child relationship. I have added an order-by attribute to the map and it just won't pay attention to it. Where as any other where clauses are in each query no problem. Does anyone have any idea why this might be happening and if there is anyway around it? I will be disappointed if I can't work away around this.
You should look into one of the LINQ providers for NHibernate. What your looking for is a way to delay-load the results for your query. The greatest power of LINQ is that it does exactly that...delay-loads the results of your queries. When you actually build a query, in reality its creating an expression tree that represents what you want to do, so that it can actually be done at a later date. By using a LINQ provider for NHibernate, you would then be able to do something like the following: ``` public abstract class Repository<T> where T: class { public abstract T GetByID(int id); public abstract IQueryable<T> GetAll(); public abstract T Insert(T entity); public abstract void Update(T entity); public abstract void Delete(T entity); } public class RecipientRepository: Repository<Recipient>; { // ... public override IQueryable<Recipient> GetAll() { using (ISession session = /* get session */) { // Gets a query that will return all Recipient entities if iterated IQueryable<Recipient> query = session.Linq<Recipient>(); return query; } } // ... } public class RecipientList { public IQueryable<Recipient> Recipients { RecipientRepository repository = new RecipientRepository(); return repository.GetAll(); // Returns a query, does not evaluate, so does not hit database } } // Consuming RecipientList in some higher level service, you can now do: public class RecipientService { public IList<Recipient> GetPagedList(int page, int size) { RecipientList list = // get instance of RecipientList IQueryable<Recipient> query = list.Recipients.Skip(page*size).Take(size); // Get your page IList<Recipient> listOfRecipients = query.ToList(); // <-- Evaluation happens here! reutrn listOfRecipients; } } ``` With the above code (its not a great example, but it does demonstrate the general idea), you build up an expression representing what you want to do. Evaluation of that expression happens only once...and when evaluation happens, your database is queried with a specific query that will only return the specific subset of rows you actually requested. No need to load up all the records, then filter them down later on to the single page you requested...no waste. If an exception occurs before you evaluate, for whatever reason, you never even hit the database, increasing efficiency even more. This power can go much farther than querying a single page of results. The extension methods .Skip() and .Take() are available on all IQueryable<T> and IEnumerable<T> objects, along with a whole bunch of others. In addition, you have .Where(), .Except(), .Join(), and many, many more. This gives you the power to, say, .GetAll(), then filter the possible results of that query with one or more calls to .Where(), finishing with a .Skip(...).Take(...), ending in a single evaluation at your .ToList() (or .ToArray()) call. This would require that you change your domain somewhat, and start passing IQueryable<T> or IEnumerable<T> around in place of IList<T>, and only convert to an IList<T> at your higher-level, 'publicly facing' services.
Implementing IPagedList<T> on my models using NHibernate
[ "", "c#", "asp.net", "nhibernate", "interface", "asp.net-3.5", "" ]
Why does this not compile on VC 2005? ``` bool isTrue(bool, bool) { return true; } void foo(); #define DO_IF(condition, ...) if (condition) foo(__VA_ARGS__); void run() { DO_IF(isTrue(true, true)); // error C2143: syntax error : missing ')' before 'constant' } ``` Running this through the preprocessor alone outputs: ``` bool isTrue(bool, bool) { return true; } void foo(); void run() { if (isTrue(true true)) foo();; } ``` Notice the missing comma in the penultimate line. **Last Edit:** LOL! ``` bool isTrue(bool, bool) { return true; } void foo(); #define DO_IF(condition, ...) if (condition) { foo(__VA_ARGS__); } void run() { DO_IF(isTrue(true ,, true)); // ROTFL - This Compiles :) } ```
Macros with indefinite numbers of arguments don't exist in the 1990 C standard or the current C++ standard. I think they were introduced in the 1999 C standard, and implementations were rather slow to adopt the changes from that standard. They will be in the forthcoming C++ standard (which I think is likely to come out next year). I haven't bothered to track C99 compliance in Visual Studio, mostly because the only things I use C for anymore require extreme portability, and I can't get that with C99 yet. However, it's quite likely that VS 2005 lacked parts of C99 that VS2008 had. Alternately, it could be that you were compiling the program as C++. Check your compiler properties.
Run your code through CPP (C preprocessor) to see what substitutions CPP does for your macro. You could do it either by invoking `cpp` or providing `-E` parameter to compiler (if you use `gcc`, of course).
Passing multi-param function into a macro
[ "", "c++", "c", "macros", "" ]
I am creating a game that lets the player enter input, changes some states, then checks if a "goal value" is true (obviously this description is muchly simplified), and I want to be able to have that goal value be anything from if the players life is below a certain value to if the amount of enemies remaining is equal to zero. Is there any "expression class" that can hold a simple "value1 compare-operator value2" and check it? ie: ``` expression goal(x = 4); ``` if not, does anybody have any suggestions as to how I could develop an expression class? EDIT: another (more towards what I am trying to achieve) example: ``` game.init(){ expression goal = FileRead(goalfile); } game.checkstate(){ if(goal) exit(1); } //exit 1 is the games win state //another more specific eg.: class level1 { public: expression goal(total_enemies == 0); }; class level2 { public: expression goal(player.x == goal.x && player.y == goal.y); }; ```
**Dynamic expressions** If you want to receive a string from the user and built an expression from that, maybe the [C++ Mathematical Expression Library](http://partow.net/programming/exprtk/index.html) fits your bill? ``` template<typename T> void trig_function() { std::string expression_string = "clamp(-1.0,sin(2 * pi * x) + cos(x / 2 * pi),+1.0)"; T x; exprtk::symbol_table<T> symbol_table; symbol_table.add_variable("x",x); symbol_table.add_constants(); exprtk::expression<T> expression; expression.register_symbol_table(symbol_table); exprtk::parser<T> parser; parser.compile(expression_string,expression); for (x = T(-5.0); x <= T(+5.0); x += 0.001) { T y = expression.value(); printf("%19.15f\t%19.15f\n",x,y); } } ``` There are also the possibility embed a scripting language, such as [Lua](http://www.lua.org) or [Python](http://www.python.org), which will give you (even) more power. This is something to consider if you're writing a game, since you'll likely want to script large parts of it. If you're using [Qt](http://qt-project.org/), you can use [QtScript](http://qt-project.org/doc/qt-4.8/qtscript.html) (Javascript-ish) to run expressions that read (static or dynamic) properties from your QObject-derived objects. Using one of the above keeps you from having to write your own parser, AST and evaluator, however for a small set of operators it shouldn't be too hard to hack together something if you use [Boost.Spirit](http://boost-spirit.com/home/) or some other decent parsing library. **Static expressions** For selecting between a set of predefined expressions (i.e. known at compile time), you should store the expression in a polymorphic function object. For C++11, if that's available to you, use `std::function` and lambda expressions. ``` std::function<bool (int, int)> expr = [](int a, int b) { a*2 < b }; ``` For earlier compilers, I recommend function and bind, either in [Boost](http://www.boost.org) (boost::) or C++0x TR1 (std::), depending on your compiler. Also, Boost.Lambda will be of help here, as it allows you to construct and store expressions for later evaluation. However, if you're not familiar with C++ and templates (or functional programming), it will likely scare you quite a bit. With that you could write ``` using namespace boost::lambda; boost::function<bool (int, int)> myexpr1 = (_1 + _2) > 20; boost::function<bool (int, int)> myexpr2 = (_1 * _2) > 42; std::cout << myexpr1(4,7) << " " << myexpr2(2,5); ``` with bind, it'd look like: ``` boost::function<bool (Player&)> check = bind(&Player::getHealth, _1) > 20; Player p1; if (check(p1)) { dostuff(); } check = bind(&Player::getGold, _1) < 42; if (check(p1)) { doOtherStuff(); } ```
There is no standard way to compile expressions during runtime. You'll have to do it some other way. You might consider using a scripting language, like Lua or Python, and embed it in your C++. That would allow your players the ability to program to the extent you want them to.
Is there any kind of "expression class" (C++)
[ "", "c++", "expression", "" ]
I am trying to convert URLs in a piece of text into hyperlinks - using regular expressions. I have managed to achieve this but the problem is when there are already existing links in the text so ``` bla bla blah www.google.com bla blah <a href="www.google.com">www.google.com</a> ``` should result in ``` bla bla blah <a href="http://www.google.com">www.google.com</a> bla blah <a href="www.google.com">www.google.com</a> ``` not ``` bla bla blah <a href="http://www.google.com">www.google.com</a> bla blah <a href="<a href="http://www.google.com">www.google.com</a></a>"><a href="http://www.google.com">www.google.com</a></a> ```
Finally finished it: ``` function add_url_links($data) { $data = preg_replace_callback('/(<a href=.+?<\/a>)/','guard_url',$data); $data = preg_replace_callback('/(http:\/\/.+?)([ \\n\\r])/','link_url',$data); $data = preg_replace_callback('/^(http:\/\/.+?)/','link_url',$data); $data = preg_replace_callback('/(http:\/\/.+?)$/','link_url',$data); $data = preg_replace_callback('/{{([a-zA-Z0-9+=]+?)}}/','unguard_url',$data); return $data; } function guard_url($arr) { return '{{'.base64_encode($arr[1]).'}}'; } function unguard_url($arr) { return base64_decode($arr[1]); } function link_url($arr) { return guard_url(array('','<a href="'.$arr[1].'">'.$arr[1].'</a>')).$arr[2]; } ```
This is almost impossible to do with a single regular expression. I would instead recommend a state-machine based approach. Something like this (in pseudo-code) ``` state = OUTSIDE_LINK for pos (0 .. length input) switch state case OUTSIDE_LINK if substring at pos matches /<a/ state = INSIDE_LINK else if substring at pos matches /(www.\S+|\S+.com|\S+.org)/ substitute link case INSIDE_LINK if substring at post matches /<\/a>/ state = OUTSIDE_LINK ```
regex to turn URLs into links without messing with existing links in the text
[ "", "php", "regex", "" ]
I have a combo box and input box. If I enter any letter in input box then all the words or sentence that match with that letter should display in the combo box assuming that a list of words or sentence contain in the list. ``` ex1:) input box: a combo box : America Australia joy is in Austria ``` For this example I want JavaScript regex patterns. Anybody give me suggestion.
Not sure I understand exactly what you're asking for, but I think you don't want regex, you just want jQuery: Like this: ``` <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script> $j = jQuery.noConflict(); $j(document).ready(init); function init() { $j('#MyEditBox').change( filterCombo ).keyup( filterCombo ); } function filterCombo() { var InputText = $j(this).val(); $j('#MyCombo option:not(:contains('+ InputText +'))').hide(); $j('#MyCombo option:contains('+ InputText +')').show(); } </script> </head> <body> <input type="text" id="MyEditBox" /> <select multiple id="MyCombo"> <option>America <option>Australia <option>Something else <option>Joy is in Austria <option>Wibble </select> </html> ``` **Update:** This one will only match whole words: ``` <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script> $j = jQuery.noConflict(); $j(document).ready(init); function init() { $j('#MyEditBox').change( filterCombo ).keyup( filterCombo ); } function filterCombo() { var InputText = $j(this).val(); if (InputText.length > 0) { $j('#MyCombo option') .hide() .filter(function() { return hasWholeWord( $j(this).val() , InputText ) }) .show() ; } else { $j('#MyCombo option').show(); } } function hasWholeWord( Text , Word ) { return (new RegExp('\\b'+Word+'\\b','i').test( Text )); } </script> </head> <body> <input type="text" id="MyEditBox" value="" /> <select multiple id="MyCombo"> <option>America <option>Australia <option>Something else <option>Joy is in Austria <option>Wibble </select> </html> ```
Have the word put into a word boundary as you type. Just replace the [word here] part below with your typing from the textbox. The expression would be: ``` \b[word here]\b ``` Also, here's a good [regex tester](http://regexpal.com/).
Javascript regex pattern
[ "", "javascript", "regex", "" ]
Could someone explain the main benefits for choosing one over the other and the detriments that come with that choice?
They solve different problems, LinkedHashMap does a mapping of keys to values, a LinkedHashSet simply stores a collection of things with no duplicates. A linked hash map is for mapping key/value pairs -- for example, storing names and ages: ``` Map<String,Integer> namesAndAges = new LinkedHashMap<String,Integer>(); namesAndAges.put("Benson", 25); namesAndAges.put("Fred", 19); ``` On the other hand, a linked hash set is for storing a collection of one thing -- names, for example: ``` Set<String> names = new LinkedHashSet<String>(); names.add("Benson"); names.add("Fred"); ```
LinkedHashSet internally contain a doubly-linked list running through all of its entries that defines the order of elements. This class permits null elements. **This class implementation is not synchronized, so it must be synchronized externally.** **LinkedHashMap is not synchronized either and must be synchronized externally** For example: ``` Map map = Collections.synchronizedMap(new LinkedHashMap()); ``` Other than that LinkedHashSet stores single values per element and LinkedHashMap stores key/value pair. In the diagram below you can see java.util.Collections. Solid boxes show concrete class implementation
What are the pros and cons of LinkedHashMaps vs. LinkedHashSets?
[ "", "java", "linkedhashmap", "linkedhashset", "" ]
I'm trying to process audio data. I'm working with Java. I've extracted the audio data to an array. Now I should pass N data samples to a function that calculates the Discrete Fourier Transform (or Fast Fourier Transform, which is more efficient). I've read documentation but I'm getting more and more confused. What I'm trying to calculate is the magnitude spectrum (|X(k)|). Can anyone help me? Thanks
Richard G. Baldwin has a number of very good articles on Fast Fourier Transform algorithms in Java on the Developer.com website. In particular, the following articles should prove to be useful: **Fun with Java, Understanding the Fast Fourier Transform (FFT) Algorithm** <http://www.developer.com/java/other/article.php/3457251/Fun-with-Java-Understanding-the-Fast-Fourier-Transform-FFT-Algorithm.htm> **Spectrum Analysis using Java, Sampling Frequency, Folding Frequency, and the FFT Algorithm** <http://www.developer.com/java/other/article.php/3380031/Spectrum-Analysis-using-Java-Sampling-Frequency-Folding-Frequency-and-the-FFT-Algorithm.htm>
If you only want Magnitude Spectrum of audio, go for [jAudio API](http://www.music.mcgill.ca/~mcennis/doc/index.html). It provides class for calculating MS.
Processing Audio Data using Fourier Transforms in Java
[ "", "java", "audio", "wav", "fft", "" ]
Is it possible to let Visual Studio automatically create an event handler method for an UI component within the markup view? Let's say I have ``` <asp:label runat="server" /> ``` and would like to handle the OnPreRender event.. How do you create the handler method? Manually or do you switch to design view and double click the event within the properties window?
You can automatically create a handler method by going to your page's OnLoad or Page\_Load method, and adding a handler for the event. For example, for this Label: ``` <asp:label ID="MyLabel" runat="server" /> ``` You would do this: ``` protected void OnLoad(object sender, EventArgs e) { MyLabel.PreRender += } ``` At this point IntelliSense should kick in and offer to generate an event handler for you. If you hit TAB a couple of times, you should have a new MyLabel\_PreRender method. Good luck!
You should be able to simply write the event handler in markup view and use tab completion to generate the method in code and specify it in markup at the same time. This is a feature that is new to VS.NET 2008 I believe, so if you're using a previous version you may not have this feature.
Automatically create event handler from markup view (c#)
[ "", "c#", "visual-studio", "" ]
I need to render a partialview to a string, and I am trying to convert a C# example to VB.Net, as I am stuck with that for this project. This is causing me a headache from these two problems: 1. ObjectViewData - I can't figure out what that is 2. RenderPartial is a sub, but seems to be used as a function - I don' get it I reference the MVCContrib.UI, so I don't need to convert that. But these two functions, I do need to convert: (from [brightmix.com](http://www.brightmix.com/blog/how-to-renderpartial-to-string-in-asp-net-mvc/)) ``` /// Static Method to render string - put somewhere of your choosing public static string RenderPartialToString(string userControl, object viewData, ControllerContext controllerContext) { HtmlHelper h = new HtmlHelper(new ViewContext(controllerContext, new WebFormView("omg"), null, null), new ViewPage()); var blockRenderer = new BlockRenderer(controllerContext.HttpContext); string s = blockRenderer.Capture( () => RenderPartialExtensions.RenderPartial(h, userControl, viewData) ); return s; } /// Your Controller method... public ActionResult MakeStringForMe() { var objectViewData = new objectViewData { SomeString = "Dude", SomeNumber = 1 }; string s = RenderPartialToString("~/Views/Controls/UserControl.ascx", objectViewData, this.ControllerContext); View(); } ``` Here is my attempt at converting it to VB.Net ``` 'Static Method to render string - put somewhere of your choosing' Public Shared Function RenderPartialToString(ByVal userControl As String, ByVal viewData As Object, ByVal controllerContext As ControllerContext) As String Dim h As New HtmlHelper(New ViewContext(controllerContext, New WebFormView("omg"), Nothing, Nothing), New ViewPage()) Dim blockRenderer As New MvcContrib.UI.BlockRenderer(controllerContext.HttpContext) Dim s As String = blockRenderer.Capture(RenderPartialExtensions.RenderPartial(h, UserControl, viewData)) End Function Public Function MakeStringForMe() As ActionResult Dim objectViewData As objectViewData = New objectViewData With {.SomeString = "Dude", .SomeNumber = 1} Dim s As String = RenderPartialToString("~/Views/Controls/UserControl.ascx", objectViewData, Me.ControllerContext) View() End Function ``` [![alt text](https://i.stack.imgur.com/iKESA.png)](https://i.stack.imgur.com/iKESA.png)
This line: ``` Dim s As String = blockRenderer.Capture(RenderPartialExtensions.RenderPartial(h, UserControl, viewData)) ``` is NOT equivalent to your original line: ``` string s = blockRenderer.Capture( () => RenderPartialExtensions.RenderPartial(h, userControl, viewData) ); ``` The C# example is using a lambda, while the VB example is just calling the method directly, which doesn't return a value. The compiler isn't lying to you. Try this instead: ``` Dim s = blockRender.Capture(New Action(Of String)(Function() RenderPartialExtensions.RenderPartial(h, UserControl, viewData))) ``` I took a look at Capture and it's expecting an Action which is just a delegate, and it looks like the compiler can't infer the delegate's signature to wrap the anonymous function. So we'll give it a helping hand and wrap the lambda ourselves.
You could do it manually or try using <http://www.developerfusion.com/tools/convert/csharp-to-vb/> EDIT: also your code has ``` View() ``` at the end of ``` Public Function MakeStringForMe() ``` this should be ``` Return View() ``` In response to point 2 the code isn't using the renderPartial sub it is using the RenderPartialToString function. HTH OneSHOT
Convert C# to VB.Net - Using MVCContrib Blockrenderer to render a partial view to a string
[ "", "c#", "asp.net-mvc", "vb.net", "mvccontrib", "" ]
I'm making a small program in Java using the Robot class. The program takes over the mouse. while in the course of debugging if it starts acting in a way that I don't want it's hard to quit the program, since I can't move the mouse over to the terminate button in eclipse, and I can't use hotkeys to hit it because the mouse is constant clicking in another window, giving that window focus instead. What I'd like to do is just hook up a keylistener so that when I hit q I can quit the program, but the only way I know how to do this involves making a window, and that window needs focus to capture the input. Is there a way to listen for keyboard or mouse input from anywhere, regardless of what has focus?
This is not a trivial problem and Java doesn't give you a way to do it elegantly. You can use a solution like banjollity suggested but even that won't work all the time if your errant mouse clicks open another fullsized window currently open in your taskbar for example. The fact is, Java by default gives developers very little control over the OS. This is due to 2 main reasons: security (as citied by java documentation) and the fact that different operating systems handle events completely differently and making one unified model to represent all of these would probably not make a whole lot of sense. So to answer your question, I imagine what you want is some kind of behaviour for your program where it listens for keypresses globally, not just in your application. Something like this will require that you access the functionality offered by your OS of choice, and to access it in Java you are going to need to do it through a Java Native Interface (JNI) layer. So what you want to do is: 1. Implement a program in C that will listen for global keypresses on your OS, if this OS is Windows than look for documentation on windows hooks which is well docuemented by Microsoft and MSDN on the web and other places. If your OS is Linux or Mac OS X then you will need to listen for global keypresses using the X11 development libraries. This can be done on an ubunutu linux distro according to a Howto that I wrote at <http://ubuntuforums.org/showthread.php?t=864566> 2. Hook up your C code to your Java code through JNI. This step is actually the easier step. Follow the procedure that I use in my tutorial at <http://ubuntuforums.org/showthread.php?t=864566> under both windows and linux as the procedure for hooking up your C code to your Java code will be identical on both OSes. The important thing to remember is that its much easier to get your JNI code working if you first code and debug your C/C++ code and make sure that it is working. Then integrating it with Java is easy.
There is a library that does the hard work for you: <https://github.com/kwhat/jnativehook>
Listening for input without focus in Java
[ "", "java", "keylistener", "" ]
I'm importing data into an LDAP store. The attribute in question is of type OctetString. I have a normal string that I need to get into that attribute. I'm using C# (.net 3.5) How do I do it?
As far as I know, an OctetString is just a byte array. Not to be confused with Octal (base 8) Completely open to correction but some random googling would seem to agree... This will convert your string to a byte array ``` byte[] octets = System.Text.Encoding.ASCII.GetBytes("abcd"); ```
``` System.Text.Encoding utf8 = System.Text.Encoding.UTF8; byte[] octets = utf8.GetBytes("RΓ©ne"); ```
How do I convert a string into an OctetString (C#)?
[ "", "c#", "ldap", "attributes", "" ]
What is the best way of parsing command-line arguments in C++ if the program is specified to be run like this: ``` prog [-abc] [input [output]] ``` Is there some way of doing this built into the standard library, or do I need to write my own code? --- Related: * [Parsing command line arguments in a unicode C++ application](https://stackoverflow.com/questions/332849/parsing-command-line-arguments-in-a-unicode-c-application)
[Boost.Program\_options](http://www.boost.org/doc/libs/release/libs/program_options/) should do the trick
The suggestions for `boost::program_options` and GNU getopt are good ones. However, for simple command line options I tend to use std::find For example, to read the name of a file after a `-f` command line argument. You can also just detect if a single-word option has been passed in like `-h` for help. ``` #include <algorithm> char* getCmdOption(char ** begin, char ** end, const std::string & option) { char ** itr = std::find(begin, end, option); if (itr != end && ++itr != end) { return *itr; } return 0; } bool cmdOptionExists(char** begin, char** end, const std::string& option) { return std::find(begin, end, option) != end; } int main(int argc, char * argv[]) { if(cmdOptionExists(argv, argv+argc, "-h")) { // Do stuff } char * filename = getCmdOption(argv, argv + argc, "-f"); if (filename) { // Do interesting things // ... } return 0; } ``` On thing to look out for with this approach you must use std::strings as the value for std::find otherwise the equality check is performed on the pointer values. --- I hope it is okay to edit this response instead adding a new one, as this is based on the original answer. I re-wrote the functions slightly and encapsulated them in a class, so here is the code. I thought it might be practical to use it that way as well: ``` class InputParser{ public: InputParser (int &argc, char **argv){ for (int i=1; i < argc; ++i) this->tokens.push_back(std::string(argv[i])); } /// @author iain const std::string& getCmdOption(const std::string &option) const{ std::vector<std::string>::const_iterator itr; itr = std::find(this->tokens.begin(), this->tokens.end(), option); if (itr != this->tokens.end() && ++itr != this->tokens.end()){ return *itr; } static const std::string empty_string(""); return empty_string; } /// @author iain bool cmdOptionExists(const std::string &option) const{ return std::find(this->tokens.begin(), this->tokens.end(), option) != this->tokens.end(); } private: std::vector <std::string> tokens; }; int main(int argc, char **argv){ InputParser input(argc, argv); if(input.cmdOptionExists("-h")){ // Do stuff } const std::string &filename = input.getCmdOption("-f"); if (!filename.empty()){ // Do interesting things ... } return 0; } ```
Parsing Command Line Arguments in C++?
[ "", "c++", "command-line-arguments", "" ]
I'm not sure if I am abusing Enums here. Maybe this is not the best design approach. I have a enum which declares the possible parameters to method which executes batch files. ``` public enum BatchFile { batch1, batch2 } ``` I then have my method: ``` public void ExecuteBatch(BatchFile batchFile) { string batchFileName; ... switch (batchFile) { case BatchFile.batch1: batchFileName = "Batch1.bat"; break; case BatchFile.batch2: batchFileName = "Batch2.bat"; break; default: break; } ... ExecuteBatchFile(batchFileName); } ``` So I was wondering if this is sound design. Another option I was thinking was creating a Dictionary<> in the constructor like this: ``` Dictionary<BatchFile, String> batchFileName = new Dictionary<BatchFile, string>(); batchFileName.Add(BatchFile.batch1, "batch1.bat"); batchFileName.Add(BatchFile.batch2, "batch2.bat"); ``` Then instead of using a switch statement I would just go: ``` public void ExecuteBatch(BatchFile batchFile) { ExecuteBatchFile(batchFileName[batchFile]); } ``` I'm guessing the latter is the better approach.
I'd probably go for a design along these lines: ``` public interface IBatchFile { void Execute(); } public class BatchFileType1 : IBatchFile { private string _filename; public BatchFileType1(string filename) { _filename = filename; } ... public void Execute() { ... } } public class BatchFileType2 : IBatchFile { private string _filename; public BatchFileType2(string filename) { _filename = filename; } ... public void Execute() { ... } } ``` In fact, I'd extract any common functionality into a `BatchFile` base class
What if you suddenly need a third batch file? You have to modify your code, recompile your library and everybody who uses it, has to do the same. Whenever I find myself writing magic strings that might change, I consider putting them into an extra configuration file, keeping the data out of the code.
Are Enum the right way to go here?
[ "", "c#", "dictionary", "enums", "" ]
Can someone point me out to some C# code examples or provide some code, where a Dictionary has been used as a property for a Class. The examples I have seen so far don't cover all the aspects viz how to declare the dictionary as property, add, remove, and retrieve the elements from the dictionary.
Here's a quick example ``` class Example { private Dictionary<int,string> _map; public Dictionary<int,string> Map { get { return _map; } } public Example() { _map = new Dictionary<int,string>(); } } ``` Some use cases ``` var e = new Example(); e.Map[42] = "The Answer"; ```
sample code: ``` public class MyClass { public MyClass() { TheDictionary = new Dictionary<int, string>(); } // private setter so no-one can change the dictionary itself // so create it in the constructor public IDictionary<int, string> TheDictionary { get; private set; } } ``` sample usage: ``` MyClass mc = new MyClass(); mc.TheDictionary.Add(1, "one"); mc.TheDictionary.Add(2, "two"); mc.TheDictionary.Add(3, "three"); Console.WriteLine(mc.TheDictionary[2]); ``` **EDIT** When you use C# version 6 or later, you can also use this: ``` public class MyClass { // you don't need a constructor for this feature // no (public) setter so no-one can change the dictionary itself // it is set when creating a new instance of MyClass public IDictionary<int, string> TheDictionary { get; } = new Dictionary<int, string>(); } ```
.NET Dictionary as a Property
[ "", "c#", ".net", "dictionary", "properties", "" ]
Let's say I have a generic list of `Fruit` (`List<Fruit> fruits = new List<Fruit>()`). I then add a couple of objects (all derived from `Fruit`) - `Banana`, `Apple`, `Orange` but with different properties on the derived objects (such as `Banana.IsYellow`). ``` List<Fruit> fruits = new List<Fruit>(); Banana banana1 = new Banana(); Banana banana2 = new Banana(); Apple apple1 = new Apple(); Orange orange2 = new Orange(); fruits.Add(banana1); fruits.Add(banana2); fruits.Add(apple1); fruits.Add(orange1); ``` Then I can do this: ``` foreach(Banana banana in fruits) Console.Write(banana.IsYellow); ``` But at execution time of course this is not valid because there is no `IsYellow`-property on the Apple and Orange objects. How do I get only the bananas, apples, oranges etc from the `List<Fruit>`?
``` foreach(Banana b in fruits.OfType<Banana>()) ```
You could just do ``` foreach(Fruit fruit in fruits) { Banana b = fruit as Banana; if(b != null) { Console.Write(b.IsYellow); } } ```
How do I get a particular derived object in a List<T>?
[ "", "c#", ".net", "list", "collections", "filter", "" ]
After finishing two cs classes, I've started working on a personal project in Java. I am writing a program that will look through a music collection and attempt to set the 'Composer' tag by looking at the filename and meta tags. I am comparing these against a composer list I have created as a simple text file. My question is this: What is a good method for comparing two strings to try to find a best match of sorts? For exammple, in my case suppose I have a file called 'Pulenc - Gloria in excelsis Deo.flac'. In my composer list I have 'Poulenc, Francis'. I want to be able to read 'Pulenc', and see that it is very close to 'Poulenc' so that I can have the composer tag set correctly. A friend suggested I look into using Cosine Distance (which I'd never heard of before), and another recommended Levenshtein Distance. Are either of these a good approach or are there other methods that may work better?
It sounds like the [Levenshtein Distance](http://en.wikipedia.org/wiki/Levenshtein_distance) is exactly what you need. The [Cosine Distance](http://www.comp.rgu.ac.uk/staff/sy/PhD_Thesis_html/page_67.htm) seems to deal with longer texts, and [phonetic algorithms](http://en.wikipedia.org/wiki/Phonetic_algorithm) like Soundex will probably yield poor results for names, most of which are not intended to be pronounced using English pronounciation rules.
There's a [project called SimMetrics](http://sourceforge.net/projects/simmetrics/), run by the [University of Sheffield](http://nlp.shef.ac.uk/wig/) in the UK that will be able to help you out. I wrote a little bit about it [in my blog](http://chillijam.co.uk/2009/05/13/fuzzy-matching-of-names/) from a .NET point of view, but I believe the project also has a Java implementation available.
Comparing Composer Names, Or How do I find a 'close enough' match between two strings?
[ "", "java", "string", "" ]
Imagine four lists, all at least have this Id string property, but may have other properties: ``` public class A //or B, C, D { public string Id { get; set; } //..other properties } //so: List<A> a1 = new List<A>(); List<B> a2 = new List<B>(); List<C> a3 = new List<C>(); List<D> a4 = new List<D>(); ``` I want to select all DISTINCT ids in: a1, combined with a2, a3 and a4 I thought LINQ syntax would be ideal but how do you combine these to an IEnumerable result with a single string property, for example something with a definition of class A.
Are they really all lists of the same type? Or do you have ``` List<A> a1 = new List<A>(); List<B> a2 = new List<B>(); List<C> a3 = new List<C>(); List<D> a4 = new List<D>(); ``` and you want to combine those because all 4 types have a common string Id property? OK, your edit shows I was on the right track. You need an Interface that defines the string Id property and each type A, B, C and D need to implement that Interface. Then each list will be of the Interface type and the concat answers will work. If you don't have ability to define the interface, then you could use LINQ to query each list for only the Id field (you should get `IQueryable<String>` results) and then concat those results. Edit: Here's a LINQ query that should give you what you're looking for: ``` var uniqueIds = (from a in a1 select a.Id).Concat( from b in a2 select b.Id).Concat( from c in a3 select c.Id).Concat( from d in a4 select d.Id).Distinct(); ```
Since they are different types, I would select first the *Id property* to get an IEnumerable<string>, and then concatenate the results: ``` var query = a1.Select(a=> a.Id) .Concat(a2.Select(b=> b.Id)) .Concat(a3.Select(c=> c.Id)) .Concat(a4.Select(d=> d.Id)) .Distinct(); ```
LINQ selecting distinct from 4 IEnumerable lists
[ "", "c#", "linq", "ienumerable", "distinct", "" ]
Guys when the JVM Crashes it writes an Error Log hs\_err\_pid.log. I want to find out what caused the JVM to crash ? How to understand these Logs, is it documented anywhere on how this Log is arranged. I tried to search on the Net but to no avail :-( Pointing out to relevant URL's will be appreciated. Thanks.
Unless you are calling native code (JNI), nothing in your code should ever make JVM crash; so the stack trace information in that log file is probably not meant to be very useful to most developers. That's probably why it might not be documented (at least externally). So the best thing is probably to file a bug report as suggested by the error message. But, if you really do want to understand it, [Kohsuke's Blog](https://community.oracle.com/blogs/kohsuke/2009/02/19/crash-course-jvm-crash-analysis) has the goods. As usual. :)
To start with, look for the topmost line that looks something like "ntdll.dll+0x2000". If the hotspot is occurring in *your* native code (i.e. the DLL is one of yours), then find out how to persuade your compiler to produce a list of mappings from DLL offset to line number. Obviously, that may mean you need to re-run with the newly compiled DLL and wait for the problem to occur again. Otherwise, see if searching for that specific line brings up something in Google, bearing in mind that the same error could mean a whole host of things. And see if the DLL name looks like it's something recognisable, e.g. a printer driver name, graphics driver, or some other component that you can track down to a particular call. Whatever that component is, you may be able to upgrade it to a fixed version, or avoid making the call in question. If you're not sure what the component is, it may just be "the JVM" that you need to upgrade-- upgrading at least to the latest update/minor version nubmer of whatever version you're on is probably a good idea. In the past I've also seen bugs in the JIT compiler that can be temporarily solved by telling it not to attempt to compile the particular method in question-- as I recall vaguely, in these cases, the hotspot error gives some clue as to which method it was (possibly just the dump of the Java stack), but I don't have an example to hand to recall the details.
How to understand Java Hotspot Errors
[ "", "java", "jvm", "crash", "jvm-hotspot", "" ]
I can't find the relevant portion of the spec to answer this. In a conditional operator statement in Java, are both the true and false arguments evaluated? So could the following throw a NullPointerException ``` Integer test = null; test != null ? test.intValue() : 0; ```
Since you wanted the spec, here it is (from [Β§15.25 Conditional Operator ? :](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25), the last sentence of the section): > The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.
I know it is old post, but look at very similar case and then vote me :P Answering original question : only one operand is evaluated BUT: ``` @Test public void test() { Integer A = null; Integer B = null; Integer chosenInteger = A != null ? A.intValue() : B; } ``` This test will throw `NullPointerException` always and in this case IF statemat is not equivalent to ?: operator. The reason is here <http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.25>. The part about boxing/unboxing is embroiled, but it can be easy understood looking at: > "If one of the second and third operands is of type `boolean` and the type of the other is of type `Boolean`, then the type of the conditional expression is `boolean`." The same applies to `Integer.intValue()` Best regards!
Java ternary (immediate if) evaluation
[ "", "java", "conditional-operator", "short-circuiting", "" ]
Hi guys I have a simple membership based website where users log in and have their own profiles. I woudl like to be able to tell at any given point in time how many users or rather which users are currently logged into my website. Its a simple membership based system in php. One way I uderstand it creating a table in a db and storing login details there and session data as well but can this be done in some other way i.e. anyway to find out how many sessions have been started and all the unique users online.
The best way to do this is record the `lastActivityTime` for each user. When they access a page, log the time in their db-record. Once you're doing that, run a simple query to count all records that have a `lastActivityTime` less than 5 minutes from the `Current Time`. So rather than asking "how many users are logged in," you're asking "how many users were recently active."
The key problem with the whole 'monitoring active sessions' issue is that you (the server) are not necessarily in full control of the session. User's browsers can expire the sessions at any given time, so you cannot guarantee active users at any point. If it is extremely important to know the current users, then add a column to their user table specifying a timestamp, and update that field every time they load a page. If that column is less than about a minute out of date, then they can be considered active. An extra thing you can do (used a lot by online chatrooms to maintain an active 'chat' list), is to poll a page at a given interval (using AJAX), and then even if they don't refresh the page you still know they are there. If an ajax request doesn't arrive at the specified interval, the user has navigated away, or shut their browser.
How do I find out total number of sessions created i.e. number of logged in users?
[ "", "php", "session", "membership", "" ]
Thanks for all the great answers, this helps a lot! --- Hello, I need some advice/help (obviously) I'm pretty new to jquery/ajax in general but I have been able to do quite a bit so far. Here is what I am TRYING to do and then what I have managed to do so far. I am trying to emulate the wordpress post categories. Where you are writing a post and then when you want to add it to a category it lets you just create new checkbox categories on the spot! I have managed to get it working to where I send the request to a php script and it adds the record to my DB and then it appends the new checkbox to the bottom of my list. The issue I have is that I need to return the two values from PHP, the ID and the NAME. Right now I can return the name but I am not sure how to return them separately so that I can manipulate them in the JS. I might be going about this in the wrong way completely. The idea is that I would create the new category records and then append them back to the category list using JS and then I would checkmark them and when I click "save" the values (IDs) would be sent to the current row (post) in the DB. I hope i'm making some sense. If you have any questions please ask away and if you have any ideas or answers please let me know! Thanks!
Try returning the text as JSON. Depending on the jQuery AJAX method you are using you can set a custom callback (a function that gets called after the first function has returned). For example if you're using the $.post method you could do something like this: backend.php: ``` $return_value = array(); $return_value['value1'] = 'data 1'; $return_value['value2'] = 'data 2'; echo json_encode($return_value); ``` frontend.js: ``` $.post("backend.php", '', function(data) { alert(data.value1); // Would show data 1 alert(data.value2); // Would show data 2 }, "json"); ```
Well, I have and idea of what you are trying to do: Until now, you were returning the ID of the newly created category in plaintext from the php to the calling javascript. Now you want to return *both* the ID and the NAME of the newly created category. There are two ways to do this: using XML or JSON. (on may argue there are more ways. and indded, there are.) in XML: ``` <response> <ID>2</ID> <NAME>jquery</NAME> </response> ``` in JSON: ``` { id : 2, name : "jquery" } ``` parsing JSON in javascript is a trivial matter. parsing XML can be done using jQuery, just look up the jQuery ajax docs. Cheers, jrh.
jquery and PHP - Sending information back from php to the JS
[ "", "php", "jquery", "ajax", "" ]
I'm using the `Obsolete` attribute (as just suggested by fellow programmers) to show a warning if a certain method is used. Is there a way to suppress the warning similar to CodeAnalysis' `SuppressMessage` at points where the use is justified? This needs to work for `[Obsolete("Some message")]` which generates warning 618 and the plain `[Obsolete]` attribute with no message which generates warning 612.
Use `#pragma warning disable`: ``` using System; class Test { [Obsolete("Message")] static void Foo(string x) { } static void Main(string[] args) { #pragma warning disable 0618 // This one is okay Foo("Good"); #pragma warning restore 0618 // This call is bad Foo("Bad"); } } ``` Restore the warning afterwards so that you won't miss "bad" calls.
The *intent* is to disable the warning for obsolete *usage*, regardless of whether the construct is marked with `[Obsolete]` or `[Obsolete("Message")]`. So use both [CS0612](http://msdn.microsoft.com/en-us/library/h0h063ka.aspx) *and* [CS0618](http://msdn.microsoft.com/en-us/library/x5ye6x1e.aspx): ``` #pragma warning disable 612, 618 ... #pragma warning restore 612, 618 ```
Selectively suppress custom Obsolete warnings
[ "", "c#", "visual-studio-2008", "" ]
On a site that I'm working on, I'm displaying results from a database query. Each page shows 15 results, so if there are 45 results returned from the query, they will be displayed on 3 separate pages, each containing 15 results. I want the user to be able to select any number of items from the first page, then switch to the other pages and select items from those pages as well, while still remembering the items that were selected on the first page. (Eventually, when the user has selected all the items, he will click a Submit button.) So if the user navigates back to the first page, the items that he checked should show up as being selected. On pages that I've seen on the Web, when the user navigates back to the first page, all the checkboxes are cleared again (which is not what I want). Any ideas on the best way to achieve this? Thanks.
Remembering the selections in-between pages means you have some state that needs storing somewhere. There are a variety of ways to do it, but it boils down to one of these... 1. Keep it on the client (e.g. cookies) 2. Keep it on the server (e.g. in a database) 3. Keep sending it backwards and forwards (e.g. hidden form field, as in ASP.NET viewstate) A common abstraction offered by platforms such as PHP and ASP.NET is the idea of "session". The actual implementation of session state might be some combination of those 3 possibilities above, and it probably offers the easiest route. I suggest you look at session state in PHP.
use hidden inputs to carry over the results from the previous set ``` <!-- hidden fields --> <input type='hidden' name='whatever[]' value='whatever'/> <!-- checkboxes --> <input type='checkbox' name='whatever[]' value='whatever'/> ```
How to select items from multiple pages using PHP, HTML, etc?
[ "", "php", "html", "checkbox", "" ]
How can I manipulate group policy based restriction for the controlpanel and the taskmanager in C#?
Have a look at WMI. Here is a link to an article on WMI Group policy objects: <http://msdn.microsoft.com/en-us/library/aa375082(VS.85).aspx> This tool will generate example c# code for you: [WMICodeCreator](http://www.microsoft.com/downloads/details.aspx?FamilyID=2cc30a64-ea15-4661-8da4-55bbc145c30e&displaylang=en)
you can use Registry key to restriction task manager and control panel easily!
How do I configure group policies using C#?
[ "", "c#", "taskmanager", "gpo", "controlpanel", "" ]
How to create array of labels with Microsoft Visual C# Express Edition ? Is there way to do it with graphical (drag'n'drop) editor or I have to manually add it to auto generated code ?
You have to manually add it. But don't add it to auto generated code as it can be overwritten by Visual Studio designer. I would add it in Load event handler for the form. The code can look like this: ``` Label[] labels = new Label[10]; labels[0] = new Label(); labels[0].Text = "blablabla"; labels[0].Location = new System.Drawing.Point(100, 100); ... labels[9] = new Label(); ... ``` PS. Your task seems a little unusual to me. What do you want to do? Maybe there are better ways to accomplish your task.
You can add the labels to the form using the GUI editor, then add those to the array in form load. ``` Label[] _Labels = new Label[3]; private void MyForm_Load(object sender, EventArgs e) { _Labels[0] = this.Label1; _Labels[1] = this.Label2; _Labels[2] = this.Label3; } ``` This will at least make setting the location easier. Also you might want to consider using the [FlowLayoutPanel](http://msdn.microsoft.com/en-us/library/f9e8s203.aspx) if you're dynamically creating labels (or any control really).
Array of Labels
[ "", "c#", ".net", "" ]
I'd like to implement a voting system on my site, without having to force them to create an account. They would ultimately be voting up/down a piece of content which has a unique ID. * I know that I could store entries in a table with IP/ID, but what if there are more than one user coming from the same IP? * Is there a way to uniquely identify visitors without it being tied to their external ip? * If created a GUID, store it in a cookie on that machine, could it be retrieved later on that same computer with the same IP? A different IP? Any thoughts on these questions, or any insight to a better approach would be greatly appreciated.
Yes, you could use a cookie and set the expiration very far into the future; however, there is nothing stopping anyone from clearing their cache and voting again. Your best bet, is to use the cookie and don't allow votes from the same IP within 15 minutes of each other... without registration thats the best you can do.
You could identify users based on more than just their IP. For example you could include the IP + the entire request header information (such as Browser, Version Numbers, Capabilities) and hash that. That will more or less uniquely identify your user (not 100% though, unfortunately.)
Implementing a voting system without requiring registration
[ "", "php", "database-design", "cookies", "project-planning", "voting-system", "" ]
I need to build a jar file that includes (other, external projects') Maven artefacts. The artefacts are to be included just like stuff in `src/main/resources`, without any processing. Even though they happen to be jar files themselves, they are not compile time dependencies for my code and should not be added to the classpath, at neither the compile, the test, or the runtime stages. I can get this done by downloading the files and placing them into `src/main/resources`, but I would rather have them resolved using the Maven repository.
Here's an example of what you can add to your pom-- it'll copy the artifact with the specified ID from the specified project into the location you specify. ``` <plugin> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy</id> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>id.of.the.project.group.to.include</groupId> <artifactId>id-of-the-project's-artifact-to-include</artifactId> <version>${pom.version}</version> </artifactItem> </artifactItems> <includeArtifactIds>id-of-the-project's-artifact-to-include</includeArtifactIds> <outputDirectory>${project.build.directory}/etc-whatever-you-want-to-store-the-dependencies</outputDirectory> </configuration> </execution> </executions> </plugin> ```
You could use the [dependency plugin](http://maven.apache.org/plugins/maven-dependency-plugin/) to download and put your required artefacts into the `target/classes` directory during the process-resources phase. See the [example usage for copying artefacts](http://maven.apache.org/plugins/maven-dependency-plugin/examples/copying-artifacts.html)
Specify non-compile dependencies in Maven and package them as resources
[ "", "java", "maven-2", "build-automation", "" ]
This is a sample of the data that I have. ``` -ID- -Rank- -Type- -Status- -Amount- 1142474 2 Under Offer Approved 23 1148492 1 Present Current 56 1148492 2 Under Offer Approved 3 2273605 1 Present Current 24 ``` Where the ID is the same I only want the record with the highest rank. So the end result of the query. ``` -ID- -Rank- -Type- -Status- -Amount- 1142474 2 Under Offer Approved 23 1148492 1 Present Current 56 2273605 1 Present Current 24 ``` Now to get the original data set is an expensive operation, so **I *don't* want to** do a **group by the ID** and then **mins the rank** and **then joins back** onto the dataset again. Hence the query needs to do its work another way. Cheers Anthony
``` select t1.id , t1.rank , t1.type , t1.status , t1.amount from my_table t1 left outer join my_table as t2 on t1.id = t2.id and t2.rank < t1.rank where t2.id is null ```
This will work: ``` with temp as ( select *, row_number() over (partition by id order by rank) as rownum from table_name ) select * from temp where rownum = 1 ``` Will give one record per id where rank represents the least number
Advanced grouping without using a sub query
[ "", "sql", "sql-server", "t-sql", "" ]
I'm trying to update Table1 in DB1 with data from Table2 in DB2. I can connect and get the data from DB2 Table2 into DB1 Table1, but the issue I'm having is getting the MOST RECENT data from DB2 Table2. I'm looking at 3 fields in DB2: f1, f2, & f3. f1 contains duplicates (and is where I'm matching from DB1 Table1) and f3 is a date field and I want to grab the most recent date to update DB1 Table1. Below is some of the code I've been using: ``` Update Table1 Set f2 = c.f2, f3 = convert(varchar, c.f3, 101) From Table1 b inner join Server.DB.dbo.Table2 c on b.f1 = c.f1 Where b.f1 = c.f1 ``` Sample Data: ``` c.f1 c.f2 c.f3 8456 RS47354 06/30/2009 8456 M101021 10/31/2009 (want this one) 7840 5574 NULL 7840 RH013057 06/30/2010 (want this one) 7650 RS48100 06/30/2007 7650 RS49010 06/30/2009 (want this one) b.f1 b.f2 b.f3 8456 Null Null 7840 Null Null 7650 Null Null ``` Eventually, this will be set inside an SSIS package. Any and all help appreciated! -JFV
I'm not sure if this is the fasted code in the world, it obviously depends on how close the two servers are and how much data you have in each table. ``` UPDATE Table1 SET f2 = T2.f2, f3 = convert(varchar, T2.f3, 101) FROM Table1 T1 INNER JOIN Server.DB.dbo.Table2 T2 ON T1.f1 = T2.f1 WHERE T2.f3 = (SELECT MAX(f3) FROM Server.DB.dbo.Table2 WHERE f1 = T1.f1) ``` An alternative (if you have that much control) is to create a trigger on Table2 which puts the latest version into a temporary table whenever it is updated. Update: Corrected the code.
``` UPDATE T1 SET f2 = T2.f2, f3 = T2.f3 -- If it's a date, save it as a date, not a VARCHAR FROM dbo.Table1 T1 INNER JOIN Server.db.dbo.Table2 T2 ON T2.f1 = T1.f1 LEFT OUTER JOIN Server.db.dbo.Table2 T2_later ON T2_later.f1 = T2.f1 AND T2_later.f3 > T2.f3 WHERE T2_later.f1 IS NULL ``` This may have some performance problems doing it across servers if Table2 is large. It might be better to create a view in that database and use that for the updates: ``` CREATE VIEW dbo.T2_Latest AS SELECT T2.f1, T2.f2, T2.f3 FROM dbo.Table2 T2 LEFT OUTER JOIN dbo.Table2 T2_later ON T2_later.f1 = T2.f1 AND T2_later.f3 > T2.f3 WHERE T2_later.f1 IS NULL ``` Then you just need to join on f1 (you don't need that criteria in both the INNER JOIN and the WHERE clause by the way). The view will filter out the earlier rows BEFORE it needs to compare them across servers. In SSIS there are other solutions, using the Merge component, Lookup component, or Join component which will probably work better.
How to update another table with the most recent data in SQL?
[ "", "sql", "sql-server-2005", "ssis", "" ]
I am getting a NullReferenceException when running my multi-threaded application, but only when I run in Release mode outside of the debugger. The stack trace gets logged, and it always points to the same function call. I put several logging statements in the function to try to determine how far it would get, and every statement gets logged, including one on the last line of the function. What is interesting is that when the NullReferenceException occurs, the statement after the function call does not get logged: ``` // ... logger.Log( "one" ); // logged Update( false ); logger.Log( "eleven" ); // not logged when exception occurs } private void Update( bool condition ) { logger.Log( "one" ); // logged // ... logger.Log( "ten" ); // logged, even when exception occurs } ``` The exception does not occur every time the function is called. Is it possible that the stack is being corrupted either before or during execution of the function such that the return address is lost, resulting in the null reference? I didn't think that sort of thing was possible under .NET, but I guess stranger things have happened. I tried replacing the call to the function with the contents of the function, so everything happens inline, and the exception then occurs on a line that looks like this: ``` foreach ( ClassItem item in classItemCollection ) ``` I have verified through logging that the "classItemCollection" is not null, and I also tried changing the foreach to a for in case the IEnumerator was doing something funny, but the exception occurs on the same line. Any ideas on how to investigate this further? **Update:** Several responders have suggested possible solutions having to do with making sure the logger isn't null. To be clear, the logging statements were added for debugging purposes after the exception started happening.
I found my null reference. Like Fredrik and micahtan suggested, I didn't provide enough information for the community to find a solution, so I figured I should post what I found just to put this to rest. This is a representation of what was happening: ``` ISomething something = null; //... // the Add method returns a strong reference to an ISomething // that it creates. m_object holds a weak reference, so when // "this" no longer has a strong reference, the ISomething can // be garbage collected. something = m_object.Add( index ); // the Update method looks at the ISomethings held by m_object. // it obtains strong references to any that have been added, // and puts them in m_collection; Update( false ); // m_collection should hold the strong reference created by // the Update method. // the null reference exception occurred here something = m_collection[ index ]; return something; ``` The problem turned out to be my use of the "something" variable as a temporary strong reference until the Update method obtained a permanent one. The compiler, in Release mode, optimizes away the "something = m\_object.Add();" assignment, since "something" isn't used until it is assigned again. This allowed the ISomething to be garbage collected, so it no longer existed in m\_collection when I tried to access it. All I had to do was ensure that I held a strong reference until after the call to Update. I am doubtful that this will be of any use to anyone, but in case anyone was curious, I didn't want to leave this question unanswered.
The fact that it logs "ten" would make me look first at: * is `logger` ever assigned... is this perhaps becoming null somehow * is the bug inside `Log` itself Hard to tell without enough context for either - but that is how I'd investigate it. You could also add a simple `null` test somewhere; as a cheeky approach, you could rename the `Log` method to something else, and add an extension method: ``` [Conditional("TRACE")] public static void Log(this YourLoggerType logger, string message) { if(logger==null) { throw new ArgumentNullException("logger", "logger was null, logging " + message); } else { try { logger.LogCore(message); // the old method } catch (Exception ex) { throw new InvalidOperationException( "logger failed, logging " + message, ex); } } } ``` Your existing code should call the new `Log` extension method, and the exception will make it clear exactly where it barfed. Maybe change it back once fixed... or maybe leave it.
NullReferenceException when function returns
[ "", "c#", "weak-references", "" ]
I need a way to execute the os.system() module as different UID's. It would need to behave similar to the following BASH code (note these are not the exact commands I am executing): ``` su user1 ls ~ mv file1 su user2 ls ~ mv file1 ``` The target platform is GNU Linux Generic. Of course I could just pass these to the os.system module, but how to send the password? Of course I could run the script as root, but that's sloppy and insecure. Preferably I would like to do with without requiring any passwords to be in plain text.
The function you're looking for is called `os.seteuid`. I'm afraid you probably won't escape executing the script as root, in any case, but I think you can use the `capabilities(7)` framework to 'fence in' the execution a little, so that it can change users--but not do any of the other things the superuser can. Alternatively, you *might* be able to do this with PAM. But generally speaking, there's no 'neat' way to do this, and David Cournapeau is absolutely right that it's traditional for admin scripts to run with privileges.
I think that's not trivial: you can do that with a shell because each command is launched into its own process, which has its own id. But with python, everything will have the uid of the python interpreted process (of course, assuming you don't launch subprocesses using the subprocess module and co). I don't know a way of changing the user of a process - I don't know if that's even possible - even if it were, you would at least need admin privileges. What are you trying to do exactly ? This does not sound like the right thing to do for admin purpose, for example. Generally, admin scripts run in a priviledge user - because nobody knows the password of user 2 except user 2 (in theory). Being root means su user always work for a 'normal' user, without requesting password.
Executing shell commands as given UID in Python
[ "", "python", "linux", "permissions", "os.system", "" ]
I am trying to open a file in c++ and the server the progam in running on is based on tux. ``` string filename = "../dir/input.txt"; works but string filename = "~jal/dir1/dir/input.txt"; fails ``` Is there any way to open a file in c++ when the filename provided is in the second format?
The `~jal` expansion is performed by the shell (bash/csh/whatever), not by the system itself, so your program is trying to look into the folder named `~jal/`, not `/home/jal/`. I'm not a C coder, but `getpwent()` may be what you need.
You could scan the string, replacing `~user` by the appropriate directory. The [POSIX](http://www.opengroup.org/onlinepubs/9699919799/functions/wordexp.html) function [`wordexp`](http://www.kernel.org/doc/man-pages/online/pages/man3/wordexp.3.html) does that, and a few other things * variable substitution, like you can use `$HOME` * optional command substitution, like `$(echo foo)` (can be disabled) * arithmetic expansion, like `$((3+4))` * word splitting, like splitting `~/a ~/b` into two words * wildcard expansion, like `*.cpp` * and quoting, like `"~/a ~/b"` remains that
Opening a file on unix using c++
[ "", "c++", "unix", "" ]
I'm working in Microsoft Visual C# 2008 Express. I found this snippet of code: ``` public static int RandomNumber(int min, int max) { Random random = new Random(); return random.Next(min, max); } ``` the problem is that I've run it more than 100 times, and it's ALWAYS giving me the same answer when my min = 0 and max = 1. I get 0 every single time. (I created a test function to run it - really - I'm getting 0 each time). I'm having a hard time believing that's a coincidence... is there something else I can do to examine or test this? (I did re-run the test with min = 0 and max = 10 and the first 50ish times, the result was always "5", the 2nd 50ish times, the result was always "9". ?? I need something a little more consistently random... -Adeena
The problem with min = 0 and max = 1 is that min is inclusive and max is exclusive. So the only possible value for that combination is 0.
``` random = new Random(); ``` This initiates random number generator with current time (in sec). When you call your function many times before system clock changed, the random number generator is initiated with the same value so it returns same sequence of values.
Why does it appear that my random number generator isn't random in C#?
[ "", "c#", "random", "" ]
How can tell if my object's value is a float or int? For example, I would like this to return me bool value.
Are you getting the value in string form? If so there is no way to unambiguously tell which one it isbecause there are certain numbers that can be represented by both types (quite a few in fact). But it is possible to tell if it's one or the other. ``` public bool IsFloatOrInt(string value) { int intValue; float floatValue; return Int32.TryParse(value, out intValue) || float.TryParse(value, out floatValue); } ```
I'm assuming you mean something along the lines of... ``` if (value is int) { //... } if (value is float) { //... } ```
How can tell if my object's value is a float or int?
[ "", "c#", ".net", "asp.net", "" ]
I'm validating allot of fields now in PHP, and I have to preform basic (string length ect.) and more complex (strip <> tags, for example) Can anyone recommend a class that does this, or maybe a framework, or maybe some functions that do these things?
I assume you're validating POSTed forms: use [Zend\_Form](http://framework.zend.com/manual/en/zend.form.html) and [Zend\_Filter](http://framework.zend.com/manual/en/zend.filter.html)
If you're using PHP >= 5.2.0 then you can use PHP's built in [filter functions](http://php.net/manual/en/ref.filter.php). In particular, have a look at [filter\_var\_array](http://php.net/manual/en/function.filter-var-array.php), which you can use to validate an array of inputs, each with its own validation rules. If you don't want to buy in to a complete framework then these might prove useful. Alternatively, I've found [Kohana's validation library](http://docs.kohanaphp.com/libraries/validation) to be very good.
recommendation for a php validation framework
[ "", "php", "validation", "zend-framework", "" ]
Is it possible to capture the graphics object created by the Google Earth browser plugin from a .NET WebBrowser control? With this graphics object I could create an image to use as the background image for a panel that I can then draw on top of. You cannot just use a WebBrowser control under a Panel control as the Google Earth plugin does not work. Getting the browser graphics object just returns blank. The browser DrawToBitmap method (no intelisense) returns the web page but without the Google Earth image. Any ideas?
After some more research and trial and error I am forced to admit defeat on this one, it seems imposible to show google earth on a panel when the webbrowser control hosing it is offscreen. The solution is either to live with the limitation: * Set the form you wish to draw on background to transparent * Create a new form to be the parent of the drawing form * Display google earth on the new form * Align the forms correctly and allow the child to drive the parent Or to switch to Microsoft Live Earth as there is already a [proof of concept](http://rob.runtothehills.org/archives/60) that works for WPF and winforms.
Take a look at this project of mine: <http://code.google.com/p/winforms-geplugin-control-library/> it will go some way to helping. The trick here is to capture the current image from the plugin as a bitmap and then use this (like double buffering). Especially see the 'ScreenGrabButton\_Click' method in 'GEToolStrip.cs' to see how to capture the image.
Display offscreen Google Earth on a panel?
[ "", "c#", ".net", "webbrowser-control", "google-earth-plugin", "" ]
I was recently doing a programming assignment that required us to implement in code a program specified by a UML diagram. At one point, the diagram specified that I had to create an anonymous JButton that displayed a count (starting at one) and decremented each time it was clicked. The JButton and its ActionListener both had to be anonymous. I came up with the following solution: ``` public static void main(String[] args) { JFrame f = new JFrame("frame"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(400, 400); f.getContentPane().add(new JButton() { public int counter; { this.counter = 1; this.setBackground(Color.ORANGE); this.setText(this.counter + ""); this.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { counter --; setText(counter + ""); } }); } }); f.setVisible(true); } ``` This adds an anonymous JButton, then adds another (inner) anonymous ActionListener to handle events and update the button's text as necessary. Is there a better solution? I'm pretty sure I can't declare an anonymous `JButton implements ActionListener ()`, but is there another more elegant way to achieve the same result?
I usually go something like this: ``` JPanel panel = new JPanel(); panel.add(new JButton(new AbstractAction("name of button") { public void actionPerformed(ActionEvent e) { //do stuff here } })); ``` AbstractAction implements ActionListener so this should satisfy the task. It can be bad practice to squish so many lines of code together, but if you're used to reading it then it can be quite elegant.
It's quite ugly, but you could do the following using the ActionListener method and an anonymous class: ``` f.getContentPane().add(new JButton(new AbstractAction("name of button") { private int counter = 0; public void actionPerformed(ActionEvent e) { ((JButton) e.getSource()).setText(Integer.toString(counter--)); } }) { { setText("1"); } }); ``` To make it easier to access the counter you could move it out to the top level of your class and access it from both places where setText is called.
Java anonymous class that implements ActionListener?
[ "", "java", "anonymous-class", "" ]
## Summary I've got a table of items that go in pairs. I'd like to self-join it so I can retrieve both sides of the pair in a single query. It's valid SQL (I think), the SQLite engine actually does accept it, but I'm having trouble getting DBIx::Class to bite the bullet. ## Minimal example ``` package Schema::Half; use parent 'DBIx::Class'; __PACKAGE__->load_components('Core'); __PACKAGE__->table('half'); __PACKAGE__->add_columns( whole_id => { data_type => 'INTEGER' }, half_id => { data_type => 'CHAR' }, data => { data_type => 'TEXT' }, ); __PACKAGE__->has_one(dual => 'Schema::Half', { 'foreign.whole_id' => 'self.whole_id', 'foreign.half_id' => 'self.half_id', # previous line results in a '=' # I'd like a '<>' }); package Schema; use parent 'DBIx::Class::Schema'; __PACKAGE__->register_class( 'Half', 'Schema::Half' ); package main; unlink 'join.db'; my $s = Schema->connect('dbi:SQLite:join.db'); $s->deploy; my $h = $s->resultset('Half'); $h->populate([ [qw/whole_id half_id data /], [qw/1 L Bonnie/], [qw/1 R Clyde /], [qw/2 L Tom /], [qw/2 R Jerry /], [qw/3 L Batman/], [qw/3 R Robin /], ]); $h->search({ 'me.whole_id' => 42 }, { join => 'dual' })->first; ``` The last line generates the following SQL: ``` SELECT me.whole_id, me.half_id, me.data FROM half me JOIN half dual ON ( dual.half_id = me.half_id AND dual.whole_id = me.whole_id ) WHERE ( me.whole_id = ? ) ``` I'm trying to use DBIx::Class join syntax to get a `<>` operator between `dual.half_id` and `me.half_id`, but haven't managed to so far. ## Things I've tried The documentation hints towards SQL::Abstract-like syntax. I tried writing the `has_one` relationship as such: ``` __PACKAGE__->has_one(dual => 'Schema::Half', { 'foreign.whole_id' => 'self.whole_id', 'foreign.half_id' => { '<>' => 'self.half_id' }, }); # Invalid rel cond val HASH(0x959cc28) ``` Straight SQL behind a stringref doesn't make it either: ``` __PACKAGE__->has_one(dual => 'Schema::Half', { 'foreign.whole_id' => 'self.whole_id', 'foreign.half_id' => \'<> self.half_id', }); # Invalid rel cond val SCALAR(0x96c10b8) ``` ## Workarounds and why they're insufficient to me I could get the correct SQL to be generated with a complex `search()` invocation, and no defined relationship. It's quite ugly, with (too) much hardcoded SQL. It has to imitated in a non-factorable way for each specific case where the relationship is traversed. I could work around the problem by adding an `other_half_id` column and joining with `=` on that. It's obviously redundant data. I even tried to evade said redundancy by adding it through a dedicated view (`CREATE VIEW AS SELECT *, opposite_of(side) AS dual FROM half...`) Instead of the database schema it's the code that got redundant and ugly, moreso than the `search()`-based workaround. In the end I wasn't brave enough to get it working. ## Wished SQL Here's the kind of SQL I'm looking for. Please note it's only an example: I really want it done through a relationship so I can use it as a `Half` ResultSet accessor too in addition to a `search()`'s `join` clause. ``` sqlite> SELECT * FROM half l JOIN half r ON l.whole_id=r.whole_id AND l.half_id<>r.half_id WHERE l.half_id='L'; 1|L|Bonnie|1|R|Clyde 2|L|Tom|2|R|Jerry 3|L|Batman|3|R|Robin ``` ## Side notes I really am joining to self in my full expanded case too, but I'm pretty sure it's not the problem. I kept it this way for the reduced case here because it also helps keeping the code size small. I'm persisting on the join/relationship path instead of a complex `search()` because I've got multiple uses for the association, and I didn't find any "one size fits all" search expression. **Late update** [Answering my own question](https://stackoverflow.com/questions/978442/how-do-i-make-dbixclass-join-tables-using-other-operators-than/6957507#6957507) two years later, it used to be a missing functionality that has since then been implemented.
For those still interested by this, it's finally been implemented as of 0.08192 or earlier. (I'm on 0.08192 currently) One correct syntax would be: ``` __PACKAGE__->has_one(dual => 'Schema::Half', sub { my $args = shift; my ($foreign,$self) = @$args{qw(foreign_alias self_alias)}; return { "$foreign.whole_id" => { -ident => "$self.whole_id" }, "$foreign.half_id" => { '<>' => { -ident => "$self.half_id" } }, } }); ``` Trackback: [DBIx::Class Extended Relationships on fREW Schmidt's blog](http://blog.afoolishmanifesto.com/archives/1582) where I got to first read about it.
I think that you could do it by creating a new type of relationship extending `DBIx::Class::Relationship::Base` but it doesn't seem incredibly well documented. Have you considered the possibility of just adding a convenience method on the resultset set for `Half` that does a `->search({}, { join => ... }` and returns the resultset from that to you? It's not introspectable like a relationship but other than that it works pretty much as well. It uses DBIC's ability to chain queries to your advantage.
How do I make DBIx::Class join tables using other operators than `=`?
[ "", "sql", "perl", "join", "dbix-class", "" ]
I have a thread that goes out and attempts to make a connection. In the thread, I make a call to a third party library. Sometimes, this call hangs, and never returns. On the UI thread, I want to be able to cancel the connection attempt by aborting the thread, which should abort the hung call to the third party library. I've called Thread.Abort, but have now read that Thread.Abort only works when control returns to managed code. I have observed that this is true, because the thread never aborts, and I've been sitting on Thread.Join for ten minutes now. What should I do with this hung thread? Should I just null the reference and move on? I'd like to be as clean as possible--
This function in your third-party library doesn't have a timeout *or* cancel function? If so, that's pretty poor design. There's not going to be any pretty solution here, methinks... Unfortunately, there's no way you're going to get around it, short of using the Win32 API to kill the thread manually, which is certainly *not* going to be clean. However, if this third-party library is not giving you any other options, it may be the thing to do. The [`TerminateThread`](http://pinvoke.net/default.aspx/kernel32/TerminateThread.html) function is what you'll want to use, but observe the warning! To get the thread ID to pass to this function, you have to use another Win32 API call (the `Thread` class doesn't expose it directly). The approach here will be to set the value of a volatile class variable to the result of [`GetCurrentThreadId`](http://pinvoke.net/default.aspx/kernel32/GetCurrentThreadId.html) at the start of the managed thread method, and then use this thread ID later to terminate the thread.
Random thought: I wonder if you could write a second assembly as a small console exe that does this communication... launch it with `Process.Start` and capture results either via the file system or by intercepting stdout. Then if it hangs you can kill the process. A bit harsh, maybe - and obviously it has overheads of spawning a process - but it should at least be possible to kill it.
How do you handle a thread that has a hung call?
[ "", "c#", ".net", "asp.net", "multithreading", "" ]
I trying to check if a date is this date or bigger inside my linq query with boolean. But it's not working like i want. This my code ``` public bool CheckMonth(int month) { if (month > System.DateTime.Now.Month) { return true; } else if (month == System.DateTime.Now.Month) { return true; } else { return false; } } public virtual IList<DateItem> GetThreeDateToList() { var data = new ScoutDataDataContext(); var q = (from d in data.DateDetails where d.Activate == 1 && CheckMonth(d.EndDate.Month) orderby d.Date.Date.Month descending select new DateItem { Title = d.Title, Date = d.Date.Date + " - " + d.EndDate.Date, Link = d.Link, }).Take(3); return q.ToList(); } ``` Anyone who nows a diffrent way?
What is it that you want to do? According to your text you want to find out whether a given date is today or later, but the code sample compares only the month (which means that June this year is the same as June last year). If you want to compare the date (including year and day), this comparison will do the job for you: ``` yourDate.Date >= DateTime.Now.Date ```
What is the provider here? LINQ-to-SQL? Objects? Entity Framework? (from the name, it looks like LINQ-to-SQL...) Indeed, database providers won't be able to process your method; you have a few options: * inline it: `&& d.EndDate.Month >= System.DateTime.Now.Month` * map it to a UDF (LINQ-to-SQL only) that accepts a `DateTime` The first is probably easier... if you get problems with it not recognising System.DateTime.Now.Month, then do that first into a variable.
Check if date is this date or bigger
[ "", "c#", "linq", "datetime", "" ]
Python's itertools implement a [chain](http://docs.python.org/library/itertools.html#itertools.chain) iterator which essentially concatenates a number of different iterators to provide everything from single iterator. Is there something similar in C++ ? A quick look at the boost libraries didn't reveal something similar, which is quite surprising to me. Is it difficult to implement this functionality?
Came across this question while investigating for a similar problem. Even if the question is old, now in the time of C++ 11 and boost 1.54 it is pretty easy to do using the [Boost.Range](http://www.boost.org/doc/libs/1_54_0/libs/range/doc/html/index.html) library. It features a [`join`-function](http://www.boost.org/doc/libs/1_54_0/libs/range/doc/html/range/reference/utilities/join.html), which can join two ranges into a single one. Here you might incur performance penalties, as the lowest common range concept (i.e. [Single Pass Range or Forward Range](http://www.boost.org/doc/libs/1_54_0/libs/range/doc/html/range/concepts/) etc.) is used as new range's category and during the iteration the iterator might be checked if it needs to jump over to the new range, but your code can be easily written like: ``` #include <boost/range/join.hpp> #include <iostream> #include <vector> #include <deque> int main() { std::deque<int> deq = {0,1,2,3,4}; std::vector<int> vec = {5,6,7,8,9}; for(auto i : boost::join(deq,vec)) std::cout << "i is: " << i << std::endl; return 0; } ```
In C++, an iterator usually doesn't makes sense outside of a context of the begin and end of a range. The iterator itself doesn't know where the start and the end are. So in order to do something like this, you instead need to chain together ranges of iterators - range is a (start, end) pair of iterators. Takes a look at the [boost::range](http://www.boost.org/doc/libs/1_39_0/libs/range/index.html) documentation. It may provide tools for constructing a chain of ranges. The one difference is that they will have to be the same type and return the same type of iterator. It may further be possible to make this further generic to chain together different types of ranges with something like any\_iterator, but maybe not.
Chaining iterators for C++
[ "", "c++", "iterator", "" ]
A project I'm working on interacts heavily with Subversion, using svnkit. Are there any examples on running a mock in-memory svn instance, to help facilitate testing etc? Cheers Marty
It's quite straightforward to create a temporary SVN repository on the filesystem to use during the test which you can delete immediately at the end of the test. You would use file:// protocol to access it. ``` import static org.junit.Assert.*; import java.io.*; import org.apache.commons.io.FileUtils; import org.junit.*; import org.tmatesoft.svn.core.*; public class SVNTest { private static final String path = "/tmp/testrepo"; SVNURL tgtURL; @Before public void setUp() throws Exception { SVNRepositoryFactoryImpl.setup(); tgtURL = SVNRepositoryFactory.createLocalRepository( new File( path ), true , false ); } @After public void tearDown() throws IOException { FileUtils.deleteDirectory(new File(path)); } @Test public void test() { fail("Not yet implemented"); } } ```
Why don't you just create a simple SVN repository with mock data ? It's just a few commands.
Mock svn instance for testing svnkit tests
[ "", "java", "tdd", "mocking", "svnkit", "" ]
I'm displaying a FlowDocument in a FlowDocumentReader with the ViewingMode="Scroll". If I use the wheel on my mouse, the document scrolls very slowly. I'd like to increase the scroll step. 1. I've tried to change the Scroll setting of my mouse in Control Panel, but that doesn't have any effect. I think that WPF ignores that setting for the FlowDocumentScrollViewer. 2. I've added a Scroll event on the FlowDocument and FlowDocumentReader, but that doesn't fire when I use the mouse wheel. 3. I've added a Loaded event on the FlowDocumentReader, got the ScrollViewer descendant, found the ScrollBar ("PART\_VerticalScrollBar") from the scroll viewer's template and adjusted the SmallChange & LargeChange properties. That also didn't have any effect. Anyone have any ideas?
We can modify this in a Control's MouseWheel event, like Sohnee sugested, but then it'd just be solved for one specific case, and you'd have to have access to the FlowDocumentReader, which if your usinging something like MVVM, you wont. Instead, we can create an attached property that we can then set on any element with a ScrollViewer. When defining our attached property, we also are going to want a PropertyChanged callback where we will perform the actual modifications to the scroll speed. I also gave my property a default of 1, the range of speed I'm going to use is .1x to 3x, though you could just as easily do something like 1-10. ``` public static double GetScrollSpeed(DependencyObject obj) { return (double)obj.GetValue(ScrollSpeedProperty); } public static void SetScrollSpeed(DependencyObject obj, double value) { obj.SetValue(ScrollSpeedProperty, value); } public static readonly DependencyProperty ScrollSpeedProperty = DependencyProperty.RegisterAttached( "ScrollSpeed", typeof(double), typeof(ScrollHelper), new FrameworkPropertyMetadata( 1.0, FrameworkPropertyMetadataOptions.Inherits & FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(OnScrollSpeedChanged))); private static void OnScrollSpeedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { } ``` Now that we have our Attached Property we need to handle the scrolling, to do this, in the OnScrollSpeedChanged we can handle the PreviewMouseWheel event. We want to hook into the PreviewMouseWheel, since it is a tunneling event that will occur before the ScrollViewer can handle the standard MouseWheel event. Currently, the PreviewMouseWheel handler is taking in the FlowDocumentReader or other thing that we bound it to, however what we need is the ScrollViewer. Since it could be a lot of things: ListBox, FlowDocumentReader, WPF Toolkit Grid, ScrollViewer, etc, we can make a short method that uses the VisualTreeHelper to do this. We already know that the item coming through will be some form of DependancyObject, so we can use some recursion to find the ScrollViewer if it exists. ``` public static DependencyObject GetScrollViewer(DependencyObject o) { // Return the DependencyObject if it is a ScrollViewer if (o is ScrollViewer) { return o; } for (int i = 0; i < VisualTreeHelper.GetChildrenCount(o); i++) { var child = VisualTreeHelper.GetChild(o, i); var result = GetScrollViewer(child); if (result == null) { continue; } else { return result; } } return null; } private static void OnScrollSpeedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { var host = o as UIElement; host.PreviewMouseWheel += new MouseWheelEventHandler(OnPreviewMouseWheelScrolled); } ``` Now that we can get the ScrollViwer we can finally modify the scroll speed. We'll need to get the ScrollSpeed property from the DependancyObject that is being sent through. Also, we can use our helper method to get the ScrollViewer that is contained within the element. Once we have these two things, we can get and modify the ScrollViewer's VerticalOffset. I found that dividing the MouseWheelEventArgs.Delta, which is the amount that the mouse wheel changed, by 6 gets approximately the default scroll speed. So, if we multiply that by our ScrollSpeed modifier, we can then get the new offset value. We can then set the ScrollViewer's VerticalOffset using the ScrollToVerticalOffset method that it exposes. ``` private static void OnPreviewMouseWheelScrolled(object sender, MouseWheelEventArgs e) { DependencyObject scrollHost = sender as DependencyObject; double scrollSpeed = (double)(scrollHost).GetValue(Demo.ScrollSpeedProperty); ScrollViewer scrollViewer = GetScrollViewer(scrollHost) as ScrollViewer; if (scrollViewer != null) { double offset = scrollViewer.VerticalOffset - (e.Delta * scrollSpeed / 6); if (offset < 0) { scrollViewer.ScrollToVerticalOffset(0); } else if (offset > scrollViewer.ExtentHeight) { scrollViewer.ScrollToVerticalOffset(scrollViewer.ExtentHeight); } else { scrollViewer.ScrollToVerticalOffset(offset); } e.Handled = true; } else { throw new NotSupportedException("ScrollSpeed Attached Property is not attached to an element containing a ScrollViewer."); } } ``` Now that we've got our Attached Property set up, we can create a simple UI to demonstrate it. I'm going to create a ListBox, and a FlowDocumentReaders so that we can see how the ScrollSpeed will be affected across multiple controls. ``` <UniformGrid Columns="2"> <DockPanel> <Slider DockPanel.Dock="Top" Minimum=".1" Maximum="3" SmallChange=".1" Value="{Binding ElementName=uiListBox, Path=(ScrollHelper:Demo.ScrollSpeed)}" /> <ListBox x:Name="uiListBox"> <!-- Items --> </ListBox> </DockPanel> <DockPanel> <Slider DockPanel.Dock="Top" Minimum=".1" Maximum="3" SmallChange=".1" Value="{Binding ElementName=uiListBox, Path=(ScrollHelper:Demo.ScrollSpeed)}" /> <FlowDocumentReader x:Name="uiReader" ViewingMode="Scroll"> <!-- Flow Document Content --> </FlowDocumentReader> </DockPanel> </UniformGrid> ``` Now, when run, we can use the Sliders to modify the scrolling speed in each of the columns, fun stuff.
Wow. The Rmoore's answer is brilliant, but a little sophisticated. I've simplified it a bit. For those who whether don't use MVVM or can place the code inside class that has access to a target element these 2 methods will be enough for you: Place this method to your extensions: ``` public static DependencyObject GetScrollViewer(this DependencyObject o) { // Return the DependencyObject if it is a ScrollViewer if (o is ScrollViewer) { return o; } for (int i = 0; i < VisualTreeHelper.GetChildrenCount(o); i++) { var child = VisualTreeHelper.GetChild(o, i); var result = GetScrollViewer(child); if (result == null) { continue; } else { return result; } } return null; } ``` Then place the second method to a class that has access to a target UI element and subscribe it to a "PreviewMouseWheel" event ``` private void HandleScrollSpeed(object sender, MouseWheelEventArgs e) { try { if (!(sender is DependencyObject)) return; ScrollViewer scrollViewer = (((DependencyObject)sender)).GetScrollViewer() as ScrollViewer; ListBox lbHost = sender as ListBox; //Or whatever your UI element is if (scrollViewer != null && lbHost != null) { double scrollSpeed = 1; //you may check here your own conditions if (lbHost.Name == "SourceListBox" || lbHost.Name == "TargetListBox") scrollSpeed = 2; double offset = scrollViewer.VerticalOffset - (e.Delta * scrollSpeed / 6); if (offset < 0) scrollViewer.ScrollToVerticalOffset(0); else if (offset > scrollViewer.ExtentHeight) scrollViewer.ScrollToVerticalOffset(scrollViewer.ExtentHeight); else scrollViewer.ScrollToVerticalOffset(offset); e.Handled = true; } else throw new NotSupportedException("ScrollSpeed Attached Property is not attached to an element containing a ScrollViewer."); } catch (Exception ex) { //Do something... } } ```
Adjust FlowDocumentReader's Scroll Increment When ViewingMode Set to Scroll?
[ "", "c#", "wpf", "scroll", "" ]