Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I'm a complete beginner when it comes to programming. I'm taking a stab at PHP, and have seen how powerful the frameworks can be. But should I even consider trying to work with a framework until I have a strong grasp of PHP itself?
Note: I'd most likely be using CodeIgnitor, but the question applies to any of the frameworks.
|
Preferably, you should have a strong grasp of the language (and programming in general) before you start using frameworks. Frameworks can and will save you a lot of work, but you they also introduce advanced concepts and implementations.
After you gain some experience and start to wonder what's the best way to solve some common problems you have faced before - that will be a good time to give frameworks a try.
I would suggest you try to read some of the source code of the different frameworks and see if it makes sense to you. If it doesn't - you are probably not ready yet.
|
Personally I would stick to learning PHP and creating some projects without the assistance of a framework. While frameworks can abstract a lot of the messy, boring parts of a project away, it's important to still know how they work, especially when debugging.
Frameworks can be also be very complicated, and learning how to effectively use one can be difficult even with a good understanding of programming language.
|
Should a beginning PHP programmer consider frameworks?
|
[
"",
"php",
"frameworks",
""
] |
I have an application, written in C++ using MFC and Stingray libraries. The application works with a wide variety of large data types, which are all currently serialized based on MFC Document/View serialize derived functionality. I have also added options for XML serialization based on the Stingray libraries, which implements DOM via the Microsoft XML SDK. While easy to implement the performance is terrible, to the extent that it is unusable on anything other than very small documents.
What other XML serialization tools would you folks recommend for this scenario. I don't want DOM, as it seems to be a memory hog, and I'm already dealing with large in memory data. Ideally, i'd like a streaming parser that is fast, and easy to use with MFC. My current front runner is [expat](http://expat.sourceforge.net/) which is fast and simple, but would require a lot of class by class serialization code to be added. Any other efficient and easier to implement alternatives out there that people would recommend?
|
The [Boost Serialization](http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/index.html) library supports XML. This library basically consists in:
1. Start from the principles of MFC serialization and take all the good things it provides.
2. Solve every single issue of MFC serialization!
Among the improvements compared to MFC is support for XML.
Note that you don't necessarily control the XML schema of this serialization. It uses its own schema.
|
This is an age old problem. I was the team lead of the development team with the most critical path dependencies on the largest software project in the world during 1999 and 2000 and this very issue was the focus of my work during that time. I am convinced that the wheel was invented by multiple engineers who were unaware that others had already invented it. The same is true of XML Data binding in C++. I invented it too, and I've been perfecting it for over 10 years on various projects. I have a solution that addresses the issues noted here and some additional issues that repeatedly arise:
1. XML Updates. This is the ability to re-apply a subset of XML into an existing object model. In many cases the XML is bound to indexed objects and we cannot afford to re-index for each update.
2. COM and CORBA interface management. In the same respect that the XML Data Binding can be automated through object oriented practices - so can the instances of interface objects that provide that data to the application layer.
3. State Tracking. The application often needs to distinguish between an empty value vs. a missing value - both create an empty string. This provides the validation along with Data Binding.
The source code uses the least restrictive license - less so that GPL. The project is supported and managed from here:
<http://www.codeproject.com/KB/XML/XMLFoundation.aspx>
Now that it's the year 2010, I believe that nobody else will attempt to reinvent the wheel because there are a few to choose from. IMHO - this wheel is the most polished and well rounded implementation available.
Enjoy.
|
Best XML serialization library for a MFC C++ app
|
[
"",
"c++",
"xml",
"mfc",
""
] |
I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and check that at startup. Unfortunately, I don't know of any facilities in Linux that can do this.
I'm looking for something that will automatically be released should the application crash unexpectedly. I don't want to have to burden my users with having to manually delete lock files because I crashed.
|
There are several common techniques including using semaphores. The one I see used most often is to create a "pid lock file" on startup that contains the pid of the running process. If the file already exists when the program starts up, open it up and grab the pid inside, check to see if a process with that pid is running, if it is check the cmdline value in /proc/*pid* to see if it is an instance of your program, if it is then quit, otherwise overwrite the file with your pid. The usual name for the pid file is *application\_name*`.pid`.
|
The Right Thing is advisory locking using `flock(LOCK_EX)`; in Python, this is found in the [`fcntl` module](http://docs.python.org/3/library/fcntl.html).
Unlike pidfiles, these locks are always automatically released when your process dies for any reason, have no race conditions exist relating to file deletion (as the file doesn't *need* to be deleted to release the lock), and there's no chance of a different process inheriting the PID and thus appearing to validate a stale lock.
If you want unclean shutdown detection, you can write a marker (such as your PID, for traditionalists) into the file after grabbing the lock, and then truncate the file to 0-byte status before a clean shutdown (while the lock is being held); thus, if the lock is not held and the file is non-empty, an unclean shutdown is indicated.
|
Ensure a single instance of an application in Linux
|
[
"",
"python",
"linux",
"single-instance",
""
] |
This one is a case of not doing your homework.:-)
Apart from dynamic loading advantage, does it make sense to include a JavaScript library(jQuery in my case ) from a Google server when I can load it from my server as a single file comprised of the 19kb jQuery zip file + the additional JavaScript code I have written – all compressed with a JS compressor and served HTTP deflated.
With Google server I’ll have 2(parallel) HTTP round trips. One to get the jquery file and the other to get the site JavaScript code. One 19kb and the other say 20-25kb.
Under normal circumstances it would be a single 30-35kb download from my site.
|
Consider that a jQuery script downloaded from the google CDN might well already be cached on a visitor's browser, since it has consistent headers and cache control no matter where it is downloaded from. Hence, on average most users will only have to download your site-specific javascript scripts. Also, CDN generally have faster response times than single servers, since they respond from a server nearest to your location.
There is no cut and dry answer to your question, as both approaches offer good performance on modern connections. You should profile your system under duress and see what solution offers the best results (and if such optimization is even needed).
|
Are you sure scripts would be downloaded in parallel? [This example from Cuzillion](http://stevesouders.com/cuzillion/?c0=hj1hfff2_0&c1=hj1hfff2_0&t=1227551978929) seems to be saying that only IE8 can do that.
Also worth finding out is how many of your pageviews are first time visitors and how many have visited the site before to help you decide how much caching will influence download time. If you have a significant number of first time visitors it's probably worth skewing it in their favour to make the first time experience as fast as possible.
|
Streaming jquery(JS files) from a CDN (Google)
|
[
"",
"javascript",
"jquery",
"performance",
"http",
""
] |
We're writing a records management product for schools and one of the requirements is the ability to manage course schedules. I haven't looked at the code for how we deal with this (I'm on a different project at the moment), but nonetheless I started wondering how best to handle one particular part of this requirement, namely how to handle the fact that each course can be held one or more days of the week, and how best to store this information in the database. To provide some context, a bare-bones `Course` table might contain the following columns:
```
Course Example Data
------ ------------
DeptPrefix ;MATH, ENG, CS, ...
Number ;101, 300, 450, ...
Title ;Algebra, Shakespeare, Advanced Data Structures, ...
Description ;...
DaysOfWeek ;Monday, Tuesday-Thursday, ...
StartTime
EndTime
```
What I'm wondering is, what is the best way to handle the `DaysOfWeek` column in this (contrived) example? The problem I'm having with it is that is a multi-valued field: that is, you can have a course on any day of the week, and the same course can take be held on more than one day. I know certain databases natively support multi-value columns, but is there a "best practice" to handle this assuming the database doesn't natively support it?
I've come up with the following possible solutions so far, but I'm wondering if anyone has anything better:
### Possible Solution #1: Treat DaysOfWeek as a bit field
This was the first thing that popped into my head (I'm not sure if that's a good thing or not...). In this solution, `DaysOfWeek` would be defined as a byte, and the first 7 bits would be used to represent the days of week (one bit for each day). A 1 bit would indicate that a class was held on corresponding day of the week.
**Pros**: Easy to implement (the application can deal with the bit manipulations), works with any database.
**Cons**: Harder to write queries that use the `DaysOfWeek` column (although you could deal with this at the application level, or create views and stored procedues in the database to simplify this), breaks relational database model.
### Possible Solution #2: Store DaysOfWeek as a string of characters
This is essentially the same approach as using a bit field, but instead of dealing with raw bits, you assign a unique letter to each day of the week, and the `DaysOfWeek` column just stores a sequence of letters indicating what days a course is held on. For example, you might associate each weekday with a single-character code as follows:
```
Weekday Letter
------- ------
Sunday S
Monday M
Tuesday T
Wednesday W
Thursday R
Friday F
Saturday U
```
In this case, a course held on Monday, Tuesday, and Friday would have have the value `'MTF'` for `DaysOfWeek`, while a class held only on Wednesdays would have a `DaysOfWeek` value of `'W'`.
**Pros**: Easier to deal with in queries (i.e. You could use `INSTR`, or its equivalent, to determine if a class is held on a given day). Works with any database that supports INSTR or an equivalent function (most, I would guess...). Also friendlier to look at, and easy to see at a glance what is happening in queries that use the `DaysOfWeek` column.
**Cons**: The only real "con" is that, like the bitfield approach, this breaks the relational model by storing a variable number of values in a single field.
### Possible Solution #3: Use a Lookup Table (ugly)
Another possibility would be to create a new table that stores all the unique combinations of days of the week, and have the `Course.DaysOfWeek` column simply be a foreign key into this lookup table. However, this solution seems like the most inelegant one, and I only considered it because it seemed like the The Relational WayTM to do things.
**Pros**: It's the only solution that is "pure" from a relational database point of view.
**Cons**: It's inelegant and cumbersome. For example, how would you design the user interface for assigning corresponding weekdays to a given course around the lookup table? I doubt a user wants to deal with choices alongs the lines of "Sunday", "Sunday, Monday", "Sunday, Monday, Tuesday", "Sunday, Monday, Tuesday, Wednesday", and so on...
### Other Ideas?
So, is there a more elegant way to handle multiple values in a single column? Or would one the proposed solutions suffice? For what it's worth, I think my second solution is probably the best of the three possible solutions that I outlined here, but I'd be curious to see if someone has a different opinion (or indeed a different approach altogether).
|
I would avoid the string option for the sense of purity: it adds an extra layer of encoding/decoding that you do not need. It may also mess you up in the case of internationalization.
Since the number of days in a week is 7, I would keep seven columns, perhaps boolean. This will also facilitate subsequent queries. This will also be useful if the tool is ever used in countries where the workweek starts on different days.
I would avoid the lookup because that would be over-normalization. Unless your set of lookup items is not obvious or could possibly change, it's overkill. In the case of days-of-the-week (unlike US states, for example), I would sleep soundly with the fixed set.
Considering the data domain, I don't think that a bitfield would achieve any significant space savings for you and would just make your code more complex.
Finally, a word of warning about the domain: a lot of schools do weird things with their schedules where they "swap days" to balance out an equal number of weekdays of each type over the semester despite holidays. I am not clear about your system, but perhaps the best approach would be to store a table of the actual dates in which the course is expected to take place. This way, if there are two Tuesdays in a week, the teacher can get paid for showing up twice, and the teacher for the Thursday that was canceled will not pay.
|
I don't think it's hard to write queries if we use the bit option. Just use simple binary math. I think it's the most efficient method. Personally, I do it all the time. Take a look:
```
sun=1, mon=2, tue=4, wed=8, thu=16, fri=32, sat=64.
```
Now, say the course is held on mon, wed and fri. the value to save in database would be 42 (2+8+32). Then you can select courses on wednesday like this:
```
select * from courses where (days & 8) > 0
```
if you want courses on thu and fri you would write:
```
select * from courses where (days & 48) > 0
```
this article is relevant: <http://en.wikipedia.org/wiki/Bitwise_operation>
you can put days of week numbers, as constants in your code and it will be clear enough.
Hope it helps.
|
What's the best way to store the days of the week an event takes place on in a relational database?
|
[
"",
"sql",
"database-design",
""
] |
(This is related to [Floor a date in SQL server](https://stackoverflow.com/questions/85373/floor-a-date-in-sql-server).)
Does a deterministic expression exist to floor a DATETIME? When I use this as a computed column formula:
```
DATEADD(dd, DATEDIFF(dd, 0, [datetime_column]), 0)
```
the I get an error when I place an index on that column:
> Cannot create index because the key column 'EffectiveDate' is non-deterministic or imprecise.
But both DATEDIFF and DATEADD are deterministic functions by definition. Where is the catch? Is it possible?
|
My guess is that this is a bug of some sorts. In SQL 2005 I was able to create such an indexed view without a problem (code is below). When I tried to run it on SQL 2000 though I got the same error as you are getting.
The following seems to work on SQL 2000, but I get a warning that the index will be ignored AND you would have to convert every time that you selected from the view.
```
CONVERT(CHAR(8), datetime_column, 112)
```
Works in SQL 2005:
```
CREATE TABLE dbo.Test_Determinism (
datetime_column DATETIME NOT NULL DEFAULT GETDATE())
GO
CREATE VIEW dbo.Test_Determinism_View
WITH SCHEMABINDING
AS
SELECT
DATEADD(dd, DATEDIFF(dd, 0, [datetime_column]), 0) AS EffectiveDate
FROM
dbo.Test_Determinism
GO
CREATE UNIQUE CLUSTERED INDEX IDX_Test_Determinism_View ON dbo.Test_Determinism_View (EffectiveDate)
GO
```
|
Does your column [datetime\_column] have a default value set to "getDate()" ??
If so, since getdate() function is non-deterministic, this will cause this error...
Whether a user-defined function is deterministic or nondeterministic depends on how the function is coded. User-defined functions are deterministic if:
1. The function is schema-bound.
2. All built-in or user-defined
functions called by the user-defined
function are deterministic.
3. The body of the function references
no database objects outside the
scope of the function. For example,
a deterministic function cannot
reference tables other than table
variables that are local to the
function.
4. The function does not call any
extended stored procedures.
User-defined functions that do not meet these criteria are marked as nondeterministic. Built-in nondeterministic functions are not allowed in the body of user-defined functions.
|
SQL Server: Floor a date in SQL server, but stay deterministic
|
[
"",
"sql",
"sql-server",
"indexing",
"sql-server-2000",
"deterministic",
""
] |
I'm a C/Python programmer in C++ land working with the STL for the first time.
In Python, extending a list with another list uses the `.extend` method:
```
>>> v = [1, 2, 3]
>>> v_prime = [4, 5, 6]
>>> v.extend(v_prime)
>>> print(v)
[1, 2, 3, 4, 5, 6]
```
I currently use this algorithmic approach to extend vectors in C++:
```
v.resize(v.size() + v_prime.size());
copy(v_prime.begin(), v_prime.end(), v.rbegin());
```
Is this the canonical way of extending vectors, or if there is a simpler way that I'm missing?
|
From [here](https://cplusplus.com/reference/vector/vector/insert/)
```
// reserve() is optional - just to improve performance
v.reserve(v.size() + distance(v_prime.begin(),v_prime.end()));
v.insert(v.end(),v_prime.begin(),v_prime.end());
```
|
```
copy(v_prime.begin(), v_prime.end(), back_inserter(v));
```
|
C++ extend a vector with another vector
|
[
"",
"c++",
"vector",
""
] |
GWT seems like a really nice technology for Java developers who don't like (or don't know) HTML/JS/CSS to build rich web interfaces. On the server-side Grails also looks really nice, it's often described as "Rails for Java developers". I've read that Grails' "convention over configuration" approach, together with the benefits of dynamic languages (Groovy) can really reduce the amount of (boilerplate) code that needs to be written, while still leveraging best-of-breed Java technologies such as Spring and Hibernate.
Anyway, I haven't read much about how well these technologies play together. How easy is it to integrate GWT with Grails on the server-side? I'd be interested to learn about experiences of anyone that has build an application with these technologies? Recommendations on resources (books/websites) for building a GWT-Grails website would also be very welcome.
Cheers,
Don
|
Grails already has a gwt plugin: [check it out](http://grails.org/GWT+Plugin).
|
You did mention on the server side - GWT and grails actually doesn't integrate well on the serverside (not as well as you might expect given how well grails domain objects work). For RPC, the plugin it works really well.
The problem is that domain objects cannot be serialized and tranfered across the wire - after all, they groovy objects. You will need to custom make a data transfer object (DTO), and do the marshalling manually. It is possible to automate it, but there isnt any opensource code out there that does it atm - so rolling your own is the only solution.
Or see if you can get Hibernate4gwt to work with grails - but i doubt it will out of the box either.
|
integrating Grails and GWT
|
[
"",
"java",
"gwt",
"grails",
"groovy",
""
] |
I commonly find myself extracting common behavior out of classes into helper/utility classes that contain nothing but a set of static methods. I've often wondered if I should be declaring these classes as abstract, since I can't really think of a valid reason to ever instantiate these?
What would the Pros and Cons be to declaring such a class as abstract.
```
public [abstract] class Utilities{
public static String getSomeData(){
return "someData";
}
public static void doSomethingToObject(Object arg0){
}
}
```
|
You could just declare a private constructor that does nothing.
The problem with declaring the class "abstract" is that the abstract keyword usually means that class is intended to be subclassed and extended. That's definitely not what you want here.
|
Don't bother making them abstract, but include a private parameterless constructor to prevent them from ever being instantiated.
Point of comparison for those interested: in C# you would declare the class to be static, making it abstract *and* sealed (Java's final) in the compiled form, and without any instance constructor at all. That also makes it a compile-time error to declare a parameter, variable, array etc of that type. Handy.
|
Should Helper/Utility Classes be abstract?
|
[
"",
"java",
"abstract-class",
""
] |
Is `yield return` a shortcut for implementing `IEnumerable` and `IEnumerator`?
|
Yes, it is.
You can find out a lot more about it in chapter 6 of my book, C# in Depth. Fortunately chapter 6 is [available for free](http://www.manning-source.com/books/skeet/Chapter6sample.pdf) from [Manning's web site](http://manning.com/skeet/).
I also have two [other](http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx) [articles](http://csharpindepth.com/Articles/Chapter11/StreamingAndIterators.aspx) on the book's web site.
Feedback welcome.
|
To add to the link-fest, Raymond Chen did a nice little series on C# iterators a few months ago:
* <http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx>
* <http://blogs.msdn.com/oldnewthing/archive/2008/08/13/8854601.aspx>
* <http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx>
* <http://blogs.msdn.com/oldnewthing/archive/2008/08/15/8868267.aspx>
|
Is Yield Return == IEnumerable & IEnumerator?
|
[
"",
"c#",
"ienumerable",
"yield",
"iterator",
"ienumerator",
""
] |
What is the difference between a `const_iterator` and an `iterator` and where would you use one over the other?
|
`const_iterator`s don't allow you to change the values that they point to, regular `iterator`s do.
As with all things in C++, always prefer `const`, unless there's a good reason to use regular iterators (i.e. you want to use the fact that they're not `const` to change the pointed-to value).
|
They should pretty much be self-explanatory. If iterator points to an element of type T, then const\_iterator points to an element of type 'const T'.
It's basically equivalent to the pointer types:
```
T* // A non-const iterator to a non-const element. Corresponds to std::vector<T>::iterator
T* const // A const iterator to a non-const element. Corresponds to const std::vector<T>::iterator
const T* // A non-const iterator to a const element. Corresponds to std::vector<T>::const_iterator
```
A const iterator always points to the same element, so the iterator *itself* is const. But the element it points to does not have to be const, so the element it points to can be changed.
A const\_iterator is an iterator that points to a const element, so while the iterator itself can be updated (incremented or decremented, for example), the element it points to can not be changed.
|
What is the difference between const_iterator and non-const iterator in the C++ STL?
|
[
"",
"c++",
"stl",
"iterator",
"constants",
""
] |
I'd like to establish an ssh tunnel over ssh to my mysql server.
Ideally I'd return a mysqli db pointer just like I was connecting directly.
I'm on a shared host that doesn't have the [SSH2](http://ca.php.net/ssh2) libraries but I might be able to get them installed locally using PECL.
If there's a way that uses native commands that would be great.
I was thinking something like this, but without those libraries it won't work.
```
$connection = ssh2_connect('SERVER IP', 22);
ssh2_auth_password($connection, 'username', 'password');
$tunnel = ssh2_tunnel($connection, 'DESTINATION IP', 3307);
$db = new mysqli_connect('127.0.0.1', 'DB_USERNAME', 'DB_PASSWORD',
'dbname', 3307, $tunnel)
or die ('Fail: ' . mysql_error());
```
Anyone have any ideas? I'm running a shared CentOS linux host at liquidweb.
Any thoughts on making the tunnel persistent? Is it possible to establish it with another script and just take advantage of it in `PHP`?
Thanks.
|
Eric,
I think you are out of luck on this one. You can either use the ssh extension in your PHP code, or if you have access to the server, you could try to create a ssh tunnel on the command-line.
You probably need special permissions to do that, though. It also looks like you don't have ssh access to this hosting account.
--Joao
|
I would use the [autossh](http://www.harding.motd.ca/autossh/) tool to create a persistent ssh tunnel to your mysql database. Then all you have to do in your PHP code is point it to localhost.
You can test this (without automatic restart) by doing:
```
ssh -L 3306:localhost:3306 user@domain.com
```
Setup a ssh key so that you don't need to use passwords, and tweak the .ssh/authorized\_keys file on the mysql system to only allow it to be used for port forwarding.
For more info on ssh tricks see [Brian Hatch's](http://www.hackinglinuxexposed.com/articles/20030228.html) excellent series on SSH and port forwarding.
|
Connect to a MySQL server over SSH in PHP
|
[
"",
"php",
"mysql",
"ssh",
""
] |
I am not that hot at regular expressions and it has made my little mind melt some what.
I am trying to find all the tables names in a query. So say I have the query:
```
SELECT one, two, three FROM table1, table2 WHERE X=Y
```
I would like to pull out "table1, table2" or "table1" and "table2"
But what if there is no where statement. It could be the end of the file, or there could be a group by or an order by etc. I know "most" of the time this will not be an issue but I don't like the idea of coding for "most" situations and knowing I have left a hole that could cause things to go wrong later.
Is this a doable Regex expression? Am I being a Regex pleb?
(P.S. this will be done in C# but presume that doesn't matter much).
|
RegEx isn't very good at this, as it's a lot more complicated than it appears:
* What if they use LEFT/RIGHT INNER/OUTER/CROSS/MERGE/NATURAL joins instead of the a,b syntax? The a,b syntax should be avoided anyway.
* What about nested queries?
* What if there is no table (selecting a constant)
* What about line breaks and other whitespace formatting?
* Alias names?
I could go on.
What you can do is look for an sql parser, and run your query through that.
|
Everything said about the usefulness of such a regex in the SQL context. If you insist on a regex and your SQL statements always look like the one you showed (that means no subqueries, joins, and so on), you could use
```
FROM\s+([^ ,]+)(?:\s*,\s*([^ ,]+))*\s+
```
|
Regular expression to find all table names in a query
|
[
"",
".net",
"sql",
"regex",
""
] |
In what cases is it necessary to synchronize access to instance members?
I understand that access to static members of a class always needs to be synchronized- because they are shared across all object instances of the class.
My question is when would I be incorrect if I do not synchronize instance members?
for example if my class is
```
public class MyClass {
private int instanceVar = 0;
public setInstanceVar()
{
instanceVar++;
}
public getInstanceVar()
{
return instanceVar;
}
}
```
in what cases (of usage of the class `MyClass`) would I *need* to have methods:
`public synchronized setInstanceVar()` and
`public synchronized getInstanceVar()` ?
Thanks in advance for your answers.
|
It depends on whether you want your class to be thread-safe. Most classes shouldn't be thread-safe (for simplicity) in which case you don't need synchronization. If you need it to be thread-safe, you should synchronize access *or* make the variable volatile. (It avoids other threads getting "stale" data.)
|
The `synchronized` modifier is really a *bad* idea and should be avoided at all costs. I think it is commendable that Sun tried to make locking a little easier to acheive, but `synchronized` just causes more trouble than it is worth.
The issue is that a `synchronized` method is actually just syntax sugar for getting the lock on `this` and holding it for the duration of the method. Thus, `public synchronized void setInstanceVar()` would be equivalent to something like this:
```
public void setInstanceVar() {
synchronized(this) {
instanceVar++;
}
}
```
This is bad for two reasons:
* All `synchronized` methods within the same class use the exact same lock, which reduces throughput
* Anyone can get access to the lock, including members of other classes.
There is nothing to prevent me from doing something like this in another class:
```
MyClass c = new MyClass();
synchronized(c) {
...
}
```
Within that `synchronized` block, I am holding the lock which is required by all `synchronized` methods within `MyClass`. This further reduces throughput and *dramatically* increases the chances of a deadlock.
A better approach is to have a dedicated `lock` object and to use the `synchronized(...)` block directly:
```
public class MyClass {
private int instanceVar;
private final Object lock = new Object(); // must be final!
public void setInstanceVar() {
synchronized(lock) {
instanceVar++;
}
}
}
```
Alternatively, you can use the `java.util.concurrent.Lock` interface and the `java.util.concurrent.locks.ReentrantLock` implementation to achieve basically the same result (in fact, it is the same on Java 6).
|
What Cases Require Synchronized Method Access in Java?
|
[
"",
"java",
"concurrency",
"synchronization",
"methods",
"non-static",
""
] |
I am trying to improve the performance of the threaded application with real-time deadlines. It is running on Windows Mobile and written in C / C++. I have a suspicion that high frequency of thread switching might be causing tangible overhead, but can neither prove it or disprove it. As everybody knows, lack of proof is not a proof of opposite :).
Thus my question is twofold:
* If exists at all, where can I find any actual measurements of the cost of switching thread context?
* Without spending time writing a test application, what are the ways to estimate the thread switching overhead in the existing application?
* Does anyone know a way to find out the number of context switches (on / off) for a given thread?
|
While you said you don't want to write a test application, I did this for a previous test on an ARM9 Linux platform to find out what the overhead is. It was just two threads that would boost::thread::yield() (or, you know) and increment some variable, and after a minute or so (without other running processes, at least none that do something), the app printed how many context switches it could do per second. Of course this is not really exact, but the point is that both threads yielded the CPU to each other, and it was so fast that it just didn't make sense any more to think about the overhead.
So, simply go ahead and just write a simple test instead of thinking too much about a problem that may be non-existent.
Other than that, you might try like 1800 suggested with performance counters.
Oh, and I remember an application running on Windows CE 4.X, where we also have four threads with intensive switching at times, and never ran into performance issues. We also tried to implement the core threading thing without threads at all, and saw no performance improvement (the GUI just responded much slower, but everything else was the same). Maybe you can try the same, by either reducing the number of context switches or by removing threads completely (just for testing).
|
I doubt you can find this overhead somewhere on the web for any existing platform. There exists just too many different platforms. The overhead depends on two factors:
* The CPU, as the necessary operations may be easier or harder on different CPU types
* The system kernel, as different kernels will have to perform different operations on each switch
Other factors include how the switch takes place. A switch can take place when
1. the thread has used all of its time quantum. When a thread is started, it may run for a given amount of time before it has to return control to the kernel that will decide who's next.
2. the thread was preempted. This happens when another thread needs CPU time and has a higher priority. E.g. the thread that handles mouse/keyboard input may be such a thread. No matter what thread *owns* the CPU right now, when the user types something or clicks something, he doesn't want to wait till the current threads time quantum has been used up completely, he wants to see the system reacting immediately. Thus some systems will make the current thread stop immediately and return control to some other thread with higher priority.
3. the thread doesn't need CPU time anymore, because it's blocking on some operation or just called sleep() (or similar) to stop running.
These 3 scenarios might have different thread switching times in theory. E.g. I'd expect the last one to be slowest, since a call to sleep() means the CPU is given back to the kernel and the kernel needs to setup a wake-up call that will make sure the thread is woken up after about the amount of time it requested to sleep, it then must take the thread out of the scheduling process, and once the thread is woken up, it must add the thread again to the scheduling process. All these steeps will take some amount of time. So the actual sleep-call might be longer than the time it takes to switch to another thread.
I think if you want to know for sure, you must benchmark. The problem is that you usually will have to either put threads to sleep or you must synchronize them using mutexes. Sleeping or Locking/Unlocking mutexes has itself an overhead. This means your benchmark will include these overheads as well. Without having a powerful profiler, it's hard to later on say how much CPU time was used for the actual switch and how much for the sleep/mutex-call. On the other hand, in a real life scenario, your threads will either sleep or synchronize via locks as well. A benchmark that purely measures the context switch time is a synthetically benchmark as it does not model any real life scenario. Benchmarks are much more "realistic" if they base on real-life scenarios. Of what use is a GPU benchmark that tells me my GPU can in theory handle 2 billion polygons a second, if this result can never be achieved in a real life 3D application? Wouldn't it be much more interesting to know how many polygons a real life 3D application can have the GPU handle a second?
Unfortunately I know nothing of Windows programming. I could write an application for Windows in Java or maybe in C#, but C/C++ on Windows makes me cry. I can only offer you some source code for POSIX.
```
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
uint32_t COUNTER;
pthread_mutex_t LOCK;
pthread_mutex_t START;
pthread_cond_t CONDITION;
void * threads (
void * unused
) {
// Wait till we may fire away
pthread_mutex_lock(&START);
pthread_mutex_unlock(&START);
pthread_mutex_lock(&LOCK);
// If I'm not the first thread, the other thread is already waiting on
// the condition, thus Ihave to wake it up first, otherwise we'll deadlock
if (COUNTER > 0) {
pthread_cond_signal(&CONDITION);
}
for (;;) {
COUNTER++;
pthread_cond_wait(&CONDITION, &LOCK);
// Always wake up the other thread before processing. The other
// thread will not be able to do anything as long as I don't go
// back to sleep first.
pthread_cond_signal(&CONDITION);
}
pthread_mutex_unlock(&LOCK); //To unlock
}
int64_t timeInMS ()
{
struct timeval t;
gettimeofday(&t, NULL);
return (
(int64_t)t.tv_sec * 1000 +
(int64_t)t.tv_usec / 1000
);
}
int main (
int argc,
char ** argv
) {
int64_t start;
pthread_t t1;
pthread_t t2;
int64_t myTime;
pthread_mutex_init(&LOCK, NULL);
pthread_mutex_init(&START, NULL);
pthread_cond_init(&CONDITION, NULL);
pthread_mutex_lock(&START);
COUNTER = 0;
pthread_create(&t1, NULL, threads, NULL);
pthread_create(&t2, NULL, threads, NULL);
pthread_detach(t1);
pthread_detach(t2);
// Get start time and fire away
myTime = timeInMS();
pthread_mutex_unlock(&START);
// Wait for about a second
sleep(1);
// Stop both threads
pthread_mutex_lock(&LOCK);
// Find out how much time has really passed. sleep won't guarantee me that
// I sleep exactly one second, I might sleep longer since even after being
// woken up, it can take some time before I gain back CPU time. Further
// some more time might have passed before I obtained the lock!
myTime = timeInMS() - myTime;
// Correct the number of thread switches accordingly
COUNTER = (uint32_t)(((uint64_t)COUNTER * 1000) / myTime);
printf("Number of thread switches in about one second was %u\n", COUNTER);
return 0;
}
```
Output
```
Number of thread switches in about one second was 108406
```
Over 100'000 is not too bad and that even though we have locking and conditional waits. I'd guess without all this stuff at least twice as many thread switches were possible a second.
|
How to estimate the thread context switching overhead?
|
[
"",
"c++",
"c",
"multithreading",
"windows-mobile",
""
] |
The following questions are about XML serialization/deserialization and schema validation for a .net library of types which are to be used for data exchange.
---
First question, if I have a custom xml namespace say "<http://mydomain/mynamespace>" do I have to add a
```
[XmlRoot(Namespace = "http://mydomain/mynamespace")]
```
to every class in my library. Or is there a way to define this namespace as default for the whole assembly?
---
Second question, is there a reason behind the always added namespaces
```
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
```
even if there is no actual reference to any of the namespaces? I just feel they add noise to the resulting xml. Is there a way to remove them an only have the custom namespace in the resulting xml?
---
Third question, are there tools to support the generation of schema definitions (e.g. for all public [Serializable] classes of an assembly) and the validation of xml against specific schemas available?
If there are, would you recommend XML Schema from W3C or RELAX NG?
|
Just to add - the "xsi" etc is there to support things like xsi:nil on values later on - a well-known pattern for nullable values. It has to write the stream "forwards only", and it doesn't know (when it writes the first bit) whether it will need nil or not, so it assumes that writing it unnecessarily once is better than having to use the full namespace potentially lots of times.
|
1) XmlRoot can only be set at the class/struct/interface level (or on return values). So you can't use it on the assembly level. What you're looking for is the [XmlnsDefinitionAttribute](http://msdn.microsoft.com/en-us/library/system.windows.markup.xmlnsdefinitionattribute.aspx), but I believe that only is used by the XamlWriter.
2) If you're worried about clutter you should avoid xml. Well formed xml is full of clutter. I believe there are ways to interract with the xml produced by the serializer, but not directly with the XmlSerializer. You have much more control over the XML produced with the [XmlWriter](http://msdn.microsoft.com/en-us/library/10y9yyta.aspx) class. [Check here for how you can use the XmlWriter to handle namespaces.](http://msdn.microsoft.com/en-us/library/cfche0ka.aspx)
3) [XSD.exe](http://msdn.microsoft.com/en-us/library/x6c1kb0s.aspx) can be used to generate schemas for POCOs, I believe (I've always written them by hand; I may be using this soon to write up LOTS, tho!).
|
Xml Serialization and Schemas in .net (C#)
|
[
"",
"c#",
".net",
"xml",
"serialization",
""
] |
Is it possible to use [CPython](http://www.python.org/) to develop Adobe Flash based applications?
|
You can try [ming](http://www.libming.org/), a library for generating Macromedia Flash files (.swf).
It's written in C but it has wrappers that allow it to be used in C++, PHP, Python, Ruby, and Perl.
|
take a look at Flex PyPy: <http://code.google.com/p/flex-pypy/>
|
Adobe Flash and Python
|
[
"",
"python",
"flash",
"flashdevelop",
""
] |
Does anyone have any experience with running C++ applications that use the boost libraries on uclibc-based systems? Is it even possible? Which C++ standard library would you use? Is uclibc++ usable with boost?
|
We use Boost together with GCC 2.95.3, libstdc++ and STLport on an ARMv4 platform running uClinux. Some parts of Boost are not compatible with GCC 2.x but the ones that are works well in our particular case. The libraries that we use the most are *date\_time*, *bind*, *function*, *tuple* and *thread*.
Some of the libraries we had issues with were *lambda*, *shared\_pointer* and *format*. These issues were most likely caused by our version of GCC since it has problems when you have too many includes or deep levels of template structures.
If possible I would recommend you to run the boost test suite with your particular toolchain to ensure compatibility. At the very least you could compile a native toolchain in order to ensure that your library versions are compatible.
We have not used uClibc++ because that is not what our toolchain provider recommends so I cannot comment on that particular combination.
|
We are using many of the Boost libraries (thread, filesystem, signals, function, bind, any, asio, smart\_ptr, tuple) on an [Arcom Vulcan](http://www.arcom.com/pc104-ixp425-vulcan.htm) which is admittedly pretty powerful for an embedded device (64M RAM, 533MHz XScale). Everything works beautifully.
GCC 3.4 but we're not using uclib++ (Arcom provides a toolchain which includes libstd++).
Many embedded devices will happily run many of the Boost libraries, assuming decent compiler support. Just take care with usage. The Boost libraries raise the level of abstraction and it can be easy to use more resources than you think.
|
Can I use boost on uclibc linux?
|
[
"",
"c++",
"linux",
"boost",
"uclinux",
"uclibc",
""
] |
I am looking for a good menu to use in an ASP.NET. I am currently using the asp menu. I need
it to work in IE 6,7,8, Firefox and Safari. I also need it to not add a lot of overhead to the page client-side. I need to be able to load it from the database.
|
Write your own Server Control which implements the asp.net menu control but go one step further and implement the CSS friendly adapters which will give you standards compliant code instead of the usual garbage html tables that asp:menu creates.
You can read more here: <http://www.asp.net/cssadapters/Whitepaper.aspx>
|
You can use this code as inspiration: <http://trac2.assembla.com/GiusCms/browser/trunk/Controls/Controls/Menu.cs>
This control is able to use any SiteMapDataSource. Or you can simply customize it as you want. Use CSS to hide and show inner submenus.
|
Need a good ASP.NET menu
|
[
"",
"c#",
"asp.net",
"menu",
""
] |
I am creating an touch screen application using Swing and have a request to change one of buttons so that it will behave like a keyboard when the button is held down.
(First of all, I am not sure that the touch screen will allow the user to "hold down" the button, but pretend that they can for now)
I was going to go down the path of starting a loop when `mousePressed` was called and then ending the loop when `mouseReleased` was called. This will involve starting a thread and having to deal with synchronization as well as `invokeLater()` to get events back on the `EventQueue`.
Is there a very simple way to do what I want? I hope I am just not seeing the API to do it.
|
[javax.swing.Timer](http://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html) is your friend. And [here's an article](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) with some more info.
|
I would do it like this:
* Listen to mousePressed and schedule a java.util.Timer to be launched at a later time.
* The Timer does the action and set itself to schedule again.
* Listen to mouseReleased to cancel the Timer.
|
How can I make a swing JButton repeat its action when it is held down?
|
[
"",
"java",
"swing",
"event-listener",
""
] |
What's the best way to get a regular anchor (`<a href="...">`) to submit the form it is embedded in when clicked?
```
<form>
<ul>
<li>
<p>
The link could be <span>embedded <a href="" onclick="?">at any level</a></span>
in the form, so "this.parentNode.parentNode..." is no good. :(
</p>
</li>
</ul>
</form>
```
I know that the easiest way using jQuery would be
```
$('#myLink').click(function() {
$(this).parents('form:first').submit();
});
```
...but I'm trying to find a way to do this without using a library.
---
**Edit**: I'm really trying to find a method which doesn't require knowledge of the form (eg: its name, id, etc). This would be similar to how you could put this on an input element: `<input onclick="this.form.submit()" />`
|
loop through parent nodes until you find an element with tagname that indicates it's a form!
```
<form>
<ul>
<li>
<p>
The link could be <span>embedded <a href="" onclick="get_form(this).submit(); return false">at any level</a></span>
in the form, so "this.parentNode.parentNode..." is no good. :(
</p>
</li>
</ul>
</form>
<script type="text/javascript">
//<![CDATA[
function get_form( element )
{
while( element )
{
element = element.parentNode
if( element.tagName.toLowerCase() == "form" )
{
//alert( element ) //debug/test
return element
}
}
return 0; //error: no form found in ancestors
}
//]]>
</script>
```
|
Why don't you use an `<input>` or `<button>` element and just tweak it with CSS? Then it works without Javascript and is therefore more reliable.
|
How best to make a link submit a form
|
[
"",
"javascript",
"html",
"forms",
""
] |
I have the following code that creates two objects (ProfileManager and EmployerManager) where the object EmployerManager is supposed to inherit from the object ProfileManager.
However, when I do alert(pm instanceof ProfileManager); it returns false.
```
function ProfileFactory(profileType) {
switch(profileType)
{
case 'employer':
return new EmployerManager();
break;
}
}
function ProfileManager() {
this.headerHTML = null;
this.contentHTML = null;
this.importantHTML = null;
this.controller = null;
this.actions = new Array();
this.anchors = new Array();
}
ProfileManager.prototype.loadData = function(action, dao_id, toggleBack) {
var step = this.actions.indexOf(action);
var prv_div = $('div_' + step - 1);
var nxt_div = $('div_' + step);
new Ajax.Request(this.controller, {
method: 'get',
parameters: {action : this.actions[step], dao_id : dao_id},
onSuccess: function(data) {
nxt_div.innerHTML = data.responseText;
if(step != 1 && !prv_div.empty()) {
prv_div.SlideUp();
}
nxt_div.SlideDown();
for(i = 1; i <= step; i++)
{
if($('step_anchor_' + i).innerHTML.empty())
{
$('step_anchor_' + i).innerHTML = this.anchors[i];
}
}
}
}
)
}
EmployerManager.prototype.superclass = ProfileManager;
function EmployerManager() {
this.superclass();
this.controller = 'eprofile.php';
this.anchors[1] = 'Industries';
this.anchors[2] = 'Employer Profiles';
this.anchors[3] = 'Employer Profile';
this.actions[1] = 'index';
this.actions[2] = 'employer_list';
this.actions[3] = 'employer_display';
}
var pm = new ProfileFactory('employer');
alert(pm instanceof ProfileManager);
```
BTW, this is my very first attempt at Object-Oriented JavaScript, so if you feel compelled to comment on the stupidity of my approach please feel free to do so, but offer suggestions on how to approach the problem better.
|
Thanks for all of the comments. However, the solution to the problem was found in making this change to the declaration of the EmployerManager:
```
function EmployerManager() {
this.controller = 'eprofile.php';
this.anchors = new Array('Industries', 'Employer Profiles', 'Employer Profile');
this.actions = new Array('index', 'employer_list', 'employer_display');
}
EmployerManager.prototype = new ProfileManager;
```
Apparently JavaScript supports two different types of inheritance, function based and prototype based. The function based version is what I originally posted but could not make work because the EmployerManager could not see the loadData method that was part of ProfileManager's prototype.
This new example is prototype based and works now. EmployerManager is now an instance of ProfileManager.
|
I've been using something similar to Dean Edward's Base.js model.
<http://dean.edwards.name/weblog/2006/03/base/>
|
How to Establish Inheritance Between Objects in JavaScript?
|
[
"",
"javascript",
"oop",
"inheritance",
""
] |
Clearly the following is incorrect.
```
INSERT INTO `aTable` (`A`,`B`) VALUES((SELECT MAX(`A`) FROM `aTable`)*2),'name');
```
I get the value:
SQL query:
```
INSERT INTO `aTable` (`A`, `B` )
VALUES
(
(
SELECT MAX(`A`)
FROM `aTable`
) *2
, 'name'
)
```
MySQL said:
1093 - You can't specify target table 'aTable' for update in FROM clause
So, I'm trying to make a bitmap table, each row corresponds to one Bit, and has a 'map' value.
To insert in the table, I don't want to do two queries, I want to do one.
How should I do this?
No one commented on this, but since I am trying to make a bitmap, it should be \* 2 not ^ 2, my mistake, please note that is why the comments often say ^ 2, it was an error in the version that the commenters read.
|
try:
```
insert into aTable select max(a)^2, 'name' from aTable;
```
or
```
insert into aTable select max(a)^2, 'name' from aTable group by B;
```
If you need a join, you can do this:
```
insert into aTable select max(a)^2, 'name' from aTable, bTable;
```
My "Server version" is "5.0.51b-community-nt MySQL Community Edition (GPL)"
|
Actually, you can alias the table on the insert. I've seen this question all over the place, but no one seems to have tried that. Use a subquery to get the max from the table, but alias the table in the subquery.
```
INSERT INTO tableA SET fieldA = (SELECT max(x.fieldA) FROM tableA x)+1;
```
A more complex example, where you have a corresponding secondary key and might be inserting the FIRST record for the corresponding secondary key:
```
INSERT INTO tableA SET secondaryKey = 123, fieldA = COALESCE((SELECT max(x.fieldA) FROM tableA x WHERE x.secondaryKey = 123)+1,1);
```
By aliasing the table, it doesn't throw the error and seems to work. I just did this while coding something, although I can't see if there area any silly syntax errors above, I would try that type of syntax.
|
Select from same table as an Insert or Update
|
[
"",
"mysql",
"sql",
"mysql-error-1093",
""
] |
Edit: This code is fine. I found a logic bug somewhere that doesn't exist in my pseudo code. I was blaming it on my lack of Java experience.
In the **pseudo code** below, I'm trying to parse the XML shown. A silly example maybe but my code was too large/specific for anyone to get any real value out of seeing it and learning from answers posted. So, this is more entertaining and hopefully others can learn from the answer as well as me.
I'm new to Java but an experienced C++ programmer which makes me believe my problem lies in my understanding of the Java language.
Problem: When the parser finishes, my Vector is full of uninitialized Cows. I create the Vector of Cows with a default capacity (which shouldn't effect it's "size" if it's anything like C++ STL Vector). When I print the contents of the Cow Vector out after the parse, it gives the right size of Vector but all the values appear never to have been set.
Info: I have successfully done this with other parsers that don't have Vector *fields* but in this case, I'd like to use a Vector to accumulate Cow properties.
MoreInfo: I can't use generics (Vector< Cow >) so please don't point me there. :)
Thanks in advance.
```
<pluralcow>
<cow>
<color>black</color>
<age>1</age>
</cow>
<cow>
<color>brown</color>
<age>2</age>
</cow>
<cow>
<color>blue</color>
<age>3</age>
</cow>
</pluralcow>
public class Handler extends DefaultHandler{
// vector to store all the cow knowledge
private Vector m_CowVec;
// temp variable to store cow knowledge until
// we're ready to add it to the vector
private Cow m_WorkingCow;
// flags to indicate when to look at char data
private boolean m_bColor;
private boolean m_bAge;
public void startElement(...tag...)
{
if(tag == pluralcow){ // rule: there is only 1 pluralcow tag in the doc
// I happen to magically know how many cows there are here.
m_CowVec = new Vector(numcows);
}else if(tag == cow ){ // rule: multiple cow tags exist
m_WorkingCow = new Cow();
}else if(tag == color){ // rule: single color within cow
m_bColor = true;
}else if(tag == age){ // rule: single age within cow
m_bAge = true;
}
}
public void characters(...chars...)
{
if(m_bColor){
m_WorkingCow.setColor(chars);
}else if(m_bAge){
m_WorkingCow.setAge(chars);
}
}
public void endElement(...tag...)
{
if(tag == pluralcow){
// that's all the cows
}else if(tag == cow ){
m_CowVec.addElement(m_WorkingCow);
}else if(tag == color){
m_bColor = false;
}else if(tag == age){
m_bAge = false;
}
}
}
```
|
The code looks fine to me. I say set breakpoints at the start of each function and watch it in the debugger or add some print statements. My gut tells me that either `characters()` is not being called or `setColor()` and `setAge()` don't work correctly, but that's just a guess.
|
When you say that the Cows are uninitialized, are the String properties initialized to null? Or empty Strings?
I know you mentioned that this is pseudo-code, but I just wanted to point out a few potential problems:
```
public void startElement(...tag...)
{
if(tag == pluralcow){ // rule: there is only 1 pluralcow tag in the doc
// I happen to magically know how many cows there are here.
m_CowVec = new Vector(numcows);
}else if(tag == cow ){ // rule: multiple cow tags exist
m_WorkingCow = new Cow();
}else if(tag == color){ // rule: single color within cow
m_bColor = true;
}else if(tag == age){ // rule: single age within cow
m_bAge = true;
}
}
```
You really should be using tag.equals(...) instead of tag == ... here.
```
public void characters(...chars...)
{
if(m_bColor){
m_WorkingCow.setColor(chars);
}else if(m_bAge){
m_WorkingCow.setAge(chars);
}
}
```
I'm assuming you're aware of this, but this methods is actually called with a character buffer with start and end indexes.
Note also that characters(...) can be called multiple times for a single text block, returning small chunks in each call:
<http://java.sun.com/j2se/1.4.2/docs/api/org/xml/sax/ContentHandler.html#characters(char[],%20int,%20int)>
> "...SAX parsers may return all contiguous
> character data in a single chunk, or
> they may split it into several chunks..."
I doubt you'll run into that problem in the simple example you provided, but you also mentioned that this is a simplified version of a more complex problem. If in your original problem, your XML consists of large text blocks, this is something to consider.
Finally, as others have mentioned, if you could, it's a good idea to consider an XML marshalling library (e.g., JAXB, Castor, JIBX, XMLBeans, XStream to name a few).
|
Java Vector Field (private member) accumulator doesn't store my Cows!
|
[
"",
"java",
"vector",
"field",
""
] |
In C++, is (int) ch equivalent to int(ch).
If not, what's the difference?
|
They are the same thing, and also the same as `(int)(ch)`. In C++, it's generally preferred to use a named cast to clarify your intentions:
* Use `static_cast` to cast between primitive types of different sizes or signednesses, e.g. `static_cast<char>(anInteger)`.
* Use `dynamic_cast` to downcast a base class to a derived class (polymorphic types only), e.g. `dynamic_cast<Derived *>(aBasePtr)`.
* Use `reinterpret_cast` to cast between pointers of different types or between a pointer and an integer, e.g. `reinterpret_cast<uintptr_t>(somePtr)`.
* Use `const_cast` to remove the `const` or `volatile` qualifiers from variables (**VERY DANGEROUS**), e.g. `const_cast<char *>(aConstantPointer)`.
|
`int(x)` is called function-style cast by the standard and is the same as the C-style cast in every regard (for POD) [5.2.3]:
> If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4).
|
(int) ch vs. int(ch): Are they different syntaxes for the same thing?
|
[
"",
"c++",
"casting",
""
] |
I know that in JavaScript, creating a for loop like this: `for(int i = 0; i < arr.length; i++)` is costly as it computes the array length each time.
Is this behavior costly in c# for lists and arrays as well. Or at compile-time is it optimized? Also what about other languages such as Java, how is this handled?
|
It is *not* costly in C#. For one thing, there is no “calculation“: querying the length is basically an elementary operation thanks to inlining. And secondly, because ([according to its developers](http://blogs.msdn.com/ericgu/archive/2004/04/18/115566.aspx)), the compiler recognizes this pattern of access and will in fact optimize any (redundant) boundary checks for access on array elements.
And by the way, I believe that something similar is true for modern JavaScript virtual machines, and if it isn't already, it will be very soon since this is a trivial optimization.
|
1. All .Net arrays have a field containing the length of the array, so the length is not computed at usage but at creation time.
2. The .Net virtual machine is very good at eliminating bounds checks whenever possible, this is one of those cases, where the bounds check is moved outside the loop (in most situations, and if not it's just 2 instructions overhead).
Edit:
[Array Bounds Check Elimination](https://blogs.msdn.microsoft.com/clrcodegeneration/2009/08/13/array-bounds-check-elimination-in-the-clr/)
|
Is it costly to do array.length or list.count in a loop
|
[
"",
"c#",
"compiler-construction",
"performance",
"language-features",
""
] |
I have seen samples of closure from - [What is a 'Closure'?](https://stackoverflow.com/questions/36636/what-is-a-closure)
Can anyone provide simple example of when to use closure?
**Specifically, scenarios in which closure makes sense?**
Lets assume that the language doesn't have closure support, how would one still achieve similar thing?
Not to offend anyone, please post code samples in a language like c#, python, javascript, ruby etc.
I am sorry, I do not understand functional languages yet.
|
Closures are simply great tools. When to use them? Any time you like... As has already been said, the alternative is to write a class; for example, pre C# 2.0, creating a parameterised thread was a real struggle. With C# 2.0 you don't even need the `ParameterizedThreadStart' you just do:
```
string name = // blah
int value = // blah
new Thread((ThreadStart)delegate { DoWork(name, value);}); // or inline if short
```
Compare that to creating a class with a name and value
Or likewise with searching for a list (using a lambda this time):
```
Person person = list.Find(x=>x.Age > minAge && x.Region == region);
```
Again - the alternative would be to write a class with two properties and a method:
```
internal sealed class PersonFinder
{
public PersonFinder(int minAge, string region)
{
this.minAge = minAge;
this.region = region;
}
private readonly int minAge;
private readonly string region;
public bool IsMatch(Person person)
{
return person.Age > minAge && person.Region == region;
}
}
...
Person person = list.Find(new PersonFinder(minAge,region).IsMatch);
```
This is *fairly* comparable to how the compiler does it under the bonnet (actually, it uses public read/write fields, not private readonly).
The biggest caveat with C# captures is to watch the scope; for example:
```
for(int i = 0 ; i < 10 ; i++) {
ThreadPool.QueueUserWorkItem(delegate
{
Console.WriteLine(i);
});
}
```
This might not print what you expect, since the *variable* i is used for each. You could see any combination of repeats - even 10 10's. You need to carefully scope captured variables in C#:
```
for(int i = 0 ; i < 10 ; i++) {
int j = i;
ThreadPool.QueueUserWorkItem(delegate
{
Console.WriteLine(j);
});
}
```
Here each j gets captured separately (i.e. a different compiler-generated class instance).
Jon Skeet has a good blog entry covering C# and java closures [here](http://msmvps.com/blogs/jon_skeet/archive/2008/05/06/the-beauty-of-closures.aspx); or for more detail, see his book [C# in Depth](http://www.manning.com/skeet/), which has an entire chapter on them.
|
I agree with a previous answer of "all the time". When you program in a functional language or any language where lambdas and closures are common, you use them without even noticing. It's like asking "what is the scenario for a function?" or "what is the scenario for a loop?" This isn't to make the original question sound dumb, rather it's to point out that there are constructs in languages that you don't define in terms of specific scenarios. You just use them all the time, for everything, it's second nature.
This is somehow reminiscent of:
> The venerable master Qc Na was walking
> with his student, Anton. Hoping to
> prompt the master into a discussion,
> Anton said "Master, I have heard that
> objects are a very good thing - is
> this true?" Qc Na looked pityingly at
> his student and replied, "Foolish
> pupil - objects are merely a poor
> man's closures."
>
> Chastised, Anton took his leave from
> his master and returned to his cell,
> intent on studying closures. He
> carefully read the entire "Lambda: The
> Ultimate..." series of papers and its
> cousins, and implemented a small
> Scheme interpreter with a
> closure-based object system. He
> learned much, and looked forward to
> informing his master of his progress.
>
> On his next walk with Qc Na, Anton
> attempted to impress his master by
> saying "Master, I have diligently
> studied the matter, and now understand
> that objects are truly a poor man's
> closures." Qc Na responded by hitting
> Anton with his stick, saying "When
> will you learn? Closures are a poor
> man's object." At that moment, Anton
> became enlightened.
(<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html>)
|
When to use closure?
|
[
"",
"c#",
"functional-programming",
"closures",
""
] |
I’m starting a project where I need to implement a light-weight interpreter.
The interpreter is used to execute simple scientific algorithms.
The programming language that this interpreter will use should be simple, since it is targeting non- software developers (for example, mathematicians.)
The interpreter should support basic programming languages features:
* Real numbers, variables, multi-dimensional arrays
* Binary (+, -, \*, /, %) and Boolean (==, !=, <, >, <=, >=) operations
* Loops (for, while), Conditional expressions (if)
* Functions
[MathWorks MatLab](http://www.mathworks.com/) is a good example of where I’m heading, just much simpler.
The interpreter will be used as an environment to demonstrate algorithms; simple algorithms such as finding the average of a dataset/array, or slightly more complicated algorithms such as [Gaussian elimination](http://en.wikipedia.org/wiki/Gaussian_elimination) or [RSA](http://en.wikipedia.org/wiki/RSA).
Best/Most practical resource I found on the subject is Ron Ayoub’s entry on Code Project ([Parsing Algebraic Expressions Using the Interpreter Pattern](http://www.codeproject.com/KB/architecture/InterpreterPatternParsing.aspx)) - a perfect example of a minified version of my problem.
The Purple Dragon Book seems to be too much, anything more practical?
The interpreter will be implemented as a .NET library, using C#. However, resources for any platform are welcome, since the design-architecture part of this problem is the most challenging.
Any practical resources?
(please avoid “this is not trivial” or “why re-invent the wheel” responses)
|
I would write it in [ANTLR](http://www.antlr.org/). Write the grammar, let ANTLR generate a C# parser. You can ANTLR ask for a parse tree, and possibly the interpreter can already operate on the parse tree. Perhaps you'll have to convert the parse tree to some more abstract internal representation (although ANTLR already allows to leave out irrelevant punctuation when generating the tree).
|
It might sound odd, but Game Scripting Mastery is a great resource for learning about parsing, compiling and interpreting code.
You should really check it out:
[http://www.amazon.com/Scripting-Mastery-Premier-Press-Development/dp/1931841578](https://rads.stackoverflow.com/amzn/click/com/1931841578)
|
Constructing a simple interpreter
|
[
"",
"c#",
"architecture",
"compiler-construction",
"programming-languages",
""
] |
What is JDBC and where can I start learning about?
I know it's a way to access databases with Java, but what problems does it solve? Is it an ORM (or does it try to be)? Does it abstract away differences between databases, at the syntax level? What does it do? and what does it not do?
|
JDBC is a driver that allows you to access database. It provides you with a very raw way to access the database using SQL. Its primary function is to allow you (the user) to run SQL commands on the database. It is not an ORM and never will be. The sun website <http://java.sun.com/docs/books/tutorial/jdbc/> has a nice tutorial for JDBC. If you are interested in a ORM try <http://www.hibernate.org/>.
|
No, JDBC isn't an ORM. It's the [Java Database Connectivity](http://java.sun.com/javase/technologies/database/index.jsp) API and basically it provides a database-agnostic access layer with a provider model (so that new database drivers can be added easily). Vendors can add more functionality for specific database features if they wish, but developers can ignore those features if they wish to work with multiple databases.
There's no mapping involved - just modeling for connections (and pools), prepared statements, stored procedures, result sets etc.
|
What is JDBC (Java DataBase Connectivity)?
|
[
"",
"java",
"jdbc",
""
] |
What is the difference between using system() to execute a binary and using the combination of fork/execvp.
Is there any security/portablility/performance difference.
|
System also uses a `fork`/`exec`... combination. If you do `fork`/`exec` yourself you can execute parallel to your running process, while `system` is blocking (includes the `wait`).
Also `system` executes the command not direct, but via a shell (which makes problems with setuid bit) and `system` blocks/ignores certain signals (SIGINT, SIGCHILD, SIGQUIT).
|
Yes, `system()` runs the command through a shell, while `exec()` runs the command directly. Of course, introducing a shell opens up for bugs and exploits.
Edit: of course, [the man page](http://linux.die.net/man/3/system) provides more detail.
|
Difference between using fork/execvp and system call
|
[
"",
"c++",
"c",
"linux",
"unix",
""
] |
I've looked into and considered many JavaScript unit tests and testing tools, but have been unable to find a suitable option to remain fully TDD compliant. So, is there a JavaScript unit test tool that is fully TDD compliant?
|
## [Karma](http://karma-runner.github.io) or [Protractor](http://angular.github.io/protractor/#/)
Karma is a JavaScript test-runner built with Node.js and meant for unit testing.
The Protractor is for end-to-end testing and uses Selenium Web Driver to drive tests.
Both have been made by the Angular team. You can use any assertion-library you want with either.
Screencast: [Karma Getting started](http://www.youtube.com/watch?v=MVw8N3hTfCI)
**related**:
* [Should I be using Protractor or Karma for my end-to-end testing?](https://stackoverflow.com/questions/21732379/should-i-be-using-protractor-or-karma-for-my-end-to-end-testing/21733114#21733114)
* [Can Protractor and Karma be used together?](https://stackoverflow.com/questions/17070522/can-protractor-and-karma-be-used-together)
**pros**:
* Uses Node.js, so compatible with Win/OS X/Linux
* Run tests from a browser or headless with PhantomJS
* Run on multiple clients at once
* Option to launch, capture, and automatically shut down browsers
* Option to run server/clients on development computer or separately
* Run tests from a command line (can be integrated into ant/maven)
* Write tests xUnit or BDD style
* Supports multiple JavaScript test frameworks
* Auto-run tests on save
* Proxies requests cross-domain
* Possible to customize:
+ Extend it to wrap other test-frameworks (Jasmine, Mocha, QUnit built-in)
+ Your own assertions/refutes
+ Reporters
+ Browser Launchers
* Plugin for WebStorm
* Supported by NetBeans IDE
**Cons**:
* Does [not support Node.js (i.e. backend)](https://stackoverflow.com/a/16660909/1175496) testing
* No plugin for Eclipse (yet)
* No history of previous test results
# [mocha.js](http://mochajs.org)
I'm totally unqualified to comment on mocha.js's features, strengths, and weaknesses,
but it was just recommended to me by someone I trust in the JS community.
List of features, as reported by its website:
* browser support
* simple async support, including promises
* test coverage reporting
* string diff support
* JavaScript # API for running tests
* proper exit status for CI support etc
* auto-detects and disables coloring for non-ttys
* maps uncaught exceptions to the correct test case
* async test timeout support
* test-specific timeouts
* growl notification support
* reports test durations
* highlights slow tests
* file watcher support
* global variable leak detection
* optionally run tests that match a regexp
* auto-exit to prevent "hanging" with an active loop
* easily meta-generate suites & test-cases
* mocha.opts file support
* clickable suite titles to filter test execution
* node debugger support
* detects multiple calls to done()
* use any assertion library you want
* extensible reporting, bundled with 9+ reporters
* extensible test DSLs or "interfaces"
* before, after, before each, after each hook
* arbitrary transpiler support (coffee-script etc)
* TextMate bundle
## [yolpo](http://www.yolpo.com)

> This no longer exists, redirects to [sequential.js](https://sequential.js.org) instead
Yolpo is a tool to visualize the execution of JavaScript. JavaScript API developers are encouraged to write their use cases to show and tell their API. Such use cases forms the basis of regression tests.
## [AVA](https://github.com/sindresorhus/ava)
[](https://github.com/sindresorhus/ava)
Futuristic test runner with built-in support for ES2015. Even though JavaScript is single-threaded, I/O in Node.js can happen in parallel due to its async nature. AVA takes advantage of this and runs your tests concurrently, which is especially beneficial for I/O heavy tests. In addition, test files are run in parallel as separate processes, giving you even better performance and an isolated environment for each test file.
* Minimal and fast
* Simple test syntax
* Runs tests concurrently
* Enforces writing atomic tests
* No implicit globals
* Isolated environment for each test file
* Write your tests in ES2015
* Promise support
* Generator function support
* Async function support
* Observable support
* Enhanced asserts
* Optional TAP o
utput
* Clean stack traces
## [Buster.js](http://busterjs.org/)
A JavaScript test-runner built with Node.js. Very modular and flexible. It comes with its own assertion library, but you can add your own if you like. The [assertions library](http://docs.busterjs.org/en/latest/modules/referee/) is decoupled, so you can also use it with other test-runners. Instead of using `assert(!...)` or `expect(...).not...`, it uses `refute(...)` which is a nice twist imho.
> A browser JavaScript testing toolkit. It does browser testing with browser automation (think JsTestDriver), QUnit style static HTML page testing, testing in headless browsers (PhantomJS, jsdom, ...), and more. Take a look at [the overview](http://docs.busterjs.org/en/latest/overview/)!
>
> A Node.js testing toolkit. You get the same test case library, assertion library, etc. This is also great for hybrid browser and Node.js code. Write your test case with `Buster.JS` and run it both in Node.js and in a real browser.
Screencast: [Buster.js Getting started](http://www.youtube.com/watch?v=VSFGAl1BekY) (2:45)
**pros**:
* Uses Node.js, so compatible with Win/OS X/Linux
* Run tests from a browser or headless with PhantomJS (soon)
* Run on multiple clients at once
* Supports Node.js testing
* Don't need to run server/clients on development computer (no need for IE)
* Run tests from a command line (can be integrated into ant/maven)
* Write tests xUnit or BDD style
* Supports multiple JavaScript test frameworks
* Defer tests instead of commenting them out
* SinonJS built-in
* [Auto-run tests on save](http://www.youtube.com/watch?v=gKVej9SAzH4)
* Proxies requests cross-domain
* Possible to customize:
+ Extend it to wrap other test-frameworks (JsTestDriver built in)
+ Your own assertions/refutes
+ Reporters (xUnit XML, traditional dots, specification, tap, TeamCity and more built-in)
+ Customize/replace the HTML that is used to run the browser-tests
* TextMate and Emacs integration
**Cons**:
* Stil in beta so can be buggy
* No plugin for Eclipse/IntelliJ (yet)
* Doesn't group results by os/browser/version like TestSwarm \*. It does, however, print out the browser name and version in the test results.
* No history of previous test results like TestSwarm \*
* Doesn't fully work on windows [as of May 2014](http://docs.busterjs.org/en/latest/developers/windows/)
\* TestSwarm is also a Continuous Integration server, while you need a separate CI server for `Buster.js`. It does, however, output xUnit XML reports, so it should be easy to integrate with [Hudson](http://hudson-ci.org/), [Bamboo](http://www.atlassian.com/software/bamboo/overview) or other CI servers.
## [TestSwarm](https://github.com/jquery/testswarm/)
<https://github.com/jquery/testswarm>
TestSwarm is officially no longer under active development as stated on their GitHub webpage. They recommend Karma, browserstack-runner, or Intern.
## [Jasmine](https://github.com/pivotal/jasmine/)

This is a behavior-driven framework (as stated in quote below) that might interest developers familiar with Ruby or Ruby on Rails. The syntax is based on [RSpec](http://rspec.info/) that are used for testing in Rails projects.
Jasmine specs can be run from an HTML page (in qUnit fashion) or from a test runner (as Karma).
> Jasmine is a behavior-driven development framework for testing your JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM.
If you have experience with this testing framework, please contribute with more info :)
Project home: [http://jasmine.github.io/](https://github.com/pivotal/jasmine/)
## [QUnit](http://qunitjs.com/)
QUnit focuses on testing JavaScript in the browser while providing as much convenience to the developer as possible. Blurb from the site:
> QUnit is a powerful, easy-to-use JavaScript unit test suite. It's used by the jQuery, jQuery UI, and jQuery Mobile projects and is capable of testing any generic JavaScript code
QUnit shares some history with TestSwarm (above):
> QUnit was originally developed by John Resig as part of jQuery. In 2008 it got its own home, name and API documentation, allowing others to use it for their unit testing as well. At the time it still depended on jQuery. A rewrite in 2009 fixed that, now QUnit runs completely standalone.
> QUnit's assertion methods follow the CommonJS Unit Testing specification, which was to some degree influenced by QUnit.
Project home: <http://qunitjs.com/>
## [Sinon](http://sinonjs.org)
Another great tool is [sinon.js](http://sinonjs.org) by Christian Johansen, the author of [Test-Driven JavaScript Development](http://tddjs.com/). Best described by himself:
> Standalone test spies, stubs and mocks
> for JavaScript. No dependencies works
> with any unit testing framework.
## [Intern](http://theintern.io)
The [Intern Web site](http://theintern.io/#compare) provides a direct feature comparison to the other testing frameworks on this list. It offers more features out of the box than any other JavaScript-based testing system.
## [JEST](https://jestjs.io/)
A new but yet very powerful testing framework. It allows snapshot based testing as well this increases the testing speed and creates a new dynamic in terms of testing
Check out one of their talks: <https://www.youtube.com/watch?v=cAKYQpTC7MA>
Better yet: [Getting Started](https://jestjs.io/docs/en/getting-started.html)
|
Take a look at [the Dojo Object Harness (DOH) unit test framework](http://www.dojotoolkit.org/reference-guide/util/doh.html) which is pretty much framework independent harness for JavaScript unit testing and doesn't have any Dojo dependencies. There is a very good description of it at [Unit testing Web 2.0 applications using the Dojo Objective Harness](http://www.ibm.com/developerworks/web/library/wa-aj-doh/index.html).
If you want to automate the UI testing (a sore point of many developers) — check out [doh.robot](http://dojotoolkit.org/2008/08/11/doh-robot-automating-web-ui-unit-tests-real-user-events) *(temporary down. update: other link <http://dojotoolkit.org/reference-guide/util/dohrobot.html> )* and [dijit.robotx](http://blog.dojotoolkit.org/2008/10/31/doh-robot-part-2-automating-acceptance-tests-and-user-stories) *(temporary down)*. The latter is designed for an acceptance testing.
Update:
Referenced articles explain how to use them, how to emulate a user interacting with your UI using mouse and/or keyboard, and how to record a testing session, so you can "play" it later automatically.
|
JavaScript unit test tools for TDD
|
[
"",
"javascript",
"unit-testing",
"tdd",
""
] |
Can I convert a string representing a boolean value (e.g., 'true', 'false') into an intrinsic type in JavaScript?
I have a hidden form in HTML that is updated based on a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.
The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.
```
var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
```
Is there a better way to accomplish this?
|
# Do:
```
var isTrueSet = (myValue === 'true');
```
using the identity operator (`===`), which doesn't make any implicit type conversions when the compared variables have different types.
This will set `isTrueSet` to a boolean `true` if the string is "true" and boolean `false` if it is string "false" or not set at all.
For making it case-insensitive, try:
```
var isTrueSet = /^true$/i.test(myValue);
// or
var isTrueSet = (myValue?.toLowerCase?.() === 'true');
// or
var isTrueSet = (String(myValue).toLowerCase() === 'true');
```
---
## Don't:
You should probably **be cautious about using these two methods** for your specific needs:
```
var myBool = Boolean("false"); // == true
var myBool = !!"false"; // == true
```
Any string which isn't the empty string will evaluate to `true` by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.
|
# Warning
This highly upvoted legacy answer is technically correct but only covers a very specific scenario, when your string value is EXACTLY `"true"` or `"false"`.
An invalid json string passed into these functions below **WILL throw an exception**.
---
**Original answer:**
How about?
```
JSON.parse("True".toLowerCase());
```
or with jQuery
```
$.parseJSON("TRUE".toLowerCase());
```
|
How can I convert a string to boolean in JavaScript?
|
[
"",
"javascript",
"boolean-expression",
"boolean-operations",
"string-conversion",
""
] |
I want to let the user draw on an image in a browser. In other words, I need *both* bitmapped graphics and drawing capabilities, whether vector or bitmapped.
Canvas looks good, but is not supported by IE, and though there is ExCanvas, I wonder if ExCanvas is stable enough for consistent use in IE6 through 8.
Or best of all, is there an open-source image/drawing library that supports all this out of the box? I found two dozen or so Web-based image editors or drawing tools, but none support the requirements. (And I'd like to avoid Flash/Flex/Silverlight/JavaFX.)
|
Even though you said you'd like to avoid it I'd suggest Flash. You could easily use Flash 6 or 7 and these have a > 90% adoption rate. I'd be surprised if you could get that level of support with JavaScript. Flash is truly write once run anywhere, which will cut down on your development time.
|
Take a look at [RaphaelJS](http://raphaeljs.com/)... it's a cross browser implementation of drawing functions, using Canvas, VML or SVG where available. I'm not sure if it lets users draw for themselves out of the box, but it might be worth a look.
|
Drawing on top of an image in Javascript
|
[
"",
"javascript",
"image",
"browser",
"graphics",
"draw",
""
] |
What is the best way to encode URL strings such that they are rfc2396 compliant and to decode a rfc2396 compliant string such that for example %20 is replaced with a space character?
edit:
URLEncoder and URLDecoder classes do **not** encode/decode rfc2396 compliant URLs, they encode to a MIME type of application/x-www-form-urlencoded which is used to encode HTML form parameter data.
|
Use the URI class as follows:
```
URI uri = new URI("http", "//www.someurl.com/has spaces in url", null);
URL url = uri.toURL();
```
or if you want a String:
```
String urlString = uri.toASCIIString();
```
|
Your component parts, potentially containing characters that must be escaped, should already have been escaped using URLEncoder before being concatenated into a URI.
If you have a URI with out-of-band characters in (like space, "<>[]{}\|^`, and non-ASCII bytes), it's not really a URI. You can try to fix them up by manually %-escaping them, but this is a last-ditch fix-up operation and not a standard form of encoding. This is usually necessary when you are accepting potentially-malformed URIs from user input, but it's not a standardised operation and I don't know of any built-in Java library function that will do it for you; you may have to hack something up yourself with a RegExp.
In the other direction, you must take your URI apart into its component parts (each separate path part, query parameter name and value, and so on) before you can unescape each part (using an URLDecoder). There is no sensible way to %-decode a whole URI in one go; you could try to ‘decode %-escapes that do not decode to delimiters’ (like /?=&;%) but you would be left with a strange inconsistent string that doesn't conform to any URI-processing standard.
URLEncoder/URLDecoder are fine for handling URI query components, both names and values. However they are not *quite* right for handling URI path part components. The difference is that the ‘+’ character does not mean a space in a path part. You can fix this up with a simple string replace: after URLEncoding, replace ‘+’ with ‘%20’; before URLDecoding, replace ‘+’ with ‘%2B’. You can ignore the difference if you are not planning to include segments containing spaces or pluses in your path.
|
Encode and Decode rfc2396 URLs
|
[
"",
"java",
"rfc2396",
""
] |
I am pulling data out of an old-school ActiveX in the form of arrays of doubles. I don't initially know the final number of samples I will actually retrieve.
What is the most efficient way to concatenate these arrays together in C# as I pull them out of the system?
|
You can't append to an actual array - the size of an array is fixed at creation time. Instead, use a `List<T>` which can grow as it needs to.
Alternatively, keep a list of arrays, and concatenate them all only when you've grabbed everything.
See [Eric Lippert's blog post on arrays](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/arrays-considered-somewhat-harmful) for more detail and insight than I could realistically provide :)
|
Concatenating arrays is simple using linq extensions which come standard with .Net 4
Biggest thing to remember is that linq works with `IEnumerable<T>` objects, so in order to get an array back as your result then you must use the `.ToArray()` method at the end
Example of concatenating two byte arrays:
```
byte[] firstArray = {2,45,79,33};
byte[] secondArray = {55,4,7,81};
byte[] result = firstArray.Concat(secondArray).ToArray();
```
|
Most efficient way to append arrays in C#?
|
[
"",
"c#",
"arrays",
"memory-management",
""
] |
I'm using the Apache Commons EqualsBuilder to build the equals method for a non-static Java inner class. For example:
```
import org.apache.commons.lang.builder.EqualsBuilder;
public class Foo {
public class Bar {
private Bar() {}
public Foo getMyFoo() {
return Foo.this
}
private int myInt = 0;
public boolean equals(Object o) {
if (o == null || o.getClass() != getClass) return false;
Bar other = (Bar) o;
return new EqualsBuilder()
.append(getMyFoo(), other.getMyFoo())
.append(myInt, other.myInt)
.isEquals();
}
}
public Bar createBar(...) {
//sensible implementation
}
public Bar createOtherBar(...) {
//another implementation
}
public boolean equals(Object o) {
//sensible equals implementation
}
}
```
Is there syntax by which I can refer to `other`'s `Foo` reference apart from declaring the `getMyFoo()` method? Something like `other.Foo.this` (which doesn't work)?
|
No.
The best way is probably what you suggested: add a getFoo() method to your inner class.
|
No, not possible without a getter. The 'this' keyword will always point to the current instance. I'm quite curious why you would want to do this... seems like you are doing composition in the wrong way.
```
public class Foo {
public Bar createBar(){
Bar bar = new Bar(this)
return bar;
}
}
public class Bar {
Foo foo;
public Bar(Foo foo){
this.foo = foo;
}
public boolean equals(Object other) {
return foo.equals(other.foo);
}
}
```
Since using Foo.this limits creation of the inner class (Foo myFoo = new Foo(); myFoo.new Bar(); to an instance I'd say this is much cleaner.
|
How to refer to the outer class in another instance of a non-static inner class?
|
[
"",
"java",
"syntax",
"reference",
"inner-classes",
""
] |
I'm writing this question in the spirit of answering your own questions, since I found a solution to the problem, but if anyone has a better solution I would gladly listen to it.
In the application I am currently working on I am subclassing the ListView control to add some functionality of which some interacts with the ListView SelectedIndices and SelectedItems properties.
The problem is that when I try to unit test my subclass, the SelectedIndices and SelectedItems properties does not update when I add items to the selection. I tried both
```
item.Selected = true
```
and
```
listView.SelectedIndices.Add(...)
```
But SelectedIndices or SelectedItems simply does not appear to be affected. The unit tests for the other parts of the functionality works fine.
How can I unit test the selection dependent parts of my ListView subclass?
|
The problem seems to be that the SelectedIndices and SelectedItems does not update properly if the ListView has not been drawn, as is stated in this comment from the MSDN documentation of the [ListViewItem.Selected property](http://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.selected(VS.85).aspx):
> The Selected property cannot be trusted if your ListView has never been drawn (for example, it's in a TabControl, in a tab that has not been selected yet). In that case, the SelectedItems and SelectedIndices of the parent ListView are not correctly updated and will still be empty.
One solution to this problem is to create a simple dummy form class in your test, add the ListView to the form and simply show the form. After that the SelectedIndices and SelectedItems properties work as expected.
Something like this:
```
[Test]
public void CanGetSelectedItems()
{
// simple test to make sure that the SelectedIndices
// property is updated
using (var f = new DummyForm(listView))
{
f.Show();
listView.SelectedIndices.Add(0);
Assert.AreEqual(1, listView.SelectedIndices.Count);
}
}
private class DummyForm : Form
{
public DummyForm(ListView listView)
{
// Minimize and make it not appear in taskbar to
// avoid flicker etc when running the tests
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
this.Controls.Add(listView);
}
}
```
|
I found a trick you can use to get those properties populated:
listView.AccessibilityObject.ToString(); //workaround to get selecteditems properties refreshed
|
Why do SelectedIndices and SelectedItems not work when ListView is instantiated in unit test?
|
[
"",
"c#",
".net",
"winforms",
"unit-testing",
"listview",
""
] |
I wish to set a usererror string before leaving a function, depending on the return code and variable in the function.
I currently have:
```
Dim RetVal as RetType
try
...
if ... then
RetVal = RetType.FailedParse
end try
endif
...
finally
select case RetVal
case ...
UserStr = ...
end select
end try
return RetVal
```
Is it possible to use return RetType.FailedParse, then access this in the finally block?
|
The only real way of doing this in C# would be to declare a variable at the start of the method to hold the value - i.e.
```
SomeType result = default(SomeType); // for "definite assignment"
try {
// ...
return result;
}
finally {
// inspect "result"
}
```
In VB, you *might* be able to access the result directly - since IIRC it kinda works like the above (with the method name as "result") anyway. Caveat: I'm **really** not a VB person...
|
Declare the variable out of the try block, and check in the finally block if it has been set.
|
Is it legal and possible to access the return value in a finally block?
|
[
"",
"c#",
".net",
"vb.net",
"try-catch",
"seh",
""
] |
I'm looking for a good lightweight Java docking framework.
I know that Netbeans and Eclipse can be used as RCP, but I'm looking for something a little bit more lightweight.
|
Swing / AWT frameworks:
* [Raven Docking](http://raven.java.net/ravenDocking/download.html) Apache 2; 0.2 MB
* [MyDoggy](http://mydoggy.sourceforge.net/) LGPL; only JARs: 0.7 MB; Dec 2010
* [VLDocking](http://code.google.com/archive/p/vldocking/) LGPL; 0.4 MB
* [NetBeans](http://netbeans.org/features/platform/index.html) CDDL/GPL; 4.6 MB (platform.zip)
* Eclipse CPL or EPL ? only swt (?)
* [InfoNode](http://sourceforge.net/projects/infonode/) GPL or Commercial
* [Sanaware](http://www.javadocking.com/) GPL or Commercial full zip 0.3MB
* [Docking Frames](http://dock.javaforge.com/) LGPL; 3 MB
* [Jide](http://www.jidesoft.com/products/dock.htm) commercial; <3MB
* [FlexDock](http://forge.scilab.org/index.php/p/flexdock/) MIT; 0.4 MB; Nov 2011
JavaFX frameworks:
* [TiwulFX-Dock](https://github.com/panemu/tiwulfx-dock) MIT; 22 KB
* [DockFX](https://github.com/RobertBColton/DockFX) MPL-2.0; 44 KB
Inactive projects
* [SwingDocking](http://sourceforge.net/projects/swingdocking/) seems to me fully functional and fast; Apache license 2; Oct 2007
* [XUI](http://sourceforge.net/projects/xui/) will be further developed here?; MPL; 1.6 MB (XUI-jdk15.zip); Feb 2008
* JDocking CDDL; 1.3 MB (v0.8.zip) the docking part of netbeans
* [JRichClient](http://code.google.com/p/jrichclient/) GPL; derivation of flexdock; Nov 2007
|
I once evaluated several docking frameworks (including the already mentioned [flexdock](https://flexdock.dev.java.net/) and [mydoggy](http://mydoggy.sourceforge.net/) and [jdocking](https://jdocking.dev.java.net/).
Finaly I came to [Docking Frames](http://dock.javaforge.com/index.html), which I can really recommend. It is easy to use but still feature rich + good documentation and quick support from developer via forum.
|
What are good docking frameworks for Java/Swing?
|
[
"",
"java",
"swing",
"frameworks",
"docking",
""
] |
Is there any way to set an event handler without doing it manually in the classname.designer.cs file other than double clicking the UI element?
|
Click on the lightning bolt icon in the Properties window. Double-click the event you want to implement.
|
If I follow your question correctly, you can just do it in your code-behind like this:
```
myButton.Click += myHandler;
```
Or you could use an anonymous delegate:
```
myButton.Click += delegate
{
MessageBox.Show("Clicked!");
};
```
|
Setting an Event handler without doing it manually in the classname.designer.cs file
|
[
"",
"c#",
"winforms",
"events",
""
] |
Is there any Java library that supports hierarchical column?
For example (the first three row are columns) :
```
------------------------------------------------
2008 |
------------------------------------------------
January | February |
------------------------------------------------
Week1 | Week2 | Week3 | Week 1 | Week2 | Week3 |
------------------------------------------------
10 | 20 | 14 | 12 | 15 | 3 |
------------------------------------------------
```
|
May be a [JXTree](http://javadesktop.org/swinglabs/build/weekly/latest/swingx-HEAD/javadoc/org/jdesktop/swingx/JXTree.html) from [SwingLab](https://swinglabs.dev.java.net/) could approach what you are looking for.
Illustration [here](http://avatar21.superihost.com/index.php?entry=entry060514-170809), from the [Swingx](https://swingx.dev.java.net/) project
<http://avatar21.superihost.com/images/JXTableJXTreeTable.png>
|
[Infragistics WebGrid for JSF](http://www.infragistics.com/java/netadvantage/jsf/webgridoverview.aspx):
[alt text http://www.infragistics.com/uploadedImages/Products/NetAdvantage\_for\_JSF/Features/WebGrid/Gallery/WebGrid\_Hierarchical.png](http://www.infragistics.com/uploadedImages/Products/NetAdvantage_for_JSF/Features/WebGrid/Gallery/WebGrid_Hierarchical.png)
|
Hierarchical table column in Java
|
[
"",
"java",
"grid",
"hierarchical",
""
] |
I have a N-Ary non sorted in any way tree and each node can have 0-N children. Given the data structure below, how can I fill the tree view assuming you have an array of TermNodes and that array is the first level of the TreeView? I have not been able to come up with a recursive way to do this.
```
class TermNode
{
public string Name;
public string Definition;
public List<TermNode> Children
}
```
|
Thanks All I was getting confused because I did not realize that for a given TreeNode tn, tn.Nodes.Add would return the added TreeNode
Once you know that the solution is straight forward like so
```
private void /*TreeNode*/ RecursiveAdd(OntologyNode on, TreeNode tn)
{
if (on.Children.Count == 0)
{
return;
}
foreach (OntologyNode child in on.Children)
{
TreeNode tCur = tn.Nodes.Add(child.Name);
tCur.Tag = child;//optional for some selected node events
RecursiveAdd(child, tCur);
}
}
```
and to start of the recursive call
```
foreach( OntologyNode on in Nodes )
{
if (on.IsTopLevelNode == true)// internal not pertinent to this code snippet
{
TreeNode tn = tvOntoBrowser.Nodes.Add(on.Name);
tn.Tag = on;
if (on.Children.Count > 0)
{
RecursiveAdd(on, tn);
}
}
}
```
|
Here is a bit of code to get you started with the recursion. It's not tested (I can't right now), but you should get the idea:
```
public static void BuildTreeView(TreeNodeCollection Parent, List<TermNode> TermNodeList)
{
foreach (TermNode n in TermNodeList)
{
TreeNode CurrentNode = Parent.Add(n.Name);
// no need to recurse on empty list
if (n.List.Count > 0) BuildTreeView(CurrentNode.Nodes, n.List);
}
}
// initial call
List<TermNode> AllTermNodes = /* all your nodes at root level */;
BuildTreeView(treeView1.Nodes, AllTermNodes);
```
|
Filling up a TreeView control
|
[
"",
"c#",
"data-structures",
"treeview",
""
] |
What is the concept of erasure in generics in Java?
|
It's basically the way that generics are implemented in Java via compiler trickery. The compiled generic code *actually* just uses `java.lang.Object` wherever you talk about `T` (or some other type parameter) - and there's some metadata to tell the compiler that it really is a generic type.
When you compile some code against a generic type or method, the compiler works out what you really mean (i.e. what the type argument for `T` is) and verifies at *compile* time that you're doing the right thing, but the emitted code again just talks in terms of `java.lang.Object` - the compiler generates extra casts where necessary. At execution time, a `List<String>` and a `List<Date>` are exactly the same; the extra type information has been *erased* by the compiler.
Compare this with, say, C#, where the information is retained at execution time, allowing code to contain expressions such as `typeof(T)` which is the equivalent to `T.class` - except that the latter is invalid. (There are further differences between .NET generics and Java generics, mind you.) Type erasure is the source of many of the "odd" warning/error messages when dealing with Java generics.
Other resources:
* [Oracle documentation](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html)
* [Wikipedia](http://en.wikipedia.org/wiki/Generics_in_Java)
* [Gilad Bracha's Java generics guide](http://www8.cs.umu.se/kurser/tdbb24/HT05/jem/download/generics-tutorial.pdf) (PDF - highly recommended; link may need to change periodically)
* [Angelika Langer's Java Generics FAQ](http://www.angelikalanger.com/GenericsFAQ/FAQSections/Index.html)
|
Just as a side-note, it is an interesting exercise to actually see what the compiler is doing when it performs erasure -- makes the whole concept a little easier to grasp. There is a special flag you can pass the compiler to output java files that have had the generics erased and casts inserted. An example:
```
javac -XD-printflat -d output_dir SomeFile.java
```
The `-printflat` is the flag that gets handed off to the compiler that generates the files. (The `-XD` part is what tells `javac` to hand it to the executable jar that actually does the compiling rather than just `javac`, but I digress...) The `-d output_dir` is necessary because the compiler needs some place to put the new .java files.
This, of course, does more than just erasure; all of the automatic stuff the compiler does gets done here. For example, default constructors are also inserted, the new foreach-style `for` loops are expanded to regular `for` loops, etc. It is nice to see the little things that are happening automagically.
|
What is the concept of erasure in generics in Java?
|
[
"",
"java",
"generics",
""
] |
I have a read query that I execute within a transaction so that I can specify the isolation level. Once the query is complete, what should I do?
* Commit the transaction
* Rollback the transaction
* Do nothing (which will cause the transaction to be rolled back at the end of the using block)
What are the implications of doing each?
```
using (IDbConnection connection = ConnectionFactory.CreateConnection())
{
using (IDbTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadUncommitted))
{
using (IDbCommand command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = "SELECT * FROM SomeTable";
using (IDataReader reader = command.ExecuteReader())
{
// Read the results
}
}
// To commit, or not to commit?
}
}
```
EDIT: The question is not if a transaction should be used or if there are other ways to set the transaction level. The question is if it makes any difference that a transaction that does not modify anything is committed or rolled back. Is there a performance difference? Does it affect other connections? Any other differences?
|
You commit. Period. There's no other sensible alternative. If you started a transaction, you should close it. Committing releases any locks you may have had, and is equally sensible with ReadUncommitted or Serializable isolation levels. Relying on implicit rollback - while perhaps technically equivalent - is just poor form.
If that hasn't convinced you, just imagine the next guy who inserts an update statement in the middle of your code, and has to track down the implicit rollback that occurs and removes his data.
|
If you haven't changed anything, then you can use either a COMMIT or a ROLLBACK. Either one will release any read locks you have acquired and since you haven't made any other changes, they will be equivalent.
|
Should I commit or rollback a read transaction?
|
[
"",
"sql",
"database",
"transactions",
""
] |
I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.
|
Just put this in the first line of your script :
```
#!/usr/bin/env python
```
Make the file executable with
```
chmod +x myfile.py
```
Execute with
```
./myfile.py
```
|
If you want to obtain a stand-alone binary application in Python try to use a tool like py2exe or [PyInstaller](http://www.pyinstaller.org/).
|
What do I use on linux to make a python program executable
|
[
"",
"python",
"linux",
"file-permissions",
""
] |
At what point would you create your own exception class vs. using java.lang.Exception? (All the time? Only if it will be used outside the package? Only if it must contain advanced logic? etc...)
|
I think you need to ask yourself a slighly different question "What advantage does creating a new exception give me or developers who use my code?" Really the only advantage it gives you or other people is the ability to handle the exception. That seems like an obvious answer but really it's not. You should only be handling exceptions that you can reasonably recover from. If the exception you throw is a truly fatal error why give developers a chance to mis-handle it?
More in depth discussion: [Custom exceptions: When should you create them?](http://blogs.msdn.com/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx)
|
Reason one:
Need to catch specific stuff. If calling code needs to deal with a specific exceptional condition, you need to differentiate your Exception, and Java differentiates exceptions with different types, so you need to write your own.
Basically, if someone has to write:
```
catch(ExistingException e) {
if({condition}) {
{ some stuff here}
}
else {
{ different stuff here}
}
}
```
You probably want to write a specific extension; catch Exception matching is clearer than conditionals, IMHO.
Remember: your new Exception **can be** a subclass of RuntimeException
Reason two:
API consolidation. If you write an interface and you have several implementations, it's possible that they will call different APIs with a whole bunch of different non-RuntimeExceptions thrown:
```
interface MyInterface {
void methodA();
}
class MyImplA {
void methodA() throws SQLException { ... }
}
class MyImplB {
void methodA() throws IOException { ... }
}
```
Do you really want MyInterface.methodA to throw SQLException and IOException? Maybe then it makes sense to wrap the possible exceptions in a custom Exception. Which again can be a RuntimeException. Or even RuntimeException itself...
|
java.lang.Exception vs. rolling your own exception
|
[
"",
"java",
"exception",
"class",
"packaging",
""
] |
I have a suspicion that I'm using the `finally` block incorrectly, and that I don't understand the fundamentals of its purpose...
```
function myFunc() {
try {
if (true) {
throw "An error";
}
} catch (e) {
alert (e);
return false;
} finally {
return true;
}
}
```
This function will run the `catch` block, alert "An error", but then return true. Why doesn't it return false?
|
> The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception. [more](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#The_finally_Block)
The `finally` block will always run, try returning `true` after your `try` block
```
function myFunc() {
try {
if (true) {
throw "An error";
}
return true;
} catch (e) {
alert (e);
return false;
} finally {
//do cleanup, etc here
}
}
```
|
Finally blocks execute when you leave the try block. In your code this happens when you return false. That sets the return value to false and attempts to exit the function. But first it has to exit the try block which triggers the finally and overwrites the return value to true.
It is considered by many to be a good programming practice to have a single return statement per function. Consider making a var retval at the beginning of your function and setting it to true or false as appropriate throughout your function and then structuring the code so that it falls correctly through to a single return at the bottom.
|
Javascript error handling with try .. catch .. finally
|
[
"",
"javascript",
"error-handling",
"finally",
""
] |
MS SQL has a convenient workaround for concatenating a column value from multiple rows into one value:
```
SELECT col1
FROM table1
WHERE col2 = 'x'
ORDER by col3
FOR XML path('')
```
and that returns a nice recordset:
```
XML_F52E2B61-18A1-11d1-B105-00805F49916B
----------------------------------------
<col1>Foo</col1><col1>Bar</col1>
```
only the column name in the returned recordset is rather nasty!
The column name seems to include random elements (or a GUID), and hence I am reluctant to use it in my application (different instances or different servers might have another GUID). Unfortunately I cannot use \* to select the value, and due to the restrictions in the existing application I cannot iterate through returned columns, either...
Is there a way to force the column name in the returned recordset to something more sensible?
|
That should do:
```
select(
SELECT col1
FROM table1
WHERE col2 = 'x'
ORDER by col3
FOR XML path('')
) as myName
```
Not pretty but should give the result that you need
|
Try this...
```
select
(
select '@greeting' = 'hello', '@where' = 'there', '@who' = 'world'
for xml path ('salutation'), type
) as 'MyName'
```
Note: If you omit the "type" after the "for xml", you get *(I think)* a string.
|
How to choose returned column name in a SELECT FOR XML query?
|
[
"",
"sql",
"sql-server",
"xml",
"sql-server-2005",
""
] |
## Background
I am working on a legacy small-business automation system (inventory, sales, procurement, etc.) that has a single database hosted by SQL Server 2005 and a bunch of client applications. The main client (used by all users) is an MS Access 2003 application (ADP), and other clients include various VB/VBA applications like Excel add-ins and command-line utilities.
In addition to 60 or so tables (mostly in 3NF), the database contains about 200 views, about 170 UDFs (mostly scalar and table-valued inline ones), and about 50 stored procedures. As you might have guessed, some portion of so-called "business logic" is encapsulated in this mass of T-SQL code (and thus is shared by all clients).
Overall, the system's code (including the T-SQL code) is not very well organized and is very refactoring-resistant, so to speak. In particular, schemata of most of the tables cry for all kinds of refactorings, small (like column renamings) and large (like normalization).
FWIW, I have pretty long and decent application development experience (C/C++, Java, VB, and whatnot), but I am not a DBA. So, if the question will look silly to you, now you know why it is so. :-)
## Question
While thinking about refactoring all this mess (in a peacemeal fashion of course), I've come up with the following idea:
1. For each table, create a "wrapper" view that (a) has all the columns that the table has; and (b) in some cases, has some additional computed columns based on the table's "real" columns.
A typical (albeit simplistic) example of such additional computed column would be sale price of a product derived from the product's regular price and discount.
2. Reorganize all the code (both T-SQL and VB/VBA client code) so that only the "wrapper" views refer to tables directly.
So, for example, even if an application or a stored procedure needed to insert/update/delete records from a table, they'd do that against the corresponding "table wrapper" view, not against the table directly.
So, essentially this is about **isolating all the tables by views from the rest of the system**.
This approach seems to provide a lot of benefits, especially from maintainability viewpoint. For example:
* When a table column is to be renamed, it can be done without rewriting all the affected client code at once.
* It is easier to implement derived attributes (easier than using computed columns).
* You can effectively have aliases for column names.
Obviously, there must be some price for all these benefits, but I am not sure that I am seeing all the catches lurking out there.
Did anybody try this approach in practice? What are the major pitfalls?
One obvious disadvantage is the cost of maintaining "wrapper" views in sync with their corresponding tables (a new column in a table has to be added to a view too; a column deleted from a table has to be deleted from the view too; etc.). But this price seems to be small and fair for making the overall codebase more resilient.
Does anyone know any other, stronger drawbacks?
For example, usage of all those "wrapper" views instead of tables is very likely to have some adverse performance impact, but is this impact going to be substantial enough to worry about it? Also, while using ADODB, it is very easy to get a recordset that is not updateable even when it is based just on a few joined tables; so, are the "wrapper" views going to make things substantially worse? And so on, and so forth...
Any comments (especially shared real experience) would be greatly appreciated.
Thank you!
---
P.S. I stepped on the following old article that discusses the idea of "wrapper" views:
[The Big View Myth](http://www.craigsmullins.com/cnr_0299b.htm)
The article advises to avoid the approach described above. But... I do not really see any good reasons against this idea in the article. Quite the contrary, in its list of good reasons to create a view, almost each item is exactly why it is so tempting to create a "wrapper" view for each and every table (especially in a legacy system, as a part of refactoring process).
The article is really old (1999), so whatever reasons were good then may be no longer good now (and vice versa). It would be really interesting to hear from someone who considered or even tried this idea recently, with the latest versions of SQL Server and MS Access...
|
When designing a database, I prefer the following:
* no direct table access by the code (but is ok from stored procedures and views and functions)
* a base view for each table that includes all columns
* an extended view for each table that includes lookup columns (types, statuses, etc.)
* stored procedures for all updates
* functions for any complex queries
this allows the DBA to work directly with the table (to add columns, clean things up, inject data, etc.) without disturbing the code base, and it insulates the code base from any changes made to the table (temporary or otherwise)
there may be performance penalties for doing things this way, but so far they have not been significant - and the benefits of the layer of insulation have been life-savers several times
|
You won't notice any performance impact for one-table views; SQL Server will use the underlying table when building the execution plans for any code using those views. I recommend you schema-bind those views, to avoid accidentally changing the underlying table without changing the view (think of the poor next guy.)
> When a table column is to be renamed
In my experience, this rarely happens. Adding columns, removing columns, changing indexes and changing data types are the usual alter table scripts that you'll run.
> It is easier to implement derived attributes (easier than using computed columns).
I would dispute that. What's the difference between putting the calculation in a column definition and putting it in a view definition? Also, you'll see a performance hit for moving it into a view instead of a computed column. The only real advantage is that *changing* the calculation is easier in a view than by altering a table (due to indexes and data pages.)
> You can effectively have aliases for column names.
That's the real reason to have views; aliasing tables and columns, and combining multiple tables. Best practice in my past few jobs has been to use views where I needed to denormalise the data (lookups and such, as you've already pointed out.)
As usual, the most truthful response to a DBA question is "it depends" - on your situation, skillset, etc. In your case, refactoring "everything" is going to break all the apps anyways. If you do fix the base tables correctly, the indirection you're trying to get from your views won't be required, and will only double your schema maintenance for any future changes. I'd say skip the wrapper views, fix the tables and stored procs (which provide enough information hiding already), and you'll be fine.
|
SQL Server 2005: Wrapping Tables by Views - Pros and Cons
|
[
"",
"sql",
"sql-server",
"database",
"refactoring",
""
] |
Since there is no `finally` in C++ [you have to use the RAII](http://www.research.att.com/~bs/bs_faq2.html#finally) design pattern instead, if you want your code to be exception safe. One way to do this is by using the destructor of a local class like this:
```
void foo() {
struct Finally {
~Finally() { /* cleanup code */ }
} finalizer();
// ...code that might throw an exception...
}
```
This is a big advantage over the straight forward solution, because you don't have to write the cleanup code 2 times:
```
try {
// ...code that might throw an exception...
// cleanup code (no exception)
} catch (...) {
// cleanup code (exception)
throw;
}
```
A big disadvantage of the local class solution is that you can't directly access local variables in your cleanup code. So it will bloat your code a lot if you need access to them regardless:
```
void foo() {
Task* task;
while (task = nextTask()) {
task->status = running;
struct Finally {
Task* task;
Finally(Task* task) : task(task) {}
~Finally() { task->status = idle; }
} finalizer(task);
// ...code that might throw an exception...
}
}
```
**So my question is:** Is there a solution which combines both advantages? So that you a) don't have to write duplicate code and b) can access local variables in the cleanup code, like `task` in the last example, but without such code bloat.
|
Instead of defining `struct Finally`, you could extract your cleanup code in a function of the class `Task` and use Loki's [ScopeGuard](http://loki-lib.sourceforge.net/index.php?n=Idioms.ScopeGuardPointer).
```
ScopeGuard guard = MakeGuard(&Task::cleanup, task);
```
See also this [DrDobb's article](http://www.ddj.com/cpp/184403758) and this [other article](http://www.zete.org/people/jlehrer/scopeguard.html) for more about ScopeGuards.
|
I don't think there is a cleaner way to achieve what you're trying to do, but I think the main problem with the 'finally approach' in your example is an improper [separation of concerns](http://en.wikipedia.org/wiki/Separation_of_concerns).
E.g. the function foo() is responsible for the Task object's consistency, this is rarely a good idea, the methods of Task themselves should be responsible for setting the status to something sensible.
I do realise sometimes there is a real need for finally, and your code is obviously just a simple example to show a point, but those cases are rare. And a bit more contrived code in rare cases is acceptable to me.
What I'm trying to say is, you should rarely have a need for finally constructs, and for the few cases where you do, I'd say don't waste time on constructing some nicer way. It will only encourage you to use finally more than you really should...
|
Proper replacement for the missing 'finally' in C++
|
[
"",
"c++",
"exception",
"finally",
"c++-faq",
""
] |
I have some function to find a value:
```
struct FindPredicate
{
FindPredicate(const SomeType& t) : _t(t) {
}
bool operator()(SomeType& t) {
return t == _t;
}
private:
const SomeType& _t;
};
bool ContainsValue(std::vector<SomeType>& v, SomeType& valueToFind) {
return find_if(v.begin(), v.end(), FindPredicate(valueToFind)) != v.end();
}
```
Now I would like to write a function that checks if all members of a vector satisfy that predicate:
```
bool AllSatisfy(std::vector<SomeType>& v) {
/* ... */
}
```
One solution is to use the `std::count_if` algorithm.
Does anyone know a solution that involves negating the predicate?
|
The best solution is to use the [STL functional library](http://www.keithschwarz.com/cs106l/fall2007/handouts/200_STL_Functional_Library.pdf). By deriving your predicate from `unary_function<SomeType, bool>` , you'll then be able to use the `not1` function, which does precisely what you need (i.e. negating a unary predicate).
Here is how you could do that :
```
struct FindPredicate : public unary_function<SomeType, bool>
{
FindPredicate(const SomeType& t) : _t(t) {}
bool operator()(const SomeType& t) const {
return t == _t;
}
private:
const SomeType& _t;
};
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
return find_if(v.begin(),
v.end(),
not1(FindPredicate(valueToFind))) == v.end();
}
```
---
If you want to roll your own solution (which is, IMHO, not the best option...), well, you could write another predicate that is the negation of the first one :
```
struct NotFindPredicate
{
NotFindPredicate(const SomeType& t) : _t(t) {
}
bool operator()(SomeType& t) {
return t != _t;
}
private:
const SomeType& _t;
};
bool AllSatisfy(std::vector<SomeType>& v) {
return find_if(v.begin(),
v.end(),
NotFindPredicate(valueToFind)) == v.end();
}
```
Or you could do better and write a template functor negator, like :
```
template <class Functor>
struct Not
{
Not(Functor & f) : func(f) {}
template <typename ArgType>
bool operator()(ArgType & arg) { return ! func(arg); }
private:
Functor & func;
};
```
that you could use as follow :
```
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
FindPredicate f(valueToFind);
return find_if(v.begin(), v.end(), Not<FindPredicate>(f)) == v.end();
}
```
Of course, the latter solution is better because you can reuse the *Not* struct with every functor you want.
|
See the std library functor [not1](http://www.cplusplus.com/reference/misc/functional/not1.html), it returns a functor that is the logical not of whatever the functor you give it would return.
You should be able to do something like:
```
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind) {
return find_if(v.begin(), v.end(), not1(FindPredicate(valueToFind))) != v.end();
}
```
|
How can I negate a functor in C++ (STL)?
|
[
"",
"algorithm",
"stl",
"c++",
""
] |
I ran into an interesting behavior recently. It seems that if I override .equals() to take a parameter other than Object, it doesn't get called. Can anyone explain to me why this is happening? It seems to violate my understanding of polymorphism in OOP, but maybe I'm missing something.
Here's much simpler code that shows what I'm seeing:
```
public class MyClass {
private int x;
public MyClass(int n) { x = n; }
public boolean equals(Object o) { return false; }
public boolean equals(MyClass mc) { return x == mc.x; }
public static void main(String[] args) {
List<MyClass> list = new ArrayList<MyClass>();
list.add(new MyClass(3));
System.out.println("Contains 3? " + list.contains(new MyClass(3)));
}
}
```
When this is run, it prints "`Contains 3? false`". It looks like the equals(Object) function is called, even though there is another that would work. By contrast, if I write equals like this the code works as expected:
```
public boolean equals(Object o) {
if(!(o instanceof MyClass))
return false;
MyClass mc = (MyClass)o;
return x == mc.x;
}
```
Why isn't it figuring out which version of the function to call based on the type of the parameter?
|
You're mixing up "overriding" and "overloading".
Overriding -- adding a replacement definition of an existing method for purposes of polymorphism. The method must have the same signature. The signature consists of the name and argument types. Overridden methods are selected at runtime based on the runtime type of the target object.
Overloading -- adding a method with the same name but a different signature. Overloaded methods are selected at compile time based on the compile time type of the target object.
|
equals(Object) is overriding a super method; you can *not* override a super method without using the exact same signature (Well, there are some exceptions like covariant returntypes and exception).
|
When overriding equals in Java, why does it not work to use a parameter other than Object?
|
[
"",
"java",
"overloading",
""
] |
Recently I was trying to make a calendar application that will display the current year-month-date to the user. The problem is, if the user is gonna keep my application running even for the next day, how do I get notified ?? How shall I change the date displayed ? I don't wanna poll the current date to update it. Is this possible in c#.
Note: I tried out the **SystemEvent.TimeChanged** event, but it works only if the user manually changes the time / date from the control panel.
|
Can you simply work out the number of seconds until midnight, and then sleep for that long?
|
@OddThinking's answer will work (you could set a timer for the interval instead of sleeping). Another way would be to set a timer with a 1 minute interval and simply check if the system date has changed. Since you are only executing some lightweight code once a minute, I doubt the overhead would be noticable.
|
Getting notified when the datetime changes in c#
|
[
"",
"c#",
"events",
"datetime",
"systemevent",
""
] |
When editing really long code blocks (which should definitely be refactored anyway, but that's beyond the scope of this question), I often long for the ability to collapse statement blocks like one can collapse function blocks. That is to say, it would be great if the minus icon appeared on the code outline for everything enclosed in braces. It seems to appear for functions, classes, regions, namespaces, usings, but not for conditional or iterative blocks. It would be fantastic if I could collapse things like ifs, switches, foreaches, that kind of thing!
Googling into that a bit, I discovered that apparently C++ outlining in VS allows this but C# outlining in VS does not. I don't really get why. Even notepad++ will so these collapses if I select the C# formatting, so I don't get why Visual Studio doesn't.
Does anyone know of a VS2008 add-in that will enable this behavior? Or some sort of hidden setting for it?
Edited to add: inserting regions is of course an option and it did already occur to me, but quite frankly, I shouldn't have to wrap things in a region that are already wrapped in braces... if I was going to edit the existing code, I would just refactor it to have better separation of concern anyway. ("wrapping" with new methods instead of regions ;)
|
Starting with Visual Studio 2017, statement collapsing is built-in.
There are several extensions that perform this task for pre-2017 versions of VS, starting with VS 2010 version:
* [C# outline](http://visualstudiogallery.msdn.microsoft.com/4d7e74d7-3d71-4ee5-9ac8-04b76e411ea8)
* [C# outline
2012 (@MSDN)](https://visualstudiogallery.msdn.microsoft.com/bc07ec7e-abfa-425f-bb65-2411a260b926)
* [C# outline
2013 (@MSDN)](https://visualstudiogallery.msdn.microsoft.com/6c3c5dec-1534-4c42-81b1-cfd4615fd0e9)
* [C# outline
2015 (@MSDN)](https://visualstudiogallery.msdn.microsoft.com/9390e08c-d0aa-42f1-b3d2-5134aabf3b9a)
* [Visual Basic and C# Outliner](https://visualstudiogallery.msdn.microsoft.com/699ecb9d-bd8f-4f6b-b290-05c42407b43e)
The last extension supports only VS 2015 and VS 2017, but it's the most powerful one.
It supports syntax coloring inside collapsed blocks, it is more fault-tolerant and optimized.
> If the extension doesn't seem to install after you used a browser to download it, try using the built-in Visual Studio extension manager.
|
I'm not aware of add-ins, but you mentioned regions and I see nothing wrong with doing something like this...
```
foreach (Item i in Items)
{
#region something big happening here
...
#endregion
#region something big happening here too
...
#endregion
#region something big happening here also
...
#endregion
}
```
EDIT: In response to the question's EDIT: You're right, sticking a bunch of regions everywhere isn't ideal and refactoring is probably the way to go. But it seems that you're looking for something magical that will "organize" the code for you, and I don't think that exists.
|
Visual Studio C# statement collapsing
|
[
"",
"c#",
"visual-studio",
""
] |
I have a `vector` that I want to insert into a `set`. This is one of three different calls (the other two are more complex, involving `boost::lambda::if_()`), but solving this simple case will help me solve the others.
```
std::vector<std::string> s_vector;
std::set<std::string> s_set;
std::for_each(s_vector.begin(), s_vector.end(), s_set.insert(boost::lambda::_1));
```
Unfortunately, this fails with a conversion error message (trying to convert `boost::lambda::placeholder1_type` to `std::string`).
So... what's wrong with this?
|
> The error is really nasty, but boils down to the fact that it can't figure out which set::insert to use, since there's three overloads.
You can work around the ambiguity by giving bind a helpful hand, by specifying a pointer to the function you wish to use:
```
typedef std::set<std::string> s_type;
typedef std::pair<s_type::iterator, bool>(s_type::*insert_fp)(const s_type::value_type&);
std::for_each(s_vector.begin(), s_vector.end(), boost::bind(static_cast<insert_fp>(&s_type::insert), &s_set, _1));
```
It's not pretty, but it should work.
|
I would use a for-loop :-D
|
Boost.Lambda: Insert into a different data structure
|
[
"",
"c++",
"boost-lambda",
""
] |
I am trying to make the [Validation plugin](http://docs.jquery.com/Plugins/Validation) work. It works fine for individual fields, but when I try to include the demo code for the error container that contains all of the errors, I have an issue. The problem is that it shows the container with all errors when I am in all fields, but I would like to display the error container only when the user presses the submit button (but still show inline errors beside the control when losing focus).
The problem is the message in the container. When I took off the code as mentioned in the answer below for the container, the container output just displays the number of errors in plain text.
What is the trick to get a list of detailed error messages? What I would like is to display "ERROR" next to the control in error when the user presses the tab button, and to have a summary of everything at the end when he presses submit. Is that possible?
**Code with all input from here:**
```
$().ready(function() {
var container = $('div.containererreurtotal');
// validate signup form on keyup and submit
$("#frmEnregistrer").bind("invalid-form.validate", function(e, validator) {
var err = validator.numberOfInvalids();
if (err) {
container.html("THERE ARE "+ err + " ERRORS IN THE FORM")
container.show();
} else {
container.hide();
}
}).validate({
rules: {
nickname_in: {
required: true,
minLength: 4
},
prenom_in: {
required: true,
minLength: 4
},
nom_in: {
required: true,
minLength: 4
},
password_in: {
required: true,
minLength: 4
},
courriel_in: {
required: true,
email: true
},
userdigit: {
required: true
}
},
messages: {
nickname_in: "ERROR",
prenom_in: "ERROR",
nom_in: "ERROR",
password_in: "ERROR",
courriel_in: "ERROR",
userdigit: "ERROR"
}
,errorPlacement: function(error, element){
container.append(error.clone());
error.insertAfter(element);
}
});
});
```
|
You will find the documentation for the meta option in <http://docs.jquery.com/Plugins/Validation/validate#toptions>
If you want to display the errors beside the inputs **AND** in a separate error container you will need to override the `errorPlacement` callback.
From your example:
```
...
courriel_in: "ERROR",
userdigit: "ERROR"
}
,errorContainer: container
,errorPlacement: function(error, element){
var errorClone = error.clone();
container.append(errorClone);
error.insertAfter(element)
}
// We don't need this options
//,errorLabelContainer: $("ol", container)
//,wrapper: 'li'
//,meta: "validate"
});
...
```
The `error` parameter is a jQuery object containing a `<label>` tag. The `element` parameter is the input that has failed validation.
# Update to comments
With the above code the error container will not clear errors because it contains a cloned copy. It's easy to solve this if jQuery gives a "hide" event, but it doesn't exist. Let's add a hide event!
1. First we need the [AOP plugin](http://plugins.jquery.com/project/AOP)
2. We add an advice for the hide method:
```
jQuery.aop.before({target: jQuery.fn, method: "hide"},
function(){
this.trigger("hide");
});
```
3. We bind the hide event to hide the cloned error:
```
...
,errorPlacement: function(error, element){
var errorClone = error.clone();
container.append(errorClone);
error.insertAfter(element).bind("hide", function(){
errorClone.hide();
});
}
...
```
Give it a try
|
First your container should be using an ID instead of a class.. (I'm going to assume that ID is 'containererreurtotal')
Then Try this..
```
$().ready(function() {
$('div#containererreurtotal').hide();
// validate signup form on keyup and submit
$("#frmEnregistrer").validate({
errorLabelContainer: "#containererreurtotal",
wrapper: "p",
errorClass: "error",
rules: {
nickname_in: { required: true, minLength: 4 },
prenom_in: { required: true, minLength: 4 },
nom_in: { required: true, minLength: 4 },
password_in: { required: true, minLength: 4 },
courriel_in: { required: true, email: true },
userdigit: { required: true }
},
messages: {
nickname_in: { required: "Nickname required!", minLength: "Nickname too short!" },
prenom_in: { required: "Prenom required!", minLength: "Prenom too short!" },
nom_in: { required: "Nom required!", minLength: "Nom too short!" },
password_in: { required: "Password required!", minLength: "Password too short!" },
courriel_in: { required: "Courriel required!", email: "Courriel must be an Email" },
userdigit: { required: "UserDigit required!" }
},
invalidHandler: function(form, validator) {
$("#containererreurtotal").show();
},
unhighlight: function(element, errorClass) {
if (this.numberOfInvalids() == 0) {
$("#containererreurtotal").hide();
}
$(element).removeClass(errorClass);
}
});
});
```
I am assuming here that you want a <p> tag around each of the individual errors. Typically I use a <ul> container for the actual container (instead of the div you used called 'containererreurtotal') and a <li> for each error (this element is specified in the "wrapper" line)
If you specify #containererreurtotal as display: none; in your CSS, then you dont need the first line in the ready function ( $('div#containererreurtotal').hide(); )
|
How to display jQuery Validation error container only on submit
|
[
"",
"javascript",
"jquery",
""
] |
Lists in C# have the `.ToArray()` method. I want the inverse, where an array is transformed into a list. I know how to create a list and loop through it but I would like a one liner to swap it back.
I am using the `String.Split` method in the .NET 2.0 environment, so LINQ, etc. is not available to me.
|
```
string s = ...
new List<string>(s.Split(....));
```
|
In .Net 3.5, the `System.Linq` namespace includes an extension method called `ToList<>()`.
|
string.split returns a string[] I want a List<string> is there a one liner to convert an array to a list?
|
[
"",
"c#",
"arrays",
"generics",
"list",
""
] |
I have two PHP files that I need to link. How can I link the files together using PHP? The effect I want is to have the user click a button, some information is proccessed on the page, and then the result is displayed in a different page, depending on the button the user clicked.Thanks
|
I've interpreted your question differently to the others.
It sounds to me like you want to create a page with two buttons on it and execute one of your two existing PHP files, depending on which button was pressed.
If that's right, then here's a simple skeleton to achieve that. In this example, page\_1.php and page\_2.php are your two existing PHP files.
Note if you're doing a lot of this stuff, you probably want to read up on the MVC (Model-View-Controller) pattern and/or try some of the popular PHP frameworks available. It's beyond the scope of this question, but basically both those things will give you a good foundation for structuring your code so that things stay managable and don't become a mess.
```
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
switch ($_POST['command']) {
case 'show_file_1':
include 'file_1.php';
break;
case 'show_file_2':
include 'file_2.php';
break;
}
exit;
}
?>
<form method="POST">
<button name="command" value="show_file_1">Show file 1</button>
<button name="command" value="show_file_2">Show file 2</button>
</form>
```
Note: I've included only the relevant HTML and PHP to illustrate the point. Obviously you'd add `<html>`, `<head>` and `<body>` tags, and likely shuffle and modularize the PHP a bit, depending on what you're going to add.
UPDATE: I should also add that if either of your existing PHP files contain forms that POST to themselves, you may want to change the `include` to a redirect. That is:
```
include 'file_1.php';
```
would become:
```
header('Location: http://mysite.com/file_1.php');
```
It's hard to know what to recommend without knowing the nature of your existing files.
EDIT: I'm responding to the OP's second post this way because I don't have enough reputation to comment. Which line number do you get the unexpected `;` error? If I had to guess, I would say check that you're using a `:` (colon) and not `;` (semi-colon) at the end of the `case 'show_file_1'` and `case 'show_file_2'` lines.
|
It sounds like you might want an HTML form:
```
<form method="post" action="other_file.php">
<input name="foo" type="..."... /> ...
</form>
```
Then `$_POST["foo"]` will contain the value of that input in other\_file.php.
|
How do I link files in PHP?
|
[
"",
"php",
""
] |
This is a question that was sparked by [Rob Walker](https://stackoverflow.com/users/3631/rob-walker)'s answer [here](https://stackoverflow.com/questions/36455/alignment-restrictions-for-mallocfree#36466).
Suppose I declare a class/struct like so:
```
struct
{
char A;
int B;
char C;
int D;
};
```
Is it safe to assume that these members will be declared in exactly that order in memory, or is this a compiler dependent thing? I'm asking because I had always assumed that the compiler can do whatever it wants with them.
This leads into my next question. If the above example causes memory alignment issues, why can the compiler not just turn that into something like this implicitly:
```
struct
{
char A;
char C;
int B;
int D;
};
```
(I'm primarily asking about C++, but I'd be interested to hear the C answer as well)
### Related topics
* [Why doesn't GCC optimize structs?](https://stackoverflow.com/questions/118068/why-doesnt-gcc-optimize-structs)
|
C99 §6.7.2.1 clause 13 states:
> Within a structure object, the
> non-bit-field members and the units in
> which bit-fields reside have addresses
> that increase in the order in which
> they are declared.
and goes on to say a bit more about padding and addresses. The C89 equivalent section is §6.5.2.1.
C++ is a bit more complicated. In the 1998 and 2003 standards, there is §9.2 clause 12 (clause 15 in C++11):
> Nonstatic data members of a
> (non-union) class declared without an
> intervening access-specifier are
> allocated so that later members have
> higher addresses within a class
> object. The order of allocation of
> nonstatic data members separated by an
> access-specifier is unspecified
> (11.1). Implementation alignment
> requirements might cause two adjacent
> members not to be allocated
> immediately after each other; so might
> requirements for space for managing
> virtual functions (10.3) and virtual
> base classes (10.1).
|
The data members are arranged in the order declared. The compiler is free to intersperse padding to arrange the memory alignment it likes (and you'll find that many compilers have a boatload a alignment specification options---useful if mixing bits compiled by different programs.).
See also [Why doesn't GCC optimize structs?](https://stackoverflow.com/questions/118068/why-doesnt-gcc-optimize-structs).
---
It appears that this answer is somewhat obsolete for C++. You learn something everyday. Thanks aib, Nemanja.
|
Do class/struct members always get created in memory in the order they were declared?
|
[
"",
"c++",
"memory",
"memory-alignment",
""
] |
I've got a question about references between projects in a solution. Most of my previous applications have just had one or two projects in the Solution, but this time I want to divide the application further.
I'm starting a new Solution in Visual Studio 2008 now, and have created several underlying projects to divide the separate parts of my application.
But currently I'm just creating the different projects on a whim, and creating references between them when I need to. Sometimes I end up in a situation where two projects need to reference eachother, but that is not allowed since it would cause a circular dependency.
Are there any rules/tips/patterns I should keep in mind when I create the different projects, and linking them together?
Should I start from the inside, and go out? Having the "core" projects refrence all the outerlying projects, or perhaps go from the outside and in where the independent projects all reference the "core"? Or the third option where I have business in two projects, and they both reference a third project?
|
Indeed you can't have circular references, but to be honest what would be the benefit of splitting the solution into small project if you had interdependencies between all of them?
Usually before I even open Visual Studio I take a piece of paper and split my problem into logical functional areas. You can draw a Utilities assembly at the top and all the GUI's, web services and other end projects at the bottom. The Utilities project is not going to reference any other project, and the ones at the bottom will not be referenced by anything. Then you think what functionality is common for these, e.g. all GUI's can share a common UI project with common user controls and dialogs, and this UI project will reference the "object model" project, etc. The project at the bottom can only reference what is above them.
Often when it appears that you need a circular reference, you can nicely get round it by defining an interface in the lower level assembly, and providing implementation in the upper level.
Without knowing what are you exactly doing I am afraid that's the only advice I can give you.
|
It's a bit old-fashioned, but for help in deciding how to split into projects, you could look up "Coupling" and "Cohesion" in wikipedia.
Also, while we sometimes think of these decisions as "style" rather than "substance", we should remember that assembly boundaries do have meaning, both to the compiler and to the runtime. A couple of examples of that...
1. The C# compiler understands a keyword called "internal". To make the best decisions about factoring into separate projects, you should really understand the power of this.
2. The JIT compiler in the runtime will never inline a function call that crosses an assembly boundary, which has a performance implication. (The reason is to do with Code Access Security).
There are many more examples, so the decision really does make a difference.
|
Rules of thumb for adding references between C# projects?
|
[
"",
"c#",
"visual-studio",
""
] |
I have following situation:
I have loged user, standard authentication with DB table
```
$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName('users');
$authAdapter->setIdentityColumn('user_name');
$authAdapter->setCredentialColumn('password');
```
When user edits his profile, I save it into Db, but I need to update also storage (using standard Zend\_Auth\_Storage\_Session). Is there any easy way how to do it? Many thanks.
|
Your best bet would be to not use Zend\_Auth's storage to hold information that's likely to change - by default it only holds the identity (for good reason). I'd probably make a User class that wrapped all the Auth, ACL (and probably profile) functionality that uses a static get\_current() method to load the user stashed in the session. This bypasses all the consistency issues you run into when stuffing it into the session as well as giving you a single point from which to implement caching if/when you actually need the performance boost.
|
```
$user = Zend_Auth::getInstance()->getIdentity();
$user->newValue = 'new value';
```
Assuming you are updating the session data in the same statement you are updating the database in there is no need to call the db again.
|
Updating Zend_Auth_Storage after edit users profile
|
[
"",
"php",
"zend-framework",
"authentication",
"zend-auth",
""
] |
I'm trying to read the data in a Win32 ListView owned by another process. Unfortunately, my WriteProcessMemory() call fails with the error "This function is not supported on this system." when I specify "NULL" for the base address in my VirtualAlloc() call. If, however, I offset that VirtualAlloc() address by some "magic" value that I got lucky with and picked at random during a moment of frustration, the call works on my system, but fails on other ones. (see the code below)
Can anybody suggest what this magical offset is doing for me? By trial and error, I can find values that work on specific systems, but I can't find a general solution to this problem.
Thanks,
PaulH
```
#define MAGIC_OFFSET (DWORD)0x01020000
LVHITTESTINFO hti = { 0 };
hti.pt = clientPoint;
LPVOID lpBuffer = ::VirtualAlloc( NULL, 1, MEM_RESERVE, PAGE_READWRITE );
::VirtualFree( lpBuffer, 0, MEM_RELEASE );
lpBuffer = ::VirtualAlloc( (LPVOID)((DWORD)lpBuffer + MAGIC_OFFSET), sizeof( hti ), MEM_RESERVER, PAGE_READWRITE );
DWORD dwBuffer = (DWORD)lpBuffer + MAGIC_OFFSET - sizeof( hti );
if( !::WriteProcessMemory( hProcess, (LPVOID)dwBuffer, (LPVOID)&hti, sizeof( hti ), NULL ) )
return 0;
if( ListView_HitTest( hWndListView, (LPVOID)dwBuffer ) < 0 )
return 0;
if( !::ReadProcessMemory( hProcess, (LPVOID)dwBuffer, (LPVOID)&hti, sizeof( hti ), NULL ) )
return 0;
::VirtualFree( lpBuffer, 0, MEM_RELEASE );
```
Clarification (added by Cd-MaN): this is on a Windows Mobile platform, probably non-x86 architecture. So the situation may be different (are there separate address spaces in ARM processors?).
|
Instead of trying to allocate memory in another process, why not use named shared memory instead. This article will take you through the basic setup of [shared memory](http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx), and I did a quick check to make sure these functions are supported by [Windows Mobile 5](http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx).
|
VirtualAlloc allocates memory in **YOUR** address space. It is absolutely not valid to use that address when writing the memory space of another process. You should be using [VirualAllocEx](http://msdn.microsoft.com/en-us/library/aa366907(VS.85).aspx) instead and passing in the hProcess.
You are just getting lucky and scribbling over some random piece of memory when it works.
If specifying NULL to the first parameter of the VirtualAllocEx isn't supported when you are querying another process (no idea if it is or isn't) ... then you could use [VirtualQueryEx](http://msdn.microsoft.com/en-us/library/aa366907(VS.85).aspx) to map out the address space of the other process and find a valid free region to pass to VirtualAlloc.
You will likely have to put this in a retry loop since the state of the other processes address space could change while you are looking for an empty spot.
|
Win32 WriteProcessMemory() magical offset value
|
[
"",
"c++",
"winapi",
"visual-c++",
"virtualalloc",
""
] |
In my application I have a number of panes from m\_wndspliter classes. What I want to do is at run time show and hide one of these panes. Whilst with the following code I can show and hide the view associated with the pane, I can't temporarily remove the pane itself.
```
CWnd * pCurView = m_wndSplitter2.GetPane(2, 0);
if( !pCurView == NULL )
{
if( fShow )
{
pCurView->ShowWindow(SW_SHOW);
RecalcLayout();
}
else
{
pCurView->ShowWindow(SW_HIDE);
RecalcLayout();
}
}
```
Any examples / ideas ?
|
Does this help?
<http://www.codeguru.com/cpp/w-d/splitter/article.php/c1543>
I have used something very similar myself,
|
You need to call CSplitterWnd::DeleteView to do this, which basically means that you have to save your CView elsewhere if you intend to restore it. Usually this is not a problem as all data should be stored in the CDocument rather than CView, but in practice this may not be the case.
The way I have handled this in the past is to have a copy constructor for my CView classes so I could easily store them in temporary variables.
|
MFC: Showing / Hiding Splitter Panes
|
[
"",
"c++",
"windows",
"winapi",
"mfc",
"csplitterwnd",
""
] |
I'm looking for a script or application that tidies up and reformats SQL queries. I've found some good online SQL formatters (see [here](http://www.wangz.net/gsqlparser/sqlpp/sqlformat.htm)) , as well as some downloadable commercial applications. I'm cautious about using an online service as I don't want to risk copies of these queries being stored somewhere they might be compromised, if only in a web server's cache (and it is against my employer's policy).
Does anyone know of any open-source applications, scripts, or downloadable freeware that might help me out with this?
It probably bears mentioning that I'm working on a Windows platform at work, but I am open to suggestions for other operating systems.
Cheers!
**Update**
I have used SQLInform as suggested by Vinko Vrsalovic to excellent effect. Thanks Vinko!
Something that might also be worth watching is [SQLTidy](http://code.google.com/p/sqltidy/), a young project on Google Code which could turn into something great in the long run.
|
Some things to try out (SQLinForm is free until 2009). It's weird how some niches totally lack good open source tools.
<http://www.trialpay.com/checkout/?c=bb7014d&tid=6rGUpGo>
<http://www.sqlinform.com>
<http://www.fileheap.com/software-universal-sql-editor-download-11096.html>
An Emacs macro:
<http://www.emacswiki.org/emacs-en/tsql-indent.el>
|
Something else... this freeware tool works for PL/SQL, so maybe there's a use for that in there.
PL/SQL Tidy (Broken Link)
|
Free Software or Scripts for Formatting SQL Queries
|
[
"",
"sql",
"code-formatting",
""
] |
I'm in javascript, running this in the console
```
d = new Date();
d.setMonth(1);
d.setFullYear(2009);
d.setDate(15);
d.toString();
```
outputs this:
```
"Sun Mar 15 2009 18:05:46 GMT-0400 (EDT)"
```
Why would this be happening? It seems like a browser bug.
|
That's because when you initialize a new Date, it comes with today's date, so today is Oct 30 2008, then you set the month to February, so there is no February 30, so set first the day, then the month, and then the year:
```
d = new Date();
d.setDate(15);
d.setMonth(1);
d.setFullYear(2009);
```
But as [@Jason W](https://stackoverflow.com/questions/251941/the-fifteenth-of-february-isnt-found#251976), says it's better to use the Date constructor:
```
new Date(year, month, date [, hour, minute, second, millisecond ]);
```
|
It's probably best to construct a Date object in one step to avoid the Date object being in an ambiguous or invalid state:
```
d = new Date(2009, 1, 15);
```
|
The fifteenth of February isn't found
|
[
"",
"javascript",
"date",
""
] |
I've got a database with three tables: Books (with book details, PK is CopyID), Keywords (list of keywords, PK is ID) and KeywordsLink which is the many-many link table between Books and Keywords with the fields ID, BookID and KeywordID.
I'm trying to make an advanced search form in my app where you can search on various criteria. At the moment I have it working with Title, Author and Publisher (all from the Book table). It produces SQL like:
```
SELECT * FROM Books WHERE Title Like '%Software%' OR Author LIKE '%Spolsky%';
```
I want to extend this search to also search using tags - basically to add another OR clause to search the tags. I've tried to do this by doing the following
```
SELECT *
FROM Books, Keywords, Keywordslink
WHERE Title LIKE '%Joel%'
OR (Name LIKE '%good%' AND BookID=Books.CopyID AND KeywordID=Keywords.ID)
```
I thought using the brackets might separate the 2nd part into its own kinda clause, so the join was only evaluated in that part - but it doesn't seem to be so. All it gives me is a long list of multiple copies of the one book that satisfies the `Title LIKE '%Joel%'` bit.
Is there a way of doing this using pure SQL, or would I have to use two SQL statements and combine them in my app (removing duplicates in the process).
I'm using MySQL at the moment if that matters, but the app uses ODBC and I'm hoping to make it DB agnostic (might even use SQLite eventually or have it so the user can choose what DB to use).
|
What you've done here is made a cartesian result set by having the tables joined with the commas but not having any join criteria. Switch your statements to use outer join statements and that should allow you to reference the keywords. I don't know your schema, but maybe something like this would work:
```
SELECT
*
FROM
Books
LEFT OUTER JOIN KeywordsLink ON KeywordsLink.BookID = Books.CopyID
LEFT OUTER JOIN Keywords ON Keywords.ID = KeywordsLink.KeywordID
WHERE Books.Title LIKE '%JOEL%'
OR Keywords.Name LIKE '%GOOD%'
```
|
You need to join the 3 tables together, which gives you a tablular resultset. You can then check any columns you like, and make sure you get *distinct* results (i.e. no duplicates).
Like this:
```
select distinct b.*
from books b
left join keywordslink kl on kl.bookid = b.bookid
left join keywords k on kl.keywordid = k.keywordid
where b.title like '%assd%'
or k.keyword like '%asdsad%'
```
You should also try to avoid starting your LIKE values with a percent sign (%), as this means SQL Server can't use an index on that column and has to perform a full (and slow) table scan. This starts to make your query into a "starts with" query.
Maybe consider the full-text search options in SQL Server, also.
|
SELECT with ORs including table joins
|
[
"",
"sql",
""
] |
We are logging any exceptions that happen in our system by writing the Exception.Message to a file. However, they are written in the culture of the client. And Turkish errors don't mean a lot to me.
So how can we log any error messages in English without changing the users culture?
|
This issue can be partially worked around. The Framework exception code loads the error messages from its resources, based on the current thread locale. In the case of some exceptions, this happens at the time the Message property is accessed.
For those exceptions, you can obtain the full US English version of the message by briefly switching the thread locale to en-US while logging it (saving the original user locale beforehand and restoring it immediately afterwards).
Doing this on a separate thread is even better: this ensures there won't be any side effects. For example:
```
try
{
System.IO.StreamReader sr=new System.IO.StreamReader(@"c:\does-not-exist");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString()); //Will display localized message
ExceptionLogger el = new ExceptionLogger(ex);
System.Threading.Thread t = new System.Threading.Thread(el.DoLog);
t.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
t.Start();
}
```
Where the ExceptionLogger class looks something like:
```
class ExceptionLogger
{
Exception _ex;
public ExceptionLogger(Exception ex)
{
_ex = ex;
}
public void DoLog()
{
Console.WriteLine(_ex.ToString()); //Will display en-US message
}
}
```
However, as [Joe](https://stackoverflow.com/users/13087/joe) correctly points out in a comment on an earlier revision of this reply, some messages are already (partially) loaded from the language resources at the time the exception is thrown.
This applies to the 'parameter cannot be null' part of the message generated when an ArgumentNullException("foo") exception is thrown, for example. In those cases, the message will still appear (partially) localized, even when using the above code.
Other than by using impractical hacks, such as running all your non-UI code on a thread with en-US locale to begin with, there doesn't seem to be much you can do about that: the .NET Framework exception code has no facilities for overriding the error message locale.
|
A contentious point perhaps, but instead of setting the culture to `en-US`, you can set it to `Invariant`. In the `Invariant` culture, the error messages are in English.
```
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
```
It has the advantage of not looking biased, especially for non-American English speaking locales. (a.k.a. avoids snide remarks from colleagues)
|
Exception messages in English?
|
[
"",
"c#",
".net",
"exception",
"localization",
""
] |
I have a class library with all my database logic. My DAL/BLL.
I have a few web projects which will use the same database and classes, so I thought it was a good idea to abstract the data layer into its own project.
However, when it comes to adding functionality to classes for certain projects I want to add methods to certain classes.
For example, my data layer has Product and SomeItem objects:
```
// Data Access Layer project
namespace DAL {
public class Product {
//implementation here
}
public class SomeItem {
//implementation here
}
}
```
In one project I want to add an interface that is used by different content items, so I have a class called:
```
// This is in Web Project
namespace DAL {
public partial class Product : ICustomBehaviour {
#region ICustomBehaviour Implementation
TheSharedMethod();
#endregion
}
}
```
**Is it a good idea to write a partial class in a separate project (creating a dependency) using the *same* namespace? If it's a bad idea, how can I get this type of functionality to work?**
It doesn't seem to want to merge them at compile time, so I'm not sure what I'm doing wrong.
|
You can't write a partial class across projects. A partial class is a compile-time-only piece of syntactic sugar - the whole type ends up in a single assembly, i.e. one project.
(Your original DAL file would have to declare the class to be partial as well, by the way.)
|
Using Visual Studio 2015 and later **it is possible** to split partial classes across projects: use [shared projects](https://stackoverflow.com/q/30634753/814206 "What is the difference between a Shared Project and a Class Library in Visual Studio 2015? - Stack Overflow") (see also [this MSDN blog](https://blogs.msdn.microsoft.com/dotnet/2014/04/21/sharing-code-across-platforms/ "Sharing code across platforms | .NET Blog")).
For my situation I required the following:
* A class library that defines some classes used as interface by several client applications.
* The client application.
* A setup application that creates tables in the database.
Due to limitations of the installer this setup has to be self contained. It cannot reference any assemblies beyond the .NET framework. The setup should insert some enum constants into tables, so ideally it should reference the class library.
The setup can import a Shared Project.
* As shared project is similar to copy pasting code, so I want to move as little as possible into the shared project.
The following example demonstrates how partial classes and shared projects allow splitting classes over different projects.
In Class Library, Address.cs:
```
namespace SharedPartialCodeTryout.DataTypes
{
public partial class Address
{
public Address(string name, int number, Direction dir)
{
this.Name = name;
this.Number = number;
this.Dir = dir;
}
public string Name { get; }
public int Number { get; }
public Direction Dir { get; }
}
}
```
Class Library is a normal Visual Studio Class Library. It imports the SharedProject, beyond that its .csproj contains nothing special:
```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<!-- standard Visual Studio stuff removed -->
<OutputType>Library</OutputType>
<!-- standard Visual Studio stuff removed -->
</PropertyGroup>
<!-- standard Visual Studio stuff removed -->
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Address.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="..\SharedProject\SharedProject.projitems" Label="Shared" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
```
`Address.Direction` is implemented in the SharedProject:
```
namespace SharedPartialCodeTryout.DataTypes
{
public partial class Address
{
public enum Direction
{
NORTH,
EAST,
SOUTH,
WEST
}
}
}
```
SharedProject.shproj is:
```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<ProjectGuid>33b08987-4e14-48cb-ac3a-dacbb7814b0f</ProjectGuid>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
<PropertyGroup />
<Import Project="SharedProject.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
</Project>
```
And its .projitems is:
```
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<HasSharedItems>true</HasSharedItems>
<SharedGUID>33b08987-4e14-48cb-ac3a-dacbb7814b0f</SharedGUID>
</PropertyGroup>
<PropertyGroup Label="Configuration">
<Import_RootNamespace>SharedProject</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Address.Direction.cs" />
</ItemGroup>
</Project>
```
The regular client uses `Address` including `Address.Direction`:
```
using SharedPartialCodeTryout.DataTypes;
using System;
namespace SharedPartialCodeTryout.Client
{
class Program
{
static void Main(string[] args)
{
// Create an Address
Address op = new Address("Kasper", 5297879, Address.Direction.NORTH);
// Use it
Console.WriteLine($"Addr: ({op.Name}, {op.Number}, {op.Dir}");
}
}
}
```
The regular client csproj references the Class Library and **not** SharedProject:
```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<!-- Removed standard Visual Studio Exe project stuff -->
<OutputType>Exe</OutputType>
<!-- Removed standard Visual Studio Exe project stuff -->
</PropertyGroup>
<!-- Removed standard Visual Studio Exe project stuff -->
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SharedPartialCodeTryout.DataTypes\SharedPartialCodeTryout.DataTypes.csproj">
<Project>{7383254d-bd80-4552-81f8-a723ce384198}</Project>
<Name>SharedPartialCodeTryout.DataTypes</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
```
The DbSetup uses only the enums:
The DbSetup.csproj does not reference Class Library; it only imports SharedProject:
```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<!-- Removed standard Visual Studio Exe project stuff -->
<OutputType>Exe</OutputType>
<!-- Removed standard Visual Studio Exe project stuff -->
<?PropertyGroup>
<!-- Removed standard Visual Studio Exe project stuff -->
<ItemGroup>
<Reference Include="System" />
<Reference Include="Microsoft.CSharp" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="..\SharedProject\SharedProject.projitems" Label="Shared" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
```
To conclude:
> Can you split a partial class across projects?
Yes, use Visual Studio's Shared Projects.
> Is it a good idea to write a partial class in a separate project (creating a dependency) using the same namespace?
Often not (see the other answers); in some situations and if you know what you are doing it can be handy.
|
Should you use a partial class across projects?
|
[
"",
"c#",
"partial-classes",
""
] |
Is it possible to catch an error when using JSONP with jQuery? I've tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I'm testing. Here is what I've tried (keep in mind that these all work successfully, but I want to handle the case when it fails):
```
jQuery.ajax({
type: "GET",
url: handlerURL,
dataType: "jsonp",
success: function(results){
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
}
});
```
And also:
```
jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
});
```
I've also tried adding the $.ajaxError but that didn't work either:
```
jQuery(document).ajaxError(function(event, request, settings){
alert("Error");
});
```
|
It seems that JSONP requests that don't return a successful result never trigger any event, success or failure, and for better or worse that's apparently by design.
After searching their bug tracker, there's [a patch](http://dev.jquery.com/attachment/ticket/3442/jsonabort.patch) which may be a possible solution using a timeout callback. See [bug report #3442](http://dev.jquery.com/attachment/ticket/3442). If you can't capture the error, you can at least timeout after waiting a reasonable amount of time for success.
|
[Here](https://stackoverflow.com/a/19075640/2314737)'s my extensive answer to a similar question.
Here's the code:
```
jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });
```
|
How do I catch jQuery $.getJSON (or $.ajax with datatype set to 'jsonp') error when using JSONP?
|
[
"",
"javascript",
"jquery",
"jsonp",
""
] |
What on earth is a caret in the context of a CSplitterWnd class? I can't find any documentation relating explicitly to CSplitterWnds...
EDIT: Specifically, what do these functions *actually* do:
```
CWnd * pCurView = m_wndSplitter2.GetPane(2, 0);
pCurView->ShowCaret()
pCurView->HideCaret()
```
EDIT2: Please note, I know what a caret is, I am specifically asking about the functions within the context of the CSlitterWnd Class. I have seen the MSDN documentation and it offers no real explaination.
|
Any CWnd can have a caret, but only CWnd inheritors that CreateCaret first actually display one. @DannySmurf gives you one example - CEditView - of a CView that creates a caret that you can show and hide.
Depending on the specific kind of CView you've got on your pane, ShowCaret is probably irrelevant. It has nothing to do with CSplitterWnd.
|
Specifically;
```
CWnd * pCurView = m_wndSplitter2.GetPane(2, 0);
```
Get a pane, as in a CView derived class, surrounded by your splitter window
```
pCurView->ShowCaret()
```
Show the littler vertical bar at the text editing position in that view. This is the cursor used in any text editing control such as a CEdit
```
pCurView->HideCaret()
```
Hide the caret / vertical cursor.
|
MFC: What on earth is a CSplitterWnd Caret?
|
[
"",
"c++",
"mfc",
"caret",
"cwnd",
""
] |
I need to avoid being vulnerable to SQL injection in my ASP.NET application. How might I accomplish this?
|
Even though your question is very generic, a few rules always apply:
* Use parameterized queries (`SqlCommand` with `SqlParameter`) and put user input into parameters.
* Don't build SQL strings out of unchecked user input.
* Don't assume you can build a sanitizing routine that can check user input for every kind of malformedness. Edge cases are easily forgotten. Checking numeric input may be simple enough to get you on the safe side, but for string input just use parameters.
* Check for second-level vulnerabilites - don't build SQL query strings out of SQL table values if these values consist of user input.
* Use stored procedures to encapsulate database operations.
|
Use parameters! It really is that simple :-)
Create your queries like this (for MS Sql server with C#):
```
SqlCommand getPersons = new SqlCommand("SELECT * FROM Table WHERE Name = @Name", conn);
```
Here @Name is the parameter where you want to avoid sql injection and conn is an SqlConnection object.
Then to add the parameter value you do the following:
```
getPersons.Parameters.AddWithValue("@Name", theName);
```
Here theName is a variable that contains the name you are searching for.
Now it should be impossible to do any sql injections on that query.
Since it is this simple there is no reason not to use parameters.
|
How can I avoid SQL injection attacks in my ASP.NET application?
|
[
"",
".net",
"asp.net",
"sql",
"security",
"sql-injection",
""
] |
In C#, I am using a library that defines an enum. I would like to allow consumers of my code (in a different assembly) to pass in an enum value as a parameter to one of my functions without having to reference the underlying library themselves.
Is there a way for me to expose the library's enumeration to my consumers?
|
You could define your own enum with the values you want to support, expose that to your consumers, and simply convert it to the library's enum before you call into it. Since enums are just numbers behind the scenes, it's easy to convert one enum's values to another's.
|
You can offer an overload that takes an int, describe which values are valid, then perform the cast yourself. Alternatively, you can offer a different enumeration in your library, then convert it before calling into the second library.
|
Exposing an enum from a library class
|
[
"",
"c#",
".net",
"oop",
"enums",
""
] |
I have to call ping from c++ code.I'd like to easily read the output for further utilizations.
I have come up with two solutions:
* use a fork and a pipe, redirect ping output to the pipe and then parse it
* find a library suited for the purpose to use a ping(ip\_addresss) function directly
I'd like the latter but i didn't find anything that was clearly a standard solution.
How would you do it ?
|
I would go with your first option. Linux is built around the concept of having small, specialized apps which do one thing really well, communicating with pipes. Your app shouldn't include a library to implement ping, since there is already a built-in command to do it, and it works very well!
|
From the educational point of view invoking an external binary is very **inadvisable**. Especially for a simple task such as sending an ICMP echo request, you should learn a bit of socket.
|
What is the best method to ping in c++ under linux?
|
[
"",
"c++",
"linux",
""
] |
While working on an existing project I suddenly got the following error when trying to compile the solution:
*error MSB3105: The item "[filename]" was specified more than once in the "Resources" parameter. Duplicate items are not supported by the "Resources" parameter.*
Now, as far as I'm aware, I did not make any change to the project that affects the resources. Also I have checked each and every file within the project, but there is no duplicate reference anywhere to this file.
Now I already found some forum entries regarding this error:
1) Open the .csproj file and remove the duplicate reference. [Tried this, but I cannot find any duplicates in it]
2) In a 'partial class' project, move everything to a single class. [ Could try this, but the project has been split up into partial classes since the start, and I do not want to change this just because of the error ]
So what else could cause this ?
|
Did you try showing all files in the Solution Explorer? You could have a duplicate .rsx file somewhere in there.
|
I found the answer in [.NET forum posting](http://archives.devshed.com/forums/net-206/main-form-and-partial-class-1918921.html) by Roy Green, and Theresa was right after all, though I did not recognize it.
If you have your main form class split up into partial classes, the partial sections end up in the solution explorer as separate items. And if you double click on them they show up in the designer mode as a normal form. But if you (accidentally) drop a control on these forms, Visual Studio creates a new .resx file and a InitializeComponent routine for it. But since this form is actually just part of the Main Form class it leads to the 'duplicate resources' error. And there is no other solution but to remove the InitializeComponent routine and delete the .resx file by hand.
|
What could cause Visual Studio / C# error MSB3105: Duplicate resources
|
[
"",
"c#",
"visual-studio",
""
] |
What regex pattern would need I to pass to `java.lang.String.split()` to split a String into an Array of substrings using all whitespace characters (`' '`, `'\t'`, `'\n'`, etc.) as delimiters?
|
Something in the lines of
```
myString.split("\\s+");
```
This groups all white spaces as a delimiter.
So if I have the string:
```
"Hello[space character][tab character]World"
```
This should yield the strings `"Hello"` and `"World"` and omit the empty space between the `[space]` and the `[tab]`.
As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send *that* to be parsed. What you want, is the literal `"\s"`, which means, you need to pass `"\\s"`. It can get a bit confusing.
The `\\s` is equivalent to `[ \\t\\n\\x0B\\f\\r]`.
|
In most regex dialects there are a set of convenient character summaries you can use for this kind of thing - these are good ones to remember:
`\w` - Matches any word character.
`\W` - Matches any nonword character.
`\s` - Matches any white-space character.
`\S` - Matches anything but white-space characters.
`\d` - Matches any digit.
`\D` - Matches anything except digits.
A search for "Regex Cheatsheets" should reward you with a whole lot of useful summaries.
|
How to split a string with any whitespace chars as delimiters
|
[
"",
"java",
"string",
"whitespace",
"split",
""
] |
I'm trying to build a console application without using the CRT, or any other imports than kernel32.lib in any case. I get my code to compile, but can't wrap the linker around a few problems:
```
unresolved external symbol @__security_check_cookie@4
unresolved external symbol "int __cdecl FreeLibrary(void *)" (?FreeLibrary@@YAHPAX@Z)
unresolved external symbol "void * __cdecl LoadLibraryW(wchar_t *)" (?LoadLibraryW@@YAPAXPA_W@Z)
unresolved external symbol "int (__cdecl*__cdecl GetProcAddress(void *,char *))(void)" (?GetProcAddress@@YAP6AHXZPAXPAD@Z)
unresolved external symbol _wmainCRTStartup
```
FreeLibrary, LoadLibraryW and GetProcAddress I've brought in to program explicitly, not using windows.h:
```
#pragma comment(lib, "kernel32.lib")
typedef int(*FARPROC)();
void* LoadLibraryW( wchar_t* lpLibFileName );
FARPROC GetProcAddress( void* hModule, char* lpProcName );
int FreeLibrary( void* hLibModule );
```
I suppose something is wrong with my prototypes.
However, the bigger problem are `__security_check_cookie` and `_wmainCRTStartup`, which obviously have something to do with the CRT.
So I'm wondering how I'd go about overriding the default `int wmain(int argc, wchar_t* argv[])` for entrypoint, and how to get rid of whatever the security cookie is.
|
\_wmainCRTStartup is the function that calls wmain()
IIRC it should be available in some .o file that you can link with, look in your lib directory.
Maybe this is useful reading too: [Reduce EXE and DLL Size with LIBCTINY.LIB](http://msdn.microsoft.com/en-us/magazine/cc301696.aspx) (and Matt Pietrek rocks :-)
|
Well, answering myself here to sum up, in case someone else finds this page looking for info.
As MSalters advised, the security cookie code can be stolen from the CRT source, but doing that I found that the `/GS-` compiler flag can be used to avoid the security stuff altogether.
As SoapBox said, the API functions need to be `__stdcall`, as well as the entry point does.
I fixed the entry point issue with linker command line flag `/entry:wmain`.
And finally, as Tomek pointed out, the API functions gotta be in extern C!
So:
```
#pragma comment(lib, "kernel32.lib")
typedef int(*FARPROC)();
extern "C" {
void* __stdcall LoadLibraryW( wchar_t* lpLibFileName );
FARPROC __stdcall GetProcAddress( void* hModule, char* lpProcName );
int __stdcall FreeLibrary( void* hLibModule );
typedef int (__stdcall *f_MessageBoxW_t)( unsigned long hWnd, wchar_t* lpText, wchar_t* lpCaption, unsigned long uType);
f_MessageBoxW_t fnMsg;
void* hUser;
};
int __stdcall wmain(int argc, wchar_t* argv[])
{
hUser = LoadLibraryW( L"user32.dll" );
fnMsg = (f_MessageBoxW_t)GetProcAddress( hUser, "MessageBoxW" );
fnMsg( 0, L"foo", L"bar", 0 );
FreeLibrary( hUser );
return 0;
}
```
|
Building console apps without CRT & default headers?
|
[
"",
"c++",
"windows",
"visual-studio-2008",
"visual-c++",
""
] |
So lets say I'm using Python's [ftplib](http://www.python.org/doc/2.5.2/lib/module-ftplib.html) to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.
|
Using retrlines() probably isn't the best idea there, since it just prints to the console and so you'd have to do tricky things to even get at that output. A likely better bet would be to use the nlst() method, which returns exactly what you want: a list of the file names.
|
## This best answer
You may want to use `ftp.nlst()` instead of `ftp.retrlines()`. It will give you exactly what you want.
If you can't, read the following :
## Generators for sysadmin processes
In his now famous review, [Generator Tricks For Systems Programmers An Introduction](http://www.dabeaz.com/generators/Generators.pdf), David M. Beazley gives a lot of receipes to answer to this kind of data problem with wuick and reusable code.
E.G :
```
# empty list that will receive all the log entry
log = []
# we pass a callback function bypass the print_line that would be called by retrlines
# we do that only because we cannot use something better than retrlines
ftp.retrlines('LIST', callback=log.append)
# we use rsplit because it more efficient in our case if we have a big file
files = (line.rsplit(None, 1)[1] for line in log)
# get you file list
files_list = list(files)
```
Why don't we generate immediately the list ?
Well, it's because doing it this way offer you much flexibility : you can apply any intermediate generator to filter files before turning it into `files_list` : it's just like pipe, add a line, you add a process without overheat (since it's generators). And if you get rid off `retrlines`, it still work be it's even better because you don't store the list even one time.
EDIT : well, I read the comment to the other answer and it says that this won't work if there is any space in the name.
Cool, this will illustrate why this method is handy. If you want to change something in the process, you just change a line. Swap :
```
files = (line.rsplit(None, 1)[1] for line in log)
```
and
```
# join split the line, get all the item from the field 8 then join them
files = (' '.join(line.split()[8:]) for line in log)
```
Ok, this may no be obvious here, but for huge batch process scripts, it's nice :-)
|
How do I parse a listing of files to get just the filenames in Python?
|
[
"",
"python",
"parsing",
"scripting",
"ftp",
"ftplib",
""
] |
Here's the scenario. I'm debugging my own app (C/C++) which is using some library developed by another team in the company. An assertion fails when my code generates some edge case. Its a pain because the assertion is not formulated correctly so the library function is working OK but I get all these interruptions where I just have to continue (lots as its in a loop) so I can get to the stuff I'm actually interested in. I have to use the debug version of the library when debugging for other reasons. The other team wont fix this till next release (hey, it works on our machine).
Can I tell the debugger to ignore the breakpoints asserted by this section of code (i.e. can it auto-continue for me).
|
If the code is triggering breakpoints on its own (by \_\_debugbreak or int 3), you cannot use conditional breakpoints, as the breakpoints are not know to Visual Studio at all. However, you may be able to disable any such breakpoints you are not interested in by modifying the code from the debugger. Probably not what you want, because you need to repeat this in each debugging session, however still may be better than nothing. For more information read [How to disable a programmatical breakpoint / assert?](https://stackoverflow.com/questions/115237/how-to-disable-a-programmatical-breakpoint-assert).
|
There's no good way to automatically ignore ASSERT() failures in a debug library. If that's the one you have to use, you're just going to have to convince the other team that this needs fixed now, or if you have the source for this library, you could fix or remove the assertions yourself just to get your work done in the meantime.
|
Can I set Visual Studio 2005 to ignore assertions in a specific region of code while debugging
|
[
"",
"c++",
"c",
"debugging",
"visual-studio-2005",
"assert",
""
] |
We are experiencing some slowdowns on our web-app deployed on a Tomcat 5.5.17 running on a Sun VM 1.5.0\_06-b05 and our hosting company doesn't gives enough data to find the problem.
We are considering installing [lambda probe](http://www.lambdaprobe.org) on the production server but it requires to enable JMX (com.sun.management.jmxremote) in order to obtain memory and CPU statistics.
Does enabling JMX incur a serious performance penalty?
If we enable JMX, are we opening any security flaw? Do I need to setup secure authentication if we are only enabling local access to JMX?
Is anyone using the same (tomcat + lambda probe) without problems on production?
### UPDATE
Looking at the answers it seems that enabling JMX alone doesn't incur significant overhead to the VM. The extra work may come if the monitoring application attached to the VM, be it *JConsole*, *lambda probe* or any other, is polling with excessive dedication.
|
You can cross out security flaws by using secure authentication. Just keeping the JMX service ready does not incur any significant overhead and is generally a good idea. There's a benchmark [here](http://weblogs.java.net/blog/emcmanus/archive/2006/07/how_much_does_i.html) about this.
|
The overhead from JMX is low and you can fix the security by úsing SSL and authentication. Set -Dcom.sun.management.jmxremote.ssl=true and -Dcom.sun.management.jmxremote.authenticate=true
See here for [here](http://java.sun.com/j2se/1.5.0/docs/guide/management/agent.html) for more information about setting up certificates etc.
The overhead becomes a problem when you start to instrument the code. The overhead can be substantial and the instrumentation might affect the behaviour of your application. You will not see what you get, the so called [heisenberg effect](http://en.wikipedia.org/wiki/Uncertainty_principle).
If you want low overhead I would use the tools that come with [JRockit](http://www.oracle.com/technology/products/jrockit/missioncontrol/index.html). They piggyback on the information the JVM collects all the time. The JVM keeps statistics of which methods are the running the most to decide which methods it should optimize. The JVM also keeps track of memory usage/patterns to decide which gc-stategy to select. JRockit exposes that kind data to the JRockit tools without adding the instrumentation overhead you normally would get from a separate [JMVTI](http://java.sun.com/j2se/1.5.0/docs/guide/jvmti/index.html)-agent.
|
Is a good idea to enable jmx (lambda probe) on a production server?
|
[
"",
"java",
"performance",
"security",
"tomcat",
"jmx",
""
] |
I have a incoming stream of bytes (unsigned char) from either a file or network. I need this data placed in a class, and is looking for a NET-way of doing this.
I bet some does this all the time, so I guess there is a better method to do this than using BitConverter.
I realize I supplied too litle information. Let me try with an example class:
```
class data {
void doSmething();
int var1;
float var2;
}
```
Then I want to transfer the data (var1 and var2) contained in this class over f.ex. a network socket and receive the data on the other end
|
As Jon mentioned, it's not clear, what you need. Maybe you are talking about maybe it is [Binary serialization](http://msdn.microsoft.com/en-us/library/72hyey7b(VS.71).aspx) what you are looking for?
|
It's not entirely clear what you mean, but if you're basically looking for a way to buffer the data so you can get at it later, [MemoryStream](http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx) is probably your best bet. Write all your data to it, then set [Position](http://msdn.microsoft.com/en-us/library/system.io.memorystream.position.aspx) to 0 and you can read the data back again.
|
Char array to a class
|
[
"",
".net",
"c++",
"managed",
""
] |
In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following:
```
import os
os.environ["FOO"] = "A_Value"
```
When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process?
I know you typically solve this problem using something like
```
source script_name.sh
```
But this conflicts with other requirements I have.
|
No process can change its parent process (or any other existing process' environment).
You can, however, create a new environment by creating a new interactive shell with the modified environment.
You have to spawn a new copy of the shell that uses the upgraded environment and has access to the existing stdin, stdout and stderr, and does its reinitialization dance.
You need to do something like use subprocess.Popen to run `/bin/bash -i`.
So the original shell runs Python, which runs a new shell. Yes, you have a lot of processes running. No it's not too bad because the original shell and Python aren't really doing anything except waiting for the subshell to finish so they can exit cleanly, also.
|
I would use the bash eval statement, and have the python script output the shell code
child.py:
```
#!/usr/bin/env python
print 'FOO="A_Value"'
```
parent.sh
```
#!/bin/bash
eval `./child.py`
```
|
Is it possible to change the Environment of a parent process in Python?
|
[
"",
"python",
"linux",
"environment",
""
] |
I have a project that has a makefile with broken dependencies. Is there any best known way to generate a list of dependencies for the project that I can use in the makefile, other than examining each source file by hand or with a hand written perl script?
|
[GNU make](https://make.mad-scientist.net/papers/advanced-auto-dependency-generation/#combine)'s documentation provides a good solution.
Absolutely. `g++ -MM <your file>` will generate a GMake compatible list of dependencies. I use something like this:
```
# Add .d to Make's recognized suffixes.
SUFFIXES += .d
#We don't need to clean up when we're making these targets
NODEPS:=clean tags svn
#Find all the C++ files in the src/ directory
SOURCES:=$(shell find src/ -name "*.cpp")
#These are the dependency files, which make will clean up after it creates them
DEPFILES:=$(patsubst %.cpp,%.d,$(SOURCES))
#Don't create dependencies when we're cleaning, for instance
ifeq (0, $(words $(findstring $(MAKECMDGOALS), $(NODEPS))))
#Chances are, these files don't exist. GMake will create them and
#clean up automatically afterwards
-include $(DEPFILES)
endif
#This is the rule for creating the dependency files
src/%.d: src/%.cpp
$(CXX) $(CXXFLAGS) -MM -MT '$(patsubst src/%.cpp,obj/%.o,$<)' $< -MF $@
#This rule does the compilation
obj/%.o: src/%.cpp src/%.d src/%.h
@$(MKDIR) $(dir $@)
$(CXX) $(CXXFLAGS) -o $@ -c $<
```
**Note:** `$(CXX)`/`gcc` command must be [preceded with a hard tab](https://stackoverflow.com/questions/14109724/makefile-missing-separator)
What this will do is automatically generate the dependencies for each file that has changed, and compile them according to whatever rule you have in place. This allows me to just dump new files into the `src/` directory, and have them compiled automatically, dependencies and all.
|
Having now read [this portion in particular](http://make.paulandlesley.org/autodep.html#combine) I think there is a much easier solution out there, as long as you have a reasonably up to date version of gcc/g++. If you just add `-MMD` to your `CFLAGS`, define a variable `OBJS` representing all your object files, and then do:
```
-include $(OBJS:%.o=%.d)
```
then that should get you both an efficient and simple automatic dependency build system.
|
generate dependencies for a makefile for a project in C/C++
|
[
"",
"c++",
"c",
"makefile",
"dependencies",
""
] |
I am working on localization for an app where custom patterns are used to format the date-time.
one example is:
dd-MM HH:mm
I need to get localized versions of this custom format for dates, so that I get the date using numbers, and the time, basically using the local order (dd MM or MM dd) and the local seperator for both date and time.
This is fairly trivial, as long as I am using the default formatting, but as soon as I stray from these, the formatting becomes hardcoded.
Any ideas?
Thanks, Jonas
edit:
I have the cultureInfo objects, the problem is that when I do a DateTime.ToString("ES-es"), I get too much info - I need only month+day, but with the default ToString, I get year+month+day
Edit again:
I see how I can change the ShortDate pattern for each CultureInfo object I use. However, I also need the default ShortDate pattern in some situations, so changing that would, unfortunately, leave me with another, equivalent problem.
Final edit: in case anyone cares. I never did find a solution, so I ended up coding a static function that checks the current CultureInfo, and returns the correctly formatted date, sans year.
|
Look at the DateTimeFormatInfo class (CultureInfo.DateTimeFormat property), in particular the properties DateSeparator, TimeSeparator, ShortDatePattern.
|
Perhaps you could try this:
```
DateTime.Now.ToString(new System.Globalization.CultureInfo(Thread.CurrentThread.CurrentCulture.Name));
```
If i want for example to display the time for a particular culture, i would do this:
```
DateTime.Now.ToString(new System.Globalization.CultureInfo("ES-es"))
```
The cultureinfo acts as the IFormatProvider.
|
Localization of date-time using custom patterns
|
[
"",
"c#",
"datetime",
"localization",
""
] |
I've been a Delphi (D7) developer for many sometime already, I've always been wondering about the .NET + C# stuffs. What I mean are about not the "Delphi for .NET" or "Oxygene" tech/plugin, but clean .NET/C#.
How much different is it from Delphi? And some other questions...
* Is Mono/SharpDevelop (any others that I should know of?) as capable as the Non-Free Visual Studio?
* In terms of deployment, how does it work? The Assembly + Framework + Executable?
* The Framework (3.5 latest?) works something like the JVM for the Java world, correct? Does it take care of the supporting/making use of techs like Multi-Cores or Windows specific optimizations?
* C# has some similarities to Object Pascal, shouldn't be too tough to adapt, right?
Thanks.
|
Re the first point: have you tried the (free) [VIsual Studio Express Edition](http://www.microsoft.com/Express/)? For a lot of things, this is perfectly capable. You just don't get as many helpers / designers, and no plug-in support (for IDE extensions).
Re the second: excluding some [nasty tricks](http://www.yoda.arachsys.com/csharp/faq/#framework.required), you can't create a pure native executable from .NET; it relies *heavily* on the framework being available on the local machine. An assembly is just a package of IL, and can be contained (typically) in either a dll, or bootstrapped into an exe that loads the assemblies entry-point; but in this scenario the exe is just a simple loader plus a regular assembly.
Actually, the CLR is more like the JVM; the "framework" is really just the equiavalent of a BCL. The main MS framework+CLR certainly has some Windows specific optimizations, but other runtimes/frameworks ([compact](http://msdn.microsoft.com/en-us/netframework/aa497273.aspx), [micro](http://msdn.microsoft.com/en-us/embedded/bb278106.aspx), [Silverlight](http://silverlight.net/), [Mono](http://www.mono-project.com/)) will have different optimizations.
Re multi-core - you have full threading support (for doing it yourself) - but the main *automated* multi-core support will (hopefully) be in .NET 4.0 with the "[parallel extensions](http://msdn.microsoft.com/en-us/concurrency/default.aspx)" work.
Re the last point: should be very familiar indeed. Actually, if you want to do some comparisons, "[reflector](http://www.red-gate.com/products/reflector/)" (free) can take a compiled assembly and show you the code in either C# or delphi (or a few others).
[update re questions]
IL = Intermediate Language; .NET doesn't compile to native CPU instructions, but to something in-between that becomes CPU instruction at runtime (compiled "Just In Time" (JIT) on a method-by-method basis). This means that the JIT compiler can optimize the same IL for the local machine. You can do this in advance using [NGen](http://msdn.microsoft.com/en-us/library/6t9t5wcf(VS.80).aspx).
CLR = Common Language Runtime; essentially the VM
BCL = Base Class Library; the set of classes shared my many apps
Re deployment: first, install the .NET framework on the client ;-p
After that - various options. At the simplest level, you can just copy the exe/etc onto the local machine and run. For example, I use "robocopy" to push code to web-servers.
For full local installs of a complex client app, msi is an option (and the full VS IDE will help you with this).
For simple clients, you can use [ClickOnce](http://msdn.microsoft.com/en-us/library/t71a733d(VS.80).aspx) - which packages the app into a signed bundle that provides self-updating etc capabilities and allows you to make statements about what security you need (full trust, etc). Express Edition allows you to author ClickOnce packages. ClickOnce can even be used on locked down clients where the user can't install apps, since the app is isolated and sand-boxed.
Finally, you can run a .NET app off a network share, but there are some security implications: the "Code Access Security" layer won't give a network share "full trust" (although there were some recent changes to this so that mapped (F: etc) shares are trusted). So you'd need to use CASPOL at each client to trust the code. ClickOnce would be easier ;-p
|
As an addition to Marc's answer, these were the minor pleasant surprises during my transition from D6 to C#:
* better OOP, no global variables ("var MainForm: TMainForm" and the like)
* everything is strongly typed (in general, you can have no pointer types)
* with Windows Forms, the "textual .dfm file" (here YourForm.Designer.cs) is actually C# code rather than a resource description in a custom language. (This changed dramatically with WPF and XAML, though.)
* custom value types ("structs") are possible (e.g. you can have a "complex" type that behaves just as an integer or a single, living on the stack)
* operator overloading
And the minor unpleasant surprises:
* no Delphi-like class references ("class of xxx", e.g. "type TControlClass: class of TControl")
* no indexed properties (you can fake that with nested classes, though)
Well, that's all I can think of right now, a few years down the road.
|
Delphi to .NET + C#
|
[
"",
"c#",
".net",
"delphi",
""
] |
std::next\_permutation (and std::prev\_permutation) permute all values in the range `[first, last)` given for a total of n! permutations (assuming that all elements are unique).
is it possible to write a function like this:
```
template<class Iter>
bool next_permutation(Iter first, Iter last, Iter choice_last);
```
That permutes the elements in the range `[first, last)` but only chooses elements in the range `[first, choice_last)`. ie we have maybe 20 elements and want to iterate through all permutations of 10 choices of them, 20 P 10 options vs 20 P 20.
* Iter is a random access iterator for my purposes, but if it can be implemented as a bidirectional iterator, then great!
* The less amount of external memory needed the better, but for my purposes it doesn't matter.
* The chosen elements on each iteration are input to the first elements of the sequence.
*Is such a function possible to implement? Does anyone know of any existing implementations?*
Here is essentially what I am doing to hack around this. Suggestions on how to improve this are also welcome.
* Start with a vector `V` of `N` elements of which I want to visit each permutation of `R` elements chosen from it (`R <= N`).
* Build a vector `I` of length `R` with values `{ 0, 1, 2, ... R - 1 }` to serve as an index to the elements of `V`
* On each iteration, build a vector `C` of length `R` with values `{ V[I[0]], V[I[1]], ... V[I[R - 1]] }`
* Do something with the values in `C`.
* Apply a function to permute the elements of `I` and iterate again if it was able to.
That function looks like this:
```
bool NextPermutationIndices(std::vector<int> &I, int N)
{
const int R = I.size();
for (int i = R - 1; ; --i) {
if (I[i] < N - R + i) {
++I[i];
return true;
}
if (i == 0)
return false;
if (I[i] > I[i-1] + 1) {
++I[i-1];
for (int j = i; j < R; ++j)
I[j] = I[j-1] + 1;
return true;
}
}
}
```
That function is very complicated due to all the possible off-by-one errors, as well everything using it are more complicated than is probably necessary.
---
***EDIT:***
It turns out that it was **significantly** easier than I had even imagined. From [here](http://photon.poly.edu/~hbr/boost/combinations.html), I was able to find exact implementations of many of the exact algorithms I needed (combinations, permutations, etc.).
```
template<class BidirectionalIterator>
bool next_partial_permutation(BidirectionalIterator first,
BidirectionalIterator middle,
BidirectionalIterator last)
{
std::reverse(middle, last);
return std::next_permutation(first, last);
}
```
Plus there is a combination algorithm there that works in a similar way. The implementation of that is much more complication though.
|
To iterate over nPk permutations, I've used the `for_each_permutation()` algorithm presented in [this old CUJ article](http://www.ddj.com/cpp/184401912) before. It uses a nice algorithm from Knuth which rotates the elements in situ, leaving them in the original order at the end. Therefore, it meets your no external memory requirement. It also works for BidirectionalIterators. It doesn't meet your requirement of looking like `next_permutation()`. However, I think this is a win - I don't like stateful APIs.
|
Source code for a Java combination generator is at **<http://www.merriampark.com/comb.htm>**. Strip out the Java idioms, and it's almost exactly what you're looking for, implemented as a generator to keep a lid on your memory usage.
---
This problem is from the mathematical field known as **Combinatorics**, which is part of **Discrete mathematics**. Discrete math is crucial to practitioners of computer science, as it includes nearly all of the math we use daily (like logic, algorithms, counting, relations, graph theory, etc.). I highly recommend [*Discrete and Combinatorial Mathematics: An applied introduction*](https://rads.stackoverflow.com/amzn/click/com/0201726343) or
[*Discrete Mathematics and Its Applications*](https://rads.stackoverflow.com/amzn/click/com/0071244743), if you can afford it.
(Note: this question is related to "[Algorithm for Grouping](https://stackoverflow.com/questions/199677/algorithm-for-grouping)," but not quite a duplicate since this question asks to solve it in the general case.)
|
Is it possible to write a function like next_permutation but that only permutes r values, instead of n?
|
[
"",
"c++",
"algorithm",
""
] |
I am using Borland Builder C++ 2009. I want to add a button to a form that allows the user to open a file in Excel that I specify. I can't think of how to do this. I know how to link with other code and executables -- is there a Microsoft Excel executable that I could use? How could I specify the file then? Any hints on this, or at least a place to look online, would be greatly appreciated.
|
Assuming that the file type is registered with Excel, you could call ShellExecute() on the file, using the "open" verb. This will cause the file to be opened as if double clicked by the user in Explorer and will invoke Excel.
If that isn't the case, and you can assume that Excel is installed, you could instead pass "excel" to ShellExecute() as the application, and the path of the file as the parameter. (Note that I didn't test this, but it worked from the Run dialog, so I think that it should work from ShellExecute() as well).
|
Thanks, Andy. I am using ShellExecute() as you suggested, giving Excel as the application and the path of the file as the parameter. It works to open Excel, however, it cannot seem to find the file. I have tried moving the file around, typing in the entire path, part of the path with no change. Here is the code I use:
```
ShellExecute(NULL, "open" ,"Excel.exe", "C:\\Documents and Settings\\Lab1\\My Documents\\Waypoint Tool.xls", NULL, SW_SHOWNORMAL);
```
So, I need to figure out why it isn't able to find this file.
Thank you for the suggestion to use ShellExecute though. I think I am on the right track!
|
Open a Specified File in Excel from a GUI - Borland C++
|
[
"",
"c++",
"excel",
"c++builder",
""
] |
I want to be replace any occurrence of more than one space with a single space, but take no action in text between quotes.
Is there any way of doing this with a Java regex? If so, can you please attempt it or give me a hint?
|
Here's another approach, that uses a lookahead to determine that all quotation marks after the current position come in matched pairs.
```
text = text.replaceAll(" ++(?=(?:[^\"]*+\"[^\"]*+\")*+[^\"]*+$)", " ");
```
If needed, the lookahead can be adapted to handle escaped quotation marks inside the quoted sections.
|
When trying to match something that can be contained within something else, it can be helpful to construct a regular expression that matches both, like this:
```
("[^"\\]*(?:\\.[^"\\]*)*")|( +)
```
This will match a quoted string or two or more spaces. Because the two expressions are combined, it will match a quoted string OR two or more spaces, but not spaces within quotes. Using this expression, you will need to examine each match to determine if it is a quoted string or two or more spaces and act accordingly:
```
Pattern spaceOrStringRegex = Pattern.compile( "(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")|( +)" );
StringBuffer replacementBuffer = new StringBuffer();
Matcher spaceOrStringMatcher = spaceOrStringRegex.matcher( text );
while ( spaceOrStringMatcher.find() )
{
// if the space group is the match
if ( spaceOrStringMatcher.group( 2 ) != null )
{
// replace with a single space
spaceOrStringMatcher.appendReplacement( replacementBuffer, " " );
}
}
spaceOrStringMatcher.appendTail( replacementBuffer );
```
|
Regex Question - One or more spaces outside of a quote enclosed block of text
|
[
"",
"java",
"regex",
"quotes",
""
] |
A problem I've encountered a few time in my career is in a tiered service architecture a single downstream system can bring down the entire client application if it gets into a state where all its threads are consumed on a deadlock or some sort of infinite loop bug in that system. Under these conditions the server socket on the Java EE server is still accepting and queueing requests from client applications. This causes the client application to use up all its threads waiting for responses from properly established socket connections. Then all users are locked out of the system as their requests are also being queued.
I've thought of a few solutions but I was wondering if the community has some better ones.
1. Isolated thread pools for downstream requests. This becomes a problem because you compound the number of idle threads in you system creating many small pools that need to have enough threads to ensure full throughput. Spawning threads means you need to deal with Transaction and Security contexts yourself. Not really a supported Java EE solution.
2. MDB solution, the preferred asynchronous solution for Java EE, this however seems rather heavy-weight but has the added benefit of letting the app server deal with management the MDB thread pools. (Currently number one on my list)
3. ESB. This is even more heavy-weight and adds more network and processing time. But it allows you to set individual service timeouts. Also has the problem of it will take forever to get implemented in a big corporation so probably not practical for my time-frame.
Do you guys have any better ideas?
|
You are correct in that the MDB case is the normal solution, and it typically supports timeouts as well which will help keep from hanging requests. That being said, it may not really fix the problem but just shift the backup to your JMS queue without responses ever being sent back to the client. Of course if only 1 of several services cause this problem, the others will now still be accessible.
Your proposal (1) is also doable on WebSphere or Weblogic via the commonj WorkManager. It will allow you to create managed threads in these environments and is pretty lightweight.
[WorkManager and TimerManager API](http://e-docs.bea.com/wls/docs92/commonj/commonj.html)
|
We use MDBs where the queue is persisted in a database which has the benefit of messages not being lost if the system goes down.
You may also want to establish an asynchronous contract between the participating parties. What I mean by this is that a client will send you a message and rather than you doing a lot of heavy weight processing and returning a response, you simply send an acknowledgement response and later send an asynchronous message to them with the full results.
You should also establish a protocol for allowing the client to resend a message if they have not received a full response within an established time.
|
Long Transaction Time Solution for Java EE?
|
[
"",
"java",
"web-services",
"multithreading",
"jakarta-ee",
"transactions",
""
] |
I have an application that needs to hit the ActiveDirectory to get user permission/roles on startup of the app, and persist throughout.
I don't want to hit AD on every form to recheck the user's permissions, so I'd like the user's role and possibly other data on the logged-in user to be globally available on any form within the application, so I can properly hide functionality, buttons, etc. where necessary.
Something like:
```
if (UserProperties.Role == Roles.Admin)
{
btnDelete.Visible = false;
}
```
What are the best practices for storing static user data in a windows app? Solutions such as a Singleton, or global variables may work, but I was trying to avoid these.
Is a User object that gets passed around to each form's contructor just as bad?
|
Set [Thread.CurrentPrincipal](http://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal.aspx) with either the [WindowsPrincipal](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsprincipal.aspx), a [GenericPrincipal](http://msdn.microsoft.com/en-us/library/system.security.principal.genericprincipal.aspx) or your custom principal. Then, you can just call [IsInRole](http://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.isinrole.aspx):
```
if (Thread.CurrentPrincipal.IsInRole(Roles.Admin)) {
btnDelete.Visible = false;
}
```
|
Maybe my judgement is clouded by my frequent use of javascript, but I think that if you have something that is **meant** to be global, then using global variables is okay.
Global is bad when you are exposing things globally that shouldn't be. Global is okay if it is semantically correct for the intended use of the data.
|
Storing static user data in a C# windows application
|
[
"",
"c#",
"singleton",
"global-variables",
""
] |
**Problem Statement:**
I would like to create an offline database to lookup prices/info on the n most useful books to sell in the United States (where n is probably 3 million or so).
**Question:**
So, my question is (and I am open to other approaches here as well), I am trying to figure out how to use Amazon AWS to download a list of the n higest salesrank books being sold as well as some information about the book (i.e. title, prices, etc...).
**What I have done so far:**
First, something like this exists already (asellertool.com), however, I thought this would be an interesting project to work on and quite frankly, we aren't serious enough to need to pay the $30/month subscription.
Now, AWS is great (and easy) if you have a few items you want to look up, but I can't seem to figure out how enumerate on sales rank.
Originally, I was hoping to enumerate all of the book items Amazon had by ISBN. But that wasn't available either. Then I thought I could find a list of all ISBN numbers out there, but that was a dead end too. Finally I thought I could create my own list of ISBN numbers, but as I did some back of the envelope calculations, I thought better of it as my solutions would take roughly a year to go through a third of the 10 digit space at 100/second (and it was overkill anyway).
So, I am back on Sales Ranking, which is currently seems like a dead end as well. So, if you have any thoughts, I would appreciate it.
|
Amazon has a data feed service you can use which contains GZipped xml files of all their products based on top level categories. It's updated once a day and totals about 20GB/110GB of compressed/uncompressed data. Since you only need books it's more in the area of 4GB/31GB. The only thing is I'm not sure who's able to use this and what's involved with getting an account. They don't list anything about this on their website as far as I know so you will most likely have to contact someone there to find out more about it. We use this at work for stuff we do with them and it's some of the craziest xml processing I've had to do.
|
Take a look at [AWS Zone](http://www.awszone.com/index.aws), in the `Amazon E-Commerce Service` section.
|
Using Amazon AWS to create an offline database
|
[
"",
"c#",
".net",
"ruby",
"amazon-web-services",
""
] |
Simple yes or no question, and I'm 90% sure that it is no... but I'm not sure.
Can a Base64 string contain tabs?
|
It depends on what you're asking. If you are asking whether or not tabs can be base-64 encoded, then the answer is "yes" since they can be treated the same as any other ASCII character.
However, if you are asking whether or not base-64 output can contain tabs, then the answer is no. The following link is for an article detailing base-64, including which characters are considered valid:
<http://en.wikipedia.org/wiki/Base64>
|
The short answer is no - but Base64 cannot contain carriage returns either.
That is why, if you have multiple lines of Base64, you strip out any carriage returns, line feeds, and anything else that is not in the Base64 alphabet
That includes tabs.
|
Can a Base64 String contain tabs?
|
[
"",
"c#",
".net",
"base64",
""
] |
I've got a Windows Forms application with two ListBox controls on the same form.
They both have their SelectionMode set to 'MultiExtended'.
When I change the selection of one the selection of the other changes.
Now I thought I'd done something stupid with my SelectedIndexChanged handlers so I removed them and re-wrote them from scratch, and got the problem.
So I created a brand new WinForms app and dragged two ListBoxes onto the forms surface.
In the constructor I populated them both with the following.
```
List<Thing> data = new List<Thing>();
for ( int i = 0; i < 50; i++ ) {
Thing temp = new Thing();
temp.Letters = "abc " + i.ToString();
temp.Id = i;
data.Add(temp);
}
listBox1.DataSource = data;
listBox1.DisplayMember = "Letters";
listBox1.ValueMember = "Id";
List<Thing> data2 = new List<Thing>();
for ( int i = 0; i < 50; i++ ) {
Thing temp = new Thing();
temp.Letters = "abc " + i.ToString();
temp.Id = i;
data2.Add(temp);
}
listBox2.DataSource = data2;
listBox2.DisplayMember = "Letters";
listBox2.ValueMember = "Id";
```
And then I built and ran the app.
Started selecting some values to see if the symptoms were present.
And they were!
This is literally all the code I added to the form,I had not added any event handlers, I have tried it with the SelectionMode set to 'One' and 'MultiExtended'.
Can anyone give me a clue as to why this is happening.
Cheers
|
It isn't the *list* that stores the current position - it is the `CurrencyManager`. Any controls (with the same `BindingContext`) with the *same reference* as a `DataSource` will share a `CurrencyManager`. By using different list instances you get different `CurrencyManager` instances, and thus separate position.
You could achieve the same simply by using `.ToList()`, or creating a new `List<T>` with the same contents (as per your original post), or by assigning a new `BindingContext` to one of the controls:
```
control.BindingContext = new BindingContext();
```
|
I believe that your two controls are sharing a CurrencyManager. I'm not sure exactly why.
As a workaround, you could try just populating your listboxes with simple strings. Or you may want to try creating separate instances of the BindingSource component, and bind to those.
|
Changing a ListBox selection changes other ListBox's selection. What's going on?
|
[
"",
"c#",
".net",
"winforms",
"data-binding",
""
] |
We are seeing this error in a Winform application. Can anyone help on why you would see this error, and more importantly how to fix it or avoid it from happening.
```
System.ComponentModel.Win32Exception: Error creating window handle.
at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.OnVisibleChanged(EventArgs e)
at System.Windows.Forms.ButtonBase.OnVisibleChanged(EventArgs e)
```
|
Have you run Process Explorer or the Windows Task Manager to look at the GDI Objects, Handles, Threads and USER objects? If not, select those columns to be viewed (Task Manager choose View->Select Columns... Then run your app and take a look at those columns for that app and see if one of those is growing really large.
It might be that you've got UI components that you *think* are cleaned up but haven't been Disposed.
[Here's a link](http://blogs.msdn.com/jfoscoding/articles/450835.aspx) about this that might be helpful.
Good Luck!
|
The windows handle limit for your application is 10,000 handles. You're getting the error because your program is creating too many handles. You'll need to find the memory leak. As other users have suggested, use a Memory Profiler. I use the .Net Memory Profiler as well. Also, make sure you're calling the dispose method on controls if you're removing them from a form *before* the form closes (otherwise the controls won't dispose). You'll also have to make sure that there are no events registered with the control. I myself have the same issue, and despite what I already know, I still have some memory leaks that continue to elude me..
|
Winforms issue - Error creating window handle
|
[
"",
"c#",
"windows",
"winforms",
"window-handles",
""
] |
How do you modify a propertygrid at runtime in every way? I want to be able to add and remove properties and add "dynamic types", what I mean with that is a type that result in a runtime generated dropdown in the propertygrid using a TypeConverter.
I have actually been able to do both those things (add/remove properties and add dynamic type) but only separately not at the same time.
To implement the support to add and remove properties at runtime I used [this codeproject article](http://www.codeproject.com/KB/tabs/Dynamic_Propertygrid.aspx?msg=1027628) and modified the code a bit to support different types (not just strings).
```
private System.Windows.Forms.PropertyGrid propertyGrid1;
private CustomClass myProperties = new CustomClass();
public Form1()
{
InitializeComponent();
myProperties.Add(new CustomProperty("Name", "Sven", typeof(string), false, true));
myProperties.Add(new CustomProperty("MyBool", "True", typeof(bool), false, true));
myProperties.Add(new CustomProperty("CaptionPosition", "Top", typeof(CaptionPosition), false, true));
myProperties.Add(new CustomProperty("Custom", "", typeof(StatesList), false, true)); //<-- doesn't work
}
/// <summary>
/// CustomClass (Which is binding to property grid)
/// </summary>
public class CustomClass: CollectionBase,ICustomTypeDescriptor
{
/// <summary>
/// Add CustomProperty to Collectionbase List
/// </summary>
/// <param name="Value"></param>
public void Add(CustomProperty Value)
{
base.List.Add(Value);
}
/// <summary>
/// Remove item from List
/// </summary>
/// <param name="Name"></param>
public void Remove(string Name)
{
foreach(CustomProperty prop in base.List)
{
if(prop.Name == Name)
{
base.List.Remove(prop);
return;
}
}
}
```
etc...
```
public enum CaptionPosition
{
Top,
Left
}
```
My complete solution can be downloaded [here](http://helgo.net/salle/misc/PropertyGrid_2005.zip).
It works fine when I add strings, bools or enums, but when I try to add a "dynamic type" like StatesList it doesn't work. Does anyone know why and can help me to solve it?
```
public class StatesList : System.ComponentModel.StringConverter
{
private string[] _States = { "Alabama", "Alaska", "Arizona", "Arkansas" };
public override System.ComponentModel.TypeConverter.StandardValuesCollection
GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(_States);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
}
```
The method of using a TypeConverter works fine when you don't try to add the property at runtime, for example [this code](http://www.megasolutions.net/cSharp/PropertyGrid-dynamic-Dropdown-List-4124.aspx) works without any problem, but I want to be able to do both.
Please take a look at [my project](http://helgo.net/salle/misc/PropertyGrid_2005.zip).
Thanks!
|
What you do, is adding StatesList (a TypeConverter) as a property.
What you should do, is adding a property with StatesList as its TypeConverter.
|
Ah, of course!
```
myProperties.Add(new CustomProperty("Custom", "", typeof(States), false, true));
[TypeConverter(typeof(StatesList))]
public class States
{
}
```
Works like a charm, thank you!
I have updated my project, hope it can be helpful to others, it can be found [here](http://helgo.net/salle/misc/DynamicPropertyGrid_Working.zip).
|
How to modify PropertyGrid at runtime (add/remove property and dynamic types/enums)
|
[
"",
"c#",
".net",
"winforms",
"propertygrid",
""
] |
I am doing 2^1000 and I am getting this:
1.07151e+301
Is there any way to actually turn this into a proper number without the e+301, or at least can anyone show me where I can see how to turn this in to a real number, by some way working with the e+301 part?
|
So, I'm thinking that what you really want is just the ability to print it without scientific notation. If you're using `printf`, what you want is:
```
printf( "%f1000.0", value );
// note that 1000 is way larger than need be,
// I'm just too lazy to count the digits
```
With `cout`, try something like:
```
cout.setf(ios::fixed);
cout << setprecision(0) << value;
```
If you want to print it as a power of two (2^1000 vs 10715...), you're on your own.
|
There is a practical limit to how large a number that can be directly manipulated in machine registers can be. if you are using double precision floats there are a total of 64 bits, some of which are devoted to the mantissa, some to the exponent, and 1 to the sign bit.
2^1000 needs a 1001 bit integer to be represented without losing precision. In order to work with numbers like that you will need to use a library that has big number support, such as [GNU MP](http://gmplib.org/).
|
How do I avoid scientific notation for large numbers?
|
[
"",
"c++",
"math",
""
] |
Consider the following two alternatives:
* `console.log("double");`
* `console.log('single');`
The former uses double quotes around the string, whereas the latter uses single quotes around the string.
I see more and more JavaScript libraries out there using single quotes when handling strings.
Are these two usages interchangeable? If not, is there an advantage in using one over the other?
|
The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.
Using the other type of quote as a literal:
```
alert('Say "Hello"');
alert("Say 'Hello'");
```
This can get complicated:
```
alert("It's \"game\" time.");
alert('It\'s "game" time.');
```
Another option, new in ECMAScript 6, is [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) which use the *backtick* character:
```
alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);
```
Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.
Note that [JSON](https://jsonlint.com/) is formally specified to use double quotes, which may be worth considering depending on system requirements.
|
If you're dealing with JSON, it should be noted that strictly speaking, JSON strings must be double quoted. Sure, many libraries support single quotes as well, but I had great problems in one of my projects before realizing that single quoting a string is in fact not according to JSON standards.
|
Are double and single quotes interchangeable in JavaScript?
|
[
"",
"javascript",
"string",
""
] |
If you create a class library that uses things from other assemblies, is it possible to embed those other assemblies inside the class library as some kind of resource?
I.e. instead of having *MyAssembly.dll*, *SomeAssembly1.dll* and *SomeAssembly2.dll* sitting on the file system, those other two files get bundled in to *MyAssembly.dll* and are usable in its code.
---
I'm also a little confused about why .NET assemblies are *.dll* files. Didn't this format exist before .NET? Are all .NET assemblies DLLs, but not all DLLs are .NET assemblies? Why do they use the same file format and/or file extension?
|
Take a look at **[ILMerge](http://www.microsoft.com/downloads/details.aspx?FamilyID=22914587-b4ad-4eae-87cf-b14ae6a939b0&displaylang=en)** for merging assemblies.
> I'm also a little confused about why .NET assemblies are .dll files. Didn't this format exist before .NET?
Yes.
> Are all .NET assemblies DLLs,
Either DLLs or EXE normally - but can also be netmodule.
> but not all DLLs are .NET assemblies?
Correct.
> Why do they use the same file format and/or file extension?
Why should it be any different - it serves the same purpose!
|
ILMerge does merge assemblies, which is nice, but sometimes not quite what you want. For example, when the assembly in question is a strongly-named assembly, and you don't have the key for it, then you cannot do ILMerge without breaking that signature. Which means you have to deploy multiple assemblies.
As an alternative to ilmerge, you can embed one or more assemblies as resources into your exe or DLL. Then, at runtime, when the assemblies are being loaded, you can extract the embedded assembly programmatically, and load and run it. It sounds tricky but there's just a little bit of boilerplate code.
To do it, embed an assembly, just as you would embed any other resource (image, translation file, data, etc). Then, set up an AssemblyResolver that gets called at runtime. It should be set up in the static constructor of the startup class. The code is very simple.
```
static NameOfStartupClassHere()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(Resolver);
}
static System.Reflection.Assembly Resolver(object sender, ResolveEventArgs args)
{
Assembly a1 = Assembly.GetExecutingAssembly();
Stream s = a1.GetManifestResourceStream(args.Name);
byte[] block = new byte[s.Length];
s.Read(block, 0, block.Length);
Assembly a2 = Assembly.Load(block);
return a2;
}
```
The Name property on the ResolveEventArgs parameter is the name of the assembly to be resolved. This name refers to the resource, not to the filename. If you embed the file named "MyAssembly.dll", and call the embedded resource "Foo", then the name you want here is "Foo". But that would be confusing, so I suggest using the filename of the assembly for the name of the resource. If you have embedded and named your assembly properly, you can just call GetManifestResourceStream() with the assembly name and load the assembly that way. Very simple.
This works with multiple assemblies, just as nicely as with a single embedded assembly.
In a real app you're gonna want better error handling in that routine - like what if there is no stream by the given name? What happens if the Read fails? etc. But that's left for you to do.
In the rest of the application code, you use types from the assembly as normal.
When you build the app, you need to add a reference to the assembly in question, as you would normally. If you use the command-line tools, use the /r option in csc.exe; if you use Visual Studio, you'll need to "Add Reference..." in the popup menu on the project.
At runtime, assembly version-checking and verification works as usual.
The only difference is in distribution. When you deploy or distribute your app, you need not distribute the DLL for the embedded (and referenced) assembly. Just deploy the main assembly; there's no need to distribute the other assemblies because they're embedded into the main DLL or EXE.
|
Embedding assemblies inside another assembly
|
[
"",
"c#",
".net",
"dll",
"assemblies",
""
] |
I want to do something like this :
```
myYear = record.GetValueOrNull<int?>("myYear"),
```
Notice the nullable type as the generic parameter.
Since the `GetValueOrNull` function could return null my first attempt was this:
```
public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : class
{
object columnValue = reader[columnName];
if (!(columnValue is DBNull))
{
return (T)columnValue;
}
return null;
}
```
But the error I'm getting now is:
> The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method
Right! `Nullable<int>` is a `struct`! So I tried changing the class constraint to a `struct` constraint (and as a side effect can't return `null` any more):
```
public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : struct
```
Now the assignment:
```
myYear = record.GetValueOrNull<int?>("myYear");
```
Gives the following error:
> The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method
Is specifying a nullable type as a generic parameter at all possible?
|
Change the return type to `Nullable<T>`, and call the method with the non nullable parameter
```
static void Main(string[] args)
{
int? i = GetValueOrNull<int>(null, string.Empty);
}
public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct
{
object columnValue = reader[columnName];
if (!(columnValue is DBNull))
return (T)columnValue;
return null;
}
```
|
```
public static T GetValueOrDefault<T>(this IDataRecord rdr, int index)
{
object val = rdr[index];
if (!(val is DBNull))
return (T)val;
return default(T);
}
```
Just use it like this:
```
decimal? Quantity = rdr.GetValueOrDefault<decimal?>(1);
string Unit = rdr.GetValueOrDefault<string>(2);
```
|
Nullable type as a generic parameter possible?
|
[
"",
"c#",
"generics",
""
] |
I'm talking about this:
If we have the letter 'A' which is 77 in decimal and 4D in Hex.
I am looking for the fastest way to get D.
I thought about two ways:
Given x is a byte.
1. `x << 4; x >> 4`
2. `x %= 16`
Any other ways? Which one is faster?
|
I always use `x &= 0x0f`
|
Brevity is nice - explanations are better :)
* `x &= 0x0f`
> is, of course, the right answer. It exactly expresses the intent of what you're trying to achieve, and on any sane architecture will always compile down to the minimum number of instructions (i.e. 1). Do use hex rather than decimal whenever you put constants in a bit-wise operator.
* `x <<= 4; x >>= 4`
> will only work if your 'byte' is a proper unsigned type. If it was actually a signed char then the second operation might cause sign extension (i.e. your original bit 3 would then appear in bits 4-7 too).
>
> without optimization this will of course take 2 instructions, but with GCC on OSX, even `-O1` will reduce this to the first answer.
* `x %= 16`
> even without the optimizer enabled your compiler will almost certainly do the right thing here and turn that expensive div/mod operation into the first answer. However it can only do that for powers of two, and this paradigm doesn't make it quite so obvious what you're trying to achieve.
|
What is the fastest way to get the 4 least significant bits in a byte (C++)?
|
[
"",
"c++",
"optimization",
"operators",
"bit-shift",
"modulo",
""
] |
Is there any way to 'hide' the name of a class, whose sole purpose is to provide extension methods, from Intellisense?
I would like to remove the class name from the Intellisense list but need the extension methods of the class to be available to external assemblies via Intellisense in the usual way.
|
Ok, I have the answer to this. Hallgrim's suggestion of marking the class with..
```
[EditorBrowsable(EditorBrowsableState.Never)]
```
..does actually work but only where the **assembly** is being referenced, rather than the project, as would be the case in my own VS solution whilst writing the assembly that provides the class. The extension methods are available as usual.
|
I expected that you could to this with the EditorBrowsable attribute:
```
[EditorBrowsable(EditorBrowsableState.Never)]
static class MyExtensions { }
```
Unfortunately this did not seem to work.
|
How can I prevent a public class that provides extension methods from appearing in Intellisense?
|
[
"",
"c#",
"extension-methods",
"intellisense",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.