Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I want a "group by and count" command in sqlalchemy. How can I do this?
The [documentation on counting](http://www.sqlalchemy.org/docs/orm/tutorial.html#counting) says that for `group_by` queries it is better to use `func.count()`: ``` from sqlalchemy import func session.query(Table.column, func.count(Table.column)).group_by(Table.column).all() ```
If you are using `Table.query` property: ``` from sqlalchemy import func Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all() ``` If you are using `session.query()` method (as stated in miniwark's answer): ``` from sqlalchemy import func session.query(Table.column, func.count(Table.column)).group_by(Table.column).all() ```
Group by & count function in sqlalchemy
[ "", "python", "group-by", "count", "sqlalchemy", "" ]
I want to write a simple DSL in C#. Nothing too complicated. I'm looking for the .NET equivalent of Lex & Yacc. The easiest one I've found so far is GOLD Parser builder. The other choice is to use the lex & yacc available with F#, but I'm not keen to program in F# right now. If you have any suggestions for the .NET version of Lex or Yacc, I'd love to hear them! Thanks!
If you really want to stay in C#, I would recommend using the [Irony toolkit](http://www.codeplex.com/irony) - it allows you to specify grammars in C# code.
[ANTLR 3](http://www.antlr.org/) has a C# [target](http://www.antlr.org/wiki/display/ANTLR3/Antlr+3+CSharp+Target).
Parser builders for C#/.NET
[ "", "c#", ".net", "parsing", "" ]
Is there an easy way to read a single char from the console as the user is typing it in Java? Is it possible? I've tried with these methods but they all wait for the user to press *enter* key: ``` char tmp = (char) System.in.read(); char tmp = (char) new InputStreamReader(System.in).read (); char tmp = (char) System.console().reader().read(); // Java 6 ``` I'm starting to think that System.in is not aware of the user input until *enter* is pressed.
What you want to do is put the console into "raw" mode (line editing bypassed and no enter key required) as opposed to "cooked" mode (line editing with enter key required.) On UNIX systems, the 'stty' command can change modes. Now, with respect to Java... see [Non blocking console input in Python and Java](http://www.darkcoding.net/software/non-blocking-console-io-is-not-possible/). Excerpt: > If your program must be console based, > you have to switch your terminal out > of line mode into character mode, and > remember to restore it before your > program quits. There is no portable > way to do this across operating > systems. One of the suggestions is to use JNI. Again, that's not very portable. Another suggestion at the end of the thread, and in common with the post above, is to look at using [jCurses](http://sourceforge.net/projects/javacurses/).
You need to knock your console into raw mode. There is no built-in platform-independent way of getting there. [jCurses](http://sourceforge.net/projects/javacurses/) might be interesting, though. On a Unix system, this might work: ``` String[] cmd = {"/bin/sh", "-c", "stty raw </dev/tty"}; Runtime.getRuntime().exec(cmd).waitFor(); ``` [For example, if you want to take into account the time between keystrokes, here's sample code to get there.](https://web.archive.org/web/20161108171332/http://li367-160.members.linode.com/nikoschwarz/how-to-take-the-time-between-keystrokes-into-account-when-making-a-key-1/)
How to read a single char from the console in Java (as the user types it)?
[ "", "java", "input", "console", "" ]
I remember reading that static variables declared inside methods is not thread-safe. (See [What about the Meyer's singleton?](http://www.tilander.org/aurora2/Static_initialization_in_Cpp/index.html) as mentioned by [Todd Gardner](https://stackoverflow.com/questions/1052168/thread-safe-static-variables-without-mutexing/1052197#1052197)) ``` Dog* MyClass::BadMethod() { static Dog dog("Lassie"); return &dog; } ``` My library generates C++ code for end-users to compile as part of their application. The code it generates needs to initialize static variables in a thread-safe cross-platform manner. I'd like to use `boost::call_once` to mutex the variable initialization but then end-users are exposed to the Boost dependency. Is there a way for me to do this without forcing extra dependencies on end-users?
You are correct that static initialization like that isn't thread safe ([here](http://www.tilander.org/aurora2/Static_initialization_in_Cpp/index.html) is an article discussing what the compiler will turn it into) At the moment, there's no standard, thread safe, portable way to initialize static singletons. Double checked locking can be used, but you need potentially non-portable threading libraries (see a discussion [here](http://www.devarticles.com/c/a/Cplusplus/C-plus-in-Theory-Why-the-Double-Check-Lock-Pattern-Isnt-100-ThreadSafe/3/)). Here's a few options if thread safety is a must: 1. Don't be Lazy (loaded): Initialize during static initialization. It could be a problem if another static calls this function in it's constructor, since the order of static initialization is undefined(see [here](https://isocpp.org/wiki/faq/ctors#static-init-order)). 2. Use boost (as you said) or Loki 3. Roll your own singleton on your supported platforms (should probably be avoided unless you are a threading expert) 4. Lock a mutex everytime you need access. This could be very slow. Example for 1: ``` // in a cpp: namespace { Dog dog("Lassie"); } Dog* MyClass::BadMethod() { return &dog; } ``` Example for 4: ``` Dog* MyClass::BadMethod() { static scoped_ptr<Dog> pdog; { Lock l(Mutex); if(!pdog.get()) pdog.reset(new Dog("Lassie")); } return pdog.get(); } ```
Not sure whether this is what you mean or not, but you can remove the boost dependency on POSIX systems by calling `pthread_once` instead. I guess you'd have to do something different on Windows, but avoiding that is exactly why boost has a thread library in the first place, and why people pay the price of depending on it. Doing anything "thread-safely" is inherently bound up with your threads implementation. You have to depend on *something*, even if it's only the platform-dependent memory model. It is simply not possible in pure C++03 to assume anything at all about threads, which are outside the scope of the language.
Thread-safe static variables without mutexing?
[ "", "c++", "boost", "initialization", "thread-safety", "c++03", "" ]
As the user pans around a Google Map, a list of of currently visible markers is updated. This list contains up to 1000 items, and it slows down when several hundred li's are shown or hidden all at once. It's less than half a second, but it's getting annoying. An array (newLiList) contains the items which should now be visible. Another array (currentLiList) has the items which were previously visible. Both arrays contain the ids of the li's as indexes. ``` for (var i in newLiList) { if (currentLiList[i] != true) { $("ul#theList li#"+i).show(); } } for (var i in currentLiList) { if (newLiList[i] != true) { $("ul#theList li#"+i).hide(); } } ``` Is there a faster way to do this?
You could store the `<li>` elements in an array directly so you don't have to do hundreds of CSS selector lookups. Then instead of `$("ul#theList li#"+i)` you just do `liArray[i]`. FYI, `"ul#theList li#<i>"` is equivalent to just `"#<i>"` since element IDs are (supposed to be) unique. You don't need the extra context.
For every single .show() and .hide() function call, you're causing a redraw in the browser. Setting the whole list to display none before you change the list items will prevent the browser from having to recalculate the flow of the document every time, and then you could set the list back to block. Alternatively, if you don't want the flicker of the list disappearing, you could clone the list, make all the items hide that should hide, and then replace the old list with the new.
Javascript - Fastest way to show and hide lots of list items
[ "", "javascript", "jquery", "performance", "google-maps", "" ]
I was reading about the template name resolution [here](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=387). Just to get the feel of the things I replicated the code like this: ``` void f (char c) { std::cout<<"f(char)\n"; } template <class T> void g(T t) { f(1); f(T(1)); f(t); d++; } double d; void f(int n) { std::cout<<"f(int)\n"; } void test() { std::cout<<"First call\n"; g(1); std::cout<<"Second call\n"; g('a'); } int main() { test(); return 0; } ``` According to the article linked I should have a compiler error for the d++ statement. Also for the first call of g(1), I should have one call of f(char) followed by two calls of f(int) and for the second call I should get three calls of f(char). However, when I compiled this using Vs2008, it compiled fine without any errors. Also, the output was: > First call > > f(int) > > f(int) > > f(int) > > Second call > > f(int) > > f(char) > > f(char) I am now wondering which one is correct? The article I am linking to or the VS2008 output? Any clue which is correct?
> Also for the first call of g(1), I should have one call of f(char) followed by two calls of f(int) and for the second call I should get three calls of f(char). This is not the expected result with a Standard compliant compiler. Since both time you call it with a fundamental type, you will *not* get name lookup at the instantiation context for the function call. Name lookup at instantiation context only happens for argument dependent lookup (called *lookup using associated namespaces*). Both of `int` and `char` do not have argument dependent lookup, an thus *all* the function calls you do will call `f(char)` after you removed the `d++` line. --- Since i understand you won't possibly just believe me, here is the Standard quote, out of `14.6.4.2`: > For a function call that depends on a template parameter, if the function name is an unqualified-id but not a template-id, the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2) except that: > > * For the part of the lookup using unqualified name lookup (3.4.1), only function declarations with external linkage from the template definition context are found. > * For the part of the lookup using associated namespaces (3.4.2), only function declarations with external linkage found in either the template definition context or the template instantiation context are found. Note that the article uses a defective example of the Standard (at `14.6/9`) (and note that examples are non-normative: They can't change or state rules. Their purpose entirely is illustrative). The defect has been fixed and is incorporated into the upcoming Standard. See [this defect report](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#197). --- As you see, you will have to change from `int` / `char` to some user defined type (enums or classes) too see the effect of lookup in instantiation context. Read this answer [Order affects visibility](https://stackoverflow.com/questions/804217/function-template-declaration-order-affects-visibility-sometimes/804686#804686) for more information.
The article is correct about whether `d++` should compile. Visual C++ does not do two-phase template instantiation - it does pretty much all its parsing at instatiation time. Gcc and [Comeau](http://www.comeaucomputing.com/tryitout/) will give the correct error and will call the correct `f`.
Name resolution in templates
[ "", "c++", "templates", "" ]
I need to do a numeric calculation based on CSS properties. However, when I use this to get info: ``` $(this).css('marginBottom') ``` it returns the value '10px'. Is there a trick to just getting the number part of the value no matter whether it is `px` or `%` or `em` or whatever?
This will clean up all non-digits, non-dots, and not-minus-sign from the string: ``` $(this).css('marginBottom').replace(/[^-\d\.]/g, ''); ``` UPDATED for negative values
``` parseInt($(this).css('marginBottom'), 10); ``` [`parseInt`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt) will automatically ignore the units. For example: ``` var marginBottom = "10px"; marginBottom = parseInt(marginBottom, 10); alert(marginBottom); // alerts: 10 ```
How to get just numeric part of CSS property with jQuery?
[ "", "javascript", "jquery", "css", "parsing", "" ]
I've got a class which inherits from a `List<MagicBean>`. It works well and as expected in all respects except one: when I add the `[DebuggerDisplay]` attribute. Even though looking at List has its as `[DebuggerDisplay("Count = {Count}")]`, if I so much as copy and paste that onto mine, I lose the ability to look directly at all of the MagicBeans I have without drilling into base->private members while debugging. How do I get the best of both worlds? IE: Custom value in the value column, and Visual Studio not hiding my magic beans from me?
You can get the effect you need by using the [DebuggerTypeProxy](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggertypeproxyattribute.aspx) attribute. You need to create a class to make a debug "visualisation" of your inherited list: ``` internal sealed class MagicBeanListDebugView { private List<MagicBean> list; public MagicBeanListDebugView(List<MagicBean> list) { this.list = list; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public MagicBean[] Items{get {return list.ToArray();}} } ``` You can then declare this class to be used by the debugger for displaying your class, along with the `DebuggerDisplay` attribute: ``` [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(MagicBeanListDebugView))] public class MagicBeanList : List<MagicBean> {} ``` This will give you the "Count = 3" message when you hover over an instance of your inherited list in Visual Studio, and a view of the items in the list when you expand the root node, without having to drill down into the base properties. Using `ToString()` to specifically get debug output is not a good approach, unless of course you are already overriding `ToString()` for use in your code elsewhere, in which case you can make use of it.
After looking at the "[Using DebuggerDisplay Attribute](http://msdn.microsoft.com/en-us/library/x810d419.aspx)" article on MSDN, they suggest that you could override the ToString() function of your class as an alternate option rather than using DebuggerDisplay attribute. Overriding the ToString() method won't hide your beans either. > If a C# object has an overridden > ToString(), the debugger will call the > override and show its result instead > of the standard {}. **Thus, if > you have overridden ToString(), you do > not have to use DebuggerDisplay.** If > you use both, the DebuggerDisplay > attribute takes precedence over the > ToString() override. Are you able to override the ToString() method on your class or are you using it for other purposes? I don't know if you've already considered this or not, but I thought I'd suggest it just incase it helps. :-) For completeness so anyone else can quickly mock it up; here's a quick example that I made: ``` namespace StackOverflow { //broken BeanPouch class that uses the DebuggerDisplay attribute [System.Diagnostics.DebuggerDisplay("Count = {Count}")] class BrokenBeanPouch : List<MagicBean> { } //working BeanPouch class that overrides ToString class WorkingBeanPouch : List<MagicBean> { public override string ToString() { return string.Format("Count = {0}", this.Count); } } class Program { static WorkingBeanPouch myWorkingBeans = new WorkingBeanPouch() { new MagicBean() { Value = 4.99m }, new MagicBean() { Value = 5.99m }, new MagicBean() { Value = 3.99m } }; static BrokenBeanPouch myBrokenBeans = new BrokenBeanPouch() { new MagicBean() { Value = 4.99m }, new MagicBean() { Value = 5.99m }, new MagicBean() { Value = 3.99m } }; static void Main(string[] args) { //break here so we can watch the beans in the watch window System.Diagnostics.Debugger.Break(); } } class MagicBean { public decimal Value { get; set; } } } ```
How to make [DebuggerDisplay] respect inherited classes or at least work with collections?
[ "", "c#", "visual-studio", "visual-studio-2008", "debugging", "visual-studio-2008-sp1", "" ]
Assuming I have the following two JQuery functions - The first, which works: ``` $("#myLink_931").click(function () { $(".931").toggle(); }); ``` and the second, which doesn't work: ``` $("#myLink_931").click(function () { var class_name = $(this).attr("id").split('_')[1]; $("."+class_name).toggle(); }); ``` I want to replace the first with the second, which is more generalizable, but can't find any obvious syntactical problem with the second which might be preventing it from working. My guess is there's a problem with the syntax: ``` "."+class_name ``` Is this bad syntax?
They work the same. **[Working Demo](http://jsbin.com/inuko)**
This is what debuggers are for. Step through the code and make sure class\_name is calculated as you expect. The debugger should let you view the result of "."+class\_name as well.
Shoud these two JQuery functions produce the same behavior?
[ "", "javascript", "jquery", "" ]
I am interested in learning how a database engine works (i.e. the internals of it). I know most of the basic data structures taught in CS (trees, hash tables, lists, etc.) as well as a pretty good understanding of compiler theory (and have implemented a very simple interpreter) but I don't understand how to go about writing a database engine. I have searched for tutorials on the subject and I couldn't find any, so I am hoping someone else can point me in the right direction. Basically, I would like information on the following: * How the data is stored internally (i.e. how tables are represented, etc.) * How the engine finds data that it needs (e.g. run a SELECT query) * How data is inserted in a way that is fast and efficient And any other topics that may be relevant to this. It doesn't have to be an on-disk database - even an in-memory database is fine (if it is easier) because I just want to learn the principals behind it. Many thanks for your help.
If you're good at reading code, studying SQLite will teach you a whole boatload about database design. It's small, so it's easier to wrap your head around. But it's also professionally written. [SQLite 2.5.0 for Code Reading](https://github.com/davideuler/SQLite-2.5.0-for-code-reading) <http://sqlite.org/>
The answer to this question is a huge one. expect a PHD thesis to have it answered 100% ;) but we can think of the problems one by one: * How to store the data internally: you should have a data file containing your database objects and a caching mechanism to load the data in focus and some data around it into RAM assume you have a table, with some data, we would create a data format to convert this table into a binary file, by agreeing on the definition of a column delimiter and a row delimiter and make sure such pattern of delimiter is never used in your data itself. i.e. if you have selected <\*> for example to separate columns, you should validate the data you are placing in this table not to contain this pattern. you could also use a row header and a column header by specifying size of row and some internal indexing number to speed up your search, and at the start of each column to have the length of this column like "Adam", 1, 11.1, "123 ABC Street POBox 456" you can have it like <&RowHeader, 1><&Col1,CHR, 4>Adam<&Col2, num,1,0>1<&Col3, Num,2,1>111<&Col4, CHR, 24>123 ABC Street POBox 456<&RowTrailer> * How to find items quickly try using hashing and indexing to point at data stored and cached based on different criteria taking same example above, you could sort the value of the first column and store it in a separate object pointing at row id of items sorted alphabetically, and so on * How to speed insert data I know from Oracle is that they insert data in a temporary place both in RAM and on disk and do housekeeping on periodic basis, the database engine is busy all the time optimizing its structure but in the same time we do not want to lose data in case of power failure of something like that. so try to keep data in this temporary place with no sorting, append your original storage, and later on when system is free resort your indexes and clear the temp area when done good luck, great project.
How to write a simple database engine
[ "", "sql", "database", "theory", "database-engine", "" ]
I want to reset an object. Can I do it in the following way? ``` anObject->~AnObject(); anObject = new(anObject) AnObject(); // edit: this is not allowed: anObject->AnObject(); ``` This code is obviously a subset of typical life cycle of an object allocated by in placement new: ``` AnObject* anObject = malloc(sizeof(AnObject)); anObject = new (anObject) AnObject(); // My step 2. // ... anObject->~AnObject(); // My step 1. free(anObject) // EDIT: The fact I used malloc instead of new doesn't carry any meaning ``` The only thing that's changed is the order of constructor and destructor calls. So, why in the [following FAQ](http://yosefk.com/c++fqa/dtor.html#fqa-11.9) all the threatening appear? > [11.9] But can I explicitly call a > destructor if I've allocated my object > with new? > > FAQ: You can't, unless the object was > allocated with placement new. Objects > created by new must be deleted, which > does two things (remember them): calls > the destructor, then frees the memory. > > FQA: Translation: delete is a way to > explictly call a destructor, but it > also deallocates the memory. You can > also call a destructor without > deallocating the memory. It's ugly and > useless in most cases, but you can do > that. The destructor/constructor call is obviously normal C++ code. Guarantees used in the code directly result from the in placement new guarantees. It is **the core of the standard**, it's rock solid thing. How can it be called "dirty" and be presented as something unreliable? Do you think it's possible, that the in-placement and non-in-placement implementation of new are different? I'm thinking about some sick possibility, that the regular new can for example put size of the memory block allocated before the block, which in-placement new obviously would not do (because it doesn't allocate any memory). This could result in a gap for some problems... **Is such new() implementation possible?**
Don't get sucked in by the FQA troll. As usual he gets the facts wrong. You can certainly call the destructor directly, for all objects whether they are created with placement new or not. Ugly is in the eye of the beholder, it is indeed rarely needed, but the only hard fact is that both memory allocation and object creation must be balanced. "Regular" new/delete simplifies this a bit by tying memory allocation and object creation together, and stack allocation simplifies it even further by doing both for you. However, the following is perfectly legal: ``` int foo() { CBar bar; (&bar)->~CBar(); new (&bar) CBar(42); } ``` Both objects are destroyed, and the stack memory is automatically recycled too. yet unlike the FQA claims, the first call of the destructor is not preceded by placement new.
Why not implement a Clear() method, that does whatever the code in the body of the destructor does? The destructor then just calls Clear() and you call Clear() directly on an object to "reset it". Another option, assuming your class supports assignment correctly: ``` MyClass a; ... a = MyClass(); ``` I use this pattern for resetting std::stack instances, as the stack adaptor does not provide a clear function.
Call destructor and then constructor (resetting an object)
[ "", "c++", "memory-management", "new-operator", "" ]
I've started to use mysql\_data\_seek () as an easy way to roll pagination transparently into my database class by shifting the pointer and reading the current 'page'. What are the performance implications of doing this? I am only reading the data I need into PHP itself, but in most cases the SELECT covers the whole table - is this bad, and will I hit problems with massive tables?
If I understand your idea you select *all* records in the table, then skip the first n\*page records with mysql\_data\_seek() in order to "get to" the current page and read n records. If you have a lot of records you might not want to do that because <http://php.net/mysql_data_seek> says: > Note: The function mysql\_data\_seek() can be used in conjunction only with mysql\_query(), not with mysql\_unbuffered\_query() The difference between mysql\_query() and the unbuffered version is that mysql\_query() returns only after the whole result set has been copied from the MySQL server to the PHP process' memory while after the unbuffered version each mysql\_fetch\_xyz() has to receive the next record from the server. If you have a lot of records and you have to transfer *all* of them for *each single* request that sounds a bit suboptimal. I guess you want to do this to get the total amount of records *and* the current subset with only one query. With MySQL you can have both, a LIMIT clause and the total number of records (that would be in the result set without the LIMIT clause), ```` ``` SELECT SQL_CALC_FOUND_ROWS id FROM foo ORDER BY id LIMIT 20,10 ``` ```` see <http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows>
I imagine that using the appropriate `LIMIT` clause in your `SELECT` statement is more efficient (it will definitely save lookup time atleast), but I don't know how the internals of how `mysql_data_seek` works, specifically if it reads `x` records and discards them, or whether it works like filesystem `seek` commands do (sends a signal to MySQL telling it to skip sending the next `x` records). If it works the first way, I'd expect a minimal speedup doing it this way. If it was the later way, I'd expect a speedup, but not as much as simply using the appropriate `LIMIT` clause.
Performance implications of mysql_data_seek
[ "", "php", "performance", "" ]
So I am baffled by this one. I have a function that is responsible for a non-secure item warning message to appear when viewing my web page from with IE6 on SSL. If I comment out the entire function the message goes way. If I just comment out the one method call it remains. What is really driving me nuts is if I remove all of the logic from within the method.... the message remains???!!! I literally have to comment out the whole method including the signature. The method contains JQuery library logic but I don't see why that would matter when all of the function logic is commented except for the signature. Has anyone seen this before? Here is the function: ``` function styleNavigationCorners() { if (!($.browser.msie && $.browser.version.substr(0, 1) == '6')) { $(".DecisionPointTitle").corner({ tl: { radius: 8 }, tr: { radius: 8 }, bl: { radius: 8 }, br: { radius: 8 }, antiAlias: true, autoPad: false }); $(".DecisionPointHeadline").corner({ tl: { radius: 8 }, tr: { radius: 8 }, bl: false, br: false, antiAlias: true, autoPad: false }); $("#NavigationFooter").corner({ bl: { radius: 8 }, br: { radius: 8 }, tl: false, tr: false, antiAlias: true, autoPad: false }); } } ``` This still gives me the non-secure warning? : ``` function styleNavigationCorners() { // if (!($.browser.msie && $.browser.version.substr(0, 1) == '6')) { // $(".DecisionPointTitle").corner({ // tl: { radius: 8 }, // tr: { radius: 8 }, // bl: { radius: 8 }, // br: { radius: 8 }, // antiAlias: true, // autoPad: false // }); // $(".DecisionPointHeadline").corner({ // tl: { radius: 8 }, // tr: { radius: 8 }, // bl: false, // br: false, // antiAlias: true, // autoPad: false // }); // $("#NavigationFooter").corner({ // bl: { radius: 8 }, // br: { radius: 8 }, // tl: false, // tr: false, // antiAlias: true, // autoPad: false // }); // } } ``` I have searched for duplicate function signatures have found none. Can anyone help? Thanks! -Nick
Can I assume you are using the [curvy corners jquery wrap](http://www.aspcode.net/JQuery-Curvy-Corners.aspx)? If so then you will find the following issue with that library. It runs the following on ie6 ``` document.write("<script id='__ie_onload' defer='defer' src='javascript:void(0)'><\/script>"); ``` Setting the src to void will cause the non secure warning. IIRC you could try changing this to javascript:false - again another hack or even include a blank file on the server and point to that to avoid the warning for sure. Whatever you opt for youll have to change the source library. Just as an aside - Do you really need those corners? 26k minified of js is a hefty price to pay!
IE6 contains a bug here. JavaScript-protocol URIs are treated as insecure, and this results in a mixed content warning when they are encountered. See my answer here: [How To Tell What Files IE Thinks Are "nonsecure"?](https://stackoverflow.com/questions/96382/how-to-tell-what-files-ie-thinks-are-nonsecure/1022020#1022020) for a tool that will help you verify that it's the JavaScript-protocol URI causing the issue.
JavaScript Method results in Non Secure Item IE6
[ "", "javascript", "jquery", "internet-explorer", "ssl", "https", "" ]
I am on python 2.6 for Windows. I use os.walk to read a file tree. Files may have non-7-bit characters (German "ae" for example) in their filenames. These are encoded in Pythons internal string representation. I am processing these filenames with Python library functions and that fails due to wrong encoding. How can I convert these filenames to proper (unicode?) python strings? I have a file "d:\utest\ü.txt". Passing the path as unicode does not work: ``` >>> list(os.walk('d:\\utest')) [('d:\\utest', [], ['\xfc.txt'])] >>> list(os.walk(u'd:\\utest')) [(u'd:\\utest', [], [u'\xfc.txt'])] ```
If you pass a Unicode string to `os.walk()`, you'll get Unicode results: ``` >>> list(os.walk(r'C:\example')) # Passing an ASCII string [('C:\\example', [], ['file.txt'])] >>> >>> list(os.walk(ur'C:\example')) # Passing a Unicode string [(u'C:\\example', [], [u'file.txt'])] ```
I was looking for a solution for Python 3.0+. Will put it up here incase someone else needs it. ``` rootdir = r'D:\COUNTRY\ROADS\' fs_enc = sys.getfilesystemencoding() for (root, dirname, filename) in os.walk(rootdir.encode(fs_enc)): # do your stuff here, but remember that now # root, dirname, filename are represented as bytearrays ```
Convert python filenames to unicode
[ "", "python", "unicode", "" ]
I was wondering how I can get the graphics card model/brand from code particularly from DirectX 9.0c (from within C++ code).
At runtime, you can query the device model and vendor: * In OpenGL, use the command glGetString(GL\_VENDOR) or GL\_RENDERER or GL\_VERSION to get the information you're after. * In DirectX 9, it appears the info is in the Microsoft config system, and is queried from the device database. It's section 3 of this document, which also has example code: <http://msdn.microsoft.com/en-us/library/bb204848(VS.85).aspx> Using the same system you can get such information as the amount of ram the video card has, the driver number, etc.
The easiest way in DirectX is through [IDirect3D9::GetAdapterIdentifier](http://msdn.microsoft.com/en-us/library/windows/desktop/bb174317%28v=vs.85%29.aspx). Just create a [D3DADAPTER\_IDENTIFIER9](http://msdn.microsoft.com/en-us/library/windows/desktop/bb172505%28v=vs.85%29.aspx) object, pass a pointer to it to GetAdapterIdentifier. DirectX fills out the graphics card description as a string in the Description field. It also includes information on which display device the card is, and what driver version you have. You get something like this: * Description: "NVIDIA GeForce GTX 570" * Device: "\.\DISPLAY1" * Driver: "nvd3dum.dll"
Get the graphics card model?
[ "", "c++", "graphics", "model", "directx", "intel", "" ]
I'm building a website where many of the pages are very interactive without having any communication with the web server. Basically, a page represents a kind of DHTML interface, where users can click on various *divs* to move them around and perform other actions. In the end, the user is able to save the "state" of all divs on the screen and only then the HTTP request is sent to the server. I'm trying to use MVC approach (via CodeIgniter) and these actions are mostly handled by JQuery and a few custom JavaScript functions I wrote. I have a lot of JavaScript code that covers the logic. Currently, all the code is in the *View* of CodeIgniter's MVC, but I somehow feel that is wrong. I'm thinking I should move some of the code to some kind of controller, but a JavaScript one instead of PHP controller provided by CI. Should I create some kind of a parallel MVC in JavaScript?
If you end up having lot's of Javascript code and most of the functionality running client side, server side cannot help much. You need to have your JQuery and other JavaScript code organized well. Not sure if there are any MVC frameworks existing specifically for JavaScript. Did one of my own years ago when had to work with the project with huge loads of JavaScript. However you don't necessarily need to do full blown MVC, just having simple model in place and handlers (controllers) for the logic in place will help you a lot. But if you code relies on JavaScript it's a biiiig mistake if you don't really thing how you construct your JavaScript software.
As an aside, another thing you have to look out for with implementing business logic code in JavaScript is that the code you're running runs outside the your application's trust boundary -- that is, because it runs on each client, it is technically possible for a client to send you bad data. That can be a big problem, especially if you have authorization logic in the front end. Not knowing what your code is, I will say that you want to take the code which requires a high level of trust out of JS entirely. Save JS for UI sugar. If you do that, it's entirely acceptable to have lots of JS code in your "view" -- as long as it pertains just to manipulating the client-side presentation. But yes, on the other hand, I do see how you could view this effort as a model-view-controller(Client)-controller(Server) pattern. But I think that's OK...
Where to place heavy jQuery code in web development MVC pattern?
[ "", "php", "jquery", "codeigniter", "model-view-controller", "" ]
I'm very familiar with using Enums in other languages, but I'm having some difficulty in Java with a particular use. The Sun documentation for Enums boldly states: > "Java programming language enums are far more powerful than their counterparts in other languages, which are little more than glorified integers." Well, that's dandy, but I kind of need to have a constant datatype representation for each of the Enums, for comparison reasons in a switch statement. The situation is as follows: I'm constructing nodes which will represent a given space, or 'slot' in a maze graph, and these nodes must be able to be constructed from a 2D integer array which represents the maze. Here's what I've got for the MazeNode class, which is currently where the problem is (the switch statement barks): **NOTE: I know this code does not function, due to the dynamic item in the case statement. It is there to illustrate what I'm after.** ``` public class MazeNode { public enum SlotValue { empty(0), start(1), wall(2), visited(3), end(9); private int m_representation; SlotValue(int representation) { m_representation = representation; } public int getRepresentation() { return m_representation; } } private SlotValue m_mazeNodeSlotValue; public MazeNode(SlotValue s) { m_mazeNodeSlotValue = s; } public MazeNode(int s) { switch(s) { case SlotValue.empty.getRepresentation(): m_mazeNodeSlotValue = SlotValue.start; break; case SlotValue.end.getRepresentation(): m_mazeNodeSlotValue = SlotValue.end; break; } } public SlotValue getSlotValue() { return m_mazeNodeSlotValue; } } ``` So the code complains on the switch statement with "case expressions must be constant expressions" -- I can see why the compiler might have trouble, since technically they are dynamic, but I'm not sure what approach to take to resolve this. Is there a better way? The bottom line is I need the Enum to have corresponding integer values for comparison against the incoming 2D array of integers in the program.
You can use something like this: ``` import java.util.HashMap; import java.util.Map; public class MazeNode { public enum SlotValue { empty(0), start(1), wall(2), visited(3), end(9); protected int m_representation; SlotValue(int representation) { m_representation = representation; } private static final Map<Integer, SlotValue> mapping = new HashMap<Integer, SlotValue>(); static { for (SlotValue slotValue : SlotValue.values()) { mapping.put(slotValue.m_representation, slotValue); } } public static SlotValue fromRepresentation(int representation) { SlotValue slotValue = SlotValue.mapping.get(representation); if (slotValue == null) // throw your own exception throw new RuntimeException("Invalid representation:" + representation); return slotValue; } } private SlotValue m_mazeNodeSlotValue; public MazeNode(SlotValue s) { m_mazeNodeSlotValue = s; } public MazeNode(int s) { m_mazeNodeSlotValue = SlotValue.fromRepresentation(s); } public SlotValue getSlotValue() { return m_mazeNodeSlotValue; } public static void main(String[] args) { MazeNode m = new MazeNode(2); System.out.println(m.getSlotValue()); m = new MazeNode(9); System.out.println(m.getSlotValue()); } } ```
An alternate approach to the other suggestions is that you can enter the values in the enum constructors rather than having to loop over afterwards: ``` public class MazeNode { private static final Map<Integer, SlotValue> mapping = new HashMap<Integer, SlotValue>(); enum SlotValue { empty(0),start(1),wall(2),visited(3),end(9); private final int m_representation; SlotValue(int representation) { m_representation = representation; mapping.put(Integer.valueOf(representation), this); } } SlotValue getSlotValue(int representation) { return mapping.get(Integer.valueOf(representation)); } } ```
Switch Statement for Enum Value Representations in Java
[ "", "java", "enums", "switch-statement", "" ]
I was reading litb's question about SFINAE [here](https://stackoverflow.com/questions/822059/sfinae-with-invalid-function-type-or-array-type-parameters) and I was wondering exactly what his code is declaring. A simpler (without the templates) example is below: ``` int (&a())[2]; ``` What exactly is that declaring? What is the role of the &? To add to my confusion, if I declare the following instead ``` int b()[2]; ``` I get an error about declaring a function that returns an array, while the first line has no such error (therefore, one would think the first declaration is **not** a function). However, if I try to assign a ``` a = a; ``` I get an error saying I'm attempting to assign the function a... so now it **is** a function. What exactly is this thing?
There's these awesome programs called cdecl and c++decl. They're very helpful for figuring out complicated declarations, especially for the byzantine forms that C and C++ use for function pointers. ``` tyler@kusari ~ $ c++decl Type `help' or `?' for help c++decl> explain int (&a())[2] declare a as function returning reference to array 2 of int c++decl> explain int b()[2] declare b as function returning array 2 of int ``` a returns a reference, b does not.
For future reference, you may find this link helpful when you have a particularly difficult C/C++ declaration to decipher: [How To Read C Declarations](http://www.antlr.org/wiki/display/CS652/How+To+Read+C+Declarations) For completeness, I will repeat what others have said to directly answer your question. ``` int (&a())[2]; ``` ...declares *a* to be a zero-argument function which returns a reference to an integer array of size 2. (Read the basic rules on the link above to have a clear understanding of how I came up with that.) ``` int b()[2]; ``` ...declares *b* to be a zero-argument function which returns an integer array of size two. Hope this helps.
Does this line declare a function? C++
[ "", "c++", "function-declaration", "" ]
I am writing a file splitting program, to assist with using large files with iPod notes. I want to use tmpfile() in cstdio but it returns a file\* not an fstream object. I know it's not possible in standard C++ but does anyone know any libraries that work well with the standard that have the ability to convert a FILE\* to an std::fstream object? Or, if not is tmpfile() functionality available in the standard, or another library? Thanks! My OS is Windows XP and I use either Dev-C++ 4.9.9.2 or MS Visual Studio 2008 as my compiler.
If all you want is a temporary file, use [tmpnam()](http://cplusplus.com/reference/clibrary/cstdio/tmpnam/) instead. That returns char\* name that can be used for a temporary file, so just open a fstream object with that name. Something like: ``` #include <cstdio> #include <fstream> ... char name[L_tmpnam]; tmpnam(name); //also could be: //char *name; //name = tmpnam(NULL); std::fstream file(name); ``` You do have to delete the file yourself, though, using [remove()](http://cplusplus.com/reference/clibrary/cstdio/remove/) or some other method.
You can use the benefits of c++ streams by pumping your data via the << syntax into a std::stringstream and later write it the .str().c\_str() you get from it via the the C-API to the FILE\*. ``` #include <sstream> #include <cstdio> #include <string> using namespace std; int main() { stringstream ss; ss << "log start" << endl; // ... more logging FILE* f_log = fopen("bar.log", "w"); string logStr = ss.str(); fwrite(logStr.c_str(), sizeof(char), logStr.size(), f_log); fclose(f_log); return 0; } ```
mixing C and C++ file operations
[ "", "c++", "c", "" ]
I wanted to ask whether you know about some free C# libraries (dlls) that calculate CK metrics (mainly Cyclomatic Complexity). I would need that for a project I'm planning to do. I know that there are already some finished solutions that calculate CK metrics and display it to you in various forms, but what I would need is one that I could use from within my application. So before starting and writing one myself I first wanted to ask you. Thanks
**DrivenMetrics** is a open source C# command line tool. The core functionalities are isolated from the command line console client as a library (Core project is available [here](http://github.com/garrensmith/DrivenMetrics/tree/master/src/Core/)). Even if quite simple, it may fit your need: it's free, counts the the number of lines and calculates the cyclomatic complexity (number of potential code paths) of methods. This is performed through direct analysis of the IL thanks to [Mono.Cecil](http://www.mono-project.com/Cecil) (the same library NDepend relies on). This allows the analysis to be performed on assemblies built from code written in C#, VB.Net,... * The project has been announced [here](http://garrens.drivensoftware.net/post/Net-Coding-metric-released.aspx). * The code source is available on [github](http://github.com/garrensmith/DrivenMetrics). * A packaged release is also [available](http://github.com/garrensmith/DrivenMetrics/downloads). * It works both on Windows and Mono. --- **UPDATE:** Another option would be the *amazing* **Gendarme**, a static analysis tool from the **Mono** project. As a sample of usage, the code below display the cyclomatic complexity of every method in an assembly. ``` ModuleDefinition module = ModuleDefinition.ReadModule(fullPathToTheAssembly); foreach (var type in module.Types) { foreach (var me in type.Methods) { if (!me.HasBody || me.IsGeneratedCode() || me.IsCompilerControlled) continue; var r = AvoidComplexMethodsRule.GetCyclomaticComplexity(me); Console.WriteLine("{0}: {1}", me.ToString(), r); } } ``` * The project is described [here](http://www.mono-project.com/Gendarme) * The code source is available on [github](https://github.com/mono/mono-tools/tree/master/gendarme) * Packaged releases are also [available](https://github.com/spouliot/gendarme/downloads) * It works both on Windows and Mono
I am using [SourceMonitor](http://www.campwoodsw.com/sourcemonitor.html), which is a nice freeware app that measures code complexity and other metrics for a variety of languages including C#. We drive it from the command line to produce XML output, then we use LINQ to XML to extract and sort the data we are interested in. We then use NVelocity to create HTML reports. I know its not a managed library, but you might find it can do what you need.
Free C# metrics calculation library (DLL)
[ "", "c#", "code-metrics", "" ]
I have a Winforms dialog that contains among other controls a TextBox that allows a single line of input. I would like to allow the user to be able to press Ctrl-Backspace to delete an entire word. This is not the default behaviour with the out-of-the-box TextBox; I get a *rectangle* character, rather than having the word deleted. I have confirmed the `ShortcutsEnabled` property is set to `True`. I did find that I can use a RichTextBox rather than a TextBox to get the behaviour I want. The problem with this is that the apperance of the RichTextBox (border in particular) is different from that of the TextBox, and I don't need or want the ability to mark up text. So my question is how to best handle this situation? Is there some property on the TextBox that I am missing? Or is it best to use the RichTextBox, update the appearance so it is consistent, and disable markup of the text? I am relatively happy to write the code to handle the KeyDown and KeyPress events explicity if there is no better way, but thought it was worth checking first.
**/\* Update 2: Please look at <https://positivetinker.com/adding-ctrl-a-and-ctrl-backspace-support-to-the-winforms-textbox-control> as it fixes all issues with my simple solution \*/** */\* Update 1: Please look also at Damir’s answer below, it’s probably a better solution :) \*/* I would simulate Ctrl+Backspace by sending Ctrl+Shift+Left and Backspace to the TextBox. The effect is virtually the same, and there is no need to manually process control’s text. You can achieve it using this code: ``` class TextBoxEx : TextBox { protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == (Keys.Control | Keys.Back)) { SendKeys.SendWait("^+{LEFT}{BACKSPACE}"); return true; } return base.ProcessCmdKey(ref msg, keyData); } } ``` You can also modify the app.config file to force the SendKey class to use newer method of sending keys: ``` <configuration> <appSettings> <add key="SendKeys" value="SendInput" /> </appSettings> </configuration> ```
Old question, but I just stumbled upon an answer that doesn't require any extra code. **Enable autocompletion** for the textbox and CTRL-Backspace should work as you want it to. CTRL-Backspace deleting whole word to the left of the caret seems to be a '*rogue feature*' of the autocomplete handler. That's why enabling autocomplete fixes this issue. [Source 1](https://superuser.com/a/332034) | [Source 2](https://devblogs.microsoft.com/oldnewthing/20071011-00/?p=24823) -- You can enable the auto complete feature with setting the `AutoCompleteMode` and `AutoCompleteSource` to anything you like (for instance; `Suggest` and `RecentlyUsedList`)
Winforms Textbox - Using Ctrl-Backspace to Delete Whole Word
[ "", "c#", "winforms", "textbox", "" ]
I'm trying to make a function that holds state but is called with foo(). Is it possible?
I believe this is what you want: ``` var foo = (function () { var state = 0; return function () { return state++; }; })(); ``` Or, following [the Wikipedia example](http://en.wikipedia.org/wiki/Function_object): ``` var makeAccumulator = function (n) { return function (x) { n += x; return n; }; }; var acc = makeAccumulator(2); alert(acc(2)); // 4 alert(acc(3)); // 7 ``` JavaScript is one of those languages that has, IMHO, excellent support for functions as first class citizens.
Since Javascript functions are first-class objects, this is the way to do it: ``` var state = 0; var myFunctor = function() { alert('I functored: ' + state++);}; ``` The `state` variable will be available to the `myFunctor` function in its local closure. (Global in this example). The other answers to this question have the more sophisticated examples. There's no equivalent to just "implementing operator ()" on some existing object, though.
Is it possible to make a functor in JavaScript?
[ "", "javascript", "functional-programming", "functor", "" ]
I recently had an idea to create my own String class to make using PHP's functions easier. Instead of `strlen($str)` I write `$str->length()`. Makes it easier to remember parameter orders in certain functions, like `substr`. I ran some timing scripts on it and found that it's about *5 times slower* than using the regular functions. I haven't tested this in a real app yet, so I don't know how negligible that will be (1ms vs 5ms or 100ms vs 500ms?). Anyway it struck me that now PHP is now focusing more on OOP, wouldn't it make sense for strings, arrays and other basic types to be object oriented? They could then name the functions better and code would just "feel" nicer. And slowly phase out the old way of doing things. Any pros/cons to this?
You could always document your code and just use the functions that PHP has provided. It is hard to tell whether or not it is going to affect you in the long run. There are many different factors that can influence that. Give it a shot, maybe and if it does not work out switch back to the original way. Personally, I would just keep my document well documented instead of getting too fancy. If you want to make the push into more OOP your best bet is to look into a Framework. I wish PHP would make it that simple from the start. The code would look so neat.
Sure, `$somestring->length()` is nice but, on the flipside, you have to `$somestring = new String('asdf...')` whenever you make a string and then constantly convert Strings to strings and vice versa. You probably end up making things harder to write & maintain in the long run. I don't really see the PHP language ever changing in this way - it would change too much of the fundamental language. If you want a language that is like this, you're going to have to change languages, rather than hope for the language to change.
Should PHP use objects as basic data types?
[ "", "php", "oop", "class", "" ]
I am solving problem 9 on the [Project Euler](http://projecteuler.net/). In my solution I use a "goto" statement to break out of two for loops. The Problem is the following: > A Pythagorean triplet is a set of three natural numbers, a b c, for which, > > a^2 + b^2 = c^2 > > For example, 3^2 + 4^2 = 9 + 16 = 25 = 52. > > There exists exactly one Pythagorean triplet for which a + b + c = 1000. > Find the product abc. My solution is in c++: ``` int a,b,c; const int sum = 1000; int result = -1; for (a = 1; a<sum; a++){ for (b = 1; b < sum; b++){ c = sum-a-b; if (a*a+b*b == c*c){ result = a*b*c; goto found; } } } found: std::cout << "a:" << a << std::endl; std::cout << "b:" << b << std::endl; std::cout << "c:" << c << std::endl; std::cout <<"Result:" << result << std::endl; ``` Since "goto" statements are not very popular among c++ programmers, i would like to know, if this could be considered a reasonable use of "goto". Or if there is a better solution for the problem that doesn't need "goto". By that I don't mean a solution which just avoids "goto", but which avoids "goto" in a way that improves the algorithm.
`return` is a "structured" `goto` which many programmers find more acceptable! So: ``` static int findit(int sum, int* pa, int* pb, int* pc) { for (int a = 1; a<sum; a++) { for (int b = 1; b < sum; b++) { int c = sum-a-b; if (a*a+b*b == c*c) { *pa = a; *pb = b; *pc = c; return a*b*c; } } return -1; } int main() { int a, b, c; const int sum = 1000; int result = findit(sum, &a, &b, &c); if (result == -1) { std::cout << "No result!" << std::endl; return 1; } std::cout << "a:" << a << std::endl; std::cout << "b:" << b << std::endl; std::cout << "c:" << c << std::endl; std::cout <<"Result:" << result << std::endl; return 0; } ```
In my opinion it's fine to use `goto` in a situation like this. Btw, the condescending preaching against goto usually comes from people who just parrot what they heard others say or read somewhere..
Is using goto a legitimate way to break out of two loops?
[ "", "c++", "goto", "" ]
i am using FlashMessenger helper to set messages, but i am unable to retrieve messages using getMessages() method. it returns null. here is my sample code: ``` <?php class Admin_TestController extends Zend_Controller_Action { protected $_flashMessenger = null; public function init() { $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger'); $this->initView(); } public function myAction() { $this->_flashMessenger->addMessage('test message'); $this->_helper->Redirector("mynextrequest"); } public function mynextrequestAction() { zend_debug::dump($this->_flashMessenger->getMessages()); $this->render(); } } ```
i upgrade from php 5.2.0 to 5.2.9 and the problem solved.
To fix this problem you need to edit library/Zend/Controller/Action/Helper/FlashMessenger.php find the line: `self::$_session->{$this->_namespace}[] = $message;` and change it to `//self::$_session->{$this->_namespace}[] = $message; $sessionMessages = self::$_session->{$this->_namespace}; $sessionMessages[] = $message; self::$_session->{$this->_namespace} = $sessionMessages;` This issue only affects php 5.2 and so they have decided not to fix it and instead suggest upgrading the PHP version.
zend framework FlashMessenger problem
[ "", "php", "zend-framework", "" ]
How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in `settings.py` set `TIME_ZONE="UTC"`) so all datetimes were stored in the database as UTC. Stuff like [this](https://stackoverflow.com/questions/689831/changing-timezone-on-an-existing-django-project) scares me which is why I prefer UTC everywhere. But how hard will it be to store a timezone for each user and still use the standard django datetime formatting and modelform wrappers. Do I anticipate having to write date handling code everywhere to convert dates into the user's timezone and back to UTC again? I am still going through the django tutorial but I know how much of a pain it can be to deal with user timezones in some other frameworks that assume system timezone everywhere so I thought I'd ask now. My research at the moment consisted of searching the django documentation and only finding [one reference](http://docs.djangoproject.com/en/dev/ref/settings/#time-zone) to timezones. --- Additional: * There are a [few bugs submitted](http://code.djangoproject.com/ticket/2626) concerning Django and timezone handling. * Babel has [some contrib code for django](http://svn.edgewall.org/repos/babel/contrib/django/) that seems to deal with timezone formatting in locales.
**Update, January 2013**: Django 1.4 now has [time zone](https://docs.djangoproject.com/en/3.2/topics/i18n/timezones/) support!! --- Old answer for historical reasons: I'm going to be working on this problem myself for my application. My first approach to this problem would be to go with django core developer Malcom Tredinnick's advice in [this django-user's post](http://groups.google.com/group/django-users/msg/ee174701c960ff2d). You'll want to store the user's timezone setting in their user profile, probably. I would also highly encourage you to look into the [pytz module](http://pytz.sourceforge.net/), which makes working with timezones less painful. For the front end, I created a "timezone picker" based on the common timezones in pytz. I have one select box for the area, and another for the location (e.g. US/Central is rendered with two select boxes). It makes picking timezones slightly more convenient than wading through a list of 400+ choices.
It's not that hard to write timezone aware code in django: I've written simple django application which helps handle timezones issue in django projects: <https://github.com/paluh/django-tz>. It's based on Brosner (django-timezone) code but takes different approach to solve the problem - I think it implements something similar to yours and FernandoEscher propositions. All datetime values are stored in data base in one timezone (according to TIME\_ZONE setting) and conversion to appropriate value (i.e. user timezone) are done in templates and forms (there is form widget for datetimes fields which contains additional subwidget with timezone). Every datetime conversion is explicit - no magic. Additionally there is per thread cache which allows you simplify these datatime conversions (implementation is based on django i18n translation machinery). When you want to remember user timezone, you should add timezone field to profile model and write simple middleware (follow the example from doc).
Django with system timezone setting vs user's individual timezones
[ "", "python", "django", "timezone", "django-settings", "django-timezone", "" ]
I know we have ILdasm, but is there any tool out there that will let me edit .exe or .dll files without having to go through all the *rigmarole* of having to convert it to IL code, with resources includeded, etc etc, manually edit, then recompile again?
You could always use [Reflector](http://www.red-gate.com/products/reflector/) to disassemble whole namespaces to source code (not IL), but then you're still stuck without a direct editor, you have to copy/paste to a code file and recompile. On the other hand, it seems like I was wrong, Reflector has an add-in [Reflexil](https://sourceforge.net/projects/reflexil/) that looks like it'll do what you want.
check out this SourceForge project I guess it's what you're looking for: <http://sourceforge.net/projects/dile/>
(.net) Intermediate language exe editor?
[ "", "c#", ".net", "decompiling", "" ]
I created a form with a label, textbox and a button. In the form load event I called the focus() function for the textbox. But when I run my code the cursor is not coming to textbox. I need the cursor to go to text box as soon as the form is loaded. How to do it?
If you simply need to make sure a certain control gets focus when you first load a form, then change the `TabOrder` properties of all your controls (in the Designer) so that the control in question is '0', and the other elements are going up from there, '1', '2', etc. If you need to dynamically select a different control when you show a form depending on some condition, then use the following code: ``` private void Form1_Load(object sender, EventArgs e) { // You need to show the form otherwise setting focus does nothing // (there are no controls to set focus to yet!) this.Show() if (someCondition == true) control.Focus(); else control2.Focus(); } ```
Handle the `Shown` event instead. This code should work. ``` private void Form1_Shown(object sender, EventArgs e) { textBox2.Focus(); } ```
focus to text box
[ "", "c#", "" ]
I'm trying to create a tool for jQuery which crops images. I know there is already a load of already. The difference with the one i'm trying to make is that i'd like it to act like the Picture Taker interface found in many mac applications like iChat and Adium. I'm stuck completly on how to do it. Can anyone give me any ideas? [Picture Taker Documentation](http://developer.apple.com/documentation/graphicsimaging/Conceptual/ImageKitProgrammingGuide/IKImagePicker/IKImagePicker.html)
I think [Jcrop plugin](http://www.webresourcesdepot.com/jquery-image-crop-plugin-jcrop/) may help you!
The jCrop plugin does most of the work. You just need a little logic to stitch it together with a slider widget (like the jqueryui slider). Here's a quick and dirty example. You'll certainly want to host the files on your own server, but I just wanted to throw something together. One significant difference is that this code forgets where you have dragged the selection and just resizes it around the current midpoint. If that is important to you, you could probably add that functionality pretty easily. ``` <html> <head> <link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" /> <script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script> <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script> <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.slider.js"></script> <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.slider.js"></script> <script type="text/javascript" src="http://deepliquid.com/projects/Jcrop/js/jquery.Jcrop.js"></script> <link rel="stylesheet" href="http://deepliquid.com/projects/Jcrop/css/jquery.Jcrop.css" type="text/css" /> <style type="text/css"> #slider { margin: 10px; } </style> <script type="text/javascript"> var jcrop_api; $(document).ready(function(){ imgwidth = $("#cropbox").width(); imgheight = $("#cropbox").height(); aspectRatio=(imgheight > 0)?imgwidth / imgheight:1; jcrop_api = $.Jcrop('#cropbox',{ setSelect: [ 0, 0, imgwidth, imgheight ], aspectRatio: aspectRatio }); $("#slider").slider({ min: 0, max: 100, value: 100, slide: function(e,ui){ updateCrop(ui.value); } }); function updateCrop(size){ size = size / 100; maxX = $("#cropbox").width(); maxY = $("#cropbox").height(); midX = ((jcrop_api.tellSelect().x2 - jcrop_api.tellSelect().x) / 2) + jcrop_api.tellSelect().x; midY = ((jcrop_api.tellSelect().y2 - jcrop_api.tellSelect().y) / 2) + jcrop_api.tellSelect().y; midX = (midX < 0) ? midX * -1 : midX; midY = (midY < 0) ? midY * -1 : midY; sizeX = $("#cropbox").width() * size; sizeY = $("#cropbox").height() * size; x = midX - (sizeX/2); y = midY - (sizeY/2); x2 = midX + (sizeX/2); y2 = midY + (sizeY/2); // edge conditions if (x < 0){ x2 -= x2 - x; x = 0; if (x2 > maxX) x2 = maxX; } if (x2 > maxX){ x -= (x2 - maxX); x2 = maxX; if (x < 0) x = 0; } if (y < 0){ y2 -= y; y = 0; if (y2 > maxY) y2 = maxY; } if (y2 > maxY){ y -= (y2 - maxY); y2 = maxY; if (y < 0) y = 0; } jcrop_api.setSelect([ x,y,x2,y2 ]); } }); </script> </head> <body> <img src="http://deepliquid.com/projects/Jcrop/demos/demo_files/sago.jpg" id="cropbox" /> <div id="slider"></div> </body> </html> ```
How can I recreate the ImageKit Picture Taker?
[ "", "javascript", "jquery", "macos", "" ]
I believe it is related to CORBA in some way (I'm not sure). I'm curious as to its function and how it works. Google isn't helping me when I search for "IOR file", and I'm not sure what else I could search for. Thanks to anyone who can at least point me in the right direction with available resources.
An IOR file is a file which contains an **Interoperable Object Reference** which is a kind of a locator string. The IOR file itself contains the IOR. The IOR is an CDR encoded string which, depended on the CORBA version, contains various information regarding the servant who created this string. But basically it works as a locator string. Inside the IOR normally an IP, portnumber and object reference of the servant could be found. In a simple hello world example the servant (server) will create this file. The client reads this file and the client ORB (Object Request Broker) will delegate the call from the client to the servant transparently. All about CORBA: [OMG CORBA Website](http://www.corba.org/) or just visit [Wikipedia](http://en.wikipedia.org/wiki/CORBA)
IOR stands for Interoperable Object Reference and is related to Corba You can check out "Corba in 5 minutes" here : <http://www.pvv.ntnu.no/~ljosa/doc/encycmuclopedia/devenv/corba-index.html> There's a section explaining what is an IOR
What is an IOR file, what does it do, and how does it work?
[ "", "java", "corba", "" ]
Given that I have this resultset structure (superfluous fields have been stripped) ``` Id | ParentId | Name | Depth ---------------------------- ``` is it possible to have the records returned in tree order i.e. `Parent` then `Children`, if a `Child` is a `Parent`, then their `Children`, if not then `Sibling`, etc? For example, ``` Id | ParentId | Name | Depth ---------------------------- 1 NULL Major 1 2 1 Minor 2 3 1 Minor 2 4 3 Build 3 5 3 Build 3 6 1 Minor 2 /* etc, etc */ ``` The only way that I can think of doing this would be to follow this article - [Improve hierarchy performance using nested sets](http://www.codeproject.com/KB/database/nestedsets.aspx) and include `[LeftExtent]` and `[RightExtent]` fields against each record. Now the SQL in the article works fine when `Ids` are unique, but in this particular tree structure, a record with the same `Id` can appear in different places within the tree (the `ParentId` field is different, obviously). I think the problem is in this SQL from the article - ``` INSERT INTO @tmpStack ( EmployeeID, LeftExtent ) SELECT TOP 1 EmployeeID, @counter FROM Employee WHERE ISNULL(ParentID, 0) = ISNULL(@parentid,0) /* If the Id has already been added then record is not given [LeftExtent] or [RightExtent] values. */ AND EmployeeID NOT IN (SELECT EmployeeID FROM @tmpStack) ``` How can this be altered to allow records with duplicate `Ids` to be given [LeftExtent] and [RightExtent] values, or I am completely missing an easier way to return the resultset in the order that I require?
Here's one that does the trick for me: @ParentID is just a starting point in the hierarchy, but you can pass in 0 (but I think you're using null as the base ID, so you'll get the idea) The key to ordered sorting is with the sort key that's built up. ``` WITH RoleHierarchy (RoleID, [Role], [Description], ParentID, Editable, HierarchyLevel, SortKey) AS ( -- Base SELECT RoleID, [Role], [Description], ParentID, Editable, 0 as HierarchyLevel, CAST(RoleID AS VARBINARY(300)) FROM dbo.Roles WHERE RoleID = @ParentID UNION ALL -- Recursive SELECT e.RoleID, e.[Role], e.[Description], e.ParentID, e.Editable, th.HierarchyLevel + 1 AS HierarchyLevel, CAST (th.SortKey + CAST (e.[Role] AS VARBINARY(100)) + CAST (e.[RoleID] AS VARBINARY(100)) AS VARBINARY(300)) FROM Roles e INNER JOIN RoleHierarchy th ON e.ParentID = th.RoleID WHERE e.RoleID != 0 ) SELECT RoleID, ParentID, [Role], [Description], Editable, HierarchyLevel FROM RoleHierarchy WHERE RoleID != @ParentID ORDER BY SortKey ```
You should have a look at recursive common table expressions in SQL Server 2005: * <https://web.archive.org/web/20210927200924/http://www.4guysfromrolla.com/webtech/071906-1.shtml> * <http://www.sqlservercentral.com/articles/Development/recursivequeriesinsqlserver2005/1760/> In your case, this would be something like: ``` WITH EmployeeCTE AS ( -- get the anchor SELECT ID, ParentID, Name, 0 as 'Depth' FROM Employee WHERE ParentID IS NULL -- recursively union lower levels UNION ALL SELECT e.ID, e.ParentID, e.Name, e.Depth+1 FROM Employee e INNER JOIN EmployeeCTE ON e.ParentID = EmployeeCTE.ID ) SELECT * FROM EmployeeCTE ``` This should give you a nice query result set with the data you're looking for. Or am I missing something? Marc
SQL Server Tree Hierarchy and Nested Sets with Duplicate Record ids
[ "", "sql", "sql-server", "sql-server-2005", "tree", "nested-sets", "" ]
Is there a way to get the following function declaration? ``` public bool Foo<T>() where T : interface; ``` ie. where T is an interface type (similar to `where T : class`, and `struct`). Currently I've settled for: ``` public bool Foo<T>() where T : IBase; ``` Where IBase is defined as an empty interface that is inherited by all my custom interfaces... Not ideal, but it should work... Why can't you define that a generic type must be an interface? For what it's worth, I want this because `Foo` is doing reflection where it needs an interface type... I could pass it in as a normal parameter and do the necessary checking in the function itself, but this seemed a lot more typesafe (and I suppose a little more performant, since all the checks are done at compiletime).
The closest you can do (except for your base-interface approach) is "`where T : class`", meaning reference-type. There is no syntax to mean "any interface". This ("`where T : class`") is used, for example, in WCF to limit clients to service contracts (interfaces).
I know this is a bit late but for those that are interested you can use a runtime check. ``` typeof(T).IsInterface ```
How can I use interface as a C# generic type constraint?
[ "", "c#", "generics", "interface", "constraints", "" ]
**See updated input and output data at Edit-1.** What I am trying to accomplish is turning ``` + 1 + 1.1 + 1.1.1 - 1.1.1.1 - 1.1.1.2 + 1.2 - 1.2.1 - 1.2.2 - 1.3 + 2 - 3 ``` into a python data structure such as ``` [{'1': [{'1.1': {'1.1.1': ['1.1.1.1', '1.1.1.2']}, '1.2': ['1.2.1', '1.2.2']}, '1.3'], '2': {}}, ['3',]] ``` I've looked at many different wiki markup languages, markdown, restructured text, etc but they are all extremely complicated for me to understand how it works since they must cover a large amount of tags and syntax (I would only need the "list" parts of most of these but converted to python instead of html of course.) I've also taken a look at tokenizers, lexers and parsers but again they are much more complicated than I need and that I can understand. I have no idea where to begin and would appreciate any help possible on this subject. Thanks **Edit-1**: Yes the character at the beginning of the line matters, from the required output from before and now it could be seen that the **`*`** denotes a root node with children, the **+** has children and the **-** has no children (root or otherwise) and is just extra information pertaining to that node. The **`*`** is not important and can be interchanged with **+** (I can get root status other ways.) Therefore the new requirement would be using only **`*`** to denote a node with or without children and **-** cannot have children. I've also changed it so the key isn't the text after the **`*`** since that will no doubt changer later to an actual title. For example ``` * 1 * 1.1 * 1.2 - Note for 1.2 * 2 * 3 - Note for root ``` would give ``` [{'title': '1', 'children': [{'title': '1.1', 'children': []}, {'title': '1.2', 'children': []}]}, {'title': '2', 'children': [], 'notes': ['Note for 1.2', ]}, {'title': '3', 'children': []}, 'Note for root'] ``` Or if you have another idea to represent the outline in python then bring it forward.
**Edit**: thanks to the clarification and change in the spec I've edited my code, still using an explicit `Node` class as an intermediate step for clarity -- the logic is to turn the list of lines into a list of nodes, then turn that list of nodes into a tree (by using their indent attribute appropriately), then print that tree in a readable form (this is just a "debug-help" step, to check the tree is well constructed, and can of course get commented out in the final version of the script -- which, just as of course, will take the lines from a file rather than having them hardcoded for debugging!-), finally build the desired Python structure and print it. Here's the code, and as we'll see after that the result is *almost* as the OP specifies with one exception -- but, the code first: ``` import sys class Node(object): def __init__(self, title, indent): self.title = title self.indent = indent self.children = [] self.notes = [] self.parent = None def __repr__(self): return 'Node(%s, %s, %r, %s)' % ( self.indent, self.parent, self.title, self.notes) def aspython(self): result = dict(title=self.title, children=topython(self.children)) if self.notes: result['notes'] = self.notes return result def print_tree(node): print ' ' * node.indent, node.title for subnode in node.children: print_tree(subnode) for note in node.notes: print ' ' * node.indent, 'Note:', note def topython(nodelist): return [node.aspython() for node in nodelist] def lines_to_tree(lines): nodes = [] for line in lines: indent = len(line) - len(line.lstrip()) marker, body = line.strip().split(None, 1) if marker == '*': nodes.append(Node(body, indent)) elif marker == '-': nodes[-1].notes.append(body) else: print>>sys.stderr, "Invalid marker %r" % marker tree = Node('', -1) curr = tree for node in nodes: while node.indent <= curr.indent: curr = curr.parent node.parent = curr curr.children.append(node) curr = node return tree data = """\ * 1 * 1.1 * 1.2 - Note for 1.2 * 2 * 3 - Note for root """.splitlines() def main(): tree = lines_to_tree(data) print_tree(tree) print alist = topython(tree.children) print alist if __name__ == '__main__': main() ``` When run, this emits: ``` 1 1.1 1.2 Note: 1.2 2 3 Note: 3 [{'children': [{'children': [], 'title': '1.1'}, {'notes': ['Note for 1.2'], 'children': [], 'title': '1.2'}], 'title': '1'}, {'children': [], 'title': '2'}, {'notes': ['Note for root'], 'children': [], 'title': '3'}] ``` Apart from the ordering of keys (which is immaterial and not guaranteed in a dict, of course), this is *almost* as requested -- except that here **all** notes appear as dict entries with a key of `notes` and a value that's a list of strings (but the notes entry is omitted if the list would be empty, roughly as done in the example in the question). In the current version of the question, how to represent the notes is slightly unclear; one note appears as a stand-alone string, others as entries whose value is a string (instead of a list of strings as I'm using). It's not clear what's supposed to imply that the note must appear as a stand-alone string in one case and as a dict entry in all others, so this scheme I'm using is more regular; and if a note (if any) is a single string rather than a list, would that mean it's an error if more than one note appears for a node? In the latter regard, this scheme I'm using is more general (lets a node have any number of notes from 0 up, instead of just 0 or 1 as apparently implied in the question). Having written so much code (the pre-edit answer was about as long and helped clarify and change the specs) to provide (I hope) 99% of the desired solution, I hope this satisfies the original poster, since the last few tweaks to code and/or specs to make them match each other should be easy for him to do!
Stacks are a really useful datastructure when parsing trees. You just keep the path from the last added node up to the root on the stack at all times so you can find the correct parent by the length of the indent. Something like this should work for parsing your last example: ``` import re line_tokens = re.compile('( *)(\\*|-) (.*)') def parse_tree(data): stack = [{'title': 'Root node', 'children': []}] for line in data.split("\n"): indent, symbol, content = line_tokens.match(line).groups() while len(indent) + 1 < len(stack): stack.pop() # Remove everything up to current parent if symbol == '-': stack[-1].setdefault('notes', []).append(content) elif symbol == '*': node = {'title': content, 'children': []} stack[-1]['children'].append(node) stack.append(node) # Add as the current deepest node return stack[0] ```
How can I parse marked up text for further processing?
[ "", "python", "parsing", "markdown", "markup", "lexer", "" ]
I'm trying to implement my own List system in Java. the `List` class file : ``` package RoutingDemo.List; /** * A 2-way Linked-List to store generic elements. * */ public class List { /* Instance Variables --------------------------------------------------------------------------- */ /** * Reference to element. */ private Object info; /** * Reference to previous NodeList instance. */ private List prev; /** * Reference to next NodeList instance. */ private List next; /* Constructors --------------------------------------------------------------------------- */ /** * Creates a new empty list. */ public List() { prev = null; next = null; info = null; } /* Methods --------------------------------------------------------------------------- */ /** * Adds an element to the list. * * @param o Element to be added */ public List add(Object o) { if(info == null) { info = o; prev = null; next = null; return this; } else { List temp = new List(); temp.add(o); return addList(temp); } } /** * Appends an existing list to this list. * * @param newList List to be appended */ public List addList(List newList) { if(newList.info() == null) return this; List ref = this; ref.last().setNext(newList.first()); newList.first().setPrev(ref.last()); return ref; } /** * Get number of elements in the list. * * @return number of elements in list */ public int count() { if(info == null) return 0; List ref = this.first(); int count = 0; while(true) { count++; if(!ref.isLast()) ref = ref.next(); else break; } return count; } /** * Deletes an element from the list. * * @param o Element to be deleted * @return List which does NOT * contain element o */ public List delete(Object o) { if(info == null) return this; List ref = this.first(); while(true) { if(ref.info() == o) { if(ref.isFirst() && ref.isLast()) { ref = new List(); break; } else if(ref.isFirst()) { ref = ref.next(); ref.killPrev(); break; } else if(ref.isLast()) { /* *** THIS IS THE CASE THAT WILL BE CALLED FOR THIS TEST **** */ ref = ref.prev(); ref.killNext(); break; } else { ref.prev().setNext(ref.next()); ref.next().setPrev(ref.prev()); ref = ref.prev(); break; } } else { if(!ref.isLast()) ref = ref.next(); else break; } } return ref; } /** * Moves to first element in List. * * * @return List pointing to first * element in list */ public List first() { List ref = this; while(!ref.isFirst()) { /* *** STUCK HERE *** */ ref = ref.prev(); } return ref; } /** * Returns current list element. * * @return current list element */ public Object info() { return info; } /** * Checks whether list is empty. * * @return true, if list is empty * , false otherwise. */ public boolean isEmpty() { if(count() > 0) return false; else return true; } /** * Checks whether current element is the first element. * * @return true, if current element is * first element, false otherwise. */ public boolean isFirst() { if(prev == null) return true; else return false; } /** * checks whether current element is the last element. * * @return true, if current element is * last element, false otherwise */ public boolean isLast() { if(next == null) return true; else return false; } /** * Cuts the list from next element. * * * @param l new link for current element */ public void killNext() { next = null; } /** * Cuts the list from previous element. * * * @param l new link */ public void killPrev() { prev = null; } /** * Moves to last element in List. * * * @return List pointing to last * element in list */ public List last() { List ref = this; while(!ref.isLast()) { ref = ref.next(); } return ref; } /** * Moves to next element in List * * * @return List pointing to next * element in list */ public List next() { if(!isLast()) return next; else return this; } /** * Moves to previous element in List * * * @return List pointing to previous * element in list */ public List prev() { if(!isFirst()) return prev; else return this; } /** * Sets the next link * * * @param l new link for current element */ public void setNext(List l) { next = l; } /** * Sets the prev link for current element * * * @param l new link */ public void setPrev(List l) { prev = l; } } ``` And I was testing it out like this: ``` class Example { Example() { List nl = new List(); nl = nl.add(new Node(5,6)); System.out.println("" + nl.count()); Node x = new Node(1,3); nl = nl.add(x); System.out.println("" + nl.count()); nl = nl.delete(x); System.out.println("as" + nl.count()); } } public class ListTest { public static void main(String args[]) { new Example(); } } ``` Now, everything is fine when I add the first two nodes. However, I go into an infinite loop when I call the `count()` **after** I delete a node. And after going through a lot of breakpoints, I've marked the place in the code where I get stuck. Apparently something is wrong in the `delete()` function, I cannot figure out what I'm doing wrong. For the time being, I've replaced my `delete()` code with this : ``` public List delete(Object o) { if(info == null) return this; List ref = this.first(); List temp = new List(); while(true) { if(ref.info() != o) temp.add(ref.info()); if(!ref.isLast()) ref = ref.next(); else break; } return temp; } ``` But this wouldnt be memory-friendly for huge lists. Let me know if you can spot the problem!
The problem is that your list ends up corrupted. At the point where you have 2 items in the list, it looks something like this: > 1. List { info = Node(5,6), prev = null, next = 2 } > 2. List { info = Node(1,3), prev = 2, next = null } Woops, notice the second item in the list's *prev* field is pointing at itself? Your problem is in this method: ``` public List addList(List newList) { // ... newList.first().setPrev(ref.last()); // <-- here } ``` On that line, *ref.last()* is a method that loops through looking for the last item in the list, ref. However, the last item isn't what you expect it to be, because the previous line looks like this: ``` ref.last().setNext(newList.first()); ``` What you want to look for is the last item as it would have been *before* you set it's *next* field by appending the new list on the end. However, by calling the *last* method again, you're finding the *new* last item, after the new list has been appended. That's why its last node ends up pointing to itself. Change your *addList* method to look like this: ``` public List addList(List newList) { if(newList.info() == null) return this; List ref = this; List last = ref.last(); last.setNext(newList.first()); newList.first().setPrev(last); return ref; } ``` ...and it will work. By caching the reference to the end of the list before modifying it, you have the correct reference now. Even so, your code is quite a bit more complicated than it has to be. You should look up an example of how to implement a double linked list and you will find examples that show you how to do it far simpler. Your *delete* method in particular is far too over-complicated. I also think you have problems with representing the empty list as a node containing a *null*. That seems to be causing you to have all kinds of nasty edge cases you need to check for.
It could be the fact that you are using == on Objects. ``` if(ref.info() == o) ``` Even if it isn't your exact problem for your infinite loop, it is a problem that you need to address.
Stuck in a loop
[ "", "java", "list", "loops", "infinite", "" ]
How can I connect to a MySQL database from Windows Forms?
Numerous sample of connection strings here : <http://www.connectionstrings.com/>
Use the [Connector from here](http://www.mysql.de/products/connector/). There's a [documentation](http://dev.mysql.com/doc/refman/5.0/en/connector-net.html) too.
How can I connect to MySQL from windows forms?
[ "", "c#", "mysql", "windows", "winforms", "" ]
I am trying to figure out how to process XML in java script So i googled for it. The problem is , I don't know whether the tutorials I see will work only on IE. What is the "Standard" way to process Xml data in java script? **Edit: Thanks for all your answers. I want to ask another question then. Is there some kind of 3rd party library which let me transperatly write JS code without worry about cross-browser functionality**
use the tutorials at [w3schools.com](http://www.w3schools.com/xml/xml_parser.asp). They indicate how to work with a variety of browsers e.g. (a snippet) ``` try //Internet Explorer { xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async="false"; xmlDoc.loadXML(txt); return xmlDoc; } catch(e) { parser=new DOMParser(); xmlDoc=parser.parseFromString(txt,"text/xml"); return xmlDoc; } ``` Also, just to answer your direct question. The is a standard way (in the snippet above, it's in the catch block), but internet explorer doesn't support the standard way.... so you're stuck with something like the above
Maybe you should take a look at [sarissa](http://dev.abiss.gr/sarissa/). it is a crossbrowser library that i find very useful and easy to use. It permits you to * load XML from URLs or strings, * perform XSLT transformations, * apply XPath queries Works on the major browsers and it is licensed under GPL
cross-browser standard Xml processing in Java Script
[ "", "javascript", "xml", "" ]
Here is my code for finding a sequence in a string and replacing it with another: ``` std::string find_and_replace( string &source, string find, string replace ) { size_t j; for ( ; (j = source.find( find )) != string::npos ; ) { source.replace( j, find.length(), replace ); } return source; } ``` Everything works fine when I call something like: ``` find_and_replace(test, "foo", "bar") ``` My application requires me to replace a single quote with two single quotes, not a double quote. For example I would call: ``` find_and_replace(test, "'", "''") ``` But whenever I call this, the function freezes up for some reason. Does anyone know what might be the cause of this problem? Edit: based on the answers I've gotten, I have fixed the code: ``` std::string find_and_replace( string &source, string find, string replace ) { string::size_type pos = 0; while ( (pos = source.find(find, pos)) != string::npos ) { source.replace( pos, find.size(), replace ); pos += replace.size(); } return source; } ``` I hope this helps some people having the same problem.
You've got an infinite loop because your condition doesn't move forward. You're always running `j = source.find( find )`, but you're replacing `'` with `''`, so you're always finding the first apostrophe every time and adding a new apostrophe to the string. You need to make sure you don't match the same apostrophe twice by moving where you're scanning forward every time you replace something. The `find` function takes a second parameter which is the starting position in the string to look for the substring. Once you've found the position of the first match, move the starting position up to that position plus the length of the string you're replacing it with.
Because you replace ' with '', then search for ' again, finding the first of the ones you've just put there. Which you replace. And so on.
Single quote issues with C++ find and replace function
[ "", "c++", "quotes", "replace", "" ]
I'm writing a windows service in C# that spawns multiple instances of another application I am writing. There is a chance that the application can be installed anywhere on a machine. What is the best way to let the service know where the application is located?
If you mean that the service starts a **different** app, then; options: * configure the service with a config file; put the path in there * put something in the registry during installation * use something akin to COM/COM+ registrations * *consider* the GAC if the other app is .NET (although I'm not a fan...) * environment variable? Personally, I like the config file option; it is simple and easy to maintain, and allows multiple separate (side-by-side) service and app installs
If you need to locate the folder your service is installed to you can use the following code ``` this.GetType().Assembly.Location ``` If you need to locate the folder some other application is installed to you should make a request to windows installer ``` [DllImport("MSI.DLL", CharSet = CharSet.Auto)] private static extern UInt32 MsiGetComponentPath( string szProduct, string szComponent, StringBuilder lpPathBuf, ref int pcchBuf); private static string GetComponentPath(string product, string component) { int pathLength = 1024; StringBuilder path = new StringBuilder(pathLength); MsiGetComponentPath(product, component, path, ref pathLength); return path.ToString(); } ```
What is the proper way to determine an application's location?
[ "", "c#", ".net", "windows", "windows-services", "installation", "" ]
I have a web application that is using both jQuery 1.2.6 and YUI 2.6.0 and I am thinking about upgrading one or both of these libraries. The current versions (as of this question) are [jQuery 1.3.2](http://jquery.com/) and [YUI 3.0.0 (beta 1)](http://developer.yahoo.com/yui/3/). The main reason for jQuery was the selector engine, and the main reason for YUI was components like [TreeView](http://developer.yahoo.com/yui/treeview/) and [DataTable](http://developer.yahoo.com/yui/datatable/). Now that YUI 3 [includes Sizzle](http://github.com/msweeney/yui3/commits/sizzle) (the same selector engine as jQuery), I am thinking about only upgrading YUI and removing jQuery. From both experience and [Mixing jQuery and YUI together in an app, is it easily possible?](https://stackoverflow.com/questions/201768/mixing-jquery-and-yui-together-in-an-app-is-it-easily-possible), I know I can have both, but it doesn't feel right. I prefer one way of doing AJAX calls, DOM events, plug-ins, etc. Has anyone does this or have any advice for me? We already use jQuery in [noConflict](http://docs.jquery.com/Core/jQuery.noConflict) mode to avoid the use of $.
I've not encountered any issues using the YUI Calendar widget with jQuery for all my other needs. YUI3 has a Global Object conecept which is designed to mitigate conflict issues, as I understand it. <http://developer.yahoo.com/yui/3/yui/#using> You might want to check the YUI3 road map <http://yuilibrary.com/projects/yui3/roadmap> Tree View and DataTable arnt mentioned, unless I've missed them. There are only four initial widgets mentioned for Q4 09.
This might be worth looking into as a stop gap - lets you use yui2 widgets with yui3 for migration. <http://yuilibrary.com/gallery/show/yui2>
Advice "upgrading" from jQuery 1.2.6 to YUI 3?
[ "", "javascript", "jquery", "yui", "" ]
Suppose I have 2 tables in a database. eg: Dog & Boss This is a many to many relationship, cause a boss can have more than 1 dog, and a dog can have more than 1 owner. I am the owner of Bobby, but so is my wife. But many to many is not allowed, so there is a helpertable: DogsPerBoss How to model this in code? Class Boss can have a collection of Dogs. Class Dog can have a collection of Bosses. --> at least, that is what I think. Perhaps there are better solutions? How about extra data that is in the helper-table? Should that be in de Boss-class or in the Dog-class? eg: Nickname (I call the dog "good boy" and my wife calls him "doggie") I hope my question is kinda clear? Are there any best-practices on what is the best way to achieve this? Can you give me some references? An ORM (like NHibernate) is not an option.
Why are you talking about tables? Are you creating an object model or a database model? For an object model, there's no reason a Dog can't have a `List<Owner>` and an owner have a `List<Dog>`. Only if you have attributes on the relationship do you need an intermediate class (what UML calls an Association Class). That's when you'd have a DogOwnership class with extra properties, and each Owner would have a `List<DogOwnership>`, and so would each Dog. The DogOwner would have a Dog, an Owner, and the extra properties.
``` public class Boss { private string name; private List<Hashtable> dogs; private int limit; public Boss(string name, int dogLimit) { this.name = name; this.dogs = new List<Hashtable>(); this.limit = dogLimit; } public string Name { get { return this.name; } } public void AddDog(string nickname, Dog dog) { if (!this.dogs.Contains(nickname) && !this.dogs.Count == limit) { this.dogs.Add(nickname, dog); dog.AddBoss(this); } } public void RemoveDog(string nickname) { this.dogs.Remove(nickname); dog.RemoveBoss(this); } public void Hashtable Dogs { get { return this.dogs; } } } public class Dog { private string name; private List<Boss> bosses; public Dog(string name) { this.name = name; this.bosses = new List<Boss>(); } public string Name { get { return this.name; } } public void AddBoss(Boss boss) { if (!this.bosses.Contains(boss)) { this.bosses.Add(boss); } } public void RemoveBoss(Boss boss) { this.bosses.Remove(boss); } public ReadOnlyCollection<Boss> Bosses { get { return new ReadOnlyCollection<Boss>(this.bosses); } } } ``` The above maintains the relationship of Bosses can have multiple dogs (with a limit applied) and dogs having multiple bosses. It also means that when a boss is adding a dog, they can specify a nickname for the dog which is unique to that boss only. Which means other bosses can add the same dog, but with different nicknames. As for the limit, I would probably have this as an App.Config value which you just read in before instantiating the boss object(s). So a small example would be: ``` var james = new Boss("James", ConfigurationManager.AppSettings["DogsPerBoss"]); var joe = new Boss("Joe", ConfigurationManager.AppSettings["DogsPerBoss"]); var benji = new Dog("Benji"); var pooch = new Dog("Pooch"); james.AddDog("Good boy", benji); joe.AddDog("Doggy", benji); james.AddDog("Rover", pooch); joe.AddDog("Buddy", pooch); // won't add as the preset limit has been reached. ``` You can obviously tweak this as you see fit, however, I think the fundamentals of what you are looking for are there. * Boss can have multiple dogs with limit * Dogs can have multiple bosses * Bosses can have different nicknames for same dog.
How to model a Many to many-relationship in code?
[ "", "c#", "many-to-many", "modeling", "" ]
I am trying to create some charts of data (eg <http://www.amibroker.com/>). Is there a C++ library that can do this without a lot of extra work? I'm thinking Qt or wxWindows would have something like it, but it wasn't immediately obvious. Thanks!
[Qwt](http://qwt.sourceforge.net) does at least some of the things you are trying to achieve (basic plots, bar charts and so on), and integrates well with Qt.
[FLTK](http://www.fltk.org/) is a light and portable C++ toolkit for GUI. There's a [chart class](http://www.fltk.org/doc-1.3/classFl__Chart.html). [Sample](http://www.fltk.org/doc-1.3/charts.gif).
Stock Charts in C++
[ "", "c++", "charts", "" ]
I have a textbox that i am binding to the viewmodel's string property. The string property is updated within the viewmodel and it displays the text within the textbox through binding. The issue is that i want to insert the line break after a certain number of characters in the string property and i want that the line break is shown over the textbox control. I tried appending \r\n inside the string property in viewmodel but the line break is not reflected over the textbox (i have Acceptsreturn property set to true inside the textbox) Can anybody help.
I just created a simple app that does what you describe, and it worked for me. XAML: ``` <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition /> </Grid.RowDefinitions> <TextBox Grid.Row="0" AcceptsReturn="True" Height="50" Text="{Binding Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> <Button Grid.Row="1" Click="Button_Click">Button</Button> </Grid> </Window> ``` ViewModel: ``` class ViewModel : INotifyPropertyChanged { private string text = string.Empty; public string Text { get { return this.text; } set { this.text = value; this.OnPropertyChanged("Text"); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propName) { var eh = this.PropertyChanged; if(null != eh) { eh(this, new PropertyChangedEventArgs(propName)); } } } ``` An instance of `ViewModel` is set as the `DataContext` for the `Window`. Finally, the implementation of `Button_Click()` is: ``` private void Button_Click(object sender, RoutedEventArgs e) { this.model.Text = "Hello\r\nWorld"; } ``` (I realize that the view shouldn't really modify the ViewModel's `Text` property directly, but this is just a quick sample app.) This results in the word "Hello" on the first line of the `TextBox`, and "World" is on the second line. Maybe if you post your code we can see what is different from this sample?
The solution for me was to use HTML encoded line feeds ( ). ``` Line1&#10;Line2 ``` Looks like ``` Line1 Line2 ``` From Naoki
WPF Textbox binding and line breaks
[ "", "c#", "wpf", "binding", "textbox", "" ]
What advantages are there for using either XSLT or Linq to XML for HTML parsing in C#? This is under the assumption that the html has been cleaned so it is valid xhtml. These values will eventually go into a c# object to be validated and processed. Please let me know if these are valid and if there are other things to consider. XSLT Advantages: * Easy to change quickly and deploy * Fairly well known XSLT Disadvantages: * Not compiled, so is slower to process * String manipulation can be cumbersome * Will more challenging to get into the C# object at the end Linq to XML Advantages: * Compiled, so it runs faster * Allows for better string manipulation Linq to XML Disadvantages: * Must be compiled for update Edit: I should clarify, I want these to run long term an the website may update their layout once a while. That was one of the bigger reason I thought I would use something that didn't require compiling.
Without further knowing your use case it is hard to give you general recommendations. Anyhow, you are somewhat comparing apples and oranges. LINQ to XML (and LINQ in general) is a query language whereas XSLT is a programming language to transform XML tree structures. These are different concepts. You would use a query language whenever you want to extract a certain specific piece of information from a data source to do whatever you need to do with it (be it to set fields in a C# object). A transformation, in contrast, would be useful to convert one XML representation of your data into another XML representation. So if your aim is to create C# objects from XML, you probably don't want to use XSLT but any of the other technologies offered by the .NET Framework to process XML data: the old `XmlDocument`, `XmlReader`, `XPathDocument`, `XmlSerializer` or `XDocument`. Each has it's special advantages and disadvantages, depending on input size, input complexity, desired output etc. Since you are dealing with HTML only, you might also want to have a look at the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack) on CodePlex.
In my experience, XSLT is more concise and readable when you're primarily dealing with rearranging and selecting existing xml elements. XPath is short and easy to understand, and the xml syntax avoids littering your code with `XElement` and `XAttribute` statements. XSLT works fine as a xml-tree *transform* language. However, it's string handling is poor, looping is unintuitive, and there's no meaningful concept of subroutines - you can't transform the output of another transform. So, if you want to actually fiddle with element and attribute content, then it quickly falls short. There's no problem in using both, incidentally - XSLT to normalize the structure (say, to ensure that all `table` elements have `tbody` elements), and linq-to-xml to interpret it. The prioritized conditional matching possibilities mean XSLT is easier to use when dealing with many similiar but distinct matches. Xslt is good at document simplification, but it's just missing too many basic features to be sufficient on its own. Having jumped whole-heartedly on the Linq-to-Xml bandwagon, I'd say that it has less overlap with XSLT that might seem at first glance. (And I'd positively love to see an XSLT 2.0/XQuery 1.0 implementation for .NET). In terms of performance, both techs are speedy. In fact, since it's so hard to express slow operations, you're unlikely to accidentally trigger a slow case in XSLT (unless you start playing with recursion...). By contrast, LINQ to Xml power also can make it slow: just use any heavy-weight .NET object in some inner loop and you've got a budding performance problem. Whatever you do, don't try to abuse XSLT by using it to perform anything but the simplest of logic: it's way more wordy and far less readable than the equivalent C#. If you need a bunch of logic (even simple things like `date > DateTime.Now ? "will be" : "has"` become huge bloated hacks in XSLT) and you don't want to use both XSLT and Linq to Xml, use Linq.
Advantages of XSLT or Linq to XML
[ "", "c#", "xslt", "linq-to-xml", "html-parsing", "" ]
The code below is extremely slow for tables of any significant size. (100, 1000, etc...) The culprit is instantiating my objects with `new T()`. Note that this isn't my finalized code, I've just broken parts of it out in order to more easily profile. Instantiation and initialization will happen together once I refactor the code back into shape. Is there any way to speed this up? I'm probably forgetting something really simple, or maybe I'm boned. Hopefully, the former. ``` public static IList<T> ToList<T>(this DataTable table) where T : Model, new() { T[] entities = new T[table.Rows.Count]; // THIS LOOP IS VERY VERY SLOW for (int i = 0; i < table.Rows.Count; i++) entities[i] = new T(); // THIS LOOP IS FAST for (int i = 0; i < table.Rows.Count; i++) entities[i].Init(table, table.Rows[i]); return new List<T>(entities); } ``` edit for more info: The constructor of any given `ModelType` will look like this: ``` public ModelType() { _modelInfo = new ModelTypeInfo(); } ``` The constructor of any given `ModelTypeInfo` will simply set some string and string[] values, and that class' only job is to provide the values set. **edit for even more info:** Since it seems to be a hot topic, here is what my method looks like for reals before breaking out object construction and initialization: ``` public static IList<T> ToList<T>(this DataTable table, ModelInfo modelInfo) where T : Model, new() { var tempRepository = new Repository<T>(modelInfo); var list = new List<T>(); foreach (DataRow row in table.Rows) list.Add(tempRepository.FromData(table, row)); return list; } ```
Under the covers, `new T()` generates a call to `System.Activator.CreateInstance<T>()`, which is (reflectively) slow: ``` L_0012: ldc.i4.0 L_0013: stloc.1 L_0014: br.s L_0026 L_0016: ldloc.0 L_0017: ldloc.1 L_0018: call !!0 [mscorlib]System.Activator::CreateInstance<!!T>() L_001d: stelem.any !!T L_0022: ldloc.1 L_0023: ldc.i4.1 L_0024: add L_0025: stloc.1 ``` You may wish to consider passing in a construction delegate instead.
The title of your question suggests that this has to do with the fact that the method is generic. Is allocating the same number of objects without generics faster? If not, it must be to do with whatever work's going on in your constructor. Can you post the constructor code? **EDITED** Here is something I wrote awhile ago to cache constructors in a DynamicMethod, which is very fast: In your class: ``` delegate T ConstructorDelegate(); ``` The method body: ``` DynamicMethod method = new DynamicMethod(string.Empty, typeof(T), null, MethodBase.GetCurrentMethod().DeclaringType.Module); ILGenerator il = method.GetILGenerator(); il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes)); il.Emit(OpCodes.Ret); var constructor = (ConstructorDelegate)method.CreateDelegate(typeof(ConstructorDelegate)); ```
How can I speed up instantiating a large collection of objects?
[ "", "c#", "performance", "" ]
``` {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} ``` I have a array which located in the file , how can I read it using C sharp?
Well, I would probably use a different format, but... ``` using ( Stream stream = new FileStream( @"C:\foo.txt", FileMode.Open ) ) using ( TextReader reader = new StreamReader( stream ) ) { string contents = reader.ReadToEnd( ); contents = contents.Replace( "{", "" ).Replace( "}", "" ); var values = new List<int>(); foreach ( string s in contents.Split( ',' ) ) { try { values.Add( int.Parse( s ) ); } catch ( FormatException fe ) { // ... } catch ( OverflowException oe ) { // ... } } } ```
Read the line into a string. Lose the curlies, split on commas, cast each token into an integer and append it to a List. Finally use ToArray() to get back an int[] Look at the `System.IO.File` and `System.String` type documentation in MSDN. You should find members to help you accomplish your goal.
How to read arrays from file in C#
[ "", "c#", "" ]
Let's say I have the following XML: ``` <Account> <AccountExpirationDate>6/1/2009</AccountExpirationDate> </Account> ``` I want to use LINQ to XML to parse this into an object I'll call Account: ``` public class Account { public DateTime? AccountExpirationDate { get; set; } } ``` This is the C# code I've tried, but it won't let me use null: ``` var accountSettings = from settings in templateXML.Descendants("Account") select new Account { AccountExpirationDate = string.IsNullOrEmpty(settings.Element("AccountExpirationDate").Value) ? DateTime.Parse(settings.Element("AccountExpirationDate").Value) : null }; ``` Is there a way for me to only assign AccountExpiration a date if the element exists in the XML? In my business logic it is acceptable for the value to be null. Thanks!
``` var accountSettings = from settings in templateXML.Descendants("Account") select new Account { AccountExpirationDate = string.IsNullOrEmpty((string)settings.Element("AccountExpirationDate")) ? (DateTime?)null : DateTime.Parse(settings.Element("AccountExpirationDate").Value) }; ```
You can just use: ``` from settings in templateXML.Descendants("Account") let el = settings.Element("AccountExpirationDate") let el2 = (el == null || string.IsNullOrEmpty(el.Value)) ? null : el select new Account { AccountExpirationDate = (DateTime?)el2 }; ``` there is a conversion operator that works this magic using standard xml datetime formatting, and which returns null if the element doesn't exist (note I don't read `.Value`).
Linq to XML - Check for null element while parsing for DateTime
[ "", "c#", ".net", "linq-to-xml", "" ]
It must be a somewhat common event to change the name of a property and expect the Rename functionality in Visual Studio to take care of all the necessary renaming, except for the property name of the PropertyChanged event of INotifyPropertyChanged. Is there a better way to somehow get it strongly typed so you don't need to remember to manually rename it?
Edit: `nameof` arrived in c# 6. Yay! --- There is no `nameof` / `infoof` etc; this is much discussed, but it is what it is. There is a way to do it using lambda expressions in .NET 3.5 (and parsing the expression tree), but in reality it isn't worth the overhead. For now, I'd just stick with strings (and unit tests if you are determined not to break it). --- ``` using System; using System.ComponentModel; using System.Linq.Expressions; using System.Reflection; class Program : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; static void Main() { var p = new Program(); p.PropertyChanged += (s, a) => Console.WriteLine(a.PropertyName); p.Name = "abc"; } protected void OnPropertyChanged<T>(Expression<Func<Program, T>> property) { MemberExpression me = property.Body as MemberExpression; if (me == null || me.Expression != property.Parameters[0] || me.Member.MemberType != MemberTypes.Property) { throw new InvalidOperationException( "Now tell me about the property"); } var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(me.Member.Name)); } string name; public string Name { get{return name;} set { name = value; OnPropertyChanged(p=>p.Name); } } } ```
C# 5 seem to have a solution. With an [`CallerMemberName` attribute](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx) that can be used with parameters ([One example on the net](http://jesseliberty.com/2012/06/28/c-5making-inotifypropertychanged-easier/)). ``` class Employee : INotifyPropertyChanged { private string _Name; public string Name { get { return _Name; } set { _Name = value; RaisePropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged([CallerMemberName] string caller = "") { var temp = PropertyChanged; if ( temp != null ) { temp( this, new PropertyChangedEventArgs( caller ) ); } } } ```
Is there a good strongly typed way to do PropertyChanged events in C#?
[ "", "c#", "inotifypropertychanged", "strong-typing", "" ]
I have something that looks like the following: ``` var someList = MockRepository.GenerateStub<IList<ISomething>>(); someList.Add(MockRepository.GenerateStub<ISomething>()); ``` The list gets created as a proxy correctly. However, whenever I try to add an item to the list, it doesn't add the item to the list. I have a feeling this is because the proxy class has no implementation of Add, but I'm wondering how I would remedy this situation without just doing this instead: ``` var someList = new List<ISomething>(); someList.Add(MockRepository.GenerateStub<ISomething>()); ``` Why would I want to do this? Let's say I have my own special kind of list, say MySpecialList, which is an IList, but in my unit test I don't want to go through the hassle of instanting it, I'd rather just stub it's Add behavior.
If you actually want the list to behave as a list, why are you stubbing it anyway? Is it just a list of stubs you are after? In which case instantiate a concrete list and add a stubbed ISomething to it.
You probably don't really need to have the items added do you? Can't you just set expectations on the number of times that Add() is called and then have something like Count() return the value expected? Basically you're mocking a List which, I assume, means you're testing a class that depends on the behavior and not the implementation of the list. ``` Expect.Call(() => someList.Add(1)); Expect.Call(() => someList.Add(2)); Expect.Call(() => someList.Add(3)); Expect.Call(someList.Count()).Returns(3); methodBeingTested.Call(someList); mocks.VerifyAll(); ``` That tests that 'methodBeingTested' adds three values and then calls Count() on the list it added the items to.
RhinoMocks: IList<T> Stub doesn't add items to the list after it's been stubbed
[ "", "c#", "rhino-mocks", "" ]
I just saw this topic: [Datatable vs Dataset](https://stackoverflow.com/questions/2250/datatable-vs-dataset) but it didn't solve my doubt .. Let me explain better, I was doing connection with database and needed to show the results in a GridView. (I used RecordSet when I worked with VB6 while ago and DataSet is pretty similar to it so was much easier to use DataSet.) Then a guy told me DataSet wasn't the best method to do .. So, should I 'learn' DataReader or keep using DataSet ? DataTable ? What are the pros/cons ?
That is essentially: "which is better: a bucket or a hose?" A `DataSet` is the bucket here; it allows you to carry around a disconnected set of data and work with it - but you will incur the cost of carrying the bucket (so best to keep it to a size you are comfortable with). A data-reader is the hose: it provides one-way/once-only access to data as it flies past you; you don't have to carry all of the available water at once, but it needs to be connected to the tap/database. And in the same way that you can fill a bucket with a hose, you can fill the `DataSet` with the data-reader. The point I'm trying to make is that they do different things... I don't personally use `DataSet` very often - but some people love them. I do, however, make use of data-readers for BLOB access etc.
It depends on your needs. One of the most important differences is that a DataReader will retain an open connection to your database until you're done with it while a DataSet will be an in-memory object. If you bind a control to a DataReader then it's still open. In addition, a DataReader is a forward only approach to reading data that can't be manipulated. With a DataSet you can move back and forth and manipulate the data as you see fit. Some additional features: DataSets can be serialized and represented in XML and, therefore, easily passed around to other tiers. DataReaders can't be serialized. On the other hand if you have a large amount of rows to read from the database that you hand off to some process for a business rule a DataReader may make more sense rather than loading a DataSet with all the rows, taking up memory and possibly affecting scalability. Here's a link that's a little dated but still useful: [Contrasting the ADO.NET DataReader and DataSet](http://msdn.microsoft.com/en-us/magazine/cc188717.aspx).
What's better: DataSet or DataReader?
[ "", "c#", "asp.net", "ado.net", "" ]
Does anyone know of a good tool for laying out class diagrams and the like for eclipse? Preferably soemthing that will let me draw up the relationships between the classes/interfaces and will then generate stub code for me to fill in. I've just been handed a 288 page API doc and told to implement it in Java and I want to make sure I have a good design before I start writing code.
You're probably looking for an UML tool. Check the [relevant Eclipse Plugin Central category](http://www.eclipseplugincentral.com/Web_Links-index-req-viewcatlink-cid-19.html). Note that UML has been a hype. Today, there are people who can live with its shortcomings and there are people who despise it. If you just want to collect and sort your ideas, I suggest to try a [wiki](http://moinmo.in/) or a mindmap ([XMind](http://moinmo.in/) or [FreeMind](http://moinmo.in/)).
I've evaluated several Eclipse based UML tools, and the best by far, in my opinion, was the free edition of Soyatec's eUML2 (<http://www.soyatec.com/euml2/>). Having said that, I should qualify that eUML2 was suitable *for me*, in the sense that I was looking for: 1. Primarily clas and sequence diagram creation (which happens to be the only two diagrams type the free version of eUML2 supports). 2. Built-in support for Java libraries (recognizes all classes in the project class path, I was never able to get Rational Software Architect to do this) and features (e.g., inner classes). 3. Basic code generation (specifically, Java Bean getter/setters). 4. Integration with SCMs (more on this below). If you need more diagrams than what I needed, but are willing to put up with lack of SCM integration, you may want to look into the free version of Omondo EclipseUML (<http://www.eclipsedownload.com/> - as far as I can tell, this is a fork of Soyatec's product), which supports 5-6 different diagrams types, IIRC, but will disable itself if it detects that you've turned on SCM integration on your project (which I find very annoying). Alternative, you can pay for the full versions of either of these. They are really expensive though. Let me know if you need more details.
Good tool for system design in Java/Eclipse?
[ "", "java", "eclipse", "oop", "uml", "" ]
I am storing and editing some field in a database that involves a long string of one or more sentences. whenever i enter a single quote in the textbox and want to save it it throws an exception like *"Incorrect syntax near 'l'. Unclosed quotation mark after the character string ''."* is there any idea to avoid that? **EDIT:** The query is: ``` SqlCommand com = new SqlCommand("UPDATE Questions SET Question = '[" + tbQuestion.Text + "]', Answer = '[" + tbAnswer.Text + "]', LastEdit = '" + CurrentUser.Login + "'WHERE ID = '" + CurrentQuestion.ID + "'"); ```
As KM said, **don't do this!** Do *this* instead: ``` private static void UpdateQuestionByID( int questionID, string question, string answer, string lastEdited) { using (var conn = new SqlConnection(connectionString)) { conn.Open(); const string QUERY = @"UPDATE Questions " + @"SET Question = @Question, Answer = @Answer, LastEdit = @LastEdited " + @"WHERE ID = @QuestionID"; using (var cmd = new SqlCommand(QUERY, conn)) { cmd.Parameters.AddWithValue("@Question", question); cmd.Parameters.AddWithValue("@Answer", answer); cmd.Parameters.AddWithValue("@LastEdited", lastEdited); cmd.Parameters.AddWithValue("@QuestionID", questionID); cmd.ExecuteNonQuery(); } } } ```
If you want to include a single quote into an SQL field, escape it using single quotes ``` '''Test''' = 'Text' ``` This is for SQL Server.
How to Add Quotes to a Dynamic SQL Command?
[ "", "sql", "dynamic-sql", "" ]
I'm trying to compile an old project that was originally designed for Visual Studio 2008 SP0 (I'm using SP1 now). I'm getting these errors. ``` Error 51 error LNK2019: unresolved external symbol "unsigned long __cdecl GetDeviceState(enum DEVICES_ENUM,enum DEVICE_STATE_ENUM &,int &)" (?GetDeviceState@@YAKW4DEVICES_ENUM@@AAW4DEVICE_STATE_ENUM@@AAH@Z) referenced in function _Get1394DeviceStatus Raw1394api.obj raw1394api Error 52 error LNK2019: unresolved external symbol "unsigned long __cdecl SetDeviceState(enum DEVICES_ENUM,enum DEVICE_STATE_ENUM,int &,int &)" (?SetDeviceState@@YAKW4DEVICES_ENUM@@W4DEVICE_STATE_ENUM@@AAH2@Z) referenced in function _Set1394DeviceStatus Raw1394api.obj raw1394api Error 53 error LNK2019: unresolved external symbol "bool __cdecl InstallDevice(wchar_t *)" (?InstallDevice@@YA_NPA_W@Z) referenced in function _InstallDriver Raw1394api.obj raw1394api Error 54 error LNK2019: unresolved external symbol "bool __cdecl UninstallDevice(void)" (?UninstallDevice@@YA_NXZ) referenced in function _UninstallDriver Raw1394api.obj raw1394api Error 55 fatal error LNK1120: 4 unresolved externals f:\InfoSelect My Documents\Zurvan on Windows\raw1394 for Windows by Dmitry\test\raw1394src\Debug\raw1394api.dll raw1394api ```
I would suggest to check the files mentioned in the last row.
Perhaps you need to install the latest Windows SDK.
Visual Studio 2008 build errors
[ "", "c++", "visual-studio-2008", "" ]
Is it possible to compare whole memory regions in a single processor cycle? More precisely is it possible to compare two strings in one processor cycle using some sort of MMX assembler instruction? Or is `strcmp`-implementation already based on that optimization? EDIT: Or is it possible to instruct C++ compiler to remove string duplicates, so that strings can be compared simply by their memory location? Instead of `memcmp(a,b)` compared by `a==b` (assuming that `a` and `b` are both native `const char*` strings).
Not *really*. Your typical 1-byte compare instruction takes 1 cycle. Your best bet would be to use the MMX 64-bit compare instructions( see [this page for an example)](http://www.tommesani.com/MMXComparison.html). However, those operate on registers, which have to be loaded from memory. The memory loads will significantly damage your time, because you'll be going out to L1 cache at best, which adds some 10x time slowdown\*. If you are doing some heavy string processing, you can probably get some nifty speedup there, but again, it's going to hurt. Other people suggest pre-computing strings. Maybe that'll work for your particular app, maybe it won't. Do you *have* to compare strings? Can you compare numbers? Your edit suggests comparing pointers. That's a dangerous situation unless you can specifically guarantee that you won't be doing substring compares(ie, you are comparing some two byte strings: [0x40, 0x50] with [0x40, 0x42]. Those are not "equal", but a pointer compare would say they are). Have you looked at the gcc strcmp() source? I would suggest that doing that would be the ideal starting place. \* Loosely speaking, if a cycle takes 1 unit, a L1 hit takes 10 units, an L2 hit takes 100 units, and an actual RAM hit takes *really long*.
Just use the standard C `strcmp()` or C++ `std::string::operator==()` for your string comparisons. The implementations of them are reasonably good and are probably compiled to a very highly optimized assembly that even talented assembly programmers would find challenging to match. So don't sweat the small stuff. I'd suggest looking at optimizing other parts of your code.
C++ string comparison in one clock cycle
[ "", "c++", "string", "assembly", "comparison", "" ]
I'm generating an image out of text using php. My code works perfectly on my localhost and the text is generated fine. However on my online host it doesn't generate the whole text just bits and pieces of it. Like if I were to pass the text 'This is some text' to it - it would generate just maybe an S or t. The code is fine as it works perfectly on my localhost but doesn't run on the online host. It cant be that gd isnt on the host else it would not even generate part of the image. WHats going on here :( --- **UPDATE** This is the GD CONfig on teh server - I don't think there is anything wrong with it ``` gd GD Support enabled GD Version bundled (2.0.34 compatible) FreeType Support enabled FreeType Linkage with freetype FreeType Version 2.2.1 GIF Read Support enabled GIF Create Support enabled JPG Support enabled PNG Support enabled WBMP Support enabled XBM Support enabled ``` I'm just turning email addresses and fone numbers into one image. Heres an image of what the text should look like: ![localhost image](https://i.stack.imgur.com/JA8BJ.jpg) But this is what its rendering on the online: ![online image mess](https://i.stack.imgur.com/5U5th.jpg) --- **UPDATE** I just found out something weird. If I try to create an image out of the text 'P P' it should create the following image which it does on my localhost. ![what I want](https://i.stack.imgur.com/mJ2I6.jpg) But on the online server its creating the image as so - the space is humongous and distorted. Could this be a hint as to why is it not rendering the text as it should. ![bad pic](https://i.stack.imgur.com/Ueut6.jpg) Please guys I need help here urgently :(.
Compare your local phpinfo() to the live phpinfo() and look for differences. Turn on full error reporting in the image generation script: ``` ini_set("display_errors","2"); error_reporting(E_ALL); ``` Then run it directly by pointing your browser at the URL that renders the image.
see if the GD library is install in server Correctly
Generating Image from text in php - not generating on my online host?
[ "", "php", "image-processing", "" ]
I am looking at writing a Java web application on Google App Engine. I want to be able to upload and serve images from the app but just realised that the Datastore have a 1MB limit. This is slightly too little for decent pictures. Is there an alternative way you can suggest of doing this? Perhaps storing those as static content rather than in the Datastore but there seems to be no API for this.
Now it is possible on GAE. Simply you have to store your files in [Blobstore](http://code.google.com/appengine/docs/java/blobstore/overview.html). You can upload your files like this: ``` <body> <form action="<%= blobstoreService.createUploadUrl("/upload") %>" method="post" enctype="multipart/form-data"> <input type="file" name="myFile"> <input type="submit" value="Submit"> </form> ``` And then to serve file from servlet: ``` public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { BlobKey blobKey = new BlobKey(req.getParameter("blob-key")); blobstoreService.serve(blobKey, res); ```
You can't write to the filesystem in App Engine, so static content is out for now - but an API for storing and serving blobs is on the roadmap. In the meantime, your best bet is to split the file into chunks, and store those in the datastore, or to use an external service like S3.
Storing uploaded images on Google App Engine with Java
[ "", "java", "google-app-engine", "image", "upload", "" ]
Consider the following class hierarchy: ``` public class Foo { public string Name { get; set; } public int Value { get; set; } } public class Bar { public string Name { get; set; } public IEnumerable<Foo> TheFoo { get; set; } } public class Host { public void Go() { IEnumerable<Bar> allBar = //Build up some large list //Get Dictionary<Bar, Foo> with max foo value } } ``` What I would like to do using Linq2Objects is to get an KeyValuePair where for each Bar in the allBBar collection we select the Foo with the maximum Value property. Can this be done easily in a single LINQ statement?
Sure, although my preferred solution uses [`MaxBy`](http://code.google.com/p/morelinq/source/browse/trunk/MoreLinq/MaxBy.cs) from [MoreLINQ](http://code.google.com/p/morelinq/): ``` var query = allBar.ToDictionary(x => x, // Key x => x.TheFoo.MaxBy(f => f.Value)); ``` Note that this will go pear-shaped if `TheFoo` is empty for any `Bar` instance.
Another way using Aggregate instead of OrderBy so that figuring out the max Foo is O(n) instead of O(n log n): ``` var query = allBar.ToDictionary( bar => bar, bar => bar.TheFoo.Aggregate( null, (max, foo) => (max == null || foo.Value > max.Value) ? foo : max)); ```
LINQ - Select correct values from nested collection
[ "", "c#", "linq", "linq-to-objects", "" ]
I have written this clone method for when the parent of the Employee class is abstract and the clone() method in the parent class is abstract.I wanted to copy the primitive data type of the Employee's object with this code instead of copying each primitive data type individually, but this code has problem with the line that I call clone() method. (This code is in Employee class) ``` public Object clone() { Object obj = new Object(); Object object = obj.clone(); //Emphasis here return object; } ``` the error is: The method clone() from the type Object is not visible. But my Employee class is in the class hierarchy which can access the protected clone() method in the Object class. This is my simple Employee class: ``` public class Employee extends Person implements Cloneable { private int ID; public Employee() { ID = 0; } public void setID(int ID) { this.ID = ID; } public int getID() { return ID; } public Object clone1() throws CloneNotSupportedException { try { Object obj = new Object(); Object object = obj.clone(); return object; } catch (CloneNotSupportedException ex) { return null; } } ```
Did you implement the Cloneable interface on your object? However, there are very few cases I would use clone for copying an object. One such safe example is array.clone(). I would rather use the copy-constructor idiom or manually copying / assigning values around. There is Item#11 in [Effective Java](http://java.sun.com/docs/books/effective/) (2nd edition) about the background issue. Cloneable interface is a special kind of interface as it modifies the `Object` class' behavior regarding the cloning. Basically it is a feature enabling classinterface in Java. **Edit:** Based on your example you might need to wrap the clone() call in a try-catch of CloneNotSupportedException in a general case. **Edit2:** Rephrased my answer **Edit3:** Did you override the clone() in the `public` context? In the sample you gave you try to clone an Object, which is in the java.lang package - hardly the package your code is in. **Edit4:** I think the answer is already in the other posts, just wanted to reflect on the underlying issue. **Edit5:** Try this: ``` public Object clone1() throws CloneNotSupportedException { return super.clone(); } ``` **Edit6** Then name your method `public abstract Object copy()` for example and in the implementation, use the super.clone() - to avoid confusion. **Edit7** I did some eclipsing and came out with the following solution: ``` public class Cloner { public static abstract class Person { protected abstract Object clone1() throws CloneNotSupportedException; public Object copy() throws CloneNotSupportedException { return clone1(); } } public static class Employee extends Person implements Cloneable { @Override protected Object clone1() throws CloneNotSupportedException { return super.clone(); } } public static void main(String[] args) throws Exception { new Employee().copy(); } } ``` But basically it is the same concept as renaming your abstract method to something else than clone(). **Edit8:** Fixed my sample, now it works without exception. (But the actual credit goes to *Gábor Hargitai* for `super.clone()`)
The standard pattern for making a class cloneable is: 1. Implement `Cloneable` 2. Override the `clone()` method and make it public 3. In `clone()` call `super.clone()` and then copy any mutable object's state You should **not** create a new object using `new`. The proper way is to call `super.clone()` for a new instance. `Object`'s `clone()` is special and will create a new copy of the object and copy its primitive fields and references. For example: ``` public class Person implements Cloneable { protected String name; // Note that overridden clone is public public Object clone() { Person clone = (Person)super.clone(); // No need to copy name as the reference will be // copied by Object's clone and String is immutable return clone; } } public class Employee extends Person { protected int id; protected java.awt.Point location; public Object clone() { Employee clone = (Employee )super.clone(); // No need to copy id as Object's clone has already copied it // Need to clone location as Point is mutable and could change clone.location = location.clone(); return clone; } } ```
What is wrong with this clone()?
[ "", "java", "clone", "" ]
Do you know any controls inherited from the ItemsControl that have horizontal orientation of items?
Simply change the panel used to host the items: ``` <ItemsControl ...> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> ```
While the promoted answer is great, here's an alternative if you want the items to stretch. ``` <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Rows="1" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> ```
ItemsControl with horizontal orientation
[ "", "c#", "wpf", "wpf-controls", "" ]
is there some way to tell sql server to use the (nolock) hint or every select in a stored procedure? is pretty tiresome to add it to each an every select....
found this.... [How to force nolock hint for sql server logins](https://stackoverflow.com/questions/64208/how-to-force-nolock-hint-for-sql-server-logins) seems like the best way to achieve this is to issue a SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED any other idea??? ps another related question... [NOLOCK vs. Transaction Isolation Level](https://stackoverflow.com/questions/1018651/nolock-vs-transaction-isolation-level)
As others quite rightly say, a global (nolock) is done using READ UNCOMMITTED. However, before going down that route, it's worth trying READ COMMITTED SNAPSHOT first. This means your reads won't be locked by in progress inserts / updates and means that the data isn't dirty, just out of date.
SQL Server - how to set (nolock) hint as a default?
[ "", "sql", "sql-server", "select", "locking", "nolock", "" ]
While monitoring our application in Perf Mon I noticed that the % of Time In GC is anywhere from 20 - 60% while our application is performing a long running process (varies between 30 seconds to 1.5 minutes). This seems a bit excessive to me. This raises two important questions. 1. Am I correct that this excessive? 2. How can I figure out why route causes GC spikes?
Yes, this does sound excessive. Reducing the amount of GC would probably be the single best step you could take to reducing the runtime of your application (if that is your goal). A high "% time in GC" is typically caused by allocating and then throwing away thousands or millions of objects. A good way to find out what's going on is to use a memory profiler tool. Microsoft provides the free [CLR Profiler](http://www.microsoft.com/downloads/details.aspx?familyid=A362781C-3870-43BE-8926-862B40AA0CD0&displaylang=en). This will show you every allocation, but will make your app run 10-60 times slower. You may need to run it on less input data so that it can finish analyzing in a reasonable amount of time. A great commercial tool is SciTech's [.NET Memory Profiler](http://www.memprofiler.com/). This imposes much less runtime overhead, and there is a free trial available. By taking multiple snapshots while your process is running, you can find out what type of objects are being frequently allocated (and then destroyed). Once you've identified the source of the allocations, you then need to examine the code and figure out how those allocations can be reduced. While there are no one-size-fits-all answers, some things I've encountered in the past include: * String.Split can create hundreds of small short-lived strings. If you're doing a lot of string manipulation, it can help to process the string by walking it character-by-character. * Creating arrays or lists of thousands of small classes (say, under 24 bytes in size) can be expensive; if those classes can be treated as value types, it can (sometimes) greatly improve things to change them to structs. * Creating thousands of small arrays can increase memory usage a lot (because each array has a small amount of overhead); sometimes these can be replaced with one large array and indexes into a sub-section of it. * Having a lot of finalizable objects (particularly if they're not being disposed) can put a lot of pressure on the garbage collector; ensure that you're correctly disposing all IDisposable objects, and note that your own types should (almost) [never have finalizers](http://www.bluebytesoftware.com/blog/2005/12/27/NeverWriteAFinalizerAgainWellAlmostNever.aspx). * Microsoft has an article with [Garbage Collection Guidelines](http://msdn.microsoft.com/en-us/library/ms998547.aspx#scalenetchapt05_topic10) for improving performance.
Am I correct that this excessive? **Yes, you are correct** How can I figure out why route causes GC spikes? 1.- Do take a look at **[PerfView](https://github.com/Microsoft/perfview)** > PerfView is a performance-analysis tool that helps isolate CPU- and > memory-related performance issues. See Also: [Improving Managed Code Performance](https://msdn.microsoft.com/en-us/library/ff647790.aspx) 2.- See if GC.Collect or GC.WaitForPendingFinalizers is being called anywhere in your code or third party library. The latter can cause high CPU utilization.
Reasons for seeing high "% Time in GC" in Perf Mon
[ "", "c#", ".net", "memory", "memory-management", "" ]
Is it possible to add Dependent Breakpoints(Not a Conditional Bp) ( Breakpoint1 is enabled if B2 is enabled etc..) in Eclipse... I know it is possible in Intellij IDea ..but havent found a way to get this working in Eclipse. Thanks, Pavan
Eclipse thus far only supports conditional breakpoints, where the execution will suspend if a condition supplied evaluates to true. Thus, you could set the conditional of your breakpoint to be ``` objectReference == null ``` and eclipse will hit that break point if and only if that condition evaluates to true. These expressions can be as complex as you would like, but they can only reference values from your source code, not values from the eclipse environment (thus, you can't hit a second break point if a first one was hit, like you originally asked for). This conditional logic can be accessed by right clicking on a breakpoint and selecting "Breakpoint Properties...". Instead, what I've found helpful is the "Run to Line" ability ([ctrl]+R, in the Run menu). When you're insertion point is on any later line while the execution is suspended, you can use the "Run to line" command to continue execution to that point in the source as if there was a break point set there. In essence, it basically sets and unsets a temporary breakpoint on the line of code your insertion point is at. The greatest part of the command is that it works across files, so that you can hit a break point in one file, go to the file where you would place the dependent break point, [ctrl]+R to that line in the second file. Its a great way to "breakpoint" to a specific line in a file without setting a full breakpoint that will be hit everytime.
Do you mean a conditional breakpoint. If you mean a conditional breakpoint, it is possible in Eclipse. Right click on the break point select breakpoint properties. Then you can add the condition.
Dependent Breakpoints
[ "", "java", "eclipse", "debugging", "" ]
Using Winspector I've found out the ID of the child textbox I want to change is 114. Why isn't this code changing the text of the TextBox? ``` [DllImport("user32.dll")] static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem); [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int msg, int Param, string s); const int WM_SETTEXT = 0x000c; private void SetTextt(IntPtr hWnd, string text) { IntPtr boxHwnd = GetDlgItem(hWnd, 114); SendMessage(boxHwnd, WM_SETTEXT, 0, text); } ```
The following is what I've used successfully for that purpose w/ my GetLastError error checking removed/disabled: ``` [DllImport("user32.dll", SetLastError = false)] public static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] public static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, string lParam); public const uint WM_SETTEXT = 0x000C; private void InteropSetText(IntPtr iptrHWndDialog, int iControlID, string strTextToSet) { IntPtr iptrHWndControl = GetDlgItem(iptrHWndDialog, iControlID); HandleRef hrefHWndTarget = new HandleRef(null, iptrHWndControl); SendMessage(hrefHWndTarget, WM_SETTEXT, IntPtr.Zero, strTextToSet); } ``` I've tested this code and it works, so if it fails for you, you need to be sure that you are using the right window handle (the handle of the Dialog box itself) and the right control ID. Also try something simple like editing the Find dialog in Notepad. I can't comment yet in the post regarding using (char \*) but it's not necessary. See the second C# overload in [p/Invoke SendMessage](http://www.pinvoke.net/default.aspx/user32/SendMessage.html). You can pass String or StringBuilder directly into SendMessage. I additionally note that you say that your control ID is 114. Are you certain WinSpector gave you that value in base 10? Because you are feeding it to GetDlgItem as a base 10 number. I use Spy++ for this and it returns control IDs in base 16. In that case you would use: ``` IntPtr boxHwnd = GetDlgItem(hWnd, 0x0114); ```
Please convert your control id (obtained from spy ++) from Hexdecimal Number to Decimal Number and pass that value to the GetDlgItem function.With this you will get the handle of Text box.This worked for me. ``` [DllImport("user32.dll")] static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem); [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int msg, int Param, string s); const int WM_SETTEXT = 0x000c; private void SetTextt(IntPtr hWnd, string text) { IntPtr boxHwnd = GetDlgItem(hWnd, 114); SendMessage(boxHwnd, WM_SETTEXT, 0, text); } ```
SetText of textbox in external app. Win32 API
[ "", "c#", "winapi", "interop", "" ]
I want to do the equivalent of this: ``` byte[] byteArray; enum commands : byte {one, two}; commands content = one; byteArray = (byte*)&content; ``` yes, it's a byte now, but consider I want to change it in the future? how do I make byteArray contain content? (I don't care to copy it).
The [BitConverter](http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx) class might be what you are looking for. Example: ``` int input = 123; byte[] output = BitConverter.GetBytes(input); ``` If your enum was known to be an Int32 derived type, you could simply cast its values first: ``` BitConverter.GetBytes((int)commands.one); ```
To convert any value types (not just primitive types) to byte arrays and vice versa: ``` public T FromByteArray<T>(byte[] rawValue) { GCHandle handle = GCHandle.Alloc(rawValue, GCHandleType.Pinned); T structure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); handle.Free(); return structure; } public byte[] ToByteArray(object value, int maxLength) { int rawsize = Marshal.SizeOf(value); byte[] rawdata = new byte[rawsize]; GCHandle handle = GCHandle.Alloc(rawdata, GCHandleType.Pinned); Marshal.StructureToPtr(value, handle.AddrOfPinnedObject(), false); handle.Free(); if (maxLength < rawdata.Length) { byte[] temp = new byte[maxLength]; Array.Copy(rawdata, temp, maxLength); return temp; } else { return rawdata; } } ```
how to convert a value type to byte[] in C#?
[ "", "c#", "arrays", "" ]
In VS 2008, I have an ASP.NET content page having one master page. I would like to add JavaScript functions for client side validation etc. for this page. My questions are: 1. Should I write these scripts in a separate `.js` file, or embedded within the `.aspx` file. 2. Does this choice affect the performance of the website? 3. Are there any rules for writing a JavaScript file?
It depends on your use. If its a page specific functionality then try and implement it in the page itself. If it is used by many pages then put that inside a js file. > Does it affect the performance of > website? Yes, it can. If you have a js file with thousands of lines of code and in a page you have to call only one function inside the js file. If you refer the file for this one there should be a bandwidth wastage in downloading the entire file. For this case you can write the function inside the same page itself. On the other side browser can cache a js file. So for subsequent requests if the file is present in the cache it won't be downloaded again. But in the case of JavaScript being written in the page itself, every time the page loads all of its contents will be downloaded.
I would say, you should create javascripts functions into separate .js file and link them up inside the the master page or .ASPX where it's needed. Imagine you "copy and paste" the javascripts functions in each of the .ASPX, then when that .ASPX file is loaded, it will take longer to render that page since it needs to render also the javascript functions. If you maintain it into separate .js file, the browser will only download once if it's newer or not exist before. You can also cache those .js files, so that the browsers won't reload it everytime. The other advantage is when you need to make some changes in the .js files, you just need it to modify it centrally at one file, rather than do a "Find and Replace" through numerous .ASPX
Where should I put my JavaScript - page or external file?
[ "", "asp.net", "javascript", "asp.net-2.0", "code-organization", "" ]
I have a list like: ``` list = [[1,2,3],[4,5,6],[7,8,9]] ``` I want to append a number at the start of every value in the list programmatically, say the number is 9. I want the new list to be like: ``` list = [[9,1,2,3],[9,4,5,6],[9,7,8,9]] ``` How do I go about doing this in Python? I know it is a very trivial question but I couldn't find a way to get this done.
``` for sublist in thelist: sublist.insert(0, 9) ``` **don't** use built-in names such as `list` for your own stuff, that's just a stupid accident in the making -- call YOUR stuff `mylist` or `thelist` or the like, **not** `list`. **Edit**: as the OP aks how to insert > 1 item at the start of each sublist, let me point out that the most efficient way is by assignment of the multiple items to a slice of each sublist (most list mutators can be seen as readable alternatives to slice assignments;-), i.e.: ``` for sublist in thelist: sublist[0:0] = 8, 9 ``` `sublist[0:0]` is the empty slice at the start of `sublist`, and by assigning items to it you're inserting the items at that very spot.
``` >>> someList = [[1,2,3],[4,5,6],[7,8,9]] >>> someList = [[9] + i for i in someList] >>> someList [[9, 1, 2, 3], [9, 4, 5, 6], [9, 7, 8, 9]] ``` (someList because list is already used by python)
Modifying list contents in Python
[ "", "python", "list", "" ]
I am trying to write a javascript function with an "if" statement that will execute a command if the text between two tags match. I have been able to write many "if" statements in which a command is executed when the value within an input textbox equals that of the "if" statement criteria such as: ``` function Test() { if (document.getElementById('A').value == 1) { alert('test'); } } <input type="button" id="B" onCLick="Test()"/> <input type="text" id="A"/> ``` When I enter "1" in the textbox and press the button, an alert box will appeare. The problem that I am having is that I would like to do the same with text bewteen two tags. For example: ``` function Test() { if (document.getElementById('A').value == 1) { alert('test'); } } <input type="button" id="B" onCLick="Test()"/> <p id="A">1</p> ``` In my project I would be using words instead of numbers, so I understand that I would have to surround the word in quotes. Unfortunately, this doesn't work. Is it possible to write an "if" statement like the one above that determines if text between two tags is true? Also, I have tried document.getElementById('A').text, and document.getElementById('A').innerHTML, but none of those made a difference. I ave even tried using one equal sign instead of two; however, that would make all criteria true, regardless if it were true or not. Thanks DFM
This should do what you want. ``` <html> <input id="test" type="text" value="hello"> <script> if (document.getElementById('test').value == "hello") alert("hello"); </script> </html> ```
``` if(document.getElementById("myID").innerHTML == "1") ``` Would evaluate to true if the element in question (e.g a div) had the following markup. ``` <div>1</div> ``` You could also use [jQuery](http://jquery.com "jQuery") ``` if($(element).text() == "1") ```
Javascript If Statement for Text between two Tags
[ "", "javascript", "dom", "" ]
This question has been puzzling me for a long time now. I come from a heavy and long C++ background, and since I started programming in C# and dealing with garbage collection I always had the feeling that such 'magic' would come at a cost. I recently started working in a big MMO project written in Java (server side). My main task is to optimize memory comsumption and CPU usage. Hundreds of thousands of messages per second are being sent and the same amount of objects are created as well. After a lot of profiling we discovered that the VM garbage collector was eating a lot of CPU time (due to constant collections) and decided to try to minimize object creation, using pools where applicable and reusing everything we can. This has proven to be a really good optimization so far. So, from what I've learned, having a garbage collector is awesome, but you can't just pretend it does not exist, and you still need to take care about object creation and what it implies (at least in Java and a big application like this). So, is this also true for .NET? if it is, to what extent? I often write pairs of functions like these: ``` // Combines two envelopes and the result is stored in a new envelope. public static Envelope Combine( Envelope a, Envelope b ) { var envelope = new Envelope( _a.Length, 0, 1, 1 ); Combine( _a, _b, _operation, envelope ); return envelope; } // Combines two envelopes and the result is 'written' to the specified envelope public static void Combine( Envelope a, Envelope b, Envelope result ) { result.Clear(); ... } ``` A second function is provided in case someone has an already made Envelope that may be reused to store the result, but I find this a little odd. I also sometimes write structs when I'd rather use classes, just because I know there'll be tens of thousands of instances being constantly created and disposed, and this feels really odd to me. I know that as a .NET developer I shouldn't be worrying about this kind of issues, but my experience with Java and common sense tells me that I should. Any light and thoughts on this matter would be much appreciated. Thanks in advance.
Yes, it's true of .NET as well. Most of us have the luxury of ignoring the details of memory management, but in your case -- or in cases where high volume is causing memory congestion -- then some optimizaition is called for. One optimization you might consider for your case -- something I've been thinking about writing an article about, actually -- is the combination of structs and `ref` for real deterministic disposal. Since you come from a C++ background, you know that in C++ you can instantiate an object either on the heap (using the new keyword and getting back a pointer) or on the stack (by instantiating it like a primitive type, i.e. `MyType myType;`). You can pass stack-allocated items by reference to functions and methods by telling the function to accept a reference (using the `&` keyword before the parameter name in your declaration). Doing this keeps your stack-allocated object in memory for as long as the method in which it was allocated remains in scope; once it goes out of scope, the object is reclaimed, the destructor is called, ba-da-bing, ba-da-boom, Bob's yer Uncle, and all done without pointers. I used that trick to create some amazingly performant code in my C++ days -- at the expense of a larger stack and the risk of a stack overflow, naturally, but careful analysis managed to keep that risk very minimal. My point is that you can do the same trick in C# using structs and refs. The tradeoffs? In addition to the risk of a stack overflow if you're not careful or if you use large objects, you are limited to no inheritance, and you tightly couple your code, making it it less testable and less maintainable. Additionally, you still have to deal with issues whenever you use core library calls. Still, it might be worth a look-see in your case.
This is one of those issues where it is really hard to pin down a definitive answer in a way that will help you. The .NET GC is *very* good at tuning itself to the memory needs of you application. Is it good enough that your application can be coded without you needing to worry about memory management? I don't know. There are definitely some common-sense things you can do to ensure that you don't hammer the GC. Using value types is definitely one way of accomplishing this but you need to be careful that you don't introduce other issues with poorly-written structs. For the most part however I would say that the GC will do a good job managing all this stuff for you.
Should a programmer really care about how many and/or how often objects are created in .NET?
[ "", "c#", ".net", "memory", "garbage-collection", "" ]
I have a table with timestamp values like: ``` 2009-07-14 02:00:00 ``` I need to display them at run time with 13 hours added, like: ``` 2009-07-14 15:00:00 ``` What's the simplest way to do this in PHP?
I know this was asked a long time ago and I had already chosen the answer, but I believed it's important to point new users in a more modern and correct direction, which is using the fantastic [Carbon](http://carbon.nesbot.com/) library: ``` >>> Carbon\Carbon::parse('2009-07-14 02:00:00') ... ->addHours(13) ... ->format('Y-m-d H:i:s'); => Carbon\Carbon {#869 +"date": "2009-07-14 15:00:00.000000", +"timezone_type": 3, +"timezone": "UTC", } ``` Carbon not only makes it simpler to perform the requested calculation, it also shields you against any potential mistakes you may make while manually trying to do the same thing. The shell in the above output example is Laravel Tinker. Laravel ships with Carbon, so the above statement works out-of-the-box. If you're not using a modern PHP framework, you should be. It's easy to add Carbon to it.
I know that ``` date( "Y-M-d H:i:s", strtotime( $timestamp_from_array ) + 13 * 3600 ); ``` is smelly, but it will give you an idea. `strtotime` converts the timestamp string to a timestamp value, then we add the hours and convert it back to the timestamp format in the array with the `date` function. But I suppose what you really want is to use [time zones](http://pl.php.net/manual/pl/datetimezone.getoffset.php). Edit: [igstan](https://stackoverflow.com/questions/1124752/1124811#1124811) is correct, you should also mind the daylight saving time changes between those offsets.
Add 13 hours to a timestamp
[ "", "php", "time", "" ]
Which code snippet will give better performance? The below code segments were written in C#. 1. ``` for(int tempCount=0;tempCount<list.count;tempcount++) { if(list[tempCount].value==value) { // Some code. } } ``` ``` foreach(object row in list) { if(row.value==value) { //Some coding } } ```
Well, it partly depends on the exact type of `list`. It will also depend on the exact CLR you're using. Whether it's in any way *significant* or not will depend on whether you're doing any real work in the loop. In almost *all* cases, the difference to performance won't be significant, but the difference to readability favours the `foreach` loop. I'd personally use LINQ to avoid the "if" too: ``` foreach (var item in list.Where(condition)) { } ``` EDIT: For those of you who are claiming that iterating over a `List<T>` with `foreach` produces the same code as the `for` loop, here's evidence that it doesn't: ``` static void IterateOverList(List<object> list) { foreach (object o in list) { Console.WriteLine(o); } } ``` Produces IL of: ``` .method private hidebysig static void IterateOverList(class [mscorlib]System.Collections.Generic.List`1<object> list) cil managed { // Code size 49 (0x31) .maxstack 1 .locals init (object V_0, valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<object> V_1) IL_0000: ldarg.0 IL_0001: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> class [mscorlib]System.Collections.Generic.List`1<object>::GetEnumerator() IL_0006: stloc.1 .try { IL_0007: br.s IL_0017 IL_0009: ldloca.s V_1 IL_000b: call instance !0 valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<object>::get_Current() IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: call void [mscorlib]System.Console::WriteLine(object) IL_0017: ldloca.s V_1 IL_0019: call instance bool valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<object>::MoveNext() IL_001e: brtrue.s IL_0009 IL_0020: leave.s IL_0030 } // end .try finally { IL_0022: ldloca.s V_1 IL_0024: constrained. valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<object> IL_002a: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_002f: endfinally } // end handler IL_0030: ret } // end of method Test::IterateOverList ``` The compiler treats *arrays* differently, converting a `foreach` loop basically to a `for` loop, but not `List<T>`. Here's the equivalent code for an array: ``` static void IterateOverArray(object[] array) { foreach (object o in array) { Console.WriteLine(o); } } // Compiles into... .method private hidebysig static void IterateOverArray(object[] 'array') cil managed { // Code size 27 (0x1b) .maxstack 2 .locals init (object V_0, object[] V_1, int32 V_2) IL_0000: ldarg.0 IL_0001: stloc.1 IL_0002: ldc.i4.0 IL_0003: stloc.2 IL_0004: br.s IL_0014 IL_0006: ldloc.1 IL_0007: ldloc.2 IL_0008: ldelem.ref IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: call void [mscorlib]System.Console::WriteLine(object) IL_0010: ldloc.2 IL_0011: ldc.i4.1 IL_0012: add IL_0013: stloc.2 IL_0014: ldloc.2 IL_0015: ldloc.1 IL_0016: ldlen IL_0017: conv.i4 IL_0018: blt.s IL_0006 IL_001a: ret } // end of method Test::IterateOverArray ``` Interestingly, I can't find this documented in the C# 3 spec anywhere...
A `for` loop gets compiled to code approximately equivalent to this: ``` int tempCount = 0; while (tempCount < list.Count) { if (list[tempCount].value == value) { // Do something } tempCount++; } ``` Where as a `foreach` loop gets compiled to code approximately equivalent to this: ``` using (IEnumerator<T> e = list.GetEnumerator()) { while (e.MoveNext()) { T o = (MyClass)e.Current; if (row.value == value) { // Do something } } } ``` So as you can see, it would all depend upon how the enumerator is implemented versus how the lists indexer is implemented. As it turns out the enumerator for types based on arrays are normally written something like this: ``` private static IEnumerable<T> MyEnum(List<T> list) { for (int i = 0; i < list.Count; i++) { yield return list[i]; } } ``` So as you can see, in this instance it won't make very much difference, however the enumerator for a linked list would probably look something like this: ``` private static IEnumerable<T> MyEnum(LinkedList<T> list) { LinkedListNode<T> current = list.First; do { yield return current.Value; current = current.Next; } while (current != null); } ``` In [.NET](http://en.wikipedia.org/wiki/.NET_Framework) you will find that the LinkedList<T> class does not even have an indexer, so you wouldn't be able to do your for loop on a linked list; but if you could, the indexer would have to be written like so: ``` public T this[int index] { LinkedListNode<T> current = this.First; for (int i = 1; i <= index; i++) { current = current.Next; } return current.value; } ``` As you can see, calling this multiple times in a loop is going to be much slower than using an enumerator that can remember where it is in the list.
Performance difference for control structures 'for' and 'foreach' in C#
[ "", "c#", "performance", "for-loop", "foreach", "" ]
I'm building an application that eventually needs to process cc #s. I'd like to handle it completely in my app, and then hand off the information securely to my payment gateway. Ideally the user would have no interaction with the payment gateway directly. Any thoughts? Is there an easier way?
Most payment gateways offer a few mechanisms for submitting CC payments: 1) A simple HTTPS POST where your application collects the customer's payment details (card number, expiry date, amount, optional CVV) and then submits this to the gateway. The payment parameters are sent through in the POST variables, and the gateway returns a HTTP response. 2) Via an API (often XML over HTTPS). In this case your application collects the customer's payment details, constructs an XML document encapsulating the payment details, and then posts this information to the gateway. The gateway response will be an XML document which your application then has to parse and interpret. 3) Some form of redirect to web pages hosted by the payment gateway. The payment gateway collects the customer's CC number and other details, processes the payment, and then redirects the customer back to a web page hosted by you. Option 3 is usually the easiest solution but would require the customer to interact with pages hosted by the gateway (although this can usually be made to be almost transparent). 1 and 2 above would satisfy your requirements with 1 being the simplest of the two to implement. Because your preference is to have your application collect the payment details, you may need to consider whether you need to acquire PCI DSS compliance, but there are many factors that affect this. There is a lot of information about [PCI DSS here](https://www.pcisecuritystandards.org/) and on [Wikipedia](http://en.wikipedia.org/wiki/PCI_DSS).
You will probably find that it's easier to just let the payment gateway handle it. It's best to leave PCI compliance to the experts.
payment processing - pylons/python
[ "", "python", "pylons", "payment-gateway", "payment", "" ]
I'm implementing a simple cache in C#, and trying to make it accessible from multiple threads. In the basic read case, it's easy: ``` var cacheA = new Dictionary<int, MyObj>(); // Populated in constructor public MyObj GetCachedObjA(int key) { return cacheA[key]; } ``` This is, I believe, completely thread-safe. But I'd also like to make the it self-loading. That is, if the cache isn't populated on access, it populates it before satisfying the access request. ``` Dictionary<int, MyObj> cacheB = null; public MyObj GetCachedObjB(int key) { if (cacheB == null) { PopulateCacheB(); } return cacheB[key]; } private void PopulateCacheB() { cacheB = new Dictionary<int, MyObj>(); foreach (MyObj item in databaseAccessor) { cacheB.Add(item.Key, item); } } ``` This isn't thread-safe, since a thread could access GetCachedObjB after cacheB is instantiated but before it's fully populated, if another thread is in the process of populating it. So what's the best way to perform locking on cacheB so that the cache is thread-safe?
You can use the [`lock`](http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx) statement for simple thread-safety: ``` private Dictionary<int, MyObj> cacheB = null; private readonly object cacheLockB = new object(); public MyObj GetCachedObjB(int key) { lock (cacheLockB) { if (cacheB == null) { Dictionary<int, MyObj> temp = new Dictionary<int, MyObj>(); foreach (MyObj item in databaseAccessor) { temp.Add(item.Key, item); } cacheB = temp; } return cacheB[key]; } } ``` If you need to squeeze out more performance than `lock` allows then you could use a [`ReaderWriterLockSlim`](http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx) instead, which would allow multiple threads to read from the dictionary simultaneously. When you need to populate or update the dictionary, you could just upgrade the lock to write mode.
Like this: <http://devplanet.com/blogs/brianr/archive/2008/09/26/thread-safe-dictionary-in-net.aspx> Your first example isn't thread safe at all. What if someone inserts just when another one fetches something from the map ? Inserting will likely alter the dictionary, meaning reading it could access corrupted state
Locking a self-loading cache
[ "", "c#", "multithreading", "locking", "thread-safety", "" ]
I'm running the following code, using Visual Studio 2008 SP1, on Windows Vista Business x64, quad core machine, 8gb ram. If I build a release build, and run it from the command line, it reports 31ms. If I then start it from the IDE, using F5, it reports 23353ms. Here are the times: (all Win32 builds) * DEBUG, command line: 421ms * DEBUG, from the IDE: 24,570ms * RELEASE, command line: 31ms * RELEASE, from IDE: 23,353ms code: ``` #include <windows.h> #include <iostream> #include <set> #include <algorithm> using namespace std; int runIntersectionTestAlgo() { set<int> set1; set<int> set2; set<int> intersection; // Create 100,000 values for set1 for ( int i = 0; i < 100000; i++ ) { int value = 1000000000 + i; set1.insert(value); } // Create 1,000 values for set2 for ( int i = 0; i < 1000; i++ ) { int random = rand() % 200000 + 1; random *= 10; int value = 1000000000 + random; set2.insert(value); } set_intersection(set1.begin(),set1.end(), set2.begin(), set2.end(), inserter(intersection, intersection.end())); return intersection.size(); } int main(){ DWORD start = GetTickCount(); runIntersectionTestAlgo(); DWORD span = GetTickCount() - start; std::cout << span << " milliseconds\n"; } ```
Running under a Microsoft debugger (windbg, kd, cdb, Visual Studio Debugger) by default forces Windows to use the debug heap instead of the default heap. On Windows 2000 and above, the default heap is the [Low Fragmentation Heap](http://msdn.microsoft.com/en-us/library/aa366750(VS.85).aspx), which is insanely good compared to the debug heap. You can query the kind of heap you are using with [HeapQueryInformation](http://msdn.microsoft.com/en-us/library/aa366703(VS.85).aspx). To solve your particular problem, you can use one of the many options recommended in this KB article: [Why the low fragmentation heap (LFH) mechanism may be disabled on some computers that are running Windows Server 2003, Windows XP, or Windows 2000](http://support.microsoft.com/kb/929136) For Visual Studio, I prefer adding `_NO_DEBUG_HEAP=1` to `Project Properties->Configuration Properties->Debugging->Environment`. That always does the trick for me.
Pressing pause while in the VS IDE shows that the additional time appears to be spent in malloc/free. This would lead me to believe the debugging support in MS's malloc and free implementation have additional logic if the debugger is attached. This would explain the discrepancy in times from the console and from the debugger. EDIT: Confirmed by running with CTRL+F5 v. F5 (1047ms v. 9088ms on my machine)
Why does my STL code run so slowly when I have the debugger/IDE attached?
[ "", "c++", "visual-studio", "performance", "ide", "stl", "" ]
I have following class ``` public class ButtonChange { private int _buttonState; public void SetButtonState(int state) { _buttonState = state; } } ``` I want to fire an event whenever `_buttonState` value changes, finaly I want to define an event handler in `ButtonChange` Will you guys help me please?? P.S : I dont want to use **INotifyPropertyChanged**
How about: ``` public class ButtonChange { // Starting off with an empty handler avoids pesky null checks public event EventHandler StateChanged = delegate {}; private int _buttonState; // Do you really want a setter method instead of a property? public void SetButtonState(int state) { if (_buttonState == state) { return; } _buttonState = state; StateChanged(this, EventArgs.Empty); } } ``` If you wanted the `StateChanged` event handler to know the new state, you could derive your own class from `EventArgs`, e.g. `ButtonStateEventArgs` and then use an event type of `EventHandler<ButtonStateEventArgs>`. Note that this implementation doesn't try to be thread-safe.
Property based event raising: ``` public class ButtonChange { private int _buttonState; public int ButtonState { get { return _buttonState; } set { if (_buttonState == value) return; _buttonState = value; OnButtonStateChanged(); } } public event EventHandler ButtonStateChanged; private void OnButtonStateChanged() { if (this.ButtonStateChanged != null) this.ButtonStateChanged(this, new EventArgs()); } } ```
How to create Event Handler for my Class
[ "", "c#", ".net", "" ]
If you have a string of "1,2,3,1,5,7" you can put this in an array or hash table or whatever is deemed best. How do you determine that all value are the same? In the above example it would fail but if you had "1,1,1" that would be true.
This can be done nicely using lambda expressions. For an array, named `arr`: ``` var allSame = Array.TrueForAll(arr, x => x == arr[0]); ``` For an list (`List<T>`), named `lst`: ``` var allSame = lst.TrueForAll(x => x == lst[0]); ``` And for an iterable (`IEnumerable<T>`), named `col`: ``` var first = col.First(); var allSame = col.All(x => x == first); ``` Note that these methods don't handle empty arrays/lists/iterables however. Such support would be trivial to add however.
Iterate through each value, store the first value in a variable and compare the rest of the array to that variable. The instant one fails, you know all the values are not the same.
How to Compare Values in Array
[ "", "c#", ".net", "c#-2.0", "arrays", "" ]
i am using Qprocess to execute ping to check for a host to be online or not... The problem is that the exit code that i recieve from the Qprocess->finished signal is always 2 no matter if i ping a reachable host or an unreachable one.. I am continuously pinging in a QTimer to a host(whose one folder i have mounted at client where the Qt app is running)... when i catch the exit code as returned by ping in a slot connected to QProcess->finished signal.. i always recieve exit code as 2.. i cant use direct system call through system(ping) as it hangs my app for the time ping is active... i want it to be asynchronous so i switched to QProcess... the following is the code snippet: ``` //Pinging function called inside a timer with timout 1000 QString exec="ping"; QStringList params; if(!dBool) { //params << "-c1 1.1.1.11 -i1 -w1;echo $?"; params <<" 1.1.1.11 -i 1 -w 1 -c 1";//wont ping cout<<"\n\npinging 11 ie wont ping"; } else { //params << "-c1 1.1.1.1 -i1 -w1;echo $?"; params <<" 1.1.1.1 -i 1 -w 1 -c 1";//will ping cout<<"\n\npinging 1 ie will ping"; } ping->start(exec,params); // the slot that connects with QProcess->finished signal void QgisApp::pingFinished( int exitCode, QProcess::ExitStatus exitStatus ) { cout<<"\n\nexitCode,exitStatus=="<<exitCode<<","<<exitStatus;//always 2,0!! if(exitCode==0) //if(dBool) { connectivity=true; cout<<"\n\nONLINE"; } else { connectivity=false; cout<<"\n\nOFFLINE"; } } ``` the ``` cout<<"\n\nexitCode,exitStatus=="<<exitCode<<","<<exitStatus ``` line always gives 2,0 as output no matter if 1.1.1.1 is pinged or 1.1.1.11 is pinged on terminal 1.1.1.1 is pingable and 1.1.1.11 is not (i switch bw ips through dBool flag that is set on keypress event to simulate online/offline host so that my app can behave accordingly) Any inputs would be a great help.. Thanks.
I think it's a bad practice to rely on ping.exe exit code as it's undocumented. Furthermore it's been known that in different versions of Windows the exit code is inconsistent. You could: * implement your own ping. there are plenty free implementations out there such as [this](http://www.jbox.dk/sanos/source/utils/sh/ping.c.html) (first one when searching "ping.c" in google). * parse ping.exe output and determine if the ping was successful or not. EDIT: Didn't realize you're working with Linux (next time it might be wiser to mention it in your question)... Try this when sending the arguments to ping: ``` params << "1.1.1.11" << "-i" << "1" << "-w" << "1" <<"-c" <<"1"; ``` instead of one big string.
There isn't a good cross platform way for doing this. But you can use platform specific ways. You can ping on both Windows and Linux using this: ``` #if defined(WIN32) QString parameter = "-n 1"; #else QString parameter = "-c 1"; #endif int exitCode = QProcess::execute("ping", QStringList() << parameter << "1.1.1.11"); if (exitCode==0) { // it's alive } else { // it's dead } ```
running ping with Qprocess, exit code always 2 if host reachable or not
[ "", "c++", "qt", "ping", "qprocess", "" ]
I’m trying to utilize the ".NET Framework 3.5 Client Profile" in my application but I’m not seeing the option under available perquisites. How do I get that option to show In Visual Studio 2008. This is for a ClickOnce deployment btw, and the below image is just to illustrate where ".NET Framework 3.5 Client Profile" is to go once its there. Thanks. [![alt text](https://i.stack.imgur.com/AkJ9b.png)](https://i.stack.imgur.com/AkJ9b.png) (source: [windowsclient.net](http://windowsclient.net/sitefiles/1000/wpf/presents/103_6.png))
Have you installed [Service Pack 1 for Vistual studio 2008](http://www.microsoft.com/downloads/details.aspx?FamilyId=FBEE1648-7106-44A7-9649-6D9F6D58056E&displaylang=en)?
The installer for .NET Framework 3.5 SP1 is not included in the VS2008 SP1 installer due to size restrictions. For a workaround on how to actually include it in your setup project, refer to this page: <http://blogs.msdn.com/vsto/archive/2008/11/18/how-to-include-net-framework-3-5-sp1-with-your-installer.aspx>
".NET Framework 3.5 Client Profile" Prerequisite not available in a ClickOnce Deployment
[ "", "c#", ".net", "clickonce", "" ]
On my system I can't run a simple Java application that start a process. I don't know how to solve. Could you give me some hints how to solve? The program is: ``` [root@newton sisma-acquirer]# cat prova.java import java.io.IOException; public class prova { public static void main(String[] args) throws IOException { Runtime.getRuntime().exec("ls"); } } ``` The result is: ``` [root@newton sisma-acquirer]# javac prova.java && java -cp . prova Exception in thread "main" java.io.IOException: Cannot run program "ls": java.io.IOException: error=12, Cannot allocate memory at java.lang.ProcessBuilder.start(ProcessBuilder.java:474) at java.lang.Runtime.exec(Runtime.java:610) at java.lang.Runtime.exec(Runtime.java:448) at java.lang.Runtime.exec(Runtime.java:345) at prova.main(prova.java:6) Caused by: java.io.IOException: java.io.IOException: error=12, Cannot allocate memory at java.lang.UNIXProcess.<init>(UNIXProcess.java:164) at java.lang.ProcessImpl.start(ProcessImpl.java:81) at java.lang.ProcessBuilder.start(ProcessBuilder.java:467) ... 4 more ``` Configuration of the system: ``` [root@newton sisma-acquirer]# java -version java version "1.6.0_0" OpenJDK Runtime Environment (IcedTea6 1.5) (fedora-18.b16.fc10-i386) OpenJDK Client VM (build 14.0-b15, mixed mode) [root@newton sisma-acquirer]# cat /etc/fedora-release Fedora release 10 (Cambridge) ``` **EDIT: Solution** This solves my problem, I don't know exactly why: echo 0 > /proc/sys/vm/overcommit\_memory Up-votes for who is able to explain :) Additional informations, top output: ``` top - 13:35:38 up 40 min, 2 users, load average: 0.43, 0.19, 0.12 Tasks: 129 total, 1 running, 128 sleeping, 0 stopped, 0 zombie Cpu(s): 1.5%us, 0.5%sy, 0.0%ni, 94.8%id, 3.2%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 1033456k total, 587672k used, 445784k free, 51672k buffers Swap: 2031608k total, 0k used, 2031608k free, 188108k cached ``` Additional informations, free output: ``` [root@newton sisma-acquirer]# free total used free shared buffers cached Mem: 1033456 588548 444908 0 51704 188292 -/+ buffers/cache: 348552 684904 Swap: 2031608 0 2031608 ```
What's the memory profile of your machine ? e.g. if you run `top`, how much free memory do you have ? I suspect `UnixProcess` performs a `fork()` and it's simply not getting enough memory from the OS (if memory serves, it'll `fork()` to duplicate the process and then `exec()` to run the ls in the new memory process, and it's not getting as far as that) EDIT: Re. your overcommit solution, it permits overcommitting of system memory, possibly allowing processes to allocate (but not use) more memory than is actually available. So I guess that the `fork()` duplicates the Java process memory as discussed in the comments below. Of course you don't use the memory since the 'ls' replaces the duplicate Java process.
This is the solution but you have to set: ``` echo 1 > /proc/sys/vm/overcommit_memory ```
How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?
[ "", "java", "runtime.exec", "" ]
I have a requirement. Given say Test1,Test2, I have to perform a like operation. Something like ``` select * from tblname where column_name like('Test1%','Test2%'); ``` i.e. these strings are comma separated How do I solve this? This is in SQL SERVER 2005. Thanks in Advance
Sql server 2005, try this ``` --Lookup Table DECLARE @Values TABLE( Column_Name VARCHAR(MAX) ) INSERT INTO @Values (Column_Name) SELECT 'A' INSERT INTO @Values (Column_Name) SELECT 'B' INSERT INTO @Values (Column_Name) SELECT 'ATADA' INSERT INTO @Values (Column_Name) SELECT 'TADAA' INSERT INTO @Values (Column_Name) SELECT 'Test123A' INSERT INTO @Values (Column_Name) SELECT '1Test123A' --Lookup string and delim DECLARE @LookupString VARCHAR(MAX) DECLARE @Delim VARCHAR(1) SET @LookupString = 'Test1,Test2,TADA' SET @Delim = ','; --CREATE A LOOKUP TABLE FOR SPLIT STRINGS WITH substrings (Val, Remainder) AS( SELECT CASE WHEN CHARINDEX(@Delim,@LookupString) = 0 THEN @LookupString ELSE LEFT(@LookupString,CHARINDEX(@Delim,@LookupString)-1) END, CASE WHEN CHARINDEX(@Delim,@LookupString) = 0 THEN '' ELSE RIGHT(@LookupString,LEN(@LookupString) - CHARINDEX(@Delim,@LookupString)) END UNION ALL SELECT CASE WHEN CHARINDEX(@Delim,Remainder) = 0 THEN Remainder ELSE LEFT(Remainder,CHARINDEX(@Delim,Remainder)-1) END, CASE WHEN CHARINDEX(@Delim,Remainder) = 0 THEN '' ELSE RIGHT(Remainder,LEN(Remainder) - CHARINDEX(@Delim,Remainder)) END FROM substrings WHERE CHARINDEX(@Delim,Remainder) >= 0 AND Val != '' AND Remainder != '' ) SELECT v.Column_Name, substrings.Val FROM @Values v INNER JOIN substrings ON v.Column_Name LIKE substrings.Val + '%' ```
You will need to create a TSQL statement like this: ``` SELECT * FROM tblname WHERE column_name like 'Test1%' OR column_name like 'Test2%' ``` You need an OR for each case
Multiple Search Option in SQL SERVER 2005
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I found similar questions but no answer to what I am looking for. So here goes: For a native Win32 dll, is there a Win32 API to enumerate its export function names?
`dumpbin /exports` is pretty much what you want, but that's a developer tool, not a Win32 API. [`LoadLibraryEx`](http://msdn.microsoft.com/en-us/library/ms684179.aspx) with `DONT_RESOLVE_DLL_REFERENCES` is heavily cautioned against, but happens to be useful for this particular case – it does the heavy lifting of mapping the DLL into memory (but you don't actually need or want to use anything from the library), which makes it trivial for you to read the header: the module handle returned by `LoadLibraryEx` points right at it. ``` #include <winnt.h> HMODULE lib = LoadLibraryEx("library.dll", NULL, DONT_RESOLVE_DLL_REFERENCES); assert(((PIMAGE_DOS_HEADER)lib)->e_magic == IMAGE_DOS_SIGNATURE); PIMAGE_NT_HEADERS header = (PIMAGE_NT_HEADERS)((BYTE *)lib + ((PIMAGE_DOS_HEADER)lib)->e_lfanew); assert(header->Signature == IMAGE_NT_SIGNATURE); assert(header->OptionalHeader.NumberOfRvaAndSizes > 0); PIMAGE_EXPORT_DIRECTORY exports = (PIMAGE_EXPORT_DIRECTORY)((BYTE *)lib + header-> OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); assert(exports->AddressOfNames != 0); BYTE** names = (BYTE**)((int)lib + exports->AddressOfNames); for (int i = 0; i < exports->NumberOfNames; i++) printf("Export: %s\n", (BYTE *)lib + (int)names[i]); ``` Totally untested, but I think it's more or less correct. (Famous last words.)
try this: ``` #include <stdio.h> #include <string.h> #include <stdlib.h> void EnumExportedFunctions (char *, void (*callback)(char*)); int Rva2Offset (unsigned int); typedef struct { unsigned char Name[8]; unsigned int VirtualSize; unsigned int VirtualAddress; unsigned int SizeOfRawData; unsigned int PointerToRawData; unsigned int PointerToRelocations; unsigned int PointerToLineNumbers; unsigned short NumberOfRelocations; unsigned short NumberOfLineNumbers; unsigned int Characteristics; } sectionHeader; sectionHeader *sections; unsigned int NumberOfSections = 0; int Rva2Offset (unsigned int rva) { int i = 0; for (i = 0; i < NumberOfSections; i++) { unsigned int x = sections[i].VirtualAddress + sections[i].SizeOfRawData; if (x >= rva) { return sections[i].PointerToRawData + (rva + sections[i].SizeOfRawData) - x; } } return -1; } void EnumExportedFunctions (char *szFilename, void (*callback)(char*)) { FILE *hFile = fopen (szFilename, "rb"); if (hFile != NULL) { if (fgetc (hFile) == 'M' && fgetc (hFile) == 'Z') { unsigned int e_lfanew = 0; unsigned int NumberOfRvaAndSizes = 0; unsigned int ExportVirtualAddress = 0; unsigned int ExportSize = 0; int i = 0; fseek (hFile, 0x3C, SEEK_SET); fread (&e_lfanew, 4, 1, hFile); fseek (hFile, e_lfanew + 6, SEEK_SET); fread (&NumberOfSections, 2, 1, hFile); fseek (hFile, 108, SEEK_CUR); fread (&NumberOfRvaAndSizes, 4, 1, hFile); if (NumberOfRvaAndSizes == 16) { fread (&ExportVirtualAddress, 4, 1, hFile); fread (&ExportSize, 4, 1, hFile); if (ExportVirtualAddress > 0 && ExportSize > 0) { fseek (hFile, 120, SEEK_CUR); if (NumberOfSections > 0) { sections = (sectionHeader *) malloc (NumberOfSections * sizeof (sectionHeader)); for (i = 0; i < NumberOfSections; i++) { fread (sections[i].Name, 8, 1, hFile); fread (&sections[i].VirtualSize, 4, 1, hFile); fread (&sections[i].VirtualAddress, 4, 1, hFile); fread (&sections[i].SizeOfRawData, 4, 1, hFile); fread (&sections[i].PointerToRawData, 4, 1, hFile); fread (&sections[i].PointerToRelocations, 4, 1, hFile); fread (&sections[i].PointerToLineNumbers, 4, 1, hFile); fread (&sections[i].NumberOfRelocations, 2, 1, hFile); fread (&sections[i].NumberOfLineNumbers, 2, 1, hFile); fread (&sections[i].Characteristics, 4, 1, hFile); } unsigned int NumberOfNames = 0; unsigned int AddressOfNames = 0; int offset = Rva2Offset (ExportVirtualAddress); fseek (hFile, offset + 24, SEEK_SET); fread (&NumberOfNames, 4, 1, hFile); fseek (hFile, 4, SEEK_CUR); fread (&AddressOfNames, 4, 1, hFile); unsigned int namesOffset = Rva2Offset (AddressOfNames), pos = 0; fseek (hFile, namesOffset, SEEK_SET); for (i = 0; i < NumberOfNames; i++) { unsigned int y = 0; fread (&y, 4, 1, hFile); pos = ftell (hFile); fseek (hFile, Rva2Offset (y), SEEK_SET); char c = fgetc (hFile); int szNameLen = 0; while (c != '\0') { c = fgetc (hFile); szNameLen++; } fseek (hFile, (-szNameLen)-1, SEEK_CUR); char* szName = calloc (szNameLen + 1, 1); fread (szName, szNameLen, 1, hFile); callback (szName); fseek (hFile, pos, SEEK_SET); } } } } } fclose (hFile); } } ``` example: ``` void mycallback (char* szName) { printf ("%s\n", szName); } int main () { EnumExportedFunctions ("C:\\Windows\\System32\\user32.dll", mycallback); return 0; } ``` output: ``` ActivateKeyboardLayout AddClipboardFormatListener AdjustWindowRect AdjustWindowRectEx AlignRects AllowForegroundActivation AllowSetForegroundWindow AnimateWindow AnyPopup AppendMenuA AppendMenuW ArrangeIconicWindows AttachThreadInput BeginDeferWindowPos BeginPaint BlockInput BringWindowToTop BroadcastSystemMessage BroadcastSystemMessageA BroadcastSystemMessageExA BroadcastSystemMessageExW BroadcastSystemMessageW BuildReasonArray CalcMenuBar .....etc ```
Win32 API to enumerate dll export functions?
[ "", "c++", "windows", "winapi", "dll", "" ]
I've decided to use this.variableName when referring to string/int etc.. fields. Would that include ArrayList, ListBox etc too? Like: ``` private ListBox usersListBox; private void PopulateListBox() { this.usersListBox.Items.Add(...); } ``` ...Or not? And what about classes? ``` MyClass myClass; private void PlayWithMyClass() { this.myClass = new MyClass(); this.myClass.Name = "Bob"; } ``` ? This looks kind of odd to me. And I don't know if I should use this.PublicProperty or only private fields. I'm not 100% with the C# terminology, but hopefully what I said makes sense.
I used to do that sort of thing, but now I find that IDEs are pretty smart about giving me a visual indication that I'm dealing with a member variable. I only use "this" when it's necessary to distinguish the member variable from a parameter of the same name.
the `this.` command will allow you to call anything that is in scope in the same class as you are executing. You can access private and public variables and since everything in c# is a object calling a class is the same as calling a string. You don't have to use `this` in your code if you don't want to as it is implied in c# unless a method param and a global variable are the same.
C# this.everything?
[ "", "c#", "coding-style", "" ]
Can you tell me what does the function do and how would you document the following function using **Comments**: ``` function tosql($value, $value_type, $is_delimiters = true, $use_null = true) { if (is_array($value) || strlen($value)) { switch ($value_type) { case NUMBER: case FLOAT: return preg_replace(array("/,/", "/[^0-9\.,\-]/"), array(".", ""), $value); break; case DATETIME: if (!is_array($value) && is_int($value)) { $value = va_time($value); } if (is_array($value)) { $value = va_date($this->DatetimeMask, $value); } else { return "NULL"; } break; case INTEGER: return intval($value); break; case DATE: if (!is_array($value) && is_int($value)) { $value = va_time($value); } if (is_array($value)) { $value = va_date($this->DateMask, $value); } else { return "NULL"; } break; case TIME: if (!is_array($value) && is_int($value)) { $value = va_time($value); } if (is_array($value)) { $value = va_date($this->TimeMask, $value); } else { return "NULL"; } break; case TIMESTAMP: if (!is_array($value) && is_int($value)) { $value = va_time($value); } if (is_array($value)) { $value = va_date($this->TimestampMask, $value); } else { return "NULL"; } break; case NUMBERS_LIST: case FLOATS_LIST: $values = (is_array($value)) ? $value : explode(",", $value); for ($v = 0; $v < sizeof($values); $v++) { $value = $values[$v]; $value = preg_replace(array("/,/", "/[^0-9\.,\-]/"), array(".", ""), $value); if (!is_numeric($value)) { $value = 0; } $values[$v] = $value; } return implode(",", $values); break; case INTEGERS_LIST: $values = (is_array($value)) ? $value : explode(",", $value); for ($v = 0; $v < sizeof($values); $v++) { $values[$v] = intval($values[$v]); } return implode(",", $values); break; default: $value = addslashes($value); break; } if ($is_delimiters) { $value = "'" . $value . "'"; } } elseif ($use_null) { $value = "NULL"; } else { if ($value_type == INTEGER || $value_type == FLOAT || $value_type == NUMBER || $value_type == NUMBERS_LIST || $value_type == FLOATS_LIST || $value_type == INTEGERS_LIST) { $value = 0; } elseif ($is_delimiters) { $value = "''"; } } return $value; } ```
Well giving it a quick once over it appears to be a function to safely convert a given value to a string that can be used in an SQL command. If it can't convert it then it give a suitable safe value, 'NULL', so as not to break the code. ``` usage: tosql( mydate, 'DATE' ) ``` Suggest you cut and paste something like the above above the code in a comment...
Using PHPDocumentor ``` /** * tosql * Converts a string to a valid sql string * @param string * @param string * @return string */ function tosql($value, $value_type, $is_delimiters = true, $use_null = true) { } ```
What would be the best way to document this PHP code?
[ "", "php", "documentation", "" ]
I'm trying to optimize my C++ code. I've searched the internet on using dynamically allocated C++ arrays vs using std::vector and have generally seen a recommendation in favor of std::vector and that the difference in performance between the two is negligible. For instance here - [Using arrays or std::vectors in C++, what's the performance gap?](https://stackoverflow.com/questions/381621/using-arrays-or-stdvectors-in-c-whats-the-performance-gap). However, I wrote some code to test the performance of iterating through an array/vector and assigning values to the elements and I generally found that using dynamically allocated arrays was nearly 3 times faster than using vectors (I did specify a size for the vectors beforehand). I used g++-4.3.2. However I feel that my test may have ignored issues I don't know about so I would appreciate any advice on this issue. Thanks Code used - ``` #include <time.h> #include <iostream> #include <vector> using namespace std; int main() { clock_t start,end; std::vector<int> vec(9999999); std::vector<int>::iterator vecIt = vec.begin(); std::vector<int>::iterator vecEnd = vec.end(); start = clock(); for (int i = 0; vecIt != vecEnd; i++) { *(vecIt++) = i; } end = clock(); cout<<"vector: "<<(double)(end-start)/CLOCKS_PER_SEC<<endl; int* arr = new int[9999999]; start = clock(); for (int i = 0; i < 9999999; i++) { arr[i] = i; } end = clock(); cout<<"array: "<<(double)(end-start)/CLOCKS_PER_SEC<<endl; } ```
When benchmarking C++ comtainers, it's important to enable most compiler optimisations. Several of my own answers on SO have fallen foul of this - for example, the function call overhead when something like operator[] is not inlined can be very significant.
Just for fun, try iterating over the plain array using a pointer instead of an integer index (the code should look just like the vector iteration, since the point of STL iterators is to appear like pointer arithmetic for most operations). I bet the speed will be exactly equal in that case. Which of course means you should pick the vector, since it will save you a world of headaches from managing arrays by hand.
Dynamically allocated arrays or std::vector
[ "", "c++", "performance", "optimization", "stl", "" ]
I have been using WPF for a few years now and don't have any experience with anything but managed code. I started writing an app that uses a lot of win32 interop and i started wondering if i was leaking memory or generally doing something stupid that i didn't know about... So i thought i would seek some advice! Is there any gotchas/tips/tricks when using win32 calls inside managed code? I am mostly interested in memory/garbage collection but any other tips are welcome!
There are no gotchas. You free all resources that you allocate (unless the documentation indicates that the call you make takes over the resource, relieving you from ownership), and that's all there is to it. GC doesn't enter into it at all. As a tip, `System.Runtime.InteropServices.SafeHandle` is a stock helper class to use Win32 handles RAII-style.
Almost resource you allocate in Win32 has to be deallocated with the right API call, which is documented on the MSDN page for the allocation API. This is an entirely manual process; garbage collection doesn't assist with this at all, although you can use SafeHandle or (last resort) finalizers. At the very least, use `IDisposable` wrapper classes around any resources you allocate. In some cases, these already exist in Windows Forms. You can use Perfmon or Task Manager to monitor the number of handles open in your process.
Using win32 in managed code
[ "", "c#", "wpf", "winapi", "" ]
I'm currently writing a PHP application and drivers (classes) for the database engines. I was wondering if I need to write a replication support (master-slave)? I'm a bit new to this, so, what kind of things should my project or classes worry about if I want to support load balancing/replication? Oh and this is about MySQL.
The way we use our master-slave db, is to use the master for all "active usage", and the slave for all reporting (where it doesn't matter if the data is still "catching up" slightly). Depending on your needs, you could have -all- data manipulation occur on the master, and -all- data reading occur on the slave. This especially helps when you have blocking inserts or updates. (Note: Also consider the "insert delayed" MySQL syntax where possible, which helps avoid blocking too.) As far as the PHP support for this, all you really need is to keep clean handling for multiple (two) database connections, and use the master (read/write) or slave (ONLY READ) db connection as desired.
If you think you will use the slaves to read and the master to write, then your Class needs to support at least several connections at once. I will show you the API I used, If you choose that way, I can send you the class. ShusterDb::getInstance('read')->select($sql); //makes sure this is a SELECT in the method. ShusterDb::getInstance('write')->scalar($sql);
Should my database driver classes support replication (PHP)?
[ "", "php", "mysql", "replication", "" ]
I once worked on a C++ project that took about an hour and a half for a full rebuild. Small edit, build, test cycles took about 5 to 10 minutes. It was an unproductive nightmare. What is the worst build times you ever had to handle? What strategies have you used to improve build times on large projects? **Update:** How much do you think the language used is to blame for the problem? I think C++ is prone to massive dependencies on large projects, which often means even simple changes to the source code can result in a massive rebuild. Which language do you think copes with large project dependency issues best?
1. Forward declaration 2. pimpl idiom 3. Precompiled headers 4. Parallel compilation (e.g. MPCL add-in for Visual Studio). 5. Distributed compilation (e.g. Incredibuild for Visual Studio). 6. Incremental build 7. Split build in several "projects" so not compile all the code if not needed. *[Later Edit]* 8. Buy faster machines.
My strategy is pretty simple - I don't do large projects. The whole thrust of modern computing is away from the giant and monolithic and towards the small and componentised. So when I work on projects, I break things up into libraries and other components that can be built and tested independantly, and which have minimal dependancies on each other. A "full build" in this kind of environment never actually takes place, so there is no problem.
What strategies have you used to improve build times on large projects?
[ "", "c++", "compiler-construction", "build-process", "build-automation", "" ]
In C# you can create getter/setters in a simpler way than other languages: ``` public int FooBar { get; set; } ``` This creates an internal private variable which you can't address directly, with the external property 'FooBar' to access it directly. My question is - how often do you see this abused? It seems like it has a high potential to violate encapsulation best-practices often. Don't get me wrong, I use it as appropriate, and partial variations of it for read-only write-only types of properties, but what are your unpleasant experiences with it from other authors in your code base? ***Clarification: the intended definition of abuse would indeed be creating such a property when private variables are appropriate.***
I've seen it abused (in my opinion). In particular, when the developer would *normally* write: ``` private readonly int foo; public int Foo { get { return foo; } } ``` they'll sometimes write: ``` public int Foo { get; private set; } ``` Yes, it's shorter. Yes, from outside the class it has the same appearance - but I don't view these as the same thing, as the latter form allows the property to be set elsewhere in the same class. It also means that there's no warning if the property isn't set in the constructor, and the field isn't readonly for the CLR. These are subtle differences, but just going for the second form because it's simpler and ignoring the differences feels like abuse to me, even if it's minor. Fortunately, this is now available as of C# 6: ``` // Foo can only be set in the constructor, which corresponds to a direct field set public int Foo { get; } ```
There is no "abuse" in simply not writing the field manually; and it is good to encourage all access via the property (not directly to the field) anyway! The biggest problem I know of is with [binary serialization](http://marcgravell.blogspot.com/2009/03/obfuscation-serialization-and.html), where it gets a bit tricky to change back to a regular field without making it version-incompatible - but then... use a different serializer ;-p It would be nice if there was a "proper" readonly variant, and if you didn't need to use `:this()` ctor-chaining on structs, but.... meh!
How often do you see abuse of C# shorthand getters/setters?
[ "", "c#", "encapsulation", "setter", "getter", "automatic-properties", "" ]
I'm using the Intel compiler and visual studio and I can't seem to debug values that are in maps. I get a quick preview which shows the size of the map but the elements only show up as "(error)", I'll illustrate with a quick example, i've generated a map with a single entry myMapVariable[6]=1; if I mouse over I get this "myMapVariable 1" and in the watch window I get the same thing and expanding on the plus gives a single child entry which says name = "(error)" and value = 0 (which is wrong). I've added a line to my autoexp.dat debugging file which shows the raw member variables under the child called [raw members]. I've pretty much reached the limits of my ability to dig into this further without help so I would ask if anyone here can provide some insights.
I have never been able to fix this problem using Intel, but I have now moved to the latest visual studio compiler VS2010 and this is no longer a problem. I'm marking this as the answer because I don't want to leave unanswered questions lying around.
You're most likely using aggressive optimization settings. At least your screenshot is typical of that sort of thing. In that case, the debugger is actively stuffing hot values into registers, and it may be that, at the point you're stopped, the values that are needed to properly visualize the entire map are already discarded and overwritten by something else that is enough (like, say, a pointer to a current node). I would imagine that Intel C++, which is well-known for its high-quality optimization, does this sort of thing even more often than VC++ (but I've seen such with the latter often enough as well). Consider recompiling the project in Debug configuration (which would disable the optimizer), and see if that helps.
Broken std::map visualiser in VS2005
[ "", "c++", "visual-studio", "visual-studio-2005", "stl", "visualization", "" ]
I have a generator that generates a series, for example: ``` def triangle_nums(): '''Generates a series of triangle numbers''' tn = 0 counter = 1 while True: tn += counter yield tn counter += + 1 ``` In Python 2 I am able to make the following calls: ``` g = triangle_nums() # get the generator g.next() # get the next value ``` however in Python 3 if I execute the same two lines of code I get the following error: ``` AttributeError: 'generator' object has no attribute 'next' ``` but, the loop iterator syntax does work in Python 3 ``` for n in triangle_nums(): if not exit_cond: do_something()... ``` I haven't been able to find anything yet that explains this difference in behavior for Python 3.
`g.next()` has been renamed to `g.__next__()`. The reason for this is consistency: special methods like `__init__()` and `__del__()` all have double underscores (or "dunder" in the current vernacular), and `.next()` was one of the few exceptions to that rule. This was fixed in Python 3.0. [\*] But instead of calling `g.__next__()`, use [`next(g)`](https://docs.python.org/library/functions.html#next). [\*] There are other special attributes that have gotten this fix; `func_name`, is now `__name__`, [etc.](https://docs.python.org/whatsnew/3.0.html#operators-and-special-methods)
Try: ``` next(g) ``` Check out [this neat table](http://www.diveinto.org/python3/porting-code-to-python-3-with-2to3.html#next) that shows the differences in syntax between 2 and 3 when it comes to this.
Is generator.next() visible in Python 3?
[ "", "python", "python-3.x", "iteration", "" ]
I have a very simple Mac Cocoa app that just has a Web View that loads an HTML file with some CSS and JavaScript. I have hooked up the app delegate to this method: ``` - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { NSString* filePath = [[NSBundle mainBundle] pathForResource: @"index" ofType: @"html"]; NSURL *url = [NSURL URLWithString: filePath]; [[self.webView mainFrame] loadHTMLString: [NSString stringWithContentsOfFile: filePath] baseURL: url]; } ``` The index.html file contains the following: ``` <html> <head> <title>Hello, World!</title> <link href="style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> jQuery(function($){ $('h1').fadeOut() }) </script> </head> <body> <h1>Hello, World!</h1> </body> </html> ``` The style.css file gets loaded correctly, because I set the background to grey in that, so I know it can load other assets from the resource bundle. The javascript code does not get executed. If I open index.html in Safari, the Hello World `h1` disappears, as expected. Why doesn't this happen in the app in my WebView? Do I have to do something to enable JavaScript? The box next to JavaScript is checked in Interface Builder. The code for this is available at <http://github.com/pjb3/WebViewApp>
You don't have to do anything to enable JavaScript; it's enabled in the `WebView` by default. And like you said, you can always check in Interface Builder that the JavaScript checkbox is selected. What you have to do, though, is make sure that **the `baseURL` you're specifying is correct** (since in the html file you're referring to `jquery.js` with a relative URL using just the filename) and that you've **included the `jquery.js` file into the bundle resources**. The code you posted will result in a `nil` value for the `url` variable: `+URLWithString:` expects a valid URL string (that conforms to RFC 2396) as the argument (which the filesystem path you're providing is not). What you want is `+fileURLWithPath:`, and you also need to use the filesystem path of the directory where `index.html` and `jquery.js` reside, which you can get by removing the filename from the path you've got (using `NSString`'s `-stringByDeletingLastPathComponent:`). Here's how you get the correct `baseURL`: ``` NSURL *url = [NSURL fileURLWithPath:[filePath stringByDeletingLastPathComponent]]; ```
Just a quick update for anyone still struggling with this... I was having the exact same problem where I had an html page with the prototype.js library loaded in the <head></head> section of the page. But the library was not being loaded when I opened the same page within a WebView in a Cocoa app. Actually, no script files being loaded (even my own) seemed to work in the WebView. I downloaded the above github code that from the link pjb3 provided, hoping that maybe he'd found a fix and updated it. No such luck. It still had the same problems. And then I decided to look in the package contents of the compiled app (so that would be WebViewApp/Contents/Resources off of the build/Debug or build/Release directory where XCode has compiled your app)... **Oho! The javascript files he had put in the Resources section of the XCode project weren't actually being copied over to the built app's Resources directory.** I looked in my project and it was the same problem. **The fix? Simply drag any of the scripts you've added into the "Copy Bundle Resources" section of your app target in XCode and voila, they'll be there (and things will actually work!).** I thought everything that you put in Resources was getting copied over automagically, but I guess it wasn't. And unfortunately with a WebView, unless you do a bit of work, you don't have all the great web debugging stuff that Firefox or Safari would have that would have made this problem easier to find. So, when in doubt, check if your actual compiled app has the resources it needs under its Resources directory (is this maybe the programmer's version of "Is it plugged in?"?). This took me a lot of head scratching and my only consolation for the lost hours is that I can maybe save some other folks from the same. Happy coding!
How do you enable javascript in a WebView
[ "", "javascript", "objective-c", "cocoa", "webkit", "" ]
We use the excellent [validator plugin for jQuery](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) here on Stack Overflow to do client-side validation of input before it is submitted to the server. It generally works well, however, this one has us scratching our heads. The following validator method is used on the ask/answer form for the user name field (note that you must be **logged out** to see this field on the live site; it's on every `/question` page and the `/ask` page) ``` $.validator.addMethod("validUserName", function(value, element) { return this.optional(element) || /^[\w\-\s\dÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜäëïöüçÇߨøÅ寿ÞþÐð]+$/.test(value); }, "Can only contain A-Z, 0-9, spaces, and hyphens."); ``` Now this regex looks weird but it's pretty simple: * match the beginning of the string (^) * match any of these.. + word character (\w) + dash (-) + space (\s) + digit (\d) + crazy moon language characters (àèìòù etc) * now match the end of the string ($) Yes, we ran into the [Internationalized Regular Expressions](http://www.hanselman.com/blog/InternationalizedRegularExpressions.aspx) problem. JavaScript's definition of "word character" does not include international characters.. at all. Here's the weird part: even though we've gone to the trouble of manually adding tons of the valid international characters to the regex, it *doesn't work*. You cannot enter these international characters in the input box for user name without getting the.. > Can only contain A-Z, 0-9, spaces, and hyphens .. validation return! Obviously **the validation *is* working for the other parts of the regex**.. so.. what gives? The other strange part is that this validation works in the browser's JavaScript console but not when executed as a part of our standard \*.js includes. > /^[\w-\sÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜäëïöüçÇߨøÅ寿ÞþÐð]+$/ > .test('ÓBill de hÓra') === true We've run into some really bizarre international character issues in JavaScript code before, resulting in some very, very nasty hacks. We'd like to understand what's going on here and why. Please enlighten us!
I think the email and url validation methods are a good reference here, eg. the email method: ``` email: function(value, element) { return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value); }, ``` [The script to compile that regex](http://projects.scottsplayground.com/email_address_validation/lib/email.js). In other words, replacing your arbitrary list of "crazy moon" characters with this could help: ``` [\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF] ``` Basically this avoids the character encoding issues you have elsewhere by replacing the needs-encoding characters with more general definitions. While not necessarily more readable, so far it's shorter than your full list.
It can definitely be attributed to encoding issues. Yea "ECMA shouldn't care about encoding..." blah blah, well if you're on firefox, go to **View > Character Encoding > Western (ISO-8859-1)** then try using the Name field. It works fine for me after changing the encoding manually (granted the rest of the page doesn't like the encoding switch) (on IE8 you can go to **Page > Encoding > Western European (Windows)** to get the same effect)
JavaScript validation issue with international characters
[ "", "javascript", "jquery", "validation", "internationalization", "" ]
I can't find any information on this issue; why doesn't the following code work in IE? ``` window.x = 45; delete window.x; // or delete window['x']; ``` IE reports an "object doesn't support this action" error. Does it have anything to do with that iterating over window properties in IE issue?
I would do it this way: ``` window[x] = undefined; try{ delete window[x]; }catch(e){} ```
Gasper made a comment with the solution he finished on, but I think it's worth calling out as an actual answer: ``` try { delete window.x; } catch(e) { window["x"] = undefined; } ``` Interesting issue, I was just banging my head against it tonight. The exception is thrown on IE but not Firefox. I would suspect this workaround leaks memory, so use it sparingly. It was asked, why not just assign undefined? It matters if you want to enumerate the keys later (though if you're relying on the workaround, the key enumeration still won't do what you want...). But anyhow, to highlight the difference between delete and simply assigning undefined (<http://jsfiddle.net/fschwiet/T4akL/>): ``` var deleted = { a: 1 }; var cleared = { a: 1 }; delete deleted["a"]; cleared["a"] = undefined; for(var key in deleted) { console.log("deleted has key", key); } for(var key in cleared) { console.log("cleared has key", key); } console.log("deleted has a?", deleted.hasOwnProperty('a')); console.log("cleared has a?", cleared.hasOwnProperty('a')); ``` Produces output: ``` cleared has key a deleted has a? false cleared has a? true ```
Deleting a window property in IE
[ "", "javascript", "internet-explorer", "properties", "window", "" ]
When writing a new jQuery plugin is there a straightforward way of checking that the current version of jQuery is above a certain number? Displaying a warning or logging an error otherwise. It would be nice to do something like: ``` jQuery.version >= 1.2.6 ``` in some form or another.
Here is a check I used to make sure the user was using at least v. 1.3.2 of jQuery. ``` if (/1\.(0|1|2|3)\.(0|1)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery) || /^1.2/.test($.fn.jquery)) { //Tell user they need to upgrade. } ```
Try this: ``` >>> jQuery.fn.jquery; "1.3.2" ```
jQuery Plugin Check Version
[ "", "javascript", "jquery", "" ]
What is the best-practise way of Identifying dynamically generated element on page? Let me explain. I have a list of elements, there can be as few or as many elements as the user defines, on a page. Each one of these corresponds to an item each with it's own id. Now, the user has the ability to edit or delete these elements on the page and these operations are handled with jQuery. Each element comes with a link per operation they can action (i.e delete and edit). Now a problem is knowing *which* element the user has selected. To deal with this I give each link the ID of the element as an ID attribute, which I then obtain using jQuery: ``` <a href="#" class="delete" id="<%= Model.elementID%>">Delete</a> <script type="text/javascript"> $(".delete").live("click", function (event) { event.preventDefault(); var elementID = $(this).attr("id"); //other code }); </script> ``` This is obviously far from ideal as it would mean many DOM elements could have the same ID. Alternatively I could create my own attribute such as elementID but I believe this breaks standards. So what could you recommend. How can I identify dynamically generated elements on a page?
I've done this quite a bit for my sites and my solution is a combination of where you started from and some of the comments: Use a naming convention, like "element\_type:id:action". So your example's generated be "element:23:delete". Then you can split() the .attr("id") that you've grabbed and determine what it is ("report" vs "folder"), the id, and what you want to do ("delete", "edit", "move"). This has worked out very well for me, and is very scalable. I'd keep the class, though, so that you can easily attach events via jquery. James
Why not just add a class instead. This also solves the issue of having multiple id's which as you eluded to is not allowed and will cause major issues with subsequent jquery operations. ``` <a href="#" class="delete" id="<%= Model.elementID%>">Delete</a> $(".delete").live("click", function(event) { event.preventDefault(); //other code $(yourNewElement).addClass('noob'); }); ```
Identifying dyamically generated content on a page
[ "", "c#", "jquery", "asp.net-mvc", "dynamic-content", "identification", "" ]
Is it possible to cast a custom class to a value type? Here's an example: ``` var x = new Foo(); var y = (int) x; //Does not compile ``` Is it possible to make the above happen? Do I need to overload something in `Foo` ?
You will have to overload the cast operator. ``` public class Foo { public Foo( double d ) { this.X = d; } public double X { get; private set; } public static implicit operator Foo( double d ) { return new Foo (d); } public static explicit operator double( Foo f ) { return f.X; } } ```
Create an explicit or implicit conversion: ``` public class Foo { public static explicit operator int(Foo instance) { return 0; } public static implicit operator double(Foo instance) { return 0; } } ``` The difference is, with explicit conversions you will have to do the type cast yourself: ``` int i = (int) new Foo(); ``` and with implicit conversions, you can just "assign" things: ``` double d = new Foo(); ``` [MSDN](http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx) has this to say: "By eliminating unnecessary casts, implicit conversions can improve source code readability. However, because implicit conversions do not require programmers to explicitly cast from one type to the other, care must be taken to prevent unexpected results. **In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness. If a conversion operator cannot meet those criteria, it should be marked explicit.**" (Emphasis mine)
C#: Custom casting to a value type
[ "", "c#", ".net", "casting", "" ]
**EDIT: Mozilla fixed the bug. This thread is dead.** **EDIT: This is a Mozilla bug. See this thread: <https://bugzilla.mozilla.org/show_bug.cgi?id=501853>** I have a sprite I use for my images here: <http://www.trailbehind.com/site_media/images/sprite.png> In FireFox 3.5, the sprite seems to get fetched every time I render an icon on my map, you can see the behavior in the Firebug Net Panel when you load this page and/or pan the map: <http://www.trailbehind.com/node/1148091/> I had previously had similar problems to this in Internet Explorer, but I had eventually gotten this working in Safari 3/4, FF 2/3, and IE 6/7/8. Now, something is wrong in FF 3.5 :( I tried to put this code in the of the document to prec-cache the image, but to no avail: ``` var pre = new Image(); pre.src = "/site_media/images/sprite.png"; ``` Here's the code that later creates the map markers (and fetches the sprite image again). It might be GMaps related - it doesn't seem to fetch a sprite to draw each icon or otheer image on the left... just the map. ``` //returns an image-like GIcon based on a sprite function getGIconSprite(attr) { var myicon = new GIcon(G_DEFAULT_ICON); myicon.sprite = {image:"/site_media/images/sprite.png", top:0}; myicon.iconSize = new GSize(16,16); myicon.iconAnchor = new GPoint(8,8); myicon.shadow = null; myicon.sprite.left = attr.offset*16; return myicon; } ```
This is official [FireFox 3.5 bug](https://bugzilla.mozilla.org/show_bug.cgi?id=497665). Simple hack for it is to create two class for all snipped object: one common for all with background image, and the second one with background position. That's all kids!)
There seems to be a problem with FireFox 3.5 loading images from the server and not using the cache properly. Google "firefox 3.5 not caching images" and you will notice a lot of people noticing this problem.
FireFox 3.5 Fetches Image Sprite Repetitively - how to prevent?
[ "", "javascript", "sprite", "css-sprites", "firefox3.5", "" ]
I have just found this [great tutorial](http://ad1987.blogspot.com/2008/12/create-your-own-tinyurl-with-php-and.html) as it is something that I need. However, after having a look, it seems that this might be inefficient. The way it works is, first generate a unique key then check if it exists in the database to make sure it really is unique. However, the larger the database gets the slower the function gets, right? Instead, I was thinking, is there a way to add ordering to this function? So all that has to be done is check the previous entry in the DB and increment the key. So it will always be unique? ``` function generate_chars() { $num_chars = 4; //max length of random chars $i = 0; $my_keys = "123456789abcdefghijklmnopqrstuvwxyz"; //keys to be chosen from $keys_length = strlen($my_keys); $url = ""; while($i<$num_chars) { $rand_num = mt_rand(1, $keys_length-1); $url .= $my_keys[$rand_num]; $i++; } return $url; } function isUnique($chars) { //check the uniqueness of the chars global $link; $q = "SELECT * FROM `urls` WHERE `unique_chars`='".$chars."'"; $r = mysql_query($q, $link); //echo mysql_num_rows($r); die(); if( mysql_num_rows($r)>0 ): return false; else: return true; endif; } ```
The tiny url people like to use random tokens because then you can't just troll the tiny url links. "Where does #2 go?" "Oh, cool!" "Where does #3 go?" "Even cooler!" You can type in random characters but it's unlikely you'll hit a valid value. Since the key is rather sparse (4 values each having 36\* possibilities gives you 1,679,616 unique values, 5 gives you 60,466,176) the chance of collisions is small (indeed, it's a desired part of the design) and a good SQL index will make the lookup be trivial (indeed, it's the primary lookup for the url so they optimize around it). If you really want to avoid the lookup and just unse auto-increment you can create a function that turns an integer into a string of seemingly-random characters with the ability to convert back. So "1" becomes "54jcdn" and "2" becomes "pqmw21". Similar to Base64-encoding, but not using consecutive characters. (\*) I actually like using less than 36 characters -- single-cased, no vowels, and no similar characters (1, l, I). This prevents accidental swear words and also makes it easier for someone to speak the value to someone else. I even map similar charactes to each other, accepting "0" for "O". If you're entirely machine-based you could use upper and lower case and all digits for even greater possibilities.
In the database table, there is an index on the `unique_chars` field, so I don't see why that would be slow or inefficient. ``` UNIQUE KEY `unique_chars` (`unique_chars`) ``` Don't rush to do premature optimization on something that you think might be slow. Also, there may be some benefit in a url shortening service that generates random urls instead of sequential urls.
Creating your own TinyURL
[ "", "php", "mysql", "" ]
I heard somewhere that declaring an Index on a date column is bad for performance, but I can't find any reference on the internet. Suggestions?
`DateTime` in `SQL Server 2005` (and in `SQL Server 2008` too) is stored as a `8`-byte value, consisting of: * Number of days since `Jan 1, 1900` in the first `4` bytes (the date part) * Number of `1/300` ticks from the midnight in the second `4` bytes (the time part) It's perfectly OK to index this value.
It will depend on the pattern of activity run against the database. If you are doing lots of WHEREs against the DateTime then an index will probably help. If you are doing lots of inserts, and they are not in consecutive order, then your insert speed could suffer updating the index. As in all matters of performance, test the performance using a typical workload both before and after the change, its the only way to really know if the change will help or not.
I am using SQL Server 2008, is it ok to define an Index on a DateTime column?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I use astyle to format my code most of the time, and I love it, but one annoyance is that it can't specify at least a "hint" for max line length. If you have a line of code like: ``` this->mButtonCancel->setLeftClickProc(boost::bind(&FileListDialog::cancelLeftClick, this)); ``` I would like a source code formatter to be able to wrap it even moderately intelligently: ``` this->mButtonCancel->setLeftClickProc( boost::bind(&FileListDialog::cancelLeftClick, this)); ``` ...is probably how I would format that line of code. For long argument lists, I would probably prefer to align on the open parenthesis, but clearly that won't work in this situation. Either way, astyle doesn't support doing anything with long lines that don't contain multiple statements. Does anyone know of a tool that does?
GNU Indent has support for breaking long lines. <http://www.gnu.org/software/indent/manual/indent.html#SEC12>
I've found **uncrustify** command line tool to be very usable. It has a tremendous number of options, and therefore is a bit hard, but after some practice, it is invaluable. The homepage is here: <http://uncrustify.sourceforge.net/>
Is there an automatic source code formatter that nicely wraps lines of C/C++?
[ "", "c++", "formatting", "code-formatting", "" ]
I need a simple proxy PHP function/script that can download a file from a foreign domain, and also allow me to modify the data (as strings) before retransmit. Any ideas better than "readfile($url)" ??
file\_get\_contents(), fopen(), http\_get() or [curl](http://php.net/manual/function.curl-init.php) are methods and functions you probably want to take a look at. Depending on what you are downloading and how you want to change it you could use [XML Parser](http://php.net/manual/book.xml.php), regex or a simple str\_replace().
[PHP Reverse Proxy with Apache](http://demo.loopip.com/integration_demo/search/php_reverse_proxy)
PHP simple proxy
[ "", "php", "proxy", "dns", "" ]
``` int[] myIntegers; myIntegers = new int[100]; ``` In the above code, is new int[100] generating the array on the heap? From what I've read on CLR via c#, the answer is yes. But what I can't understand, is what happens to the actual int's inside the array. As they are value types, I'd guess they'd have to be boxed, as I can, for example, pass myIntegers to other parts of the program and it'd clutter up the stack if they were left on it all the time. Or am I wrong? I'd guess they'd just be boxed and would live on the heap for as long the array existed.
Your array is allocated on the heap, and the ints are not boxed. The source of your confusion is likely because people have said that reference types are allocated on the heap, and value types are allocated on the stack. This is not an entirely accurate representation. All local variables and parameters are allocated on the stack. This includes both value types and reference types. The difference between the two is only what is *stored* in the variable. Unsurprisingly, for a value type, the *value* of the type is stored directly in the variable, and for a reference type, the value of the type is stored on the heap, and a *reference* to this value is what is stored in the variable. The same holds for fields. When memory is allocated for an instance of an aggregate type (a `class` or a `struct`), it must include storage for each of its instance fields. For reference-type fields, this storage holds just a reference to the value, which would itself be allocated on the heap later. For value-type fields, this storage holds the actual value. So, given the following types: ``` class RefType{ public int I; public string S; public long L; } struct ValType{ public int I; public string S; public long L; } ``` The values of each of these types would require 16 bytes of memory (assuming a 32-bit word size). The field `I` in each case takes 4 bytes to store its value, the field `S` takes 4 bytes to store its reference, and the field `L` takes 8 bytes to store its value. So the memory for the value of both `RefType` and `ValType` looks like this: ``` 0 ┌───────────────────┐ │ I │ 4 ├───────────────────┤ │ S │ 8 ├───────────────────┤ │ L │ │ │ 16 └───────────────────┘ ``` Now if you had three local variables in a function, of types `RefType`, `ValType`, and `int[]`, like this: ``` RefType refType; ValType valType; int[] intArray; ``` then your stack might look like this: ``` 0 ┌───────────────────┐ │ refType │ 4 ├───────────────────┤ │ valType │ │ │ │ │ │ │ 20 ├───────────────────┤ │ intArray │ 24 └───────────────────┘ ``` If you assigned values to these local variables, like so: ``` refType = new RefType(); refType.I = 100; refType.S = "refType.S"; refType.L = 0x0123456789ABCDEF; valType = new ValType(); valType.I = 200; valType.S = "valType.S"; valType.L = 0x0011223344556677; intArray = new int[4]; intArray[0] = 300; intArray[1] = 301; intArray[2] = 302; intArray[3] = 303; ``` Then your stack might look something like this: ``` 0 ┌───────────────────┐ │ 0x4A963B68 │ -- heap address of `refType` 4 ├───────────────────┤ │ 200 │ -- value of `valType.I` │ 0x4A984C10 │ -- heap address of `valType.S` │ 0x44556677 │ -- low 32-bits of `valType.L` │ 0x00112233 │ -- high 32-bits of `valType.L` 20 ├───────────────────┤ │ 0x4AA4C288 │ -- heap address of `intArray` 24 └───────────────────┘ ``` Memory at address `0x4A963B68` (value of `refType`) would be something like: ``` 0 ┌───────────────────┐ │ 100 │ -- value of `refType.I` 4 ├───────────────────┤ │ 0x4A984D88 │ -- heap address of `refType.S` 8 ├───────────────────┤ │ 0x89ABCDEF │ -- low 32-bits of `refType.L` │ 0x01234567 │ -- high 32-bits of `refType.L` 16 └───────────────────┘ ``` Memory at address `0x4AA4C288` (value of `intArray`) would be something like: ``` 0 ┌───────────────────┐ │ 4 │ -- length of array 4 ├───────────────────┤ │ 300 │ -- `intArray[0]` 8 ├───────────────────┤ │ 301 │ -- `intArray[1]` 12 ├───────────────────┤ │ 302 │ -- `intArray[2]` 16 ├───────────────────┤ │ 303 │ -- `intArray[3]` 20 └───────────────────┘ ``` Now, if you passed `intArray` to another function, the value pushed onto the stack would be `0x4AA4C288`, the address of the array, **not** a copy of the array.
Yes the array will be located on the heap. The ints inside the array will not be boxed. Just because a value type exists on the heap, does not necessarily mean it will be boxed. Boxing will only occur when a value type, such as int, is assigned to a reference of type object. For example Does not box: ``` int i = 42; myIntegers[0] = 42; ``` Boxes: ``` object i = 42; object[] arr = new object[10]; // no boxing here arr[0] = 42; ``` You may also want to check out Eric's post on this subject: * [The Stack Is An Implementation Detail, Part Two](https://web.archive.org/web/20160126132150/https://blogs.msdn.microsoft.com/ericlippert/2009/05/04/the-stack-is-an-implementation-detail-part-two/)
Arrays, heap and stack and value types
[ "", "c#", "arrays", "memory", "heap-memory", "stack-memory", "" ]