Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I'm looking for a .NET Add-in that reads in the contents of the Current Document window, lists the header declaration of all Regions, Subs, Functions, and Module Level Variables, and provides a simple Move Up/Move Down buttons to rearrange their order.
|
I find that the "File Structure Window" provided by the [Resharper](http://www.jetbrains.com/resharper/) add-in provides most of the features you are looking for. However, it is part of a comprehensive refactoring add-in and this may not suit you.
|
I haven't yet used it (as I usually just code in the regions myself, or wait until I'm doing other refactoring on an inherited project), but [Regionerate](http://www.rauchy.net/regionerate/) looks good.
|
Is there a .NET Tool/Add-in available which allows you to easily rearrange the order of Regions, Subs, Functions, and Member Variables in a Class?
|
[
"",
"c#",
"asp.net",
"vb.net",
"visual-studio",
"add-in",
""
] |
What's the difference between \n and \r (I know it has something to do with OS), and what's the best way to echo a line break that will work cross platform?
**EDIT:** In response to Jarod, I'll be using ths to echo a line break in a .txt log file, though I'm sure I'll be using it in the future for things such as echoing HTML makup onto a page.
|
* `\n` is a Linux/Unix line break.
* `\r` is a classic Mac OS (non-OS X) line break. Mac OS X uses the above unix `\n`.
* `\r\n` is a Windows line break.
I usually just use `\n` on our Linux systems and most Windows apps deal with it ok anyway.
|
Use the `PHP_EOL` constant, which is automatically set to the correct line break for the operating system that the PHP script is running on.
Note that this constant is declared since PHP 5.0.2.
```
<?php
echo "Line 1" . PHP_EOL . "Line 2";
?>
```
For backwards compatibility:
```
if (!defined('PHP_EOL')) {
switch (strtoupper(substr(PHP_OS, 0, 3))) {
// Windows
case 'WIN':
define('PHP_EOL', "\r\n");
break;
// Mac
case 'DAR':
define('PHP_EOL', "\r");
break;
// Unix
default:
define('PHP_EOL', "\n");
}
}
```
|
PHP Echo Line Breaks
|
[
"",
"php",
"cross-platform",
"newline",
"eol",
"line-breaks",
""
] |
Suppose I have this Windows wchar\_t string:
```
L"\x4f60\x597d"
```
and
```
L"\x00e4\x00a0\x597d"
```
and would like to convert it (not necessarily programmatically; it will be a one-time thing) to GCC/Linux wchar\_t format, which is UTF-32 AFAIK. How do I do it? (a general explanation would be nice, but example based on this concrete case would be helpful as well)
*Please don't direct me to character conversion sites. I would like to convert from L"\x(something)" form and not "end character" form.*
|
One of the most used libraries to do character conversion is the ICU library <http://icu-project.org/> It is e.g. used by some boost <http://www.boost.org/> libraries.
|
Would converting from UTF-16 (the Visual C++ `wchar_t` form) to UTF-8, then possibly from UTF-8 to UCS-4 (the GCC `wchar_t` form), be an acceptable answer?
If so, then in Windows you could use the `WideCharToMultiByte` function (with `CP_UTF8` for the `CodePage` parameter), for the first part of the conversion. Then you could either paste the resulting UTF-8 strings directly into your program, or convert them further. [Here](http://osdir.com/ml/org.user-groups.slug.coders/2006-12/msg00006.html) is a message showing how one person did it; you can also write your own code or do it manually (the official spec, with a section on exactly how to convert UTF-8 to UCS-4, can be found [here](http://www.cl.cam.ac.uk/~mgk25/ucs/ISO-10646-UTF-8.html)). There may be an easier way, I'm not overly familiar with the conversion stuff in Linux yet.
|
How to convert (not necessarily programmatically) between Windows' wchar_t and GCC/Linux one?
|
[
"",
"c++",
"linux",
"utf",
"wchar-t",
""
] |
I would like to construct a query that displays all the results in a table, but is offset by 5 from the start of the table. As far as I can tell, MySQL's `LIMIT` requires a limit as well as an offset. Is there any way to do this?
|
From the [MySQL Manual on LIMIT](http://dev.mysql.com/doc/refman/5.0/en/select.html#id4651990):
> To retrieve all rows from a certain
> offset up to the end of the result
> set, you can use some large number for
> the second parameter. This statement
> retrieves all rows from the 96th row
> to the last:
```
SELECT * FROM tbl LIMIT 95, 18446744073709551615;
```
|
As you mentioned it LIMIT is required, so you need to use the biggest limit possible, which is 18446744073709551615 (maximum of unsigned BIGINT)
```
SELECT * FROM somewhere LIMIT 18446744073709551610 OFFSET 5
```
|
MySQL offset infinite rows
|
[
"",
"mysql",
"sql",
"sql-limit",
""
] |
I got an HTML with the `<body onload="window.print()">`.
The question I'm trying to ask is:
* Is there any way to remove the strings that the web browsers add to the printed page?
* Such as:
+ Web site from where the page was printed
+ Page count
+ Title of the web page
+ Date of printing
|
Google Docs is now [skirting around](http://docs.google.com/support/bin/answer.py?hl=en&answer=50089) this issue by generating a PDF version of your document.
If you are using Chrome, it will automatically open the PDF in a new tab and pop up the print dialog. Other browsers will prompt you to download the resultant file (which is not necessarily obvious behavior).
While I don't find this to be an elegant solution, one should be able to recreate this fairly easily using most existing web technologies.
|
These a usually browser specific print settings.
In IE & FireFox for example you can go into page setup and change the header and footer details for printing.
I don't think this can be controlled by the web page itself.
|
Remove the default browser header and footer when printing HTML
|
[
"",
"javascript",
"html",
"printing-web-page",
""
] |
I have a Java Applet that uses AWT. In some (rare) circumstances, the platform does not refresh the screen properly. I can move or minimize/maximize the window and see that my applet refreshed properly. I am looking for code that will give me the fullest possible applet screen repaint, simulating the behaviour of a minimize/maximize.
I've tried calling various combinations of paint()/repaint()/invalidate()/update() on the parent containers and recursing on various children. However, no combination (that I've found) cleans up the framework bugs that I am encountering. I am looking for techniques to fully refresh the applet, even if they may cause some slight flickering, as I will be invoking this code only on the problematic platform.
In my tests, moving to Swing did not help resolve my problem.
By the way, this is a simplification of my previous (more complicated) post: [Java Applet, AWT Refresh problem Mac OS X 10.4](https://stackoverflow.com/questions/184491/java-applet-awt-refresh-problem-mac-os-x-104)
Edit: Investigation in threading did not solve this problem. Marking best answer as the good one.
|
This happens all the time if you are not programming carefully in AWT/Swing.
First of all, you should do ALL work on the event thread. This means you can't do any of it in your main statement (or anything it calls directly). I know every Java GUI app ever invented violates this rule, but that's the rule.
For the most part, they used to say you could use a non-awt thread until the window was "Realized" (pack/setVisible), but Sun figured out that didn't always work.
Second, when you get an event on the AWT thread, be sure to return it quickly. Never sleep or execute a long operation.
Third, (and this is an extension of "First", if you get a callback that is NOT already on the AWT worker thread, be sure to put it on the AWT thread before doing anything with the GUI.
Generally, any event generated by an AWT component will be on the correct thread. Events generated by timers, manually created threads, or the one handed to main() are not.
|
The method to use for this kind of problem is repaint, as you've mentioned. It's possible you are seeing an issue with the JVM you are using. I'd recommend using different versions of the Sun JVM and even the MS VM for IE to see if this is a VM related problem - it may actually be unrelated to your code.
I haven't actually tried this before, but a creative way (ie. nasty hack) around this might be to execute javascript from the applet to call a DOM method to do a mock resize of the window or perhaps call focus on the body in an attempt to cause an external re-drawing of the canvas.
|
Force a full Java applet refresh (AWT)
|
[
"",
"java",
"macos",
"applet",
"refresh",
"awt",
""
] |
I'm working on a simple javascript login for a site, and have come up with this:
```
<form id="loginwindow">
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="button" value="Check In" name="Submit" onclick=javascript:validate(text2.value,"username",text1.value,"password") />
</p>
</form>
<script language = "javascript">
function validate(text1,text2,text3,text4)
{
if (text1==text2 && text3==text4)
load('album.html');
else
{
load('failure.html');
}
}
function load(url)
{
location.href=url;
}
</script>
```
...which works except for one thing: hitting enter to submit the form doesn't do anything. I have a feeling it's cause I've used "onclick" but I'm not sure what to use instead. Thoughts?
---
Okay yeah so I'm well aware of how flimsy this is security-wise. It's not for anything particularly top secret, so it's not a huge issue, but if you guys could elaborate on your thoughts with code, I'd love to see your ideas. the code i listed is literally all I'm working with at this point, so I can start from scratch if need be.
|
There are several topics being discussed at once here. Let's try to clarify.
**1. Your Immediate Concern:**
(*Why won't the input button work when ENTER is pressed?*)
Use the **submit** button type.
```
<input type="submit".../>
```
..instead of
```
<input type="button".../>
```
Your problem doesn't really have anything to do with having used an **onclick** attribute. Instead, you're not getting the behavior you want because you've used the **button** input type, which simply doesn't behave the same way that submit buttons do.
In HTML and XHTML, there are default behaviors for certain elements. Input buttons on forms are often of type "submit". In most browsers, "submit" buttons **fire by default** when ENTER is pressed from a focused element **in the same form element**. The "button" input type does not. If you'd like to take advantage of that default behavior, you can change your input type to "submit".
For example:
```
<form action="/post.php" method="post">
<!--
...
-->
<input type="submit" value="go"/>
</form>
```
**2. Security concerns:**
*@Ady* mentioned a security concern. There are a whole bucket of security concerns associated with doing a **login in javascript**. These are probably outside of the **domain of this question**, especially since you've indicated that you aren't particularly worried about it, and the fact that your login method was actually just setting the location.href to a new html page (indicating that you probably don't have any real security mechanism in place).
Instead of drudging that up, here are **links to related topics** on SO, if anyone is interested in those questions directly.
* [**Is there some way I can do a user validation client-side?**](https://stackoverflow.com/questions/32710/is-there-some-way-i-can-validate-a-user-in-client-side)
* [**Encrypting Ajax calls for authentication in jQuery**](https://stackoverflow.com/questions/148068/is-encrypting-ajax-calls-for-authentication-possible-with-jquery)
**3. Other Issues:**
Here's a **quick cleanup** of your code, which just follows some best practices. It doesn't address the security concern that folks have mentioned. Instead, I'm including it simply to **illustrate some healthy habits**. If you have specific questions about why I've written something a certain way, feel free to ask. Also, **browse the stack for related topics** (as your question may have already been discussed here).
The main thing to notice is the **removal of the event attributes** (onclick="", onsubmit="", or onkeypress="") from the HTML. Those belong in javascript, and it's considered a best practice to keep the javascript events out of the markup.
```
<form action="#" method="post" id="loginwindow">
<h3>Login to view!</h3>
<label>User ID: <input type="text" id="userid"></label>
<label>Password: <input type="password" id="pass"></label>
<input type="submit" value="Check In" />
</form>
<script type="text/javascript">
window.onload = function () {
var loginForm = document.getElementById('loginwindow');
if ( loginwindow ) {
loginwindow.onsubmit = function () {
var userid = document.getElementById('userid');
var pass = document.getElementById('pass');
// Make sure javascript found the nodes:
if (!userid || !pass ) {
return false;
}
// Actually check values, however you'd like this to be done:
if (pass.value !== "secret") {
location.href = 'failure.html';
}
location.href = 'album.html';
return false;
};
}
};
</script>
```
|
Put the script directly in your html document. Change the onclick value with the function you want to use. The script in the html will tell the form to submit when the user hits enter or press the submit button.
```
<form id="Form-v2" action="#">
<input type="text" name="search_field" placeholder="Enter a movie" value=""
id="search_field" title="Enter a movie here" class="blink search-field" />
<input type="submit" onclick="" value="GO!" class="search-button" />
</form>
<script>
//submit the form
$( "#Form-v2" ).submit(function( event ) {
event.preventDefault();
});
</script>
```
|
Javascript login form doesn't submit when user hits Enter
|
[
"",
"javascript",
"forms",
"button",
"submit",
"html-input",
""
] |
I have a table that stores all the volunteers, and each volunteer will be assigned to an appropriate venue to work the event. There is a table that stores all the venues.
It stores the volunteer's appropriate venue assignment into the column `venue_id`.
```
table: venues
columns: id, venue_name
table: volunteers_2009
columns: id, lname, fname, etc.., venue_id
```
Here is the function to display the list of volunteers, and the problem I am having is to display their venue assignment. I have never worked much with MySQL joins, because this is the first time I have joined two tables together to grab the appropriate info I need.
So I want it to go to the volunteers\_2009 table, grab the venue\_id, go to the venues table, match up `volunteers_2009.venue_id to venues.id`, to display `venues.venue_name`, so in the list it will display the volunteer's venue assignment.

```
<?php
// -----------------------------------------------------
//it displays appropriate columns based on what table you are viewing
function displayTable($table, $order, $sort) {
$query = "select * from $table ORDER by $order $sort";
$result = mysql_query($query);
// volunteer's venue query
$query_venues = "SELECT volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 JOIN venues ON volunteers_2009.venue_id = venues.id";
$result_venues = mysql_query($query_venues);
if($_POST) { ?>
<table id="box-table-a">
<tr>
<th>Name</th>
<?php if($table == 'maillist') { ?>
<th>Email</th>
<?php } ?>
<?php if($table == 'volunteers_2008' || $table == 'volunteers_2009') { ?>
<th>Comments</th>
<?php } ?>
<?php if($table == 'volunteers_2009') { ?>
<th>Interests</th>
<th>Venue</th>
<?php } ?>
<th>Edit</th>
</tr>
<tr>
<?php
while($row = mysql_fetch_array($result))
{
$i = 0;
while($i <=0)
{
print '<td>'.$row['fname'].' '.$row['lname'].'</td>';
if($table == 'maillist') {
print '<td><a href="mailto:'.strtolower($row['email']).'">'.strtolower($row['email']).'</a></td>';
}
if($table == 'volunteers_2008' || $table == 'volunteers_2009') {
print '<td><small>'.substr($row['comments'], 0, 32).'</small></td>';
}
if($table == 'volunteers_2009') {
print '<td><small>1) '.$row['choice1'].'<br>2) '.$row['choice2'].'<br>3) '.$row['choice3'].'</small></td>'; ?>
<td> <?php
if($row_venues['venue_name'] != '') {
// print venue assigned
print $row_venues['venue_id'].' '.$row_venues['venue_name'].' ';
} else { print 'No Venue Assigned'; } ?>
</td> <?php
} ?>
<td><a href="?mode=upd&id=<?= $row[id] ?>&table=<?= $table ?>">Upd</a> / <a href="?mode=del&id=<?= $row[id] ?>&table=<?= $table ?>" onclick="return confirm('Are you sure you want to delete?')">Del</a></td> <?php
$i++;
}
print '</tr>';
}
print '</table>';
}
}
// -----------------------------------------------------
?>
```
|
General SQL LEFT Outer join syntax.
SELECT volunteers.id, volunteers.lname, volunteers.fname, volunteers.venue\_id, venues.venue\_name
FROM Volunteers\_2009 AS Volunteers LEFT OUTER JOIN Venues ON (Volunteers.venue\_id = Venues.id)
|
select field1, field2, field3 from venues, volunteers\_2009 where volunteers\_2009.venue\_id = venues.id
|
Join query and what do I do with it to display data correctly?
|
[
"",
"php",
"mysql",
""
] |
I have a char in c#:
```
char foo = '2';
```
Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value of the char and not the number 2. The following will work:
```
int bar = Convert.ToInt32(new string(foo, 1));
```
int.parse only works on strings as well.
Is there no native function in C# to go from a char to int without making it a string? I know this is trivial but it just seems odd that there's nothing native to directly make the conversion.
|
Interesting answers but the docs say differently:
> Use the `GetNumericValue` methods to
> convert a `Char` object that represents
> a number to a numeric value type. Use
> `Parse` and `TryParse` to convert a
> character in a string into a `Char`
> object. Use `ToString` to convert a `Char`
> object to a `String` object.
<http://msdn.microsoft.com/en-us/library/system.char.aspx>
|
This will convert it to an `int`:
```
char foo = '2';
int bar = foo - '0';
```
This works because each character is internally represented by a number. The characters `'0'` to `'9'` are represented by consecutive numbers, so finding the difference between the characters `'0'` and `'2'` results in the number 2.
|
Convert char to int in C#
|
[
"",
"c#",
"char",
"int",
""
] |
I noticed some code of a colleague today that initialized class variables in the initialization. However it was causing a warning, he says because of the order they are in. My question is why is it better to do variable initialization where it currently is and not within the curly brackets?
```
DiagramScene::DiagramScene( int slideNo, QRectF screenRect, MainWindow* parent )
: QGraphicsScene( screenRect, parent ),
myParent( parent ),
slideUndoImageCurrentIndex(-1),
nextGroupID(0),
m_undoInProgress(false),
m_deleteItemOnNextUndo(0)
line(0),
path(0)
{
/* Setup default brush for background */
scDetail->bgBrush.setStyle(Qt::SolidPattern);
scDetail->bgBrush.setColor(Qt::white);
setBackgroundBrush(scDetail->bgBrush);
}
```
|
* It is more efficient (in general). All members of a class are initialised in the constructor, whether you explicitly initialise them or not. If you do not specify an initialiser, then the default constructor of the member is run. If you assign a value in the constructor body, then the assignment operator is called again. This does not apply to scalar values, as in your example, since scalar values do not have constructors.
* You can't accidentally assign a value twice in the initialiser list.
* The compiler can check to make sure that the order in which you write the initialisers matches the order in which the members are defined in the class. The C++ standard requires that the members are initialised in the order they are declared, regardless of the order you write the initialisers. Having the compiler check this order ensures that the programmer knows which order the initialisers will be run in (again, this is more important for non-POD members than for scalars).
* Reference types and `const` members must be initialised in the initialiser list, because you can't assign to a reference or to a `const` member.
|
It's better to do the initialization of the members in the initialization list because the members are then only initialized once. This can be a huge difference in performance (and even behavior) if the members are classes themselves. If the members are all non-const, non-reference fundamental data types, then the difference is usually negligible.
**NOTE**: There are times where initialization lists are required for fundamental data types -- specifically if the type is constant or a reference. For these types, the data can only be initialized once and thus it cannot be initialized in the body of the constructor. See [**this article**](http://www.cprogramming.com/tutorial/initialization-lists-c++.html) for more information.
Note that the initialization order of the members is the order the members are declared in the class definition, not the order the members are declared in the initialization list. If the warning can be fixed by changing the order of the initialization list, then I highly recommend that you do so.
It's my recommendation that:
* You learn to like initialization lists.
* Your co-worker understand the rules for initialization order of members (and avoid warnings).
|
C++ class initialisation containing class variable initialization
|
[
"",
"c++",
"class",
"coding-style",
""
] |
Using PHP, what's the fastest way to convert a string like this: `"123"` to an integer?
Why is that particular method the fastest? What happens if it gets unexpected input, such as `"hello"` or an array?
|
I've just set up a quick benchmarking exercise:
```
Function time to run 1 million iterations
--------------------------------------------
(int) "123": 0.55029
intval("123"): 1.0115 (183%)
(int) "0": 0.42461
intval("0"): 0.95683 (225%)
(int) int: 0.1502
intval(int): 0.65716 (438%)
(int) array("a", "b"): 0.91264
intval(array("a", "b")): 1.47681 (162%)
(int) "hello": 0.42208
intval("hello"): 0.93678 (222%)
```
On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.
I'd be interested to know *why* though.
---
Update: I've run the tests again, this time with coercion `(0 + $var)`
```
| INPUT ($x) | (int) $x |intval($x) | 0 + $x |
|-----------------|------------|-----------|-----------|
| "123" | 0.51541 | 0.96924 | 0.33828 |
| "0" | 0.42723 | 0.97418 | 0.31353 |
| 123 | 0.15011 | 0.61690 | 0.15452 |
| array("a", "b") | 0.8893 | 1.45109 | err! |
| "hello" | 0.42618 | 0.88803 | 0.1691 |
|-----------------|------------|-----------|-----------|
```
**Addendum:** I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:
```
$x = "11";
(int) $x; // int(11)
intval($x); // int(11)
$x + 0; // int(11)
$x = "0x11";
(int) $x; // int(0)
intval($x); // int(0)
$x + 0; // int(17) !
$x = "011";
(int) $x; // int(11)
intval($x); // int(11)
$x + 0; // int(11) (not 9)
```
Tested using PHP 5.3.1
|
I personally feel casting is the prettiest.
```
$iSomeVar = (int) $sSomeOtherVar;
```
Should a string like 'Hello' be sent, it will be cast to integer 0. For a string such as '22 years old', it will be cast to integer 22. Anything it can't parse to a number becomes 0.
If you really do NEED the speed, I guess the other suggestions here are correct in assuming that coercion is the fastest.
|
Fastest way to convert string to integer in PHP
|
[
"",
"php",
"optimization",
"casting",
""
] |
I am a complete JSP beginner. I am trying to use a `java.util.List` in a JSP page. What do I need to do to use classes other than ones in `java.lang`?
|
Use the following import statement to import `java.util.List`:
```
<%@ page import="java.util.List" %>
```
BTW, to import more than one class, use the following format:
```
<%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %>
```
|
FYI - if you are importing a List into a JSP, chances are pretty good that you are violating MVC principles. Take a few hours *now* to read up on the [MVC approach](https://en.wikipedia.org/wiki/Model-view-controller) to web app development (including use of taglibs) - do some more googling on the subject, it's fascinating and will definitely help you write better apps.
If you are doing anything more complicated than a single JSP displaying some database results, please consider using a framework like [Spring](https://docs.spring.io/spring/docs/2.0.x/reference/mvc.html), [Grails](http://grails.asia/grails-tutorial-for-beginners-model-view-controller-mvc-pattern/), etc... It will absolutely take you a bit more effort to get going, but it will save you so much time and effort down the road that I really recommend it. Besides, it's cool stuff :-)
|
How do you import classes in JSP?
|
[
"",
"java",
"jsp",
""
] |
Using Python I want to be able to draw text at different angles using PIL.
For example, imagine you were drawing the number around the face of a clock. The number **3** would appear as expected whereas **12** would we drawn rotated counter-clockwise 90 degrees.
Therefore, I need to be able to draw many different strings at many different angles.
|
Draw text into a temporary blank image, rotate that, then paste that onto the original image. You could wrap up the steps in a function. Good luck figuring out the exact coordinates to use - my cold-fogged brain isn't up to it right now.
This demo writes yellow text on a slant over an image:
```
# Demo to add rotated text to an image using PIL
import Image
import ImageFont, ImageDraw, ImageOps
im=Image.open("stormy100.jpg")
f = ImageFont.load_default()
txt=Image.new('L', (500,50))
d = ImageDraw.Draw(txt)
d.text( (0, 0), "Someplace Near Boulder", font=f, fill=255)
w=txt.rotate(17.5, expand=1)
im.paste( ImageOps.colorize(w, (0,0,0), (255,255,84)), (242,60), w)
```
|
It's also usefull to know our text's size in pixels before we create an Image object. I used such code when drawing graphs. Then I got no problems e.g. with alignment of data labels (the image is exactly as big as the text).
```
(...)
img_main = Image.new("RGB", (200, 200))
font = ImageFont.load_default()
# Text to be rotated...
rotate_text = u'This text should be rotated.'
# Image for text to be rotated
img_txt = Image.new('L', font.getsize(rotate_text))
draw_txt = ImageDraw.Draw(img_txt)
draw_txt.text((0,0), rotate_text, font=font, fill=255)
t = img_value_axis.rotate(90, expand=1)
```
The rest of joining the two images together is already described on this page.
When you rotate by an "unregular" angle, you have to improve this code a little bit. It actually works for 90, 180, 270...
|
How do I draw text at an angle using python's PIL?
|
[
"",
"python",
"python-imaging-library",
"imaging",
""
] |
I'm pretty new to the idea of recursion and this is actually my first attempt at writing a recursive method.
I tried to implement a recursive function Max that passes an array, along with a variable that holds the array's size in order to print the largest element.
It works, but it just doesn't *feel* right!
I have also noticed that I seem to use the static modifier much more than my classmates in general...
Can anybody please provide any general tips as well as feedback as to how I can improve my code?
```
public class RecursiveTry{
static int[] n = new int[] {1,2,4,3,3,32,100};
static int current = 0;
static int maxValue = 0;
static int SIZE = n.length;
public static void main(String[] args){
System.out.println(Max(n, SIZE));
}
public static int Max(int[] n, int SIZE) {
if(current <= SIZE - 1){
if (maxValue <= n[current]) {
maxValue = n[current];
current++;
Max(n, SIZE);
}
else {
current++;
Max(n, SIZE);
}
}
return maxValue;
}
```
}
|
Your use of static variables for holding state outside the function will be a source of difficulty.
An example of a recursive implementation of a max() function in pseudocode might be:
```
function Max(data, size) {
assert(size > 0)
if (size == 1) {
return data[0]
}
maxtail = Max(data[1..size], size-1)
if (data[0] > maxtail) {
return data[0]
} else {
return maxtail
}
}
```
The key here is the recursive call to Max(), where you pass everything *except* the first element, and one less than the size. The general idea is this function says "the maximum value in this data is either the first element, or the maximum of the values in the rest of the array, whichever is larger".
This implementation requires no static data outside the function definition.
One of the hallmarks of recursive implementations is a so-called "termination condition" which prevents the recursion from going on forever (or, until you get a stack overflow). In the above case, the test for `size == 1` is the termination condition.
|
Making your function dependent on static variables is not a good idea. Here is possible implementation of recursive Max function:
```
int Max(int[] array, int currentPos, int maxValue) {
// Ouch!
if (currentPos < 0) {
raise some error
}
// We reached the end of the array, return latest maxValue
if (currentPos >= array.length) {
return maxValue;
}
// Is current value greater then latest maxValue ?
int currentValue = array[currentPos];
if (currentValue > maxValue) {
// currentValue is a new maxValue
return Max(array, currentPos + 1, currentValue);
} else {
// maxValue is still a max value
return Max(array, currentPos + 1, maxValue);
}
}
...
int[] array = new int[] {...};
int currentPos = 0;
int maxValue = array[currentPos] or minimum int value;
maxValue = Max(array, currentPos, maxValue);
```
|
Refactor this recursive method?
|
[
"",
"java",
"recursion",
""
] |
I'm looking for a way to get the name of the main HTML form so I can submit it from JavaScript.
The reason I can just set the name of the form is because the JavaScript is on a User Control that could get added to many different sites with different form names.
Thanks.
|
I'm not totally sure that this will address what you're asking for, so please comment on it:
In your script, when the User Control renders, you could have this placed in there. So long as script doesn't have a "runat" attribute, you should be good.
```
<script type="text/javascript">
var formname = '<%=this.Page.Form.Name %>';
</script>
```
|
I'm not sure , try "YourUserControl.Page.Form"
But why do you need the form name, are you going to have more than one form on your .aspx page , if not, you can get the whole post back JS code for the control that will do the post back (submit) using "Page.ClientScript.GetPostBackEventReference()" and use it to set the "OnClick" attribute of whatever you will use to submit the page.
|
Get the ASP.NET form name
|
[
"",
"asp.net",
"javascript",
"forms",
""
] |
We have a file that has a 64 bit integer as a string in it. How do we scanf() or otherwise parse this numeric string into an unsigned 64 bit integer type in C++ ?
We are aware of things like %lld etc., but a lot of ways to do this parse seem to break compiles under different compilers and stdlibs. The code should compile under gcc and the Microsoft C++ compiler (of course full compliance with standards would be a plus)
|
GCC has long long, as will compilers for C++0x. MSVC++ doesn't (yet), but does have its \_\_int64 you can use.
```
#if (__cplusplus > 199711L) || defined(__GNUG__)
typedef unsigned long long uint_64_t;
#elif defined(_MSC_VER) || defined(__BORLANDC__)
typedef unsigned __int64 uint_64_t;
#else
#error "Please define uint_64_t"
#endif
uint_64_t foo;
std::fstream fstm( "file.txt" );
fstm >> foo;
```
|
Alnitak recommends `strtoull()`, but it seems it's not [available in Win32](http://social.msdn.microsoft.com/forums/en-US/vclanguage/thread/d69a6afe-6558-4913-afb0-616f00805229/) environments. The linked-to forum thread recommends either of `_strtoui64()`, `_wcstoui64()` and `_tcstoui64()` as replacements. Perhaps this is "on the edge" of stuff that can't really be done with a single portable function call, and you might need to implement different code paths for different platforms. Or, I guess, write your own ASCII-to-64-bit converter, it's not rocket science.
|
Read 64 bit integer string from file
|
[
"",
"c++",
"parsing",
"64-bit",
"integer",
""
] |
At work we do almost everything in Java and perl, but I wanted to build out a feature using PHP and sessions. Some peeps thought that it was a bad idea to try to do PHP sessions on our system, cause it's distributed to many servers. What would the specific problem be?
|
The answer to your specific question, what would the problem be, lies in the fact that by default PHP stores its sessions in files on the filesystem. For a single webserver serving requests, this is not a problem because your session data will always be available. But what if you had two load-balanced webservers serving requests?
Imagine hitting the first webserver with a request, which creates your session file on its file system. Then, your next request hits the second webserver. The second webserver will of course not see the session file. To the user, you might log in to a website, and then suddenly be logged out.
This is not a problem specific to PHP, and is very common. The solution is to store session data in some common area. The most common method for this is to store session data either in a database accessible to all web servers, or some shared memory cache server like memcached.
|
You could also use a custom session save handler:
<http://www.php.net/manual/en/function.session-set-save-handler.php>
I haven't ever tried it, but with it you define your own save/read functions, so you can implement a database or a shared nfs backend without the need to install any extensions.
Also Msession, which was suggested by @Eran Galperin, looks very interesting as an alternative to the one I mentioned before.
|
Are PHP sessions hard to scale across a distributed system?
|
[
"",
"php",
"session",
"distributed-system",
""
] |
Please forgive my long question. I have an idea for a design that I could use some comments on. Is it a good idea to do this? And what are the pit falls I should be aware of? Are there other similar implementations that are better?
**My situation is as follows:**
I am working on a rewrite of a windows forms application that connects to a SQL 2008 (earlier it was SQL 2005) server. The application is an "expert-system" for an engineering company where we store structured data about constructions. We have control of all installations of the client software, we have no external customers or users, they are all internal to the company, and they are all be trusted not to do anything malicious to the software or database.
The current design doesn't have too many tables (about 10 - 20) but some of them have millions of records that belong to several hundred constructions. The systems performance has been ok so far, but it is starting to degrade as we are pushing the limits of the design.
As part of the rewrite I am considering splitting the database into one master database and several "child" databases where each describes one construction. Each child database should be of identical design. This should eliminate the performance problems we are seeing today since the data stored in each database would be less than one percent of the total data amount.
My concern is that instead of maintaining one database we will now get hundreds of databases that must be kept up to date. The system is constantly evolving as the companys requirements change (you know how it is), and while we try to look forward to reduce the number of changes the changes will come. So we will need a system where we keep track of all database changes done to the system so they can be applied to the child databases. Updating the client application won't be a problem, we have good control of that aspect.
I am thinking of a change tracing system where we store database scripts for all changes in a table in the master database. We can then give each change a version number and we can store a current version number in each child database. When the client program connects to a child database we can then check the version number of the database against the current version number of the master database and if there are patches with version numbers greater than the version number of the child database we run these and update the child database to the latest version.
As I see it this should work well. Any changes to the system will first be tested and validated before committed as a new version of the database. The change will then be applied to the database the first time a user opens it. I suppose we would open the database in exclusive mode while applying the changes, but as long as the changes aren't too frequent this should not be a problem.
So what do you think? Will this work? Have any of you done something similar? Should we scrap the solution and go for the monolithic system instead?
|
I have a similar situation here, though I use MySQL. Every database has a versions table that contains the version (simply an integer) and a short comment of what has changed in this version. I use a script to update the databases. Every database change can be in one function or sometimes one change is made by multiple functions. Functions contain the version number in the function name. The script looks up the highest version number in a database and applies only the functions that have a higher version number in order.
This makes it easy to update databases (just add new change functions) and allows me to quickly upgrade a recovered database if necessary (just run the script again).
Even when testing the changes before this allows for defensive changes. If you make some heavy changes on a table and you want to play it safe:
```
def change103(...):
"Create new table."
def change104(...):
"""Transfer data from old table to new table and make
complicated changes in the process.
"""
def change105(...):
"Drop old table"
def change106(...):
"Rename new table to old table"
```
if in change104() is something going wrong (and throws an exception) you can simply delete the already converted data from the new table, fix your change function and run the script again.
But I don't think that changing a database dynamically when a client connects is a good idea. Sometimes changes can take some time. And the software that accesses a database should match the schema of the database. You have somehow to keep them in sync. Maybe you could distribute a new software version and then you want to upgrade the database when a client is actually starting to use this new software. But I haven't tried that.
|
Have you considered *partitioning* your large tables by 'construction'? This could alleviate some of the growing pains by splitting the storage for the tables across files/physical devices without needing to change your application.
Adding spindles (more drives) and performing a few hours of DBA work can often be cheaper than modifying/adapting software.
Otherwise, I'd agree with @heikogerlach and these similar posts:
[How do I version my ms sql database](https://stackoverflow.com/questions/173/how-do-i-version-my-ms-sql-database-in-svn)
[Mechanisms for tracking DB schema changes](https://stackoverflow.com/questions/1607/mechanisms-for-tracking-db-schema-changes)
[How do you manage databases in development, test and production?](https://stackoverflow.com/questions/6371/how-do-you-manage-databases-in-development-test-and-production)
|
Dynamic patching of databases
|
[
"",
"sql",
"sql-server",
"database",
""
] |
All numbers that divide evenly into x.
I put in 4 it returns: 4, 2, 1
edit: I know it sounds homeworky. I'm writing a little app to populate some product tables with semi random test data. Two of the properties are ItemMaximum and Item Multiplier. I need to make sure that the multiplier does not create an illogical situation where buying 1 more item would put the order over the maximum allowed. Thus the factors will give a list of valid values for my test data.
edit++:
This is what I went with after all the help from everyone. Thanks again!
edit#: I wrote 3 different versions to see which I liked better and tested them against factoring small numbers and very large numbers. I'll paste the results.
```
static IEnumerable<int> GetFactors2(int n)
{
return from a in Enumerable.Range(1, n)
where n % a == 0
select a;
}
private IEnumerable<int> GetFactors3(int x)
{
for (int factor = 1; factor * factor <= x; factor++)
{
if (x % factor == 0)
{
yield return factor;
if (factor * factor != x)
yield return x / factor;
}
}
}
private IEnumerable<int> GetFactors1(int x)
{
int max = (int)Math.Ceiling(Math.Sqrt(x));
for (int factor = 1; factor < max; factor++)
{
if(x % factor == 0)
{
yield return factor;
if(factor != max)
yield return x / factor;
}
}
}
```
In ticks.
When factoring the number 20, 5 times each:
* GetFactors1-5,445,881
* GetFactors2-4,308,234
* GetFactors3-2,913,659
When factoring the number 20000, 5 times each:
* GetFactors1-5,644,457
* GetFactors2-12,117,938
* GetFactors3-3,108,182
|
pseudocode:
* Loop from 1 to the square root of the number, call the index "i".
* if number mod i is 0, add i and number / i to the list of factors.
realocode:
```
public List<int> Factor(int number)
{
var factors = new List<int>();
int max = (int)Math.Sqrt(number); // Round down
for (int factor = 1; factor <= max; ++factor) // Test from 1 to the square root, or the int below it, inclusive.
{
if (number % factor == 0)
{
factors.Add(factor);
if (factor != number/factor) // Don't add the square root twice! Thanks Jon
factors.Add(number/factor);
}
}
return factors;
}
```
As Jon Skeet mentioned, you could implement this as an `IEnumerable<int>` as well - use [yield](http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx) instead of adding to a list. The advantage with `List<int>` is that it could be sorted before return if required. Then again, you could get a sorted enumerator with a hybrid approach, yielding the first factor and storing the second one in each iteration of the loop, then yielding each value that was stored in reverse order.
You will also want to do something to handle the case where a negative number passed into the function.
|
The `%` (remainder) operator is the one to use here. If `x % y == 0` then `x` is divisible by `y`. (Assuming `0 < y <= x`)
I'd personally implement this as a method returning an `IEnumerable<int>` using an iterator block.
|
Best way to find all factors of a given number
|
[
"",
"c#",
".net",
"math",
""
] |
I have a class that contains a dynamically allocated array, say
```
class A
{
int* myArray;
A()
{
myArray = 0;
}
A(int size)
{
myArray = new int[size];
}
~A()
{
// Note that as per MikeB's helpful style critique, no need to check against 0.
delete [] myArray;
}
}
```
But now I want to create a dynamically allocated array of these classes. Here's my current code:
```
A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
arrayOfAs[i] = A(3);
}
```
But this blows up terribly. Because the new `A` object created (with the `A(3)` call) gets destructed when the `for` loop iteration finishes, and this means that the internal `myArray` of that `A` instance gets `delete []`-ed.
So I think my syntax must be terribly wrong? I guess there are a few fixes that seem like overkill, which I'm hoping to avoid:
* Creating a copy constructor for `A`.
* Using `vector<int>` and `vector<A>` so I don't have to worry about all this.
* Instead of having `arrayOfAs` be an array of `A` objects, have it be an array of `A*` pointers.
I would think this is just some beginners thing where there's a syntax that actually works when attempting to dynamically allocate an array of things that have internal dynamic allocation.
(Also, style critiques appreciated, since it's been a while since I did C++.)
**Update for future viewers**: All of the answers below are really helpful. Martin's is accepted because of the example code and the useful "rule of 4," but I really suggest reading them all. Some are good, succinct statements of what's wrong, and some point out correctly how and why `vector`s are a good way to go.
|
For building containers you obviously want to use one of the standard containers (such as a std::vector). But this is a perfect example of the things you need to consider when your object contains RAW pointers.
If your object has a RAW pointer then you need to remember the rule of 3 (now the rule of 5 in C++11).
* Constructor
* Destructor
* Copy Constructor
* Assignment Operator
* Move Constructor (C++11)
* Move Assignment (C++11)
This is because if not defined the compiler will generate its own version of these methods (see below). The compiler generated versions are not always useful when dealing with RAW pointers.
The copy constructor is the hard one to get correct (it's non trivial if you want to provide the strong exception guarantee). The Assignment operator can be defined in terms of the Copy Constructor as you can use the copy and swap idiom internally.
See below for full details on the absolute minimum for a class containing a pointer to an array of integers.
Knowing that it is non trivial to get it correct you should consider using std::vector rather than a pointer to an array of integers. The vector is easy to use (and expand) and covers all the problems associated with exceptions. Compare the following class with the definition of A below.
```
class A
{
std::vector<int> mArray;
public:
A(){}
A(size_t s) :mArray(s) {}
};
```
Looking at your problem:
```
A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
// As you surmised the problem is on this line.
arrayOfAs[i] = A(3);
// What is happening:
// 1) A(3) Build your A object (fine)
// 2) A::operator=(A const&) is called to assign the value
// onto the result of the array access. Because you did
// not define this operator the compiler generated one is
// used.
}
```
The compiler generated assignment operator is fine for nearly all situations, but when RAW pointers are in play you need to pay attention. In your case it is causing a problem because of the **shallow copy** problem. You have ended up with two objects that contain pointers to the same piece of memory. When the A(3) goes out of scope at the end of the loop it calls delete [] on its pointer. Thus the other object (in the array) now contains a pointer to memory that has been returned to the system.
**The compiler generated copy constructor**; copies each member variable by using that members copy constructor. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).
**The compiler generated assignment operator**; copies each member variable by using that members assignment operator. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).
So the minimum for a class that contains a pointer:
```
class A
{
size_t mSize;
int* mArray;
public:
// Simple constructor/destructor are obvious.
A(size_t s = 0) {mSize=s;mArray = new int[mSize];}
~A() {delete [] mArray;}
// Copy constructor needs more work
A(A const& copy)
{
mSize = copy.mSize;
mArray = new int[copy.mSize];
// Don't need to worry about copying integers.
// But if the object has a copy constructor then
// it would also need to worry about throws from the copy constructor.
std::copy(©.mArray[0],©.mArray[c.mSize],mArray);
}
// Define assignment operator in terms of the copy constructor
// Modified: There is a slight twist to the copy swap idiom, that you can
// Remove the manual copy made by passing the rhs by value thus
// providing an implicit copy generated by the compiler.
A& operator=(A rhs) // Pass by value (thus generating a copy)
{
rhs.swap(*this); // Now swap data with the copy.
// The rhs parameter will delete the array when it
// goes out of scope at the end of the function
return *this;
}
void swap(A& s) noexcept
{
using std::swap;
swap(this.mArray,s.mArray);
swap(this.mSize ,s.mSize);
}
// C++11
A(A&& src) noexcept
: mSize(0)
, mArray(NULL)
{
src.swap(*this);
}
A& operator=(A&& src) noexcept
{
src.swap(*this); // You are moving the state of the src object
// into this one. The state of the src object
// after the move must be valid but indeterminate.
//
// The easiest way to do this is to swap the states
// of the two objects.
//
// Note: Doing any operation on src after a move
// is risky (apart from destroy) until you put it
// into a specific state. Your object should have
// appropriate methods for this.
//
// Example: Assignment (operator = should work).
// std::vector() has clear() which sets
// a specific state without needing to
// know the current state.
return *this;
}
}
```
|
I'd recommend using std::vector: something like
```
typedef std::vector<int> A;
typedef std::vector<A> AS;
```
There's nothing wrong with the slight overkill of STL, and you'll be able to spend more time implementing the specific features of your app instead of reinventing the bicycle.
|
Dynamically allocating an array of objects
|
[
"",
"c++",
"memory-management",
"pointers",
"destructor",
"copy-constructor",
""
] |
I am using a 3rd party API which is defined in 2 DLLs. I have included those DLLs in my project and set references to them. So far so good.
However, these DLLs have at least one dependent DLL which cannot be found at runtime. I copied the missing DLL into the project and set the 'Copy to output' flag but without success.
What should I be doing here to tell the project where it should find the dependent DLL?
**Clarification**
I tried adding a reference to the missing DLL but as it wasn't recognised as a .Net component. In desperation, I added it directly to the output folder but without success.
Finally, I installed the API on the PC and it all worked. The installation sets the PATH variable and the DLL is found in the installation folder. *But how to tell the project to look in one of its internal folders?*
|
It sounds like you need to better understand the third-party library and how it uses its own dependencies. If the installation of the API solves the problem, but copying the files manually does not, then you're missing something. There's either a missing file, or some environment variable or registry entry that's required. Two things that will really help you in this is the depends tool (which is part of the C++ installation) and procmon, which will tell you all the registry keys and files that get used at runtime.
If you're lucky, it's just a file that you're missing. If that's all it is, you can use the "Build Events" section of the project to copy the needed files to the right location on a successful build. If not, you're going to have to solve this some other way - either by requiring the API be installed, or rolling your own installation project.
|
How are you deploying? Just flat files? If so, it should work as long as the file ends up in the project output directory. Does it?
If you are using another deployment, you will need to tell that engine to include it. This is different for each of msi/ClickOnce/etc.
|
C#: How to include dependent DLLs?
|
[
"",
"c#",
"visual-studio",
"deployment",
"dll",
""
] |
I've got some experience with [Bash](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29), which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.
Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.
|
Python is well suited for these tasks, and I would guess much easier to develop in and debug than Windows batch files.
The question is, I think, how easy and painless it is to ensure that all the computers that you have to run these scripts on, have Python installed.
|
## Summary
**Windows**: no need to think, use Python.
**Unix**: quick or run-it-once scripts are for Bash, serious and/or long life time scripts are for Python.
## The big talk
In a Windows environment, Python is definitely the best choice since [cmd](http://en.wikipedia.org/wiki/Command_Prompt) is crappy and PowerShell has not really settled yet. What's more Python can run on several platform so it's a better investment. Finally, Python has a huge set of library so you will almost never hit the "god-I-can't-do-that" wall. This is not true for cmd and PowerShell.
In a Linux environment, this is a bit different. A lot of one liners are shorter, faster, more efficient and often more readable in pure Bash. But if you know your quick and dirty script is going to stay around for a while or will need to be improved, go for Python since it's far easier to maintain and extend and [you will be able to do most of the task you can do with GNU tools with the standard library](http://www.google.fr/url?sa=t&source=web&ct=res&cd=2&url=http%3A%2F%2Fwww.dabeaz.com%2Fgenerators%2FGenerators.pdf&ei=yRn7SJDYCIbS0QXFvq2JDw&usg=AFQjCNE6b1w4feELQFUppm2-GFCzYyd2UQ&sig2=nUjS8CM2Pd77W_HXUq4tRw). And if you can't, you can still call the command-line from a Python script.
And of course you can call Python from the shell using -c option:
```
python -c "for line in open('/etc/fstab') : print line"
```
Some more literature about Python used for system administration tasks:
* [The IBM lab point of view](http://www.ibm.com/developerworks/aix/library/au-python/).
* [A nice example to compare bash and python to script report](http://www.unixreview.com/documents/s=9083/sam0401d/).
* [The basics](http://www.samag.com/documents/s=8964/sam0312a/0312a.htm).
* [The must-have book](https://rads.stackoverflow.com/amzn/click/com/0596515820).
|
Would Python make a good substitute for the Windows command-line/batch scripts?
|
[
"",
"python",
"command-line",
"scripting",
""
] |
Having a vector containing pointers to objects then using the clear function doesn't call the destructors for the objects in the vector. I made a function to do this manually but I don't know how to make this a generic function for any kind of objects that might be in the vector.
```
void buttonVectorCleanup(vector<Button *> dVector){
Button* tmpClass;
for(int i = 0; i < (int)dVector.size(); i++){
tmpClass = dVector[i];
delete tmpClass;
}
}
```
This is the function I have that works fine for a specific type of object in the vector but I'd like a single function that could take any kind of vector with object pointers.
|
The best thing to do is use smart pointers, such as from [Boost](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm). Then the objects will be deleted automatically.
Or you can make a template function
```
template <class T>
void vectorCleanup(vector<T *>& dVector){
T* tmpClass;
for(vector<T*>::size_type i = 0; i < dVector.size(); i++){
tmpClass = dVector[i];
delete tmpClass;
}
```
}
|
You might want to use boost's [pointer containers](http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/ptr_container.html). They are highly efficient and safe.
|
How do I create a generic std::vector destructor?
|
[
"",
"c++",
"stl",
"vector",
"destructor",
""
] |
I need to call a [VBScript](http://en.wikipedia.org/wiki/VBScript) file (.vbs file extension) in my C# Windows application.
How can I do this?
There is an add-in to access a VBScript file
in Visual Studio.
But I need to access the script in code behind. How to do this?
|
The following code will execute a VBScript script with no prompts or errors and no shell logo.
```
System.Diagnostics.Process.Start(@"cscript //B //Nologo c:\scripts\vbscript.vbs");
```
A more complex technique would be to use:
```
Process scriptProc = new Process();
scriptProc.StartInfo.FileName = @"cscript";
scriptProc.StartInfo.WorkingDirectory = @"c:\scripts\"; //<---very important
scriptProc.StartInfo.Arguments ="//B //Nologo vbscript.vbs";
scriptProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //prevent console window from popping up
scriptProc.Start();
scriptProc.WaitForExit(); // <-- Optional if you want program running until your script exit
scriptProc.Close();
```
Using the `StartInfo` properties will give you quite granular access to the process settings.
You need to use [Windows Script Host](http://en.wikipedia.org/wiki/Windows_Script_Host) if you want windows, etc. to be displayed by the script program. You could also try just executing `cscript` directly but on some systems it will just launch the editor :)
|
Another approach is to create a VB.NET Class Library project, copy your VBScript code into a VB.NET Class file, and reference the VB.NET Class Library from your C# program.
You will need to fix-up any differences between VBScript and VB.NET (should be few).
The advantage here, is that you will run the code in-process.
|
How to call a VBScript file in a C# application?
|
[
"",
"c#",
".net",
"asp.net",
".net-2.0",
"vbscript",
""
] |
Today somebody told me that interface implementation in C# is just "Can-Do" relationship, not "Is-A" relationship. This conflicts with my long-time believing in LSP(Liskov Substitution Principle). I always think that all inheritance should means "Is-A" relationship.
So, If interface implementation is just a "Can-Do" relationship. What if there is a interface "IHuman" and "IEngineer", and one class "Programmer" inherits from "IHuman" & "IEngineer"? Surely, a "Programmer" Is A "IHuman" and A "IEngineer".
If it is just "Can-Do" relationship, does it mean we cannot expect the "Programmer" instance behavior may be different between when treated as a IHuman and treated as IEngineer?
|
In my experience it doesn't really help that much to think of "is-a" and "can-do" relationships. You rapidly get into problems. It's an impedance mismatch between the real world and OO, basically. However much people actually talk about modeling the real world, you fundamentally need to understand what the relationships between types mean on the platform you're using.
Sometimes interfaces can be used as capabilities, and sometimes they can represent more of a normal "is-a" relationship. I wouldn't get too hung up about it - just make sure you understand what they can do and what they can't.
|
I tend to think of interfaces as a contract of behaviour. Interfaces such as IComparable and IEnumerable are classic examples.
In the example you gave, IHuman and IEngineer are not really behaviours.
|
C# Interface Implementation relationship is just "Can-Do" Relationship?
|
[
"",
"c#",
"inheritance",
"interface",
"liskov-substitution-principle",
""
] |
How can I count operations in C++? I'd like to analyze code in a better way than just timing it since the time is often rounded to 0 millisec.
|
You can do precise measurements by reading the time-stamp-counter (**tsc**) of the CPU, which is incremented by one at each cpu-clock.
Unfortunately the read is done inlining some assembler instructions in the code. Depending on the underlying architecture the cost of the read varies between ~11(AMD) and ~33(Intel) **tsc**. With 1 Ghz CPU you can virtually have the nano-second precision.
In order to perform a reliable and non-invasive measure of a section of code you can:
* prevent the cpu scaling frequency by disabling the cpu features such as *AMD cool'n quite* or *Intel SpeedStep*.
* repeat the test several times, collecting the measures in an array and then saving data to file for an off-line analysis.
* choose a real-time scheduling policy for the process under test such as **SHED\_RR** or **SHED\_FIFO**. Realtime policies reduce the number of context-switch between the process under test and other normal processes/kernel threads, that are blocked.
* lock all the process's virtual address space in RAM by means of mlockall() system call.
[Here](http://web.archive.org/web/20090107031753/http://awgn.antifork.org/codes++/arch-cpu.hh) you can find a quasi-portable C++ class I wrote for Linux, derived from the Linux kernel and designed to read tsc for the architectures i386, x86\_64 and ia64.
|
If you are timing code, it's worth running it a lot of times in a loop to avoid the effect of the timer resolution. So you might run the thing you're timing 10,000 times and measure the amount of time it takes to run all the iterations. It will probably only take a few seconds to run and you'll get better timing data.
|
How can I count operations in C++?
|
[
"",
"c++",
"performance",
""
] |
Up until now I have been using std::string in my C++ applications for embedded system (routers, switches, telco gear, etc.).
For the next project, I am considering to switch from std::string to std::wstring for Unicode support. This would, for example, allow end-users to use Chinese characters in the command line interface (CLI).
What complications / headaches / surprises should I expect? What, for example, if I use a third-party library which still uses std::string?
Since support for international strings isn't that strong of a requirement for the type of embedded systems that I work on, I would only do it if it isn't going to cause major headaches.
|
Note that many communications protocols require 8-bit characters (or 7-bit characters, or other varieties), so you will often need to translate between your internal wchar\_t/wstring data and external encodings.
UTF-8 encoding is useful when you need to have an 8-bit representation of Unicode characters. (See [How Do You Write Code That Is Safe for UTF-8?](https://stackoverflow.com/questions/134371/how-do-you-write-code-that-is-safe-for-utf-8) for some more info.) But note that you may need to support other encodings.
More and more third-party libraries are supporting Unicode, but there are still plenty that don't.
I can't really tell you whether it is worth the headaches. It depends on what your requirements are. If you are starting from scratch, then it will be easier to start with std::wstring than converting from std::string to std::wstring later.
|
You might get some headache because of the fact that [the C++ standard dictates that wide-streams are required to convert double-byte characters to single-byte when writing to a file, and how this conversion is done is implementation-dependent](http://www.codeproject.com/KB/stl/upgradingstlappstounicode.aspx).
|
Switching from std::string to std::wstring for embedded applications?
|
[
"",
"c++",
"unicode",
"stl",
"embedded",
""
] |
Say I've got a class like this:
```
class Test
{
int x;
SomeClass s;
}
```
And I instantiate it like this:
```
Test* t = new Test;
```
Is x on the stack, or the heap? What about s?
|
Each time you "instantiate" an object/symbol using a new (we are speaking C++ here), a new memory zone will be allocated for this object. If not, it will be put on the "local" memory zone.
The problem is that I have no standard definition for "local" memory zone.
## An example
This means that, for example:
```
struct A
{
A()
{
c = new C() ;
}
B b ;
C * c ;
}
void doSomething()
{
A aa00 ;
A * aa01 = new A() ;
}
```
The object aa00 is allocated on the stack.
As aa00::b is allocated on a "local" memory according to aa00, aa00::b is allocated inside the memory range allocated by the new aa00 instruction. Thus, aa00::b is also allocated on stack.
But aa00::c is a pointer, allocated with new, so the object designed by aa00::c is on the heap.
Now, the tricky example: aa01 is allocated via a new, and as such, on the heap.
In that case, as aa01::b is allocated on a "local" memory according to aa01, aa01::b is allocated inside the memory range allocated by the new aa01 instruction. Thus, aa01::b is on the heap, "inside" the memory already allocated for aa01.
As aa01::c is a pointer, allocated with new, the object designed by aa01::c is on the heap, in another memory range than the one allocated for aa01.
## Conclusion
So, the point of the game is:
1 - What's the "local" memory of the studied object: Stack of Heap?
2 - if the object is allocated through new, then it is outside this local memory, i.e., it is elsewhere on the heap
3 - if the object is allocated "without new", then it is inside the local memory.
4 - If the "local" memory is on the stack, then the object allocated without new is on the stack, too.
5 - If the "local" memory is on the heap, then the object allocated without new is on the heap, too, but still inside the local memory.
Sorry, I have no better vocabulary to express those concepts.
|
```
Test a;
Test *t = new Test;
```
a, and all its members, are on the stack.
The object pointed to by t, and all its members, are on the heap.
The pointer t is on the stack.
|
Are data members allocated in the same memory space as their objects in C++?
|
[
"",
"c++",
"memory-management",
""
] |
In my website, users have the possibility to store links.
During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar.
Example:
User is typing as URL:
```
http://www.sta
```
Suggestions which would be displayed:
```
http://www.staples.com
http://www.starbucks.com
http://www.stackoverflow.com
```
How can I achieve this while not reinventing the wheel? :)
|
You could try with
<http://google.com/complete/search?output=toolbar&q=keyword>
and then parse the xml result.
|
I did this once before in a Django server. There's two parts - client-side and server-side.
Client side you will have to send out XmlHttpRequests to the server as the user is typing, and then when the information comes back, display it. This part will require a decent amount of javascript, including some tricky parts like callbacks and keypress handlers.
Server side you will have to handle the XmlHttpRequests which will be something that contains what the user has typed so far. Like a url of
```
www.yoursite.com/suggest?typed=www.sta
```
and then respond with the suggestions encoded in some way. (I'd recommend JSON-encoding the suggestions.) You also have to actually get the suggestions from your database, this could be just a simple SQL call or something else depending on your framework.
But the server-side part is pretty simple. The client-side part is trickier, I think. I found this [article](http://www.phpriot.com/articles/google-suggest-ajaxac) helpful
He's writing things in php, but the client side work is pretty much the same. In particular you might find his CSS helpful.
|
How to implement Google Suggest in your own web application (e.g. using Python)
|
[
"",
"python",
"autocomplete",
"autosuggest",
""
] |
For example for the following XML
```
<Order>
<Phone>1254</Phone>
<City>City1</City>
<State>State</State>
</Order>
```
I might want to find out whether the XElement contains "City" Node or not.
|
Just use the other overload for [Elements](http://msdn.microsoft.com/en-us/library/bb348975.aspx).
```
bool hasCity = OrderXml.Elements("City").Any();
```
|
It's been a while since I did XLinq, but here goes my WAG:
```
from x in XDocument
where x.Elements("City").Count > 0
select x
```
;
|
How to determine if XElement.Elements() contains a node with a specific name?
|
[
"",
"c#",
"xml",
"linq",
".net-3.5",
""
] |
The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.
|
I get completion for my own modules in my PYTHONPATH or site-packages. I'm not sure what version of the pythoncomplete.vim script you're using, but you may want to make sure it's the latest.
EDIT: Here's some examples of what I'm seeing on my system...
This file (mymodule.py), I puth in a directory in PYTHONPATH, and then in site-packages. Both times I was able to get the screenshot below.
```
myvar = 'test'
def myfunction(foo='test'):
pass
class MyClass(object):
pass
```
|
Once I generated ctags for one of my site-packages, it started working for that package -- so I'm guessing that the omnicomplete function depends on ctags for non-sys modules.
EDIT: Not true at all.
Here's the problem -- poor testing on my part -- omnicomplete WAS working for parts of my project, just not most of it.
The issue was that I'm working on a django project, and in order to import django.db, you need to have an environment variable set. Since I couldn't import django.db, any class that inherited from django.db, or any module that imported a class that inherited from django.db wouldn't complete.
|
Is there any way to get python omnicomplete to work with non-system modules in vim?
|
[
"",
"python",
"vim",
"omnicomplete",
""
] |
Today I happens to find that one C# class can inherit one interface both in implicit and explicit way. This surprises me. If C# works in this way, then one instance can behave differently when referenced in different way.
```
interface IFoo
{
void DoSomething();
}
class Foo : IFoo
{
#region IFoo Members
public void DoSomething()
{
Console.WriteLine("do something implicitly");
}
#endregion
#region IFoo Members
void IFoo.DoSomething()
{
Console.WriteLine("do something explicitly");
}
#endregion
}
Foo f = new Foo();
f.DoSomething();
((IFoo)f).DoSomething();
```
Above code runs and output
```
do something implicitly
do something explicitly
```
I believe that this design of C# make inconsistency of behavior. Perhaps it is mandatory that one C# class can inherit from one interface in implicit or expliict way, but not both.
Is there any reason that why C# is designed in such a way?
|
Your example does **not** implement IFoo both implicitly and explicitly. You only implement IFoo.DoSometing() explicitly. You have a new method on your class called DoSomething(). It has nothing to do with IFoo.DoSomething, except that it has the same name and parameters.
|
Every class that implements an interface has a *mapping* between that class's members and the interface's members. If the class *explicitly* implements an interface member, then the explicit implementation will **always** be mapped to the interface. If there isn't an explicit implementation then an implicit implementation is expected, and that one will be mapped to the interface.
When a class has the same member name and associated types as an interface **but** it also explicitly implements the corresponding member for the interface, then the class's "implicit" implementation *isn't* considered an implementation of the interface *at all* (unless the explicit implementation calls it).
In addition to different meanings in each case where the class implements multiple interfaces with the same member name/types, even with only one interface, the *class itself* is considered to have an implicit interface which might have the same member/types as the sole interface but still mean something different.
|
Why Can A C# Class Inherit From One Interface Both Implicitly and Explicitly?
|
[
"",
"c#",
"inheritance",
"implicit",
"explicit",
""
] |
If you have a class member that is `static` and `public`. Would you write `static public` or `public static`? I know they are the same. But is there some recommendation / best practice for writing this?
|
see [this question](https://stackoverflow.com/questions/191929/is-there-a-convention-to-the-order-of-modifiers-in-c#191944)
If you download the Microsoft [StyleCop](http://code.msdn.microsoft.com/sourceanalysis) Visual Studio addin, it can validate your source code against the rules Microsoft use. It likes the access modifier to come first.
|
"public static" is far more common, so you might want to go with that just to increase readability for programmers who never stumbled upon "static public".
|
Which is recommended: "static public" or "public static"
|
[
"",
"c#",
""
] |
I have sets of 5, 6 and 7 digit numbers. I need them to be displayed in the 000/000/000 format. So for example:
12345 would be displayed as 000/012/345
and
9876543 would be displayed as 009/876/543
I know how to do this in a messy way, involving a series of if/else statements, and strlen functions, but there has to be a cleaner way involving regex that Im not seeing.
|
sprintf and modulo is one option
```
function formatMyNumber($num)
{
return sprintf('%03d/%03d/%03d',
$num / 1000000,
($num / 1000) % 1000,
$num % 1000);
}
```
|
```
$padded = str_pad($number, 9, '0', STR_PAD_LEFT);
$split = str_split($padded, 3);
$formatted = implode('/', $split);
```
|
Whats the cleanest way to convert a 5-7 digit number into xxx/xxx/xxx format in php?
|
[
"",
"php",
"regex",
""
] |
I'm consuming a third-party resource (a .dll) in a web service, and my problem is, that invoking this resource (calling a method) is done asynchronous - I need to subscribe to an event, to get the answer for my request. How do I do that in a c# web service?
**Update:**
With regard to [Sunny's answer](https://stackoverflow.com/questions/246791/invoking-asynchronous-call-in-a-c-web-service/246892#246892):
I don't want to make my web service asynchronous.
|
If the 3rd party component does not support the standard asynchronous programming model (i.e it does not use IAsyncResult), you can still achieve synchronization using AutoResetEvent or ManualResetEvent. To do this, declare a field of type AutoResetEvent in your web service class:
```
AutoResetEvent processingCompleteEvent = new AutoResetEvent();
```
Then wait for the event to be signaled after calling the 3rd party component
```
// call 3rd party component
processingCompleteEvent.WaitOne()
```
And in the callback event handler signal the event to let the waiting thread continue execution:
```
processingCompleteEvent.Set()
```
|
Assuming your 3rd party component is using the asynchronous programming model pattern used throughout the .NET Framework you could do something like this
```
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.stackoverflow.com");
IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(null, null);
asyncResult.AsyncWaitHandle.WaitOne();
using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult))
using (StreamReader responseStreamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
string responseText = responseStreamReader.ReadToEnd();
}
```
Since you need your web service operation to block you should use the IAsyncResult.AsyncWaitHandle instead of the callback to block until the operation is complete.
|
Invoking asynchronous call in a C# web service
|
[
"",
"c#",
"web-services",
"asynchronous",
"function-calls",
""
] |
I'm having trouble getting the right number of elements in the ArrayList `alt` in the JSP page below. When I view the JSP it shows the size is 1 (`<%=alt.size()%>`) when it should be 3; I think I'm adding that method to the array in the generator class, so I don't understand why it's showing 1.
This is my jsp page:
```
<%
ArrayList<Alert> a = AlertGenerator.getAlert();
pageContext.setAttribute("alt", a);
%>
<c:forEach var="alert" items="${alt}" varStatus="status" >
<p>You have <%=alt.size()%> Active Alert(s)</p>
<ul>
<li><a href="#" class="linkthree">${alert.alert1}</a></li>
<li><a href="#" class="linkthree">${alert.alert2}</a></li>
<li><a href="#" class="linkthree">${alert.alert3}</a></li>
</ul>
</c:forEach>
```
This is class that generates the alerts:
```
package com.cg.mock;
import java.util.ArrayList;
public class AlertGenerator {
public static ArrayList<Alert> getAlert() {
ArrayList<Alert> alt = new ArrayList<Alert>();
alt.add(new Alert("alert1","alert2","alert3"));
return alt;
}
}
```
This is my bean class:
```
package com.cg.mock;
public class Alert {
String alert1;
String alert2;
String alert3;
public Alert(String alert1, String alert2,String alert3) {
super();
this.alert1 = alert1;
this.alert2 = alert2;
this.alert3 = alert3;
}
public String getAlert1() {
return alert1;
}
public void setAlert1(String alert1) {
this.alert1 = alert1;
}
public String getAlert2() {
return alert2;
}
public void setAlert2(String alert2) {
this.alert2 = alert2;
}
public String getAlert3() {
return alert3;
}
public void setAlert3(String alert3) {
this.alert3 = alert3;
}
}
```
|
To get 3 Alerts you can redesign as follows. Notice that there is only one property of the alert class. You can create a new instance of the Alert for each alert.
```
package com.cg.mock;
public class Alert {
String alert1;
public Alert(String alert1) {
super();
this.alert1 = alert1;
}
public String getAlert1() {
return alert1;
}
public void setAlert1(String alert1) {
this.alert1 = alert1;
}
}
```
In the AlertGenerator:
```
ArrayList<Alert> alt = new ArrayList<Alert>();
alt.add(new Alert("alert1");
alt.add(new Alert("alert2");
alt.add(new Alert("alert3");
return alt;
```
And on the JSP:
```
<p>You have <%=alt.size()%> Active Alert(s)</p>
<ul>
<c:forEach var="alert" items="${alt}" varStatus="status" >
<li><a href="#" class="linkthree">${alert.alert1}</a></li>
</c:forEach>
</ul>
```
Notice the ul's are outside the forEach loop.
|
The problem is you have only one Alert instance in your ArrayList, but that single Alert has 3 properties: alert1, alert2, and alert3.
Take a look at the line:
```
alt.add(new Alert("alert1","alert2","alert3"));
```
You only have one add line, and it is not in a loop.
A possible solution:
```
public class Alert {
private String description;
private String status;
private Date raisedOn;
public Alert(String description, String status) {
this.description = description;
this.status = status;
this.raisedOn = new Date();
}
public String getDescription() { return description; }
public String getStatus() { return status; }
public Date getRaisedOn() { return raisedOn; }
}
....
alt.add(new Alert("Disk Almost Full", "Warning"));
alt.add(new Alert("Disk Full", "Severe"));
...
...
<table>
<tr><th>Description</th><th>Status</th><th>Raised</th></td>
<c:forEach var="alert" items="${alt}">
<tr>
<td><c:out value="${alert.description}"/></td>
<td><c:out value="${alert.status}"/></td>
<td><c:out value="${alert.raisedOn}"/></td>
</tr>
</c:forEach>
</table>
```
|
Not getting the proper size of an ArrayList in JSP
|
[
"",
"java",
"jsp",
"arraylist",
""
] |
I'm writing an intranet application for a client and I want to give them the ability to configure through an admin interface, which users and user groups can access certain areas. What I'd like to know is the best way of storing the reference to the user or group that is assigned to an area of the intranet.
Should I be using the **domain\username** and **domain\groupname** strings or should i perhaps be using the fully qualified ad name ie **ou=computer room;cn=blah** etc?
I will be storing the reference in SQL.
|
I would use domain\group in case the group gets moved or deleted/recreated. Using CN is brittle in the face of changes to the OU structure. SIDs are not human readable and will break if the object is deleted/recreated.
|
Personally, I believe that the "Domain\Username" format is sufficiently readable.
Also, if you were editing the SQL table directly, you could pretty easily insert a record for a user for testing or debugging purposes.
|
What is the best way to store a reference to an AD group?
|
[
"",
"c#",
"asp.net",
"active-directory",
""
] |
I have quickly read over the [Microsoft Lambda Expression](http://msdn.microsoft.com/en-us/library/bb397687.aspx) documentation.
This kind of example has helped me to understand better, though:
```
delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
```
Still, I don't understand why it's such an innovation. It's just a method that dies when the "method variable" ends, right? Why should I use this instead of a real method?
|
[Lambda expressions](http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx) are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL.
The following is an example of a [LINQ to Objects](http://msdn.microsoft.com/en-us/library/bb397919.aspx) expression using anonymous delegates then lambda expressions to show how much easier on the eye they are:
```
// anonymous delegate
var evens = Enumerable
.Range(1, 100)
.Where(delegate(int x) { return (x % 2) == 0; })
.ToList();
// lambda expression
var evens = Enumerable
.Range(1, 100)
.Where(x => (x % 2) == 0)
.ToList();
```
Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement [closures](http://en.wikipedia.org/wiki/Closure_(computer_science)) which can allow you to [pass local state to the function without adding parameters](http://www.srtsolutions.com/Looking-Inside-C-Closures) to the function or creating one-time-use objects.
[Expression trees](http://www.interact-sw.co.uk/iangblog/2005/09/30/expressiontrees) are a very powerful new feature of C# 3.0 that allow an API to look at the structure of an expression instead of just getting a reference to a method that can be executed. An API just has to make a delegate parameter into an `Expression<T>` parameter and the compiler will generate an expression tree from a lambda instead of an anonymous delegate:
```
void Example(Predicate<int> aDelegate);
```
called like:
```
Example(x => x > 5);
```
becomes:
```
void Example(Expression<Predicate<int>> expressionTree);
```
The latter will get passed a representation of the [abstract syntax tree](http://en.wikipedia.org/wiki/Abstract_syntax_tree) that describes the expression `x > 5`. LINQ to SQL relies on this behavior to be able to turn C# expressions in to the SQL expressions desired for filtering / ordering / etc. on the server side.
|
Anonymous functions and expressions are useful for one-off methods that don't benefit from the extra work required to create a full method.
Consider this example:
```
List<string> people = new List<string> { "name1", "name2", "joe", "another name", "etc" };
string person = people.Find(person => person.Contains("Joe"));
```
versus
```
public string FindPerson(string nameContains, List<string> persons)
{
foreach (string person in persons)
if (person.Contains(nameContains))
return person;
return null;
}
```
These are functionally equivalent.
|
C# Lambda expressions: Why should I use them?
|
[
"",
"c#",
"c#-3.0",
"lambda",
""
] |
Are there any libraries out there (preferably a self contained Text Edit Control) for .NET that have Spell Check capabilities. I would like to add the typical red underline to miss-spelled words in the edit area of my application.
Edit: To clarify, this is for WinForms
|
Not a redlining control, but: [Aspell.Net](http://aspell-net.sourceforge.net/) is a Free and Open Source .Net spell checking component. Based on the GNU Aspell project, Aspell.Net is one of the most powerful multi-lingual spelling engines available. The API is written in C# and communicates through a C++ wrapper around the Win32 Port of Aspell's C API.
Source repository at [sourceforge](http://aspell-net.cvs.sourceforge.net/viewvc/aspell-net/), checked February 2010 (Tahnks, @magnifico).
May 2012, source no longer accessible... sorry.
|
Aspell.Net looks nice, but does not seem to be maintained anymore. I could not get it to work on my machine.
After searching around SourceForge, I found [NHunspell](http://nhunspell.sourceforge.net/), which is a .Net port of the spell checker from OpenOffice.org. It provides methods to spell check, find synonyms, and hyphenate. Its actively maintained at this time, and comes with easy to understand sample code.
In the project's own words:
> Spell Checker, Hypenation and
> Thesaurus: NHunspell
>
> NHunspell is a free open source spell
> checker for the .NET Framework. C# and
> Visual Basic sample code is available
> for spell checking, hyphenation and
> synonym lookup via thesaurus.
>
> NHunspell is based on Hunspell and
> brings the Open Office spell checking,
> hyphenation and thesaurus to the
> Microsoft® .NET Framework. NHunspell
> is a .NET (C#, VB) library and wraps
> the native libraries Hunspell, Hyphen
> and MyThes.
>
> The integrated libraries are used in
> OpenOffice and work with the
> dictionaries published on
> OpenOffice.org. License
>
> NHunspell is licensed under:
> GPL/LGPL/MPL. Free use in commercial
> applications is permitted according to
> the LGPL and MPL licenses. Your
> commercial application can link
> against the NHunspell DLLs.
[NHunspell](http://nhunspell.sourceforge.net/)
|
.NET Spell Check control?
|
[
"",
"c#",
"winforms",
"spell-checking",
""
] |
A lot of my C# code follows this pattern:
```
void foo(string param1, string param2, string param3)
{
try
{
// do something...
}
catch(Exception ex)
{
LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message));
}
}
```
Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string?
OR
Do you have a more generic / better way of doing this?
|
You could use Reflection and the convention that you must pass the parameters to the LogError with the right order:
```
private static void MyMethod(string s, int x, int y)
{
try
{
throw new NotImplementedException();
}
catch (Exception ex)
{
LogError(MethodBase.GetCurrentMethod(), ex, s, x, y);
}
}
private static void LogError(MethodBase method, Exception ex, params object[] values)
{
ParameterInfo[] parms = method.GetParameters();
object[] namevalues = new object[2 * parms.Length];
string msg = "Error in " + method.Name + "(";
for (int i = 0, j = 0; i < parms.Length; i++, j += 2)
{
msg += "{" + j + "}={" + (j + 1) + "}, ";
namevalues[j] = parms[i].Name;
if (i < values.Length) namevalues[j + 1] = values[i];
}
msg += "exception=" + ex.Message + ")";
Console.WriteLine(string.Format(msg, namevalues));
}
```
|
You could use aspect oriented programming with PostSharp (have a look at <http://www.postsharp.org>, and the tutorial at <http://www.codeproject.com/KB/cs/ps-custom-attributes-1.aspx>). Basically you could do something like this:
```
public class LogExceptionAttribute : OnExceptionAspect
{
public override void OnException(MethodExecutionEventArgs eventArgs)
{
log.error("Exception occurred in method {0}", eventArgs);
}
}
[LoggingOnExceptionAspect]
public foo(int number, string word, Person customer)
{
// ... something here throws an exception
}
```
Perhaps not quite what you want, but I'm sure it can be adapted to suit your needs.
|
Generic logging of function parameters in exception handling
|
[
"",
"c#",
".net",
""
] |
I want to examine the contents of a `std::vector` in GDB, how do I do it? Let's say it's a `std::vector<int>` for the sake of simplicity.
|
To view vector std::vector myVector contents, just type in GDB:
```
(gdb) print myVector
```
This will produce an output similar to:
```
$1 = std::vector of length 3, capacity 4 = {10, 20, 30}
```
To achieve above, you need to have gdb 7 (I tested it on gdb 7.01) and some python pretty-printer. Installation process of these is described on [gdb wiki](https://sourceware.org/gdb/wiki/STLSupport).
What is more, after installing above, this works well with **Eclipse** C++ debugger GUI (and any other IDE using GDB, as I think).
|
With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:
```
print *(myVector._M_impl._M_start)@myVector.size()
```
To print only the first N elements, do:
```
print *(myVector._M_impl._M_start)@N
```
**Explanation**
This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:
```
myVector._M_impl._M_start
```
And the GDB command to print N elements of an array starting at pointer P is:
```
print P@N
```
Or, in a short form (for a standard .gdbinit):
```
p P@N
```
|
How do I print the elements of a C++ vector in GDB?
|
[
"",
"c++",
"debugging",
"stl",
"vector",
"gdb",
""
] |
I'm a complete Ada newbie, though I've used Pascal for 2-3 years during HS.
IIRC, it is possible to call Pascal compiled functions from C/C++. Is it possible to call procedures & functions written in Ada from C++?
|
According to this [old tutorial](http://www.ghs.com/download/whitepapers/ada_c++.pdf), it should be possible.
However, as illustrated by [this thread](http://archives.devshed.com/forums/programming-132/problem-passing-in-out-parameter-from-c-to-ada-1023388.html), you must be careful with the c++ extern "C" definitions of your Ada functions.
|
Here's an example using g++/gnatmake 5.3.0:
*NOTE: Be careful when passing data between C++ and Ada*
**ada\_pkg.ads**
```
package Ada_Pkg is
procedure DoSomething (Number : in Integer);
pragma Export (C, DoSomething, "doSomething");
end Ada_Pkg;
```
**ada\_pkg.adb**
```
with Ada.Text_Io;
package body Ada_Pkg is
procedure DoSomething (Number : in Integer) is
begin
Ada.Text_Io.Put_Line ("Ada: RECEIVED " & Integer'Image(Number));
end DoSomething;
begin
null;
end Ada_Pkg;
```
**main.cpp**
```
/*
TO BUILD:
gnatmake -c ada_pkg
g++ -c main.cpp
gnatbind -n ada_pkg
gnatlink ada_pkg -o main --LINK=g++ -lstdc++ main.o
*/
#include <iostream>
extern "C" {
void doSomething (int data);
void adainit ();
void adafinal ();
}
int main () {
adainit(); // Required for Ada
doSomething(44);
adafinal(); // Required for Ada
std::cout << "in C++" << std::endl;
return 0;
}
```
References:
* <https://gcc.gnu.org/onlinedocs/gnat_ugn/Building-Mixed-Ada-and-C_002b_002b-Programs.html#Building-Mixed-Ada-and-C_002b_002b-Programs>
* <http://www.ghs.com/download/whitepapers/ada_c++.pdf>
|
Can you call Ada functions from C++?
|
[
"",
"c++",
"c",
"ada",
"cross-language",
""
] |
I have a web service that is protected by requiring the consuming third party application to pass a client certificate. I have installed the certificate on the providing web service in production and on the client as well. This process is currently working fine for other clients with a similar setup. The current version is written in .NET 3.5 and works perfectly on my development machine under cassini (and running standalone), but refuses to work on my production machine with the same code and certificate setup. I have confirmed that the provider web service accepts the certificate installed on the client through the browser, but when the cert is added to a webservice call programatically, I get a 403, access is denied. I output the fingerprint of the certificate added to the call before it makes the request to the protected webservice, and it is indeed the correct certificate attached. My thinking is that somewhere along the line, it does not have access to the private key portion of the certificate.
Any ideas?
Note: I've given the IIS process access to the relevant ~/crypto directories.
This is C# and .NET 3.5
|
I had this kind of problem a couple of weeks ago. The solution in my case was to use impersonation in order to gain appropriate access to the certificate store. By default, the IIS worker thread was running as a system user, and as such had no access to the appropriate store. Adding the certificate to a specific user store, and impersonating that user solved all the issues.
I shall continue to watch this question, though, as I am aware that impersonation is not a magic bullet fix, and that there will be issues arising from it in this scenario.
|
There's a distinct reason it did not work on my machine. When running within Visual Studio, it runs with my credentials, which were used to install the certificate. Thus automatically has permission to access the private key store on the machine. *However* when running outside of cassini (in the IDE), the IIS process did not have **permissions** to access to the private key store.
Temporary solution: Run the app-domain as **Local System**. Bad for security, but it gets the application up and running (albeit band-aided) until I can work out a more permanent solution.
|
Passing a client certificate only works on my machine
|
[
"",
"c#",
"web-services",
"security",
"client-certificates",
""
] |
I need to setup an application that watches for files being created in a directory, both locally or on a network drive.
Would the `FileSystemWatcher` or polling on a timer would be the best option. I have used both methods in the past, but not extensively.
What issues (performance, reliability etc.) are there with either method?
|
I have seen the file system watcher fail in production and test environments. I now consider it a convenience, but I do not consider it reliable. My pattern has been to watch for changes with the files system watcher, but poll occasionally to catch missing file changes.
Edit: If you have a UI, you can also give your user the ability to "refresh" for changes instead of polling. I would combine this with a file system watcher.
|
The biggest problem I have had is missing files when the buffer gets full. Easy as pie to fix--just increase the buffer. Remember that it contains the file names and events, so increase it to the expected amount of files (trial and error). It does use memory that cannot be paged out, so it could force other processes to page if memory gets low.
Here is the MSDN article on buffer :
[FileSystemWatcher..::.InternalBufferSize Property](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.internalbuffersize.aspx)
Per MSDN:
> Increasing buffer size is expensive, as it comes from non paged memory that cannot be swapped out to disk, so keep the buffer as small as possible. To avoid a buffer overflow, use the NotifyFilter and IncludeSubdirectories properties to filter out unwanted change notifications.
We use 16MB due to a large batch expected at one time. Works fine and never misses a file.
We also read all the files before beginning to process even one...get the file names safely cached away (in our case, into a database table) then process them.
For file locking issues I spawn a process which waits around for the file to be unlocked waiting one second, then two, then four, et cetera. We **never** poll. This has been in production without error for about two years.
|
FileSystemWatcher vs polling to watch for file changes
|
[
"",
"c#",
"file-io",
"filesystemwatcher",
"distributed-filesystem",
""
] |
I'm sorry for this very newbish question, I'm not much given into web development. I've got this cool JavaScript in a .js file that we want to use on a small web site. (It's a script to run Cooliris on it).
How do use the .js file or attach it to my HTML code?
|
Just include this line anywhere in your HTML page:
```
<script type="text/javascript" src="yourfile.js"></script>
```
Don't forget the closing tag as IE won't recongize it without a separate closing tag.
|
```
<script type="text/javascript" src="myfile.js"></script>
```
Usually inserted in the <head> tag. After that, it depends wether or not your script need additional initialization or customisation to work.
|
How to use a .js file?
|
[
"",
"javascript",
""
] |
I have a [Bluehost](http://en.wikipedia.org/wiki/Bluehost) account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in `.htaccess`:
```
Options +ExecCGI
AddType text/html py
AddHandler cgi-script .py
```
Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don't understand how it all fits together, especially when my web server is given (Apache running at a host's machine) and not something I can really play with (except defining `.htaccess` commands).
How are [WSGI](http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface), CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say [web.py](http://webpy.org/) or [CherryPy](http://en.wikipedia.org/wiki/CherryPy)) on my basic CGI configuration? How to install WSGI support?
|
**How WSGI, CGI, and the frameworks are all connected?**
Apache listens on port 80. It gets an HTTP request. It parses the request to find a way to respond. Apache has a LOT of choices for responding. One way to respond is to use CGI to run a script. Another way to respond is to simply serve a file.
In the case of CGI, Apache prepares an environment and invokes the script through the CGI protocol. This is a standard Unix Fork/Exec situation -- the CGI subprocess inherits an OS environment including the socket and stdout. The CGI subprocess writes a response, which goes back to Apache; Apache sends this response to the browser.
CGI is primitive and annoying. Mostly because it forks a subprocess for every request, and subprocess must exit or close stdout and stderr to signify end of response.
WSGI is an interface that is based on the CGI design pattern. It is not necessarily CGI -- it does not have to fork a subprocess for each request. It can be CGI, but it doesn't have to be.
WSGI adds to the CGI design pattern in several important ways. It parses the HTTP Request Headers for you and adds these to the environment. It supplies any POST-oriented input as a file-like object in the environment. It also provides you a function that will formulate the response, saving you from a lot of formatting details.
**What do I need to know / install / do if I want to run a web framework (say web.py or cherrypy) on my basic CGI configuration?**
Recall that forking a subprocess is expensive. There are two ways to work around this.
1. **Embedded** `mod_wsgi` or `mod_python` embeds Python inside Apache; no process is forked. Apache runs the Django application directly.
2. **Daemon** `mod_wsgi` or `mod_fastcgi` allows Apache to interact with a separate daemon (or "long-running process"), using the WSGI protocol. You start your long-running Django process, then you configure Apache's mod\_fastcgi to communicate with this process.
Note that `mod_wsgi` can work in either mode: embedded or daemon.
When you read up on mod\_fastcgi, you'll see that Django uses [flup](http://pypi.python.org/pypi/flup/) to create a WSGI-compatible interface from the information provided by mod\_fastcgi. The pipeline works like this.
```
Apache -> mod_fastcgi -> FLUP (via FastCGI protocol) -> Django (via WSGI protocol)
```
Django has several "django.core.handlers" for the various interfaces.
For mod\_fastcgi, Django provides a `manage.py runfcgi` that integrates FLUP and the handler.
For mod\_wsgi, there's a core handler for this.
**How to install WSGI support?**
Follow these instructions.
<https://code.google.com/archive/p/modwsgi/wikis/IntegrationWithDjango.wiki>
For background see this
<http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment-index>
|
I think [Florian's answer](https://stackoverflow.com/questions/219110/how-python-web-frameworks-wsgi-and-cgi-fit-together/219124#219124) answers the part of your question about "what is WSGI", especially if you read [the PEP](http://www.python.org/dev/peps/pep-0333).
As for the questions you pose towards the end:
WSGI, CGI, FastCGI etc. are all protocols for a web server to *run code*, and deliver the dynamic content that is produced. Compare this to static web serving, where a plain HTML file is basically delivered as is to the client.
**CGI, FastCGI and SCGI are language agnostic.** You can write CGI scripts in Perl, Python, C, bash, whatever. CGI defines *which* executable will be called, based on the URL, and *how* it will be called: the arguments and environment. It also defines how the return value should be passed back to the web server once your executable is finished. The variations are basically optimisations to be able to handle more requests, reduce latency and so on; the basic concept is the same.
**WSGI is Python only.** Rather than a language agnostic protocol, a standard function signature is defined:
```
def simple_app(environ, start_response):
"""Simplest possible application object"""
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!\n']
```
That is a complete (if limited) WSGI application. A web server with WSGI support (such as Apache with mod\_wsgi) can invoke this function whenever a request arrives.
The reason this is so great is that we can avoid the messy step of converting from a HTTP GET/POST to CGI to Python, and back again on the way out. It's a much more direct, clean and efficient linkage.
It also makes it much easier to have long-running frameworks running behind web servers, if all that needs to be done for a request is a function call. With plain CGI, you'd have to [start your whole framework up](http://tools.cherrypy.org/wiki/RunAsCGI) for each individual request.
To have WSGI support, you'll need to have installed a WSGI module (like [mod\_wsgi](http://code.google.com/p/modwsgi/)), or use a web server with WSGI baked in (like [CherryPy](http://tools.cherrypy.org/)). If neither of those are possible, you *could* use the CGI-WSGI bridge given in the PEP.
|
How Python web frameworks, WSGI and CGI fit together
|
[
"",
"python",
"apache",
"cgi",
"wsgi",
""
] |
Having a bit of trouble with the syntax where we want to call a delegate anonymously within a Control.Invoke.
We have tried a number of different approaches, all to no avail.
For example:
```
myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); });
```
where someParameter is local to this method
The above will result in a compiler error:
> Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type
|
Because `Invoke`/`BeginInvoke` accepts `Delegate` (rather than a typed delegate), you need to tell the compiler what type of delegate to create ; `MethodInvoker` (2.0) or `Action` (3.5) are common choices (note they have the same signature); like so:
```
control.Invoke((MethodInvoker) delegate {this.Text = "Hi";});
```
If you need to pass in parameters, then "captured variables" are the way:
```
string message = "Hi";
control.Invoke((MethodInvoker) delegate {this.Text = message;});
```
(caveat: you need to be a bit cautious if using captures *async*, but *sync* is fine - i.e. the above is fine)
Another option is to write an extension method:
```
public static void Invoke(this Control control, Action action)
{
control.Invoke((Delegate)action);
}
```
then:
```
this.Invoke(delegate { this.Text = "hi"; });
// or since we are using C# 3.0
this.Invoke(() => { this.Text = "hi"; });
```
You can of course do the same with `BeginInvoke`:
```
public static void BeginInvoke(this Control control, Action action)
{
control.BeginInvoke((Delegate)action);
}
```
If you can't use C# 3.0, you could do the same with a regular instance method, presumably in a `Form` base-class.
|
Actually you do not need to use delegate keyword. Just pass lambda as parameter:
```
control.Invoke((MethodInvoker)(() => {this.Text = "Hi"; }));
```
|
Anonymous method in Invoke call
|
[
"",
"c#",
".net",
"compiler-errors",
"anonymous-methods",
""
] |
I have created a class for a dashboard item which will hold information such as placement on the dashboard, description, etc. I am currently using a pair of Collections to hold those dashboard items contained in the "library" and those items showing on the dashboard itself. I have been asked to make this dashboard multi-tab, and my first inclination was to make a new Collection for each tab. For this I would want some type of array or collection which could have many of these dashboard item collections added to it as more tabs are added to the dashboard.
Is this possible, and if so, could I get a little code snip for the declaration of such a collection? I have considered using a single collection with a variable to show which tab the item will be shown in... However, the display and routines to manage dashboard item movement between screen and library currently need those individual collections.
Edit: Thank you for your answers. While I do find them all interesting I believe I am going to go with James solution and will be marking it as the accepted answer.
|
```
List< List<Placement>> ListofListOfPlacements = new List< List<Placement>> ();
List<Placement> dashboard1 = new List<Placement>();
List<Placement> dashboard2 = new List<Placement>();
List<Placement> dashboard3 = new List<Placement>();
List<Placement> dashboard4 = new List<Placement>();
ListofListOfPlacements.Add(dashboard1);
ListofListOfPlacements.Add(dashboard2);
ListofListOfPlacements.Add(dashboard3);
ListofListOfPlacements.Add(dashboard4);
```
|
Since you are talking about tabs, it sounds to me like you want something closer to a dictionary keyed on the tab name, with a set of items per tab. .NET 3.5 added the `ILookup<,>` interface:
```
ILookup<string, Foo> items = null; //TODO
foreach (Foo foo in items["SomeTab"])
{
Console.WriteLine(foo.Bar);
}
```
Note that the MS implementation is immutable - you can't edit it after creation; however, I wrote an `EditableLookup<,>` in [MiscUtil](http://www.pobox.com/~skeet/csharp/miscutil/) that allows you to work more effectively (just like a regular .NET collection):
```
var items = new EditableLookup<string, Foo>();
items.Add("SomeTab", new Foo { Bar = "abc" });
items.Add("AnotherTab", new Foo { Bar = "def" });
items.Add("SomeTab", new Foo { Bar = "ghi" });
foreach (Foo foo in items["SomeTab"])
{ // prints "abc" and "ghi"
Console.WriteLine(foo.Bar);
}
```
Without `EditableLookup<,>`, you need to build the lookup via the `Enumerable.ToLookup` extension method.
If any part of this sounds like an option, I can add more detail...
|
Is a Collection of Collections possible and/or the best way? C# .Net 3.5
|
[
"",
"c#",
".net",
"collections",
""
] |
Is there a way to resize a `std::vector` to lower capacity when I no longer need previously reserved space?
|
Effective STL, by Scott Meyers, Item 17: Use the `swap` trick to trim excess capacity.
```
vector<Person>(persons).swap(persons);
```
After that, `persons` is "shrunk to fit".
This relies on the fact that `vector`'s copy constructor allocates only as much as memory as needed for the elements being copied.
|
If you're using C++11, you can use `vec.shrink_to_fit()`. In VS2010 at least, that does the swap trick for you.
|
How to downsize std::vector?
|
[
"",
"c++",
"stl",
"vector",
""
] |
I am trying to setup tracd for the project I am currently working on.
After creating a password file with the python script given in the [site](http://trac.edgewall.org/wiki/TracStandalone) I am trying to start the server with authentication on. But it throws up warning saying No users found in the realm. What actually is a realm - I tried using trac as the value and also tried leaving it empty. I am using Windows XP. I am using Tracd Standalone server.
The Command Line sent was: tracd --port 8000 --auth=My\_Test\_Project,D:\My\_Test\_Project\Documents\Trac\digest.txt,Trac D:\My\_Test\_Project\Documents\Trac
The Warning message was - 'Warning: found no users in realm: trac'
Thanks...
|
Replacing the above said command line with the one bellow helps.
tracd --port 8000 --auth=Trac,D:\My\_Test\_Project\Documents\Trac\digest.txt,Trac D:\My\_Test\_Project\Documents\Trac
The string after --auth= should be the environment name and not the project name.
|
Check your password digest file. Looking at mine it appears that the output is stored as a line with three fields in this format: `username:realm:passwordhash`. If your getting that warning then it could be a mismatch between the realm field in the digest file and the realm that you're passing in when launching tracd.
---
Looking in the python generator script there are three options:
* -u for user
* -p for password
* -r for realm
When I generate my digest file using this command line (assuming you named it trac-digest.py):
```
python trac-digest.py -u user -p pass >> digest.txt
```
it generates this line in my digest.txt:
```
user:trac:1d395970d2a9a075d0536a4d6e4d0679
```
So looks like the default realm is *trac* and launching tracd with the --auth option specified like the documentation says always gives me that warning 'Warning: found no users in realm: *realm*'
But when I generate my digest file using the -r parameter:
```
python trac-digest.py -u user -p pass -r realm >> digest.txt
```
it generates this line in my digest.txt:
```
user:realm:1d395970d2a9a075d0536a4d6e4d0679
```
And I no longer get that warning when I specify the realm that I passed to trac-digest.py.
|
Tracd Realm
|
[
"",
"python",
"project-management",
"wiki",
"trac",
""
] |
I'm addicted to Vim, it's now my de facto way of editing text files.
Being that it's mainly a text editor and not an IDE, has anyone got tricks for me to make it easier when developing Java apps?
Some questions I have:
* How do I invoke a maven task without leaving vi?
* Can I get code completion?
* How's the syntax highlighting?
Anything else (other than "Don't do it!") that I should know about?
|
Some tips:
* Make sure you use vim (vi improved). Linux and some versions of UNIX symlink vi to vim.
* You can get code completion with [eclim](http://eclim.sourceforge.net/)
* Or you can get vi functionality within Eclipse with [viPlugin](http://viplugin.com/)
* Syntax highlighting is great with vim
* Vim has good support for writing little macros like running ant/[maven](http://vim.wikia.com/wiki/Use_maven_with_quickfix) builds
Have fun :-)
|
I've been a Vim user for years. I'm starting to find myself starting up Eclipse occasionally (using the vi plugin, which, I have to say, has a variety of issues). The main reason is that Java builds take quite a while...and they are just getting slower and slower with the addition of highly componentized build-frameworks like maven. So validating your changes tends to take quite a while, which for me seems to often lead to stacking up a bunch of compile issues I have to resolve later, and filtering through the commit messages takes a while.
When I get too big of a queue of compile issues, I fire up Eclipse. It lets me make cake-work of the changes. It's slow, brutal to use, and not nearly as nice of an editor as Vim is (I've been using Vim for nearly a decade, so it's second nature to me). I find for precision editing—needing to fix a specific bug, needing to refactor some specific bit of logic, or something else...I simply can't be as efficient at editing in Eclipse as I can in Vim.
Also a tip:
```
:set path=**
:chdir your/project/root
```
This makes `^wf` on a classname a very nice feature for navigating a large project.
So anyway, the skinny is, when I need to add a lot of new code, Vim seems to slow me down simply due to the time spent chasing down compilation issues and similar stuff. When I need to find and edit specific sources, though, Eclipse feels like a sledge hammer. I'm still waiting for the magical IDE for Vim. There's been three major attempts I know of. There's a pure viml IDE-type plugin which adds a lot of features but seems impossible to use. There's eclim, which I've had a lot of trouble with. And there's a plugin for Eclipse which actually embeds Vim. The last one seems the most promising for real serious Java EE work, but it doesn't seem to work very well or really integrate all of Eclipse's features with the embedded Vim.
Things like add a missing import with a keystroke, hilight code with typing issues, etc, seems to be invaluable from your IDE when working on a large Java project.
|
Tips for using Vim as a Java IDE?
|
[
"",
"java",
"vim",
"ide",
""
] |
I'm developing my first Word 2007 addin, and I've added an OfficeRibbon to my project. In a button-click handler, I'd like a reference to either the current `Word.Document` or `Word.Application`.
I'm trying to get a reference via the `OfficeRibbon.Context` property, which the documentation says should refer to the current `Application` object. However, it is always `null`.
Does anyone know either
a) if there is something I need to do to make `OfficeRibbon.Context` appear correctly populated?
b) if there is some other way I can get a reference to the Word Application or active Word Document?
Notes:
* I'm using VS2008 SP1
* The ribbon looks like it has initialized fine: The ribbon renders correctly in Word; I can step the debugger through both the constructor and the OnLoad members; Button click handlers execute correctly.
* Here's [the online help for this property](http://msdn.microsoft.com/en-us/library/microsoft.office.tools.ribbon.officeribbon.context.aspx?ppud=4);
> **OfficeRibbon.Context Property**
>
> `C#`
> `public Object Context { get; internal set; }`
>
> An Object that represents the Inspector window or application instance that is associated with this OfficeRibbon object.
>
> **Remarks**
>
> In Outlook, this property refers to the Inspector window in which this OfficeRibbon is displayed.
>
> In Excel, Word, and PowerPoint, this property returns the application instance in which this OfficeRibbon is displayed.
|
I also encountered this problem while creating an Excel 2007 AddIn using VS2008 SP1. The workaround I used was to store the Application in an `internal static` property in the main AddIn class and then reference it in the event handler in my ribbon:
```
public partial class ThisAddIn
{
internal static Application Context { get; private set; }
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Context = Application;
}
...
}
public partial class MyRibbon : OfficeRibbon
{
private void button1_Click(object sender, RibbonControlEventArgs e)
{
DoStuffWithApplication(ThisAddIn.Context);
}
...
}
```
|
Try referencing the document with:
```
Globals.ThisDocument.[some item]
```
[MSDN Reference](http://msdn.microsoft.com/en-us/library/bhczd18c.aspx)
|
VSTO: Why is OfficeRibbon.Context null?
|
[
"",
"c#",
"ms-word",
"ms-office",
"vsto",
"ribbon",
""
] |
This might be a little hard to explain, but I will try.
I want to display a list of categories (stored in 1 table), and number of domains associated with each category (stored in another table).
The monkey wrench in this case is that each domain has a set of records associated with it (which are stored in a 3rd table). I only want to show the categories that have domains associated with them, and the count of domains should reflect only the domains that have records associated with them (from the 3rd table).
My current query
```
SELECT r.rev_id, c.cat_id, c.cat_name, count(d.dom_id) As rev_id_count FROM reviews r
INNER JOIN domains d ON r.rev_domain_from=d.dom_id
INNER JOIN categories c ON d.dom_catid=c.cat_id
WHERE rev_status = 1
GROUP BY cat_name
ORDER BY cat_name
```
This selects the correct category names, but shows a false count (rev\_id\_count). If the category has 2 domains in it, and each domain has 2 records, it will show count of 4, when it should be 2.
|
```
SELECT Categories.Name,count(DISTINCT categories.name) FROM Categories
JOIN Domains ON Categories.ID=Domains.CID
JOIN Records ON Records.DID=Domains.ID
GROUP BY Categories.Name
```
Tested with following setup:
```
CREATE TABLE Categories (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1))
CREATE TABLE Domains (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1), CID int)
CREATE TABLE Records (Name nvarchar(50), ID int NOT NULL IDENTITY(1,1), DID int)
INSERT INTO Records (DID) VALUES (1)
INSERT INTO Records (DID) VALUES (1)
INSERT INTO Records (DID) VALUES (2)
INSERT INTO Records (DID) VALUES (2)
INSERT INTO Records (DID) VALUES (3)
INSERT INTO Records (DID) VALUES (3)
INSERT INTO Domains (Name,CID) VALUES ('D1',1)
INSERT INTO Domains (Name,CID) VALUES ('D2',1)
INSERT INTO Domains (Name,CID) VALUES ('D5',1)
INSERT INTO Domains (Name,CID) VALUES ('D3',2)
INSERT INTO Domains (Name,CID) VALUES ('D4',2)
INSERT INTO Categories (Name) VALUES ('1')
INSERT INTO Categories (Name) VALUES ('2')
INSERT INTO Categories (Name) VALUES ('3')
```
|
```
select c.name, count(distinct d.did) from domains d
left join categories c on c.cid = d.cid
left join records r on r.did = d.did
group by c.name
```
tested with 2 categories, 2 domains per categories, random number of records per domain. result set:
```
name count
---- -----
test 2
test2 2
```
|
How would I write this 3 level deep mysql query?
|
[
"",
"sql",
"mysql",
""
] |
How can I setup a default value to a property defined as follow:
```
public int MyProperty { get; set; }
```
That is using "prop" [tab][tab] in VS2008 (code snippet).
Is it possible without falling back in the "old way"?:
```
private int myProperty = 0; // default value
public int MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}
```
Thanks for your time.
Best regards.
|
Just set the "default" value within your constructor.
```
public class Person
{
public Person()
{
this.FirstName = string.Empty;
}
public string FirstName { get; set; }
}
```
Also, they're called Automatic Properties.
|
My preference would be to do things "the old way", rather than init in the constructor. If you later add another constructor you'll have to be sure to call the first one from it, or your properties will be uninitialized.
|
How to set a default value using "short style" properties in VS2008 (Automatic Properties)?
|
[
"",
"c#",
".net",
"visual-studio-2008",
"properties",
""
] |
I'm new to the VxWorks environment, I'm wondering what C and C++ compilers are available for use with VxWorks?
|
As far as i know Tornado VxWorks IDE using gcc toolchain.
Any way i suggest to use the compiler provided by WindRiver (which i believe their version
of gcc) to avoid compatibility problems.
It's probably worth to menation the VxWorks version you having in mind.
I guess gcc version will be depend on VxWorks version and probably on target platform.
|
There are two: gcc and diab. They will be provided with your WindRiver platform (such as "General Purpose Platform 3.6"). The gcc is modified by WindRiver (and/or CodeSourcery) to work with VxWorks.
Now with VxWorks 6.9 there is a third option: Intel C++ compiler (for Intel target architectures only, 32 and 64 bit) -- diab will not target 64-bit
|
What C/C++ compilers are available for VxWorks?
|
[
"",
"c++",
"c",
"vxworks",
""
] |
Does a tool exist for dynamically altering running javascript in a browser? For example, to change the values of javascript variables during runtime.
|
Firebug , or Venkman Javascript Debugger .
|
So, Firebug really is one of the best options - or, if you are a developer that owns Visual Studio and want to debug using IE, you can do that. Let's assume you will do this with Firebug using Firefox.
First, determine where you want to alter the code and place the following line *just before* the line you want to start messing with:
```
debugger;
```
That will cause Firebug to stop the execution of the script at that point, at which point you can then step through the code and alter the values of variables.
You can also use Firebug to place breakpoints in by clicking to the left of a line of code in the script window of Firebug:

|
Does a tool exist for dynamically altering running javascript in a browser?
|
[
"",
"javascript",
"dynamic-data",
""
] |
I need to generate an XML file in C#.
I want to write the code that generates this in a file that is mostly XML with code inside of it as I can in an ASP.NET MVC page.
So I want a code file that looks like:
```
<lots of angle brackets...>
<% foreach(data in myData)
{ %>
< <%= data.somefield %>
<% } %>
More angle brackets>
```
This would generate my XML file. I would not mind using part of `System.Web` if someone tells me how I can do it without IIS overhead or kludging a generation of a web file.
**I want to use templating and I want templating that is similar to ASP.NET**
|
First off, its MUCH easier to generate XML using XElements. There are many examples floating around. Just search for "Linq to XML."
Alternatively, if you absolutely need to do templating, I'd suggest using a template engine such as [NVelocity](http://sourceforge.net/projects/nvelocity/) rather than trying to kludge ASP.NET into doing it for you.
|
Further to the above - use the new XML classes delivered with Linq - they make generation of XML in a logical fashion much much easier though you won't get down to something akin to a template in C#.
If you really need something template like then - and I know that this won't necessarily go down well - you should look at doing this part of the system in VB.NET which *does* have explicit support for template like XML generation as part of its Linq to XML implementation. At the very least you should look at what VB.NET offers before dismissing it.
The nature of .NET means that you don't have to use VB.NET for anything else, you can limit it to the class(es) necessary to do the XML generation and its "generic" in the sense that it comes with .NET and the surrounding logic should be comprehensible to any competent .NET programmer.
|
How do I create an XML file using templating similar to ASP.NET
|
[
"",
"c#",
"asp.net",
"xml",
""
] |
I have now 1gb ram at work(i hope that will change soon) and jboss takes almost half of it and that is too much, i turned off logging to file, what more can i do to reduce memory usage ?
|
You can limit the maximum memory used using the -Xmx parameter, as in any java process.
Edit the $JBOSS\_HOME/bin/run.conf and set this parameter to the desired maximum memory you want to allocate to JBoss.
Also, you can remove from the deploy directory of the server configuration you are using, the services you are not using. To be sure about what files you must remove in order to remove unused services, check the [documentation](http://www.jboss.org/file-access/default/members/jbossas/freezone/docs/Server_Configuration_Guide/beta500/html/index.html)
|
Which configuration are you using? JBoss comes with 3 [standard server configurations](http://www.jboss.org/file-access/default/members/jbossas/freezone/docs/Server_Configuration_Guide/beta500/html/ch03s02.html)
* The ***minimal*** configuration starts the core server container without any of the enterprise services. It is a good starting point if you want to build a customized version of JBoss AS that only contains the services you need.
* The ***default*** configuration is the mostly common used configuration for application developers. It supports the standard J2EE 1.4 and most of the Java EE 5.0 programming APIs (e.g., JSF and EJB3).
* The ***all*** configuration is the default configuration with clustering support and other enterprise extensions.
If you only want a specific subset of JBoss services, then start with the minimal?
Or you can [configure your own](http://www.jboss.org/file-access/default/members/jbossas/freezone/docs/Server_Configuration_Guide/beta500/html/ch04s02.html)?
|
jboss with less memory
|
[
"",
"java",
"memory",
"jakarta-ee",
"jboss",
""
] |
I have a PHP script that can encode a PNG image to a Base64 string.
I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.
|
You can use [`btoa()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa) and [`atob()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/atob) to convert to and from base64 encoding.
There appears to be some confusion in the comments regarding what these functions accept/return, so…
* `btoa()` accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, [it will probably break](https://developer.mozilla.org/en-US/docs/Web/API/window.btoa#Unicode_Strings). This isn’t a problem *if* you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.
* `atob()` returns a “string” where each character represents an 8-bit byte – that is, its value will be between `0` and `0xff`. This does *not* mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.
### See also:
* [How do I load binary image data using Javascript and XMLHttpRequest?](https://stackoverflow.com/questions/1095102/how-do-i-load-binary-image-data-using-javascript-and-xmlhttprequest)
---
Most comments here are outdated. You can probably use both `btoa()` and `atob()`, unless you support really outdated browsers.
Check here:
* <https://caniuse.com/?search=atob>
* <https://caniuse.com/?search=btoa>
|
[From here](http://www.webtoolkit.info/javascript-base64.html):
```
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
**/
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
```
Also, search for ["JavaScript base64 encoding"](http://www.google.com/search?q=javascript+base64+encode) turns up a lot of other options, and the above was the first one.
|
How can you encode a string to Base64 in JavaScript?
|
[
"",
"javascript",
"base64",
"binaryfiles",
""
] |
How do I iterate over the words of a string composed of words separated by whitespace?
Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution:
```
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string s = "Somewhere down the road";
istringstream iss(s);
do {
string subs;
iss >> subs;
cout << "Substring: " << subs << endl;
} while (iss);
}
```
|
For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL.
```
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
int main() {
using namespace std;
string sentence = "And I feel fine...";
istringstream iss(sentence);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
ostream_iterator<string>(cout, "\n"));
}
```
Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic [`copy`](https://en.cppreference.com/w/cpp/algorithm/copy) algorithm.
```
vector<string> tokens;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(tokens));
```
... or create the `vector` directly:
```
vector<string> tokens{istream_iterator<string>{iss},
istream_iterator<string>{}};
```
|
I use this to split string by a delimiter. The first puts the results in a pre-constructed vector, the second returns a new vector.
```
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
template <typename Out>
void split(const std::string &s, char delim, Out result) {
std::istringstream iss(s);
std::string item;
while (std::getline(iss, item, delim)) {
*result++ = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
```
---
Note that this solution does not skip empty tokens, so the following will find 4 items, one of which is empty:
```
std::vector<std::string> x = split("one:two::three", ':');
```
|
How do I iterate over the words of a string?
|
[
"",
"c++",
"string",
"split",
""
] |
How are assertions done in c++? Example code is appreciated.
|
Asserts are a way of explicitly checking the assumptions that your code makes, which helps you track down lots of bugs by narrowing down what the possible problems could be. They are typically only evaluated in a special "debug" build of your application, so they won't slow down the final release version.
Let's say you wrote a function that took a pointer as an argument. There's a good chance that your code will assume that the pointer is non-NULL, so why not explicitly check that with an assertion? Here's how:
```
#include <assert.h>
void function(int* pointer_arg)
{
assert(pointer_arg != NULL);
...
}
```
An important thing to note is that the expressions you assert must never have side effects, since they won't be present in the release build. So never do something like this:
```
assert(a++ == 5);
```
Some people also like to add little messages into their assertions to help give them meaning. Since a string always evaulates to true, you could write this:
```
assert((a == 5) && "a has the wrong value!!");
```
|
Assertion are boolean expressions which should typically always be true.
They are used to ensure what you expected is also what happens.
```
void some_function(int age)
{
assert(age > 0);
}
```
You wrote the function to deal with ages, you also 'know' for sure you're always passing sensible arguments, then you use an assert. It's like saying "I know this can never go wrong, but if it does, I want to know", because, well, everyone makes mistakes.
So it's not to check for sensible user input, if there are scenario's where something can go wrong, don't use an assert. Do real checks and deal with the errors.
Asserts are typically only for debug builds, so don't put code with side effects in asserts.
|
What are assertions? and why would you use them?
|
[
"",
"c++",
"assert",
""
] |
We have a ASP.Net 2.0 web application up and running with the server in the Midwest (Eastern Standard Time). At this moment all of our customers are in the same time zone as the server. We are bringing another server online in Arizona (Mountain Standard Time).
We are storing all our times in a SQL 2005 database via C# codebehind DateTime.UtcNow.
During testing we encountered some time zone conversion issues.
Our problem is that in the web browser our times are displaying the Mountain Standard Time instead of the time zone we are testing from which is Eastern Standard Time.
When we enter new information it gets stored as UTC in the database, but when we go to view that info in the browser it is displaying the Mountain Standard Time.
Below is the code which takes the UTC value from the database and displays it in the browser.
```
lblUpdatedDate.Text = Convert.ToDateTime(dr["UpdatedDate"]).ToLocalTime().ToString();
```
The above code returns Mountain Standard Time where the server is, not Eastern Standard Time where the browser is running from. How do we get the time to display where the user is?
|
I had the same issue. We sold our application to a user that was in a different time zone than the web server. We did not store any time information in UTC, but it was actually working correctly. Time displayed in the server's time zone was displaying exactly 3 hours behind. All we had to do was add a time zone drop down so they could select their time zone for the entire site (since the only users of the application would be in their time zone). We saved this setting and then inserted a function to take all datetime displays and convert from one time zone to the other using the TimeZoneInfo namespace. It works perfectly.
|
To local time will always on the server side convert to the physical location. You have a few options.
1. Store the offset value from UTC to the Users, keep times in UTC
2. Do the conversion client side via JS (Not elegant, nor appropriate, In my opinion)
3. Look at some [MSDN recommendations](http://msdn.microsoft.com/en-us/library/ms973825.aspx) and the Timezone namespace
|
Web Application Time Zone Issue
|
[
"",
"c#",
"asp.net",
"timezone",
""
] |
I'm using an HTML sanitizing whitelist code found here:
<http://refactormycode.com/codes/333-sanitize-html>
I needed to add the "font" tag as an additional tag to match, so I tried adding this condition after the `<img` tag check
```
if (tagname.StartsWith("<font"))
{
// detailed <font> tag checking
// Non-escaped expression (for testing in a Regex editor app)
// ^<font(\s*size="\d{1}")?(\s*color="((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)")?(\s*face="(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)")?\s*?>$
if (!IsMatch(tagname, @"<font
(\s*size=""\d{1}"")?
(\s*color=""((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)"")?
(\s*face=""(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)"")?
\s*?>"))
{
html = html.Remove(tag.Index, tag.Length);
}
}
```
Aside from the condition above, my code is almost identical to the code in the page I linked to. When I try to test this in C#, it throws an exception saying "`Not enough )'s`". I've counted the parenthesis several times and I've run the expression through a few online Javascript-based regex testers and none of them seem to tell me of any problems.
Am I missing something in my Regex that is causing a parenthesis to escape? What do I need to do to fix this?
**UPDATE**
After a lot of trial and error, I remembered that the `#` sign is a comment in regexes. The key to fixing this is to escape the `#` character. In case anyone else comes across the same problem, I've included my fix (just escaping the `#` sign)
```
if (tagname.StartsWith("<font"))
{
// detailed <font> tag checking
// Non-escaped expression (for testing in a Regex editor app)
// ^<font(\s*size="\d{1}")?(\s*color="((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)")?(\s*face="(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)")?\s*?>$
if (!IsMatch(tagname, @"<font
(\s*size=""\d{1}"")?
(\s*color=""((\#[0-9a-f]{6})|(\#[0-9a-f]{3})|red|green|blue|black|white)"")?
(\s*face=""(Arial|Courier\sNew|Garamond|Georgia|Tahoma|Verdana)"")?
\s*?>"))
{
html = html.Remove(tag.Index, tag.Length);
}
}
```
|
Your IsMatch Method is using the option `RegexOptions.IgnorePatternWhitespace`, that allows you to put comments inside the regular expressions, so you have to scape the # chatacter, otherwise it will be interpreted as a comment.
```
if (!IsMatch(tagname,@"<font(\s*size=""\d{1}"")?
(\s*color=""((\#[0-9a-f]{6})|(\#[0-9a-f]{3})|red|green|blue|black|white)"")?
(\s*face=""(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)"")?
\s?>"))
{
html = html.Remove(tag.Index, tag.Length);
}
```
|
I don't see anything obviously wrong with the regex. I would try isolating the problem by removing pieces of the regex until the problem goes away and then focus on the part that causes the issue.
|
Why is a left parenthesis being escaped in this Regex?
|
[
"",
"c#",
".net",
"regex",
""
] |
I'm using MSTEST inside Visual Studio 2008. How can I have each unit test method in a certain test class act as if it were the first test to run so that all global state is reset before running each test? I do not want to explicitly clean up the world using TestInitialize, ClassInitialize, AssemblyInitialize, etc. For example:
```
[TestClass]
public class MyClassTests
{
[TestMethod]
public void Test1()
{
// The "Instance" property creates a new instance of "SomeSingleton"
// if it hasn't been created before.
var i1 = SomeSingleton.Instance;
...
}
[TestMethod]
public void Test2()
{
// When I select "Test1" and "Test2" to run, I'd like Test2
// to have a new AppDomain feel so that the static variable inside
// of "SomeSingleton" is reset (it was previously set in Test1) on
// the call to ".Instance"
var i2 = SomeSingleton.Instance;
// some code
}
```
Although a [similar question](https://stackoverflow.com/questions/154180/how-does-nunit-and-mstest-handle-tests-that-change-staticshared-variables) appeared on this topic, it only clarified that tests do not run in parallel. I realize that tests run serially, but there doesn't seem to be a way to explicitly force a new AppDomain for each method (or something equivalent to clear all state).
Ideally, I'd like to specify this behavior for only a small subset of my unit tests so that I don't have to pay the penalty of a new AppDomain creation for tests that don't care about global state (the vast majority of my tests).
|
In the end, I wrote a helper that used [AppDomain.CreateDomain](http://msdn.microsoft.com/en-us/library/system.appdomain.createdomain.aspx) and then used reflection to call the unit test under a different AppDomain. It provides the isolation I needed.
[This post](http://social.msdn.microsoft.com/Forums/en-US/vststest/thread/130c923f-15cb-4a87-8d3b-0f9779080cfa/) on MSDN's forums shows how to handle the situation if you only have a few statics that need to be reset. [It](http://social.msdn.microsoft.com/Forums/en-US/vststest/thread/130c923f-15cb-4a87-8d3b-0f9779080cfa/) does mention some options (e.g. using Reflection and [PrivateType](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privatetype.aspx) ).
I continue to welcome any further ideas, especially if I'm missing something obvious about MSTEST.
|
Add a helper in your tests that uses reflection to delete the singleton instance (you can add a reset method to the singleton as well, but I would be concerned about its use). Something like:
```
public static class SingletonHelper {
public static void CleanDALFactory()
{
typeof(DalFactory)
.GetField("_instance",BindingFlags.Static | BindingFlags.NonPublic)
.SetValue(null, null);
}
}
```
Call this in your TestInitialize method. [ I know this is "cleaning up the world", but you only have to write the method once in a helper per singleton, its very trivial and gives you explicit control ]
|
How to force a MSTEST TestMethod to reset all singletons/statics before running?
|
[
"",
"c#",
"unit-testing",
"visual-studio-2008",
"mstest",
"appdomain",
""
] |
I've been writing a lot recently about Parallel computing and programming and I do notice that there are a lot of patterns that come up when it comes to parallel computing. Noting that Microsoft already has released a library along with the Microsoft Visual C++ 2010 Community Technical Preview (named Parallel Patterns Library) I'm wondering what are the common parallel programming patterns you have been using and encountering that may be worth remembering? Do you have any idioms you follow and patterns that you seem to keep popping up as you write parallel programs with C++?
|
Patterns:
* Produce/Consumer
+ One Thread produces data
+ One Thread consumes the data
* Loop parallelism
+ If you can show that each loop is independent
each iteration can be done in a sperate thread
* Re-Draw Thread
+ Other threads do work and update data structures but one thread re-draws screen.
* Main-Event Thread
+ Multiple threads can be generating events
+ One thread has to processes the events (as order is important)
+ Should try separate the Event Thread/Re-Draw Thread
This (helps) prevents the UI from freezing
But may cause excessive re-draws if not done carefully.
* Work Group
+ A set of threads waits for jobs on a que.
+ Thread extract one work item from queue (waiting if none is available).
Thread works on one work item until complete
Once completed thread returns to queue.
|
First you have to chose between shared-memory computing, and shared-nothing computing. Shared memory is easier, but doesn't scale that well - you will use shared-nothing if you either
a) have a cluster, rather than a multiprocessor system, or
b) if you have many CPUs (say, > 60), and a high degree of non-uniform memory
For shared-memory, the common solution is to use threads; they are easy to understand as a concept, and easy to use in the API (but difficult to debug).
For shared-nothing, you use some kind of messaging. In high-performance computing, MPI is established as the messaging middleware.
You then also need to design an architecture for the parallel activities. The most common approach (again because it's easy to understand) is the farmer-worker-pattern (a.k.a. master-slave).
|
Parallel Programming and C++
|
[
"",
"c++",
"design-patterns",
"parallel-processing",
"idioms",
""
] |
Will their be a new release of the compact framework with VS2010 and .net 4.0 and if so what new features will it include?
WPF?
linq to SQL?
etc
|
Visual Studio 2010 only supports developing for windows phone 7. This is a silver light based framework, it does not support win forms or native code.
VS2010 can not be used to develop for Windows Mobile 6.5 or lower.
You can however install VS2008 along side VS2010.
|
From what I heard from guys in redmond, there will be a mobile silverlight platform for both windows mobile and nokia (symbian, I think).
The "silverlight mobile" platform should be built on top of the compact framework, so it will NOT be a port of the desktop version.
There seems to be an information embargo on Windows Mobile right now, but I think things will be much clearer once Windows Mobile 7 is out.
|
.net Compact Framework 4.0
|
[
"",
"c#",
".net",
"compact-framework",
""
] |
I was loading a Bitmap Image from a File. When I tried to save the Image to another file I got the following error "A generic error occurred in GDI+". I believe this is because the file is locked by the image object.
Ok so tried calling the Image.Clone function. This still locks the file.
hmm. Next I try loading a Bitmap Image from a FileStream and load the image into memory so GDI+ doesn't lock the file. This works great except I need to generate thumbnails using Image.GetThumbnailImage method it throws an out of memory exception. Apparently I need to keep the stream open to stop this exception but if I keep the stream open then the file remains locked.
So no good with that method. In the end I created a copy of the file. So now I have 2 versions of the file. 1 I can lock and manipulate in my c# program. This other original file remains unlocked to which I can save modifications to. This has the bonus of allowing me to revert changes even after saving them because I'm manipulating the copy of the file which cant change.
Surely there is a better way of achieving this without having to have 2 versions of the image file. Any ideas?
|
I have since found an alternative method to clone the image without locking the file. [Bob Powell has it all plus more GDI resources](https://web.archive.org/web/20120419185819/http://www.bobpowell.net/imagefileconvert.htm).
```
//open the file
Image i = Image.FromFile(path);
//create temporary
Image t=new Bitmap(i.Width,i.Height);
//get graphics
Graphics g=Graphics.FromImage(t);
//copy original
g.DrawImage(i,0,0);
//close original
i.Dispose();
//Can now save
t.Save(path)
```
|
Well if you're looking for other ways to do what you're asking, I reckon it should work to create a MemoryStream, and read out the FileStream to it, and load the Image from that stream...
```
var stream = new FileStream("original-image", FileMode.Open);
var bufr = new byte[stream.Length];
stream.Read(bufr, 0, (int)stream.Length);
stream.Dispose();
var memstream = new MemoryStream(bufr);
var image = Image.FromStream(memstream);
```
Or something prettier to that extent.
Whether or not that's the way you should go about solving that problem, I don't know. :)
I've had a similar problem and wound up fixing it like this.
|
Saving a modified image to the original file using GDI+
|
[
"",
"c#",
"gdi+",
"image-manipulation",
""
] |
It appears that Directory.GetFiles() in C# modifies the Last access date of a file.
I've googled for hours and can't seem to find a work around for this issue. Is there anyway to keep all the MAC (Modified, Accessed, Created) attributes of a file?
I'm using Directory.GetDirectories(), Directory.GetFiles(), and FileInfo.
Also, the fi.LastAccessTime is giving strange results -- the date is correct, however, the time is off by 2 minutes, or a few hours.
```
Time of function execution: 10/31/2008 8:35 AM
Program Shows As Last Access Time
0_PDFIndex.html - 10/31/2008 8:17:24 AM
AdvancedArithmetic.pdf - 10/31/2008 8:31:05 AM
AdvancedControlStructures.pdf - 10/30/2008 1:18:00 PM
AoAIX.pdf - 10/30/2008 1:18:00 PM
AoATOC.pdf - 10/30/2008 12:29:51 PM
AoATOC2.pdf - 10/30/2008 1:18:00 PM
Actual Last Access Time
0_PDFIndex.html - 10/31/2008 8:17 AM
AdvancedArithmetic.pdf - 10/30/2008 12:29 PM
AdvancedControlStructures.pdf - 10/30/2008 12:29 PM
AoAIX.pdf - 10/30/2008 12:29 PM
AoATOC.pdf - 10/30/2008 12:29 PM
AoATOC2.pdf - 10/30/2008 12:29 PM
```
Below is the method I'm using. If you require more information, please let me know.
Thanks!
```
public void PopulateTreeView(string directoryValue, ref TreeNode parentNode)
{
string[] directoryArray = Directory.GetDirectories(directoryValue);
string[] fileArray = Directory.GetFiles(directoryValue, "*.*", SearchOption.AllDirectories);
try
{
#region Directories
if (directoryArray.Length != 0)
{
foreach (string directory in directoryArray)
{
DirectoryInfo di = new DirectoryInfo(directory);
TreeNode dirNode = parentNode.Nodes.Add(di.Name);
FileNode fn = new FileNode();
fn.bIsDir = true;
fn.dir = di;
dirNode.Tag = fn;
PopulateTreeView(directory, ref dirNode);
Application.DoEvents();
}
}
#endregion
#region Files
if (fileArray.Length != 0)
{
foreach (string file in fileArray)
{
FileInfo fi = new FileInfo(file);
TreeNode fileNode = parentNode.Nodes.Add(fi.Name);
FileNode fn = new FileNode();
fn.bIsDir = false;
fn.file = fi;
fileNode.Tag = fn;
fileNode.ImageIndex = 1;
Console.WriteLine(fi.Name + " - " + fi.LastAccessTime);
}
}
#endregion
}
catch (UnauthorizedAccessException)
{
parentNode.Nodes.Add("Access denied");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
Application.DoEvents();
}
}
```
---
i know the differences between the attributes. What i need is for the file to remain exactly the same all attributes and meta-data, as if my program never touched the file; this includes the last access date.
|
I know this is far from ideal, but u can use fsutil (provided with Windows) to disable last access time writing:
```
fsutil behavior set disablelastaccess 1
```
Presumably you'd set it back to 0 once done. You can invoke this using Process.Start from C#, but there must be a better programmatic way (calling into Windows API).
```
Process.Start("fsutil", "behavior set disablelastaccess 1").WaitForExit();
```
Do note that this is a global Windows setting and would also affect disk access from outside your app...
|
Access times are different from last write times. If you use fi.LastWriteTime I think you will find that the times are the same displayed in explorer or cmd window.
Of course the last access and last write could be the same, but they are not necessarily the same.
|
Directory.GetFiles keeping the last access time
|
[
"",
"c#",
"lastaccesstime",
""
] |
Suppose we have a vector/array in C++ and we wish to count which of these N elements has maximum repetitive occurrences and output the highest count. Which algorithm is best suited for this job.
example:
```
int a = { 2, 456, 34, 3456, 2, 435, 2, 456, 2}
```
the output is 4 because 2 occurs 4 times. That is the maximum number of times 2 occurs.
|
Sort the array and then do a quick pass to count each number. The algorithm has O(N\*logN) complexity.
Alternatively, create a hash table, using the number as the key. Store in the hashtable a counter for each element you've keyed. You'll be able to count all elements in one pass; however, the complexity of the algorithm now depends on the complexity of your hasing function.
|
**Optimized for space:**
Quicksort (for example) then iterate over the items, keeping track of largest count only.
At best O(N log N).
**Optimized for speed:**
Iterate over all elements, keeping track of the separate counts.
This algorithm will always be O(n).
|
Finding Frequency of numbers in a given group of numbers
|
[
"",
"c++",
"c",
"algorithm",
"puzzle",
"frequency",
""
] |
The following have been proposed for an upcoming C++ project.
* C++ Coding Standards, by Sutter and Alexandrescu
* JSF Air Vehicle C++ coding standards
* The Elements of C++ Style
* Effective C++ 3rd Edition, by Scott Meyers
Are there other choices? Or is the list above what be should used on a C++ project?
Some related links
* [Do you think a software company should impose developers a coding-style?](https://stackoverflow.com/questions/145508/do-you-think-a-software-company-should-impose-developers-a-coding-style)
* <https://stackoverflow.com/questions/66268/what-is-the-best-cc-coding-style-closed>
|
I really think it does not matter which one you adopt, as long as everyone goes along with it. Sometimes that can be hard as it seems that some styles don't agree with peoples tases. I.e. it comes down to arguing about whether prefixing all member variable with `m_` is *pretty* or not.
I have been using and modifying the [Geosoft](http://geosoft.no/development/cppstyle.html) standards for a while, these are for C++. There are some other at the [what-is-your-favorite-coding-guidelines-checklist](https://stackoverflow.com/questions/409/what-is-your-favorite-coding-guidelines-checklist#139459) thread
|
[C++ Coding Standards: 101 Rules, Guidelines, and Best Practices](https://rads.stackoverflow.com/amzn/click/com/0321113586) (C++ In-Depth Series)
by Herb Sutter and, Andrei Alexandrescu.
|
Existing Standard Style and Coding standard documents
|
[
"",
"c++",
"coding-style",
"documentation",
"standards",
""
] |
As just stated in a recent [question](https://stackoverflow.com/questions/135759/why-cant-i-inherit-iodirectory) and [answer](https://stackoverflow.com/questions/135759/why-cant-i-inherit-iodirectory#135772), you can't inherit from a static class. How does one enforce the rules that go along with static classes inside VB.NET? Since the framework is compatible between C# and VB it would make sense that there would be a way to mark a class static, but there doesn't seem to be a way.
|
Module == static class
If you just want a class that you can't inherit, use a `NotInheritable` class; but it won't be static/Shared. You could mark all the methods, properties, and members as `Shared`, but that's not strictly the same thing as a static class in C# since it's not enforced by the compiler.
If you really want the VB.Net equivalent to a C# static class, use a `Module`. It can't be inherited and all members, properties, and methods are static/shared.
|
Almost there. You've got to prevent instantiation, too.
```
NotInheritable Class MyStaticClass
''' <summary>
''' Prevent instantiation.
''' </summary>
Private Sub New()
End Sub
Public Shared Function MyMethod() As String
End Function
End Class
```
* Shared is like method of static class.
* NotInheritable is like sealed.
* Private New is like static class can not be instantiated.
See:
[MSDN - Static Classes and Static Class Members](http://msdn.microsoft.com/en-us/library/79b3xss3%28v=vs.90%29.aspx)
|
Marking A Class Static in VB.NET
|
[
"",
"c#",
"vb.net",
""
] |
During execution, how can a java program tell how much memory it is using?
I don't care how efficient it is!
|
VonC's answer is an interactive solution - if you want to know programatically, you can use [Runtime.totalMemory()](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#totalMemory()) to find out the total amount used by the JVM, and [Runtime.freeMemory()](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#freeMemory()) to find out how much of that is still available (i.e. it's allocated *to* the JVM, but not allocated *within* the JVM - new objects can use this memory).
These are instance methods - use [Runtime.getRuntime()](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#getRuntime()) to first get the singleton instance.
|
If you are have a java1.6 somewhere and your program is running in java 1.4.2, 1.5 or 1.6, you can launch a [visualVM session](https://visualvm.dev.java.net/), connect to your application, and follow the memory (and much more)

(The images are not displayed at the moment, so please refers to [Monitoring an application](https://visualvm.dev.java.net/monitor_tab.html) for an illustration.)
|
During execution, how can a java program tell how much memory it is using?
|
[
"",
"java",
"memory",
"runtime",
""
] |
What is the best jQuery status message plugin?
I like [jGrowl](http://plugins.jquery.com/project/jgrowl) and [Purr](http://plugins.jquery.com/project/purr), but jGrowl doesn't have the feature to remain sticky (not close automatially) and Purr doesn't seem to work right in IE 6.
I would like to show messages like... the site is about to go down for maintenance, your such and such job has completed, and stuff like that.
|
jGrowl does look to have sticky - see sample 2 in the demo page:
<https://github.com/stanlemon/jGrowl>
...ah - or did you mean after the page has reloaded?
I would then handle this on the server side - i.e. include a sitedown.js that triggers the growl notice each time any page is visited.
|
A few options...
* [Humanized Messages](http://code.google.com/p/humanmsg/) ([demo](http://binarybonsai.com/misc/humanmsg/), 3 KB) looks very cool, and has a nice history rollout
* [Pines Notify](http://sciactive.github.io/pnotify/) (13 KB) is extremely customizable and supports jQuery UI themes
* [jGrowl](https://github.com/stanlemon/jGrowl) (6 KB) does actually have a sticky option - use { sticky: true }
|
Best jQuery Status Message Plugin?
|
[
"",
"javascript",
"jquery",
"plugins",
"jquery-plugins",
"user-interface",
""
] |
On large tables in MSSQL; selecting specific columns results in greater speed of the query. Does the same apply to Linq to SQL?
Would this:
```
var person = from p in [DataContextObject].Persons
where p.PersonsID == 1
select new { p.PersonsID, p.PersonsAdress, p.PersonsZipcode };
```
be faster than this:
```
var person = from p in [DataContextObject].Persons
where p.PersonsID == 1
select p;
```
... ?
|
I highly recommend [LinqPad](http://linqpad.net/). It is free and lets you run LINQ queries dynamically. When you can also look at the SQL that is generated.
What you will see is that the LINQ query will translate the first query into selecting only those columns. So it is faster.
|
If you are limiting the size of the result set by only selecting a few specific columns, then YES it will have an affect.
**EDIT** ading clarification from comment
How is this better, it will reduce the size of the resultant data returned from SQL AND it will reduce the size of the objects used to store the results in memory.
This is due to the fact that in the end LINQ to SQL generates SQL, so the same performance benefits exist.
|
Linq to SQL: select optimization
|
[
"",
"sql",
"performance",
"linq-to-sql",
""
] |
I recently introduced HTML into some RSS feeds that I publish (which up to now only had plain text, no markup), and I was wondering which method is better: use character encoding (such as htmlspecialchars) or just encapsulate everything in CDATA?
It seems to me that CDATA might be easier, but I'm unclear as to whether there might be any reasons (subtle or otherwise) for choosing one approach versus the other. (For starters, the CDATA approach would be easier to read when viewing source...)
|
CDATA is for any data that should not be parsed by the XML parser. Any tags not in a CDATA block **will** be parsed by the XML parser and may take on a different meaning.
CDATA can also incur an overhead for the parsers if there is no need for it. Try to avoid CDATA blocks any time you know HTML (or otherwise) won't be used, otherwise use it.
That said, I do agree with jamesh, in that you should always prefer Atom over RSS. I produce a feed reader and when scraping feeds, always prefer Atom over RSS.
|
Personally CDATA is easier, as it allows the display of the actual HTML by the subscriber without their reader needing to do anything funny.
If you use HTML Encoding, the subscribers reader, or website iteself, must decode the source to display the HTML
|
Which is better for encoding HTML for RSS?
|
[
"",
"php",
"rss",
"cdata",
""
] |
Is there any method?
My computer is AMD64.
```
::std::string str;
BOOL loadU(const wchar_t* lpszPathName, int flag = 0);
```
When I used:
```
loadU(&str);
```
the VS2005 compiler says:
```
Error 7 error C2664:: cannot convert parameter 1 from 'std::string *__w64 ' to 'const wchar_t *'
```
How can I do it?
|
If you have a std::wstring object, you can call `c_str()` on it to get a `wchar_t*`:
```
std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();
```
Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in [`MultiByteToWideChar`](http://msdn.microsoft.com/en-us/library/dd319072%28v=vs.85%29.aspx) routine. That will give you an `LPWSTR`, which is equivalent to `wchar_t*`.
|
First convert it to std::wstring:
```
std::wstring widestr = std::wstring(str.begin(), str.end());
```
Then get the C string:
```
const wchar_t* widecstr = widestr.c_str();
```
This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByteToWideChar() ensures that this scenario is handled properly.
|
I want to convert std::string into a const wchar_t *
|
[
"",
"c++",
"stl",
"wchar-t",
"stdstring",
""
] |
I am all about using ASP.NET MVC, but one of the areas that I hope gets improved on is Client-Side Validation.
I know the most recent version (Preview 5) has a lot of new features for Validation, but they all seem to be after the page has been posted.
I have seen an interesting article by [Steve Sanderson](http://blog.codeville.net/2008/04/30/model-based-client-side-validation-for-aspnet-mvc/)... using Live Validation, Castle.Components.Validator.dll, and a Validator framework he made.
I have used it in my project, but I am hoping something like it will get integrated into the official ASP.NET MVC release. I definitely think the business rules should reside either on the model or in the controller rather than in the View.
Have any of you used a similar approach?
Are you aware of something like this being added to the official ASP.NET MVC release?
|
*"Obviously you'll still need to validate your input on the server side for the small percentage of users who disable javascript."*
Just an update to this comment. Server-side validation has nothing to do with users that run with JavaScript disabled. Instead, it is needed for security reasons, and to do complex validation that can't be done on the client. A form should always have server-side validation. Client-side validation is only there as a convenience.
A malicious user could easily post data to your form bypassing any client-side validation that you have in place. **Never trust input data!**
|
I agree with other posters, client side validation is strictly for improving user experience.
Check out the [JQuery Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) plugin. It's super easy to get started with basic validation -- literally one line of JS plus adding class names to the input controls. It's also very powerful. You can extend to do whatever you want.
|
ASP.NET MVC Client Side Validation
|
[
"",
"javascript",
"asp.net-mvc",
"validation",
"client-side",
""
] |
Ok, this probably has a really simple answer, but I've never tried to do it before: How do you launch a web page from within an app? You know, "click here to go to our FAQ", and when they do it launches their default web browser and goes to your page. I'm working in C/C++ in Windows, but if there's a broader, more portable way to do it I'd like to know that, too.
|
```
#include <windows.h>
void main()
{
ShellExecute(NULL, "open", "http://yourwebpage.com",
NULL, NULL, SW_SHOWNORMAL);
}
```
|
I believe you want to use the ShellExecute() function which should respect the users choice of default browser.
|
Launch web page from my application
|
[
"",
"c++",
"c",
"windows",
"browser",
""
] |
I've worked on several PHP projects and always I have problems with organizing my work. Where do you develop your application - on localhost, remote server or maybe production one(!) ?
When I work on my localhost after making some major path I send new files by ftp - but sometimes it happens to forget about one file and it is just tiring to browse several directiores to copy changed files.
What best practises do you propose?
|
This is how we manage our commercial site:
1. Develop in a local sand box
2. Check-in to SVN
3. Automated build/test from SVN onto internal
dev server
4. Scripted deploy using rsync to staging
server for QA/UAT
5. Scripted deploy onto production
servers.
Staging and production servers are both hosted by the ISP and are hardware and version matched and run RHEL, internal Dev server is version matched CentOS.
This way, when code hits the production servers there shouldn't be any nasty surprises as even the deploy scripts get checked in stage 4.
|
[Google App Engine](http://code.google.com/appengine/) has an apposite tool that automatically uploads to the production environment files that are modified; don't know if there's something similar for PHP.
So, doing a dev2prod script (a script that does this automatically) should be a good solution.
To do local source file management, everyone may suggest you to use a [source code control system](http://en.wikipedia.org/wiki/Revision_control).
|
How do you manage PHP Project Development Lifecycle?
|
[
"",
"php",
"lifecycle",
""
] |
One of classes in my program uses some third-party library. Library object is a private member of my class:
```
// My.h
#include <3pheader.h>
class My
{
...
private:
3pObject m_object;
}
```
The problem with this - any other unit in my program that uses My class should be configured to include 3p headers. Moving to another kind of 3p will jeopardize the whole build...
I see two ways to fix this - one is to is to make 3pObject extern and turn m\_Object into a pointer, being initialized in constructor; second is to create an "interface" and "factory" classes and export them...
Could you suggest another ways to solve that ?
|
Use the "pimpl" idiom:
```
// header
class My
{
class impl;
std::auto_ptr<impl> _impl;
};
// cpp
#include <3pheader.h>
class My::impl
{
3pObject _object;
};
```
|
The Private Implementation (PIMPL) pattern:
<http://www.codeproject.com/KB/tips/PIMPL.aspx>
Basically, you define that your class holds a pointer to a struct that you forward declare. Then you define the struct inside the cpp file and use the constructor and destructor in your class to create/delete the PIMPL.
:)
|
C++ headers - separation between interface and implementation details
|
[
"",
"c++",
"coding-style",
""
] |
I'm new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them.
The problem I'm having is that in my data access layer, I want to have static methods, but I can't put a static method in an interface.
What's the best way around this? Should I just use instance methods (which seems wrong) or is there another solution?
|
I would use a method object pattern. Have a static instance of this, and call it in the static method. It should be possible to subclass for testing, depending on your mocking framework.
i.e. in your class with the static method have:
```
private static final MethodObject methodObject = new MethodObject();
public static void doSomething(){
methodObject.doSomething();
}
```
and your method object can be a very simple, easily-tested:
```
public class MethodObject {
public void doSomething() {
// do your thang
}
}
```
|
Yes, you use instance methods. Static methods basically say, "There is one way to accomplish this functionality - it's not polymorphic." Mocking relies on polymorphism.
Now, if your static methods logically don't care about what implementation you're using, they might be able to take the interfaces as parameters, or perhaps work without interacting with state at all - but otherwise you should be using instances (and probably dependency injection to wire everything together).
|
How to mock with static methods?
|
[
"",
"c#",
".net",
"mocking",
"interface",
"static-methods",
""
] |
I'm currently writing an edit-in-place script for MooTools and I'm a little stumped as to how I can make it degrade gracefully without JavaScript while still having some functionality. I would like to use progressive enhancement in some way. I'm not looking for code, but more a concept as to how one would approach the situation. If you have any ideas or know of any edit-in-place scripts that degrade gracefully, please share.
|
It sounds like you might be approaching this from the wrong direction. Rather than creating the edit-in-place and getting it degrade nicely (the Graceful Degradation angle), you should really be creating a non-Javascript version for editing and then adding the edit-in-place using Javascript after page load, reffered to as [Progressive Enhancement](http://en.wikipedia.org/wiki/Progressive_enhancement).
There are two options for this. Create the display as a form with a submit button that works without Javascript, then using Javascript replace the inputs with some kind of label that performs the edit-in-place. You should be able to use a combination of labels and id attributes to pick out the correct properties for your edit-in-place implementation to work. The other option if you don't want a form to display by default is to display the values with an button/link for turning it into a form using server-side processing, then adding the edit-in-palce to that.
|
You can't do edit-in-place at all without JavaScript, so graceful degradation for it consists of making sure that the user can still edit the item in question when JavaScript isn't available.
As such, I'd just have a link to edit the entire item in question and then create the edit-in-place controls in JavaScript on page load, hiding the edit link if you'd rather than users use edit-in-place when available.
|
Any ideas on how to make edit-in-place degradable?
|
[
"",
"javascript",
"mootools",
"graceful-degradation",
"progressive-enhancement",
"edit-in-place",
""
] |
Given the following java enum:
```
public enum AgeRange {
A18TO23 {
public String toString() {
return "18 - 23";
}
},
A24TO29 {
public String toString() {
return "24 - 29";
}
},
A30TO35 {
public String toString() {
return "30 - 35";
}
},
}
```
Is there any way to convert a string value of "18 - 23" to the corresponding enum value i.e. AgeRange.A18TO23 ?
Thanks!
|
The best and simplest way to do it is like this:
```
public enum AgeRange {
A18TO23 ("18-23"),
A24TO29 ("24-29"),
A30TO35("30-35");
private String value;
AgeRange(String value){
this.value = value;
}
public String toString(){
return value;
}
public static AgeRange getByValue(String value){
for (final AgeRange element : EnumSet.allOf(AgeRange.class)) {
if (element.toString().equals(value)) {
return element;
}
}
return null;
}
}
```
Then you just need to invoke the `getByValue()` method with the `String` input in it.
|
You could always create a map from string to value - do so statically so you only need to map it once, assuming that the returned string remains the same over time. There's nothing built-in as far as I'm aware.
|
How to convert string result of enum with overridden toString() back to enum?
|
[
"",
"java",
"enums",
"enumeration",
"converters",
""
] |
I have a form a user can enter their name, then it will add it to $message to be sent in an email.
Is it better to use `$_POST` or `$_REQUEST`?
Here is a snippet of using `$_REQUEST`
```
$message.= "Name: ".$_REQUEST["fname"]." ".$_REQUEST["mname"]." ".$_REQUEST["lname"]."\n";
```
|
The answer is: It depends on how you want it to be used.
If you're using `$_POST`, that means it can only come in via POST.
If you're using `$_REQUEST`, that means you accept POST, GET (and COOKIE, but it's mainly the first two we're interested in).
For something like this, `$_POST` would probably be neater, but if you were making a search engine, allowing to set up a search URL would probably be a good idea. However, you might want to allow for a ton of special parameters to narrow down the search, and if that can take up a lot of URL space, you'll probably want to allow POSTDATA as well.
As Dylan mentions, keep in mind that neither is a replacement for any kind of security.
|
My approach used to be to use **$\_REQUEST** for everything which I think is a big mistake. Lately, I've been trying to be more diligent about using GET only for read-requests & POST only for write-requests.
To that end, I think using **$\_GET** for GET requests & **$\_POST** for POST requests makes my intent much more clear in my code.
|
When posting info from a form, is it better to use $_REQUEST or $_POST?
|
[
"",
"php",
""
] |
In DB2, you can name a column ORDER and write SQL like
```
SELECT ORDER FROM tblWHATEVER ORDER BY ORDER
```
without even needing to put any special characters around the column name. This is causing me pain that I won't get into, but my question is: why do databases allow the use of SQL keywords for object names? Surely it would make more sense to just not allow this?
|
I largely agree with the sentiment that keywords shouldn't be allowed as identifiers. Most modern computing languages have 20 or maybe 30 keywords, in which case imposing a moratorium on their use as identifiers is entirely reasonable. Unfortunately, SQL comes from the old COBOL school of languages ("computing languages should be as similar to English as possible"). Hence, SQL (like COBOL) has several [hundred keywords](http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/topic/com.ibm.db2.luw.sql.ref.doc/doc/r0001095.html).
I don't recall if the SQL standard says anything about whether reserved words *must* be permitted as identifiers, but given the extensive (excessive!) vocabulary it's unsurprising that several SQL implementations permit it.
Having said that, using keywords as identifiers isn't half as silly as the whole concept of quoted identifiers in SQL (and these aren't DB2 specific). Permitting case sensitive identifiers is one thing, but quoted identifiers permit all sorts of nonsense including spaces, diacriticals and in some implementations (yes, including DB2), control characters! Try the following for example:
```
CREATE TABLE "My
Tablé" ( A INTEGER NOT NULL );
```
Yes, that's a line break in the middle of an identifier along with an e-acute at the end... (which leads to interesting speculation on what encoding is used for database meta-data and hence whether a non-Unicode database would permit, say, a table definition containing Japanese column names).
|
Many SQL parsers (expecially DB2/z, which I use) are smarter than some of the regular parsers which sometimes separate lexical and semantic analysis totally (this separation is mostly a good thing).
The SQL parsers can figure out based on context whether a keyword is valid or should be treated as an identifier.
Hence you can get columns called ORDER or GROUP or DATE (that's a particularly common one).
It does annoy me with some of the syntax coloring editors when they brand an identifier with the keyword color. Their parsers aren't as 'smart' as the ones in DB2.
|
Why can you have a column named ORDER in DB2?
|
[
"",
"sql",
"database",
"db2",
""
] |
How do I query an Oracle database to display the names of all tables in it?
|
```
SELECT owner, table_name
FROM dba_tables
```
This is assuming that you have access to the `DBA_TABLES` data dictionary view. If you do not have those privileges but need them, you can request that the DBA explicitly grants you privileges on that table, or, that the DBA grants you the `SELECT ANY DICTIONARY` privilege or the `SELECT_CATALOG_ROLE` role (either of which would allow you to query any data dictionary table). Of course, you may want to exclude certain schemas like `SYS` and `SYSTEM` which have large numbers of Oracle tables that you probably don't care about.
Alternatively, if you do not have access to `DBA_TABLES`, you can see all the tables that your account has access to through the `ALL_TABLES` view:
```
SELECT owner, table_name
FROM all_tables
```
Although, that may be a subset of the tables available in the database (`ALL_TABLES` shows you the information for all the tables that your user has been granted access to).
If you are only concerned with the tables that you own, not those that you have access to, you could use `USER_TABLES`:
```
SELECT table_name
FROM user_tables
```
Since `USER_TABLES` only has information about the tables that you own, it does not have an `OWNER` column – the owner, by definition, is you.
Oracle also has a number of legacy data dictionary views-- `TAB`, `DICT`, `TABS`, and `CAT` for example-- that could be used. In general, I would not suggest using these legacy views unless you absolutely need to backport your scripts to Oracle 6. Oracle has not changed these views in a long time so they often have problems with newer types of objects. For example, the `TAB` and `CAT` views both show information about tables that are in the user's recycle bin while the `[DBA|ALL|USER]_TABLES` views all filter those out. `CAT` also shows information about materialized view logs with a `TABLE_TYPE` of "TABLE" which is unlikely to be what you really want. `DICT` combines tables and synonyms and doesn't tell you who owns the object.
|
Querying `user_tables` and `dba_tables` didn't work.
This one did:
```
select table_name from all_tables
```
|
Get list of all tables in Oracle?
|
[
"",
"sql",
"oracle",
""
] |
In Visual Studio 2008 in a C# WinForms project, there is a button on a form. In the properties view, the property "Font" is set to "Arial Unicode MS".
What do I need to put into the property "Text", so I get the unicode character \u0D15 displayed on the button?
When I put \u0D15 into the "Text" property, the button displays the six characters "\u0D15" instead of one unicode character.
In the following PDF, you can see the unicode character for \u0D15:
<http://unicode.org/charts/PDF/U0D00.pdf>
|
You don't have to escape your unicode characters in strings as C# is inherently unicode. Just put your unicode characters as they are into the string. For example:
```
button1.Text = "日本";
```
|
One possible way is to run "charmap" and copypaste from there or copypaste it from elsewhere.
|
How to put unicode characters on a System.Windows.Forms.Button in C#?
|
[
"",
"c#",
"visual-studio",
"unicode",
"character",
""
] |
I am trying to adapt an existing code to a 64 bit machine. The main problem is that in one function, the previous coder uses a void\* argument that is converted into suitable type in the function itself. A short example:
```
void function(MESSAGE_ID id, void* param)
{
if(id == FOO) {
int real_param = (int)param;
// ...
}
}
```
Of course, on a 64 bit machine, I get the error:
```
error: cast from 'void*' to 'int' loses precision
```
I would like to correct this so that it still works on a 32 bit machine and as cleanly as possible. Any idea ?
|
Use `intptr_t` and `uintptr_t`.
To ensure it is defined in a portable way, you can use code like this:
```
#if defined(__BORLANDC__)
typedef unsigned char uint8_t;
typedef __int64 int64_t;
typedef unsigned long uintptr_t;
#elif defined(_MSC_VER)
typedef unsigned char uint8_t;
typedef __int64 int64_t;
#else
#include <stdint.h>
#endif
```
Just place that in some .h file and include wherever you need it.
Alternatively, you can download Microsoft’s version of the `stdint.h` file from [here](http://msinttypes.googlecode.com/svn/trunk/stdint.h">http://msinttypes.googlecode.com/svn/trunk/stdint.h) or use a portable one from [here](http://www.azillionmonkeys.com/qed/pstdint.h">http://www.azillionmonkeys.com/qed/pstdint.h).
|
I'd say this is the modern C++ way:
```
#include <cstdint>
void *p;
auto i = reinterpret_cast<std::uintptr_t>(p);
```
**EDIT**:
## The correct type to the the Integer
So the right way to store a pointer as an integer is to use the `uintptr_t` or `intptr_t` types. (See also in cppreference [integer types for C99](http://en.cppreference.com/w/c/types/integer)).
These types are defined in `<stdint.h>` for C99 and in the namespace `std` for C++11 in `<cstdint>` (see [integer types for C++](http://en.cppreference.com/w/cpp/types/integer)).
**C++11 (and onwards) Version**
```
#include <cstdint>
std::uintptr_t i;
```
**C++03 Version**
```
extern "C" {
#include <stdint.h>
}
uintptr_t i;
```
**C99 Version**
```
#include <stdint.h>
uintptr_t i;
```
## The correct casting operator
In C there is only one cast and using the C cast in C++ is frowned upon (so don't use it in C++). In C++ there are different types of casts, but `reinterpret_cast` is the correct cast for this conversion (see also [here](http://en.cppreference.com/w/cpp/language/reinterpret_cast)).
**C++11 Version**
```
auto i = reinterpret_cast<std::uintptr_t>(p);
```
**C++03 Version**
```
uintptr_t i = reinterpret_cast<uintptr_t>(p);
```
**C Version**
```
uintptr_t i = (uintptr_t)p; // C Version
```
## Related Questions
* [What is uintptr\_t data type](https://stackoverflow.com/questions/1845482/what-is-uintptr-t-data-type)
|
Converting a pointer into an integer
|
[
"",
"c++",
"gcc",
"casting",
"64-bit",
"32-bit",
""
] |
I am having dependency troubles. I have two classes: `Graphic` and `Image`. Each one has its own .cpp and .h files. I am declaring them as the following:
`Graphic.h`:
```
#include "Image.h"
class Image;
class Graphic {
...
};
```
`Image.h`:
```
#include "Graphic.h"
class Graphic;
class Image : public Graphic {
...
};
```
When I try to compile, I get the following error:
```
Image.h:12: error: expected class-name before ‘{’ token
```
If I remove the forward declaration of `Graphic` from `Image.h` I get the following error:
```
Image.h:13: error: invalid use of incomplete type ‘struct Graphic’
Image.h:10: error: forward declaration of ‘struct Graphic’
```
|
This worked for me:
Image.h:
```
#ifndef IMAGE_H
#define IMAGE_H
#include "Graphic.h"
class Image : public Graphic {
};
#endif
```
Graphic.h:
```
#ifndef GRAPHIC_H
#define GRAPHIC_H
#include "Image.h"
class Graphic {
};
#endif
```
The following code compiles with no error:
```
#include "Graphic.h"
int main()
{
return 0;
}
```
|
You don't need to include Image.h or forward declare Image in Graphic.h - that's a circular dependency. If Graphic.h depends on anything in Image.h you need to split that out into a third header. (If Graphic has an Image member, that just isn't going to work.)
|
How do you inherit from a class in a different header file?
|
[
"",
"c++",
"inheritance",
"organization",
""
] |
Do you have any sugestions of tools to ease the task of understanding C/C++ code? We just inherited a large piece of software written by others and we need to quickly get up to speed on it. Any advice on tools that might simplify this task?
|
[SourceInsight](http://sourceinsight.com) and [Understand for C++](http://www.scitools.com) are the best tools you can get for c/c++ code analysis including flow charts.
|
Profiling software gives you an idea of which functions have been called.
If you can use Linux, try [KCachegrind](https://kcachegrind.github.io/html/Home.html)
|
Tool to visualise code flow (C/C++)
|
[
"",
"c++",
"c",
"code-analysis",
""
] |
The interop library is slow and needs MS Office installed.
Many times you don't want to install MS Office on servers.
I'd like to use [Apache POI](http://en.wikipedia.org/wiki/Apache_POI), but I'm on .NET.
I need only to extract the text portion of the files, not creating nor "storing information" in Office files.
I need to tell you that I've got a very large document library, and I can't convert it to newer XML files.
I don't want to write a parser for the binaries files.
A library like Apache POI does this for us. Unfortunately, it is only for the Java platform. Maybe I should consider writing this application in Java.
I am still not finding an open source alternative to POI in .NET, I think I'll write my own application in Java.
|
For all MS Office versions:
* You could use the third-party components like [TX Text Controls](http://www.textcontrol.com/) for Word and [TMS Flexcel Studio](http://www.tmssoftware.com/site/flexcelnet.asp) for Excel
For the new Office (2007):
* You could do some basic stuff using .net functionality from `system.io.packaging`. See how at <http://msdn.microsoft.com/en-us/library/bb332058.aspx>
For the old Office (before 2007):
* The old Office formats are now documented: <http://www.microsoft.com/interop/docs/officebinaryformats.mspx>. If you want to do something really easy you might consider trying it. But be aware that these formats are VERY complex.
|
Check out the [Aspose components](http://www.aspose.com/categories/default.aspx). They are designed to mimic the Interop functionality without requiring a full Office install on a server.
|
How can I read MS Office files in a server without installing MS Office and without using the Interop Library?
|
[
"",
"java",
".net",
"apache",
"ms-office",
"office-interop",
""
] |
I am new to PHP and trying to get the following code to work:
```
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
"ARTICLE_NO :{$row['ARTICLE_NO']} <br>" .
"ARTICLE_NAME :{$row['ARTICLE_NAME']} <br>" .
"SUBTITLE :{$row['SUBTITLE']} <br>" .
"CURRENT_BID :{$row['CURRENT_BID']} <br>" .
"START_PRICE :{$row['START_PRICE']} <br>" .
"BID_COUNT :{$row['BID_COUNT']} <br>" .
"QUANT_TOTAL :{$row['QUANT_TOTAL']} <br>" .
"QUANT_SOLD :{$row['QUANT_SOLD']} <br>" .
"STARTS :{$row['STARTS']} <br>" .
"ENDS :{$row['ENDS']} <br>" .
"ORIGIN_END :{$row['ORIGIN_END']} <br>" .
"SELLER_ID :{$row['SELLER_ID']} <br>" .
"BEST_BIDDER_ID :{$row['BEST_BIDDER_ID']} <br>" .
"FINISHED :{$row['FINISHED']} <br>" .
"WATCH :{$row['WATCH']} <br>" .
"BUYITNOW_PRICE :{$row['BUYITNOW_PRICE']} <br>" .
"PIC_URL :{$row['PIC_URL']} <br>" .
"PRIVATE_AUCTION :{$row['PRIVATE_AUCTION']} <br>" .
"AUCTION_TYPE :{$row['AUCTION_TYPE']} <br>" .
"INSERT_DATE :{$row['INSERT_DATE']} <br>" .
"UPDATE_DATE :{$row['UPDATE_DATE']} <br>" .
"CAT_1_ID :{$row['CAT_1_ID']} <br>" .
"CAT_2_ID :{$row['CAT_2_ID']} <br>" .
"ARTICLE_DESC :{$row['ARTICLE_DESC']} <br>" .
"DESC_TEXTONLY :{$row['DESC_TEXTONLY']} <br>" .
"COUNTRYCODE :{$row['COUNTRYCODE']} <br>" .
"LOCATION :{$row['LOCATION']} <br>" .
"CONDITIONS :{$row['CONDITIONS']} <br>" .
"REVISED :{$row['REVISED']} <br>" .
"PAYPAL_ACCEPT :{$row['PAYPAL_ACCEPT']} <br>" .
"PRE_TERMINATED :{$row['PRE_TERMINATED']} <br>" .
"SHIPPING_TO :{$row['SHIPPING_TO']} <br>" .
"FEE_INSERTION :{$row['FEE_INSERTION']} <br>" .
"FEE_FINAL :{$row['FEE_FINAL']} <br>" .
"FEE_LISTING :{$row['FEE_LISTING']} <br>" .
"PIC_XXL :{$row['PIC_XXL']} <br>" .
"PIC_DIASHOW :{$row['PIC_DIASHOW']} <br>" .
"PIC_COUNT :{$row['PIC_COUNT']} <br>" .
"ITEM_SITE_ID :{$row['ITEM_SITE_ID']};
}
include 'closedb.php';
?>
```
However I get this error:
```
Parse error: syntax error, unexpected $end in C:\Programme\EasyPHP 2.0b1\www\test.php on line 56
```
I would also like to know if there is perhaps an easier way to obtain mysql records instead of typing by hand?
edit:
I fixed the semicolon and quote issue, and now get:
```
Parse error: syntax error, unexpected T_STRING in C:\Programme\EasyPHP 2.0b1\www\test.php on line 51
```
I am sorry I don't know how to make colors in the code.
|
**Edit**
You say that you're still getting an error. Did you remember to add a **.** when you removed that extra semi-colon?
---
You have a semi-colon in the middle of your string, two lines after the echo.

Also, the end of the string is missing a double-quote.

---
As far as a cleaner way to output all the values goes, you can loop over the result array like this:
```
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach($row as $field=>$value)
{
echo "$field: {$value} <br />";
}
}
```
|
For the second part of your question, you could do this if field names are all logical:
```
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach($row as $key => $value)
{
echo "$key: $value\n";
}
}
```
|
Troubleshooting "unexpected $end" error
|
[
"",
"php",
""
] |
Im getting frustrated because of OpenDNS and other services (ie: roadrunner) that now always returns a ping even if you type any invalid url ie: lkjsdaflkjdsjf.com --- I had created software for my own use that would ping a url to verify if the site was up or not. This no longer works. Does anyone have any ideas about this?
Requirements:
1. It should work with any valid web site, even ones i dont control
2. It should be able to run from any network that has internet access
I would greatly appreciate to hear how others now handle this. I would like to add, im attempting to do this using System.Net in c#
Thank you greatly :-)
New addition: Looking for a solution that i can either buy and run on my windows machine, or program in c#. :-)
**Update:**
Thank you all very much for your answers. Ultimately i ended up creating a solution by doing this:
1. Creating a simple webclient that downloaed the specified page from the url (may change to just headers or use this to notify of page changes)
2. Read in xml file that simply lists the full url to the site/pages to check
3. Created a windows service to host the solution so it would recover server restarts.
4. On error an email and text message is sent to defined list of recipients
5. Most values (interval, smtp, to, from, etc) are defined in the .config for easy change
I will be taking some of your advice to add 'features' to this later, which includes:
* AJAX page for real-time monitoring. I will use WCF to connect to the existing windows service from the asp.net page
* Download Headers only (with option for page change comparison)
* make more configurable (ie: retries on failure before notification)
|
You could create a simple web page with an address bar for the website and some javascript that uses AJAX to hit a site. If you get any HTTP response other than 200 on the async callback, the site isn't working.
```
<html>
<head>
<script language="javascript" type="text/javascript">
<!--
var ajax = new XMLHttpRequest();
function pingSite() {
ajax.onreadystatechange = stateChanged;
ajax.open('GET', document.getElementById('siteToCheck').value, true);
ajax.send(null);
}
function stateChanged() {
if (ajax.readyState == 4) {
if (ajax.status == 200) {
document.getElementById('statusLabel').innerHTML = "Success!";
}
else {
document.getElementById('statusLabel').innerHTML = "Failure!";
}
}
}
-->
</script>
</head>
<body>
Site To Check:<br />
<input type="text" id="siteToCheck" /><input type="button" onclick="javascript:pingSite()" />
<p>
<span id="statusLabel"></span>
</p>
</body>
```
This code depends on the browser not being IE and I haven't tested it, but it should give you a really good idea.
|
[Wget](http://www.gnu.org/software/wget/) is a nice alternative. It will check not only whether the machine is active, but also whether the HTTP server is accepting connections.
|
Ping always succeeds, cant easily check uptime using ping on a url
|
[
"",
"c#",
".net",
"ping",
"system.net",
""
] |
Is there any built-in functionality for classical set operations on the java.util.Collection class? My specific implementation would be for ArrayList, but this sounds like something that should apply for all subclasses of Collection. I'm looking for something like:
```
ArrayList<Integer> setA ...
ArrayList<Integer> setB ...
ArrayList<Integer> setAintersectionB = setA.intersection(setB);
ArrayList<Integer> setAminusB = setA.subtract(setB);
```
After some searching, I was only able to find home-grown solutions. Also, I realize I may be confusing the idea of a "Set" with the idea of a "Collection", not allowing and allowing duplicates respectively. Perhaps this is really just functionality for the Set interface?
In the event that nobody knows of any built-in functionality, perhaps we could use this as a repository for standard practice Java set operation code? I imagine this wheel has been reinvented numerous times.
|
Intersection is done with `Collection.retainAll`; subtraction with `Collection.removeAll`; union with `Collection.addAll`. In each case, as `Set` will act like a set and a `List` will act like a list.
As mutable objects, they operate in place. You'll need to explicitly copy if you want to retain the original mutable object unmutated.
|
I would recommend [Google Guava](https://code.google.com/p/guava-libraries/). The [Sets](https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/Sets.html) class seems to have exactly what you are looking for. It has a [intersection](https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/Sets.html#intersection-java.util.Set-java.util.Set-) method and a [difference](https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/Sets.html#difference-java.util.Set-java.util.Set-) method.
[This presentation](http://smallwig.blogspot.com/2008/08/google-collections-presentation.html) is probably something you want to watch if you're interested. It refers to Google Collections, which was Guava's original name.
|
Classical set operations for java.util.Collection
|
[
"",
"java",
"collections",
"set",
""
] |
I am writing a C library that reads a file into memory. It skips the first 54 bytes of the file (header) and then reads the remainder as data. I use fseek to determine the length of the file, and then use fread to read in the file.
The loop runs once and then ends because the EOF is reached (no errors). At the end, bytesRead = 10624, ftell(stream) = 28726, and the buffer contains 28726 values. I expect fread to read 30,000 bytes and the file position to be 30054 when EOF is reached.
C is not my native language so I suspect I've got a dumb beginner mistake somewhere.
Code is as follows:
```
const size_t headerLen = 54;
FILE * stream;
errno_t ferrno = fopen_s( &stream, filename.c_str(), "r" );
if(ferrno!=0) {
return -1;
}
fseek( stream, 0L, SEEK_END );
size_t bytesTotal = (size_t)(ftell( stream )) - headerLen; //number of data bytes to read
size_t bytesRead = 0;
BYTE* localBuffer = new BYTE[bytesTotal];
fseek(stream,headerLen,SEEK_SET);
while(!feof(stream) && !ferror(stream)) {
size_t result = fread(localBuffer+bytesRead,sizeof(BYTE),bytesTotal-bytesRead,stream);
bytesRead+=result;
}
```
---
Depending on the reference you use, it's quite apparent that adding a "b" to the mode flag is the answer. Seeking nominations for the bonehead-badge. :-)
[This reference](http://www.cplusplus.com/reference/clibrary/cstdio/fopen.html) talks about it in the second paragraph, second sentence (though not in their table).
[MSDN](http://msdn.microsoft.com/en-us/library/z5hh6ee9(VS.80).aspx) doesn't discuss the binary flag until halfway down the page.
[OpenGroup](http://www.opengroup.org/onlinepubs/009695399/functions/fopen.html) mentions the existance of the "b" tag, but states that it "shall have no effect".
|
perhaps it's a binary mode issue. Try opening the file with `"r+b"` as the mode.
**EDIT**: as noted in a comment `"rb"` is likely a better match to your original intent since `"r+b"` will open it for read/write and `"rb"` is read-only.
|
Also worth noting that simply including binmode.obj into your link command will do this for you for all file opens.
|
Why is fread reaching the EOF early?
|
[
"",
"c++",
"c",
"file-io",
"stdio",
"feof",
""
] |
I am working on an iGoogle-like application. Content from other applications (on other domains) is shown using iframes.
How do I resize the iframes to fit the height of the iframes' content?
I've tried to decipher the javascript Google uses but it's obfuscated, and searching the web has been fruitless so far.
**Update:** Please note that content is loaded from other domains, so the [same-origin policy](https://en.wikipedia.org/wiki/Same-origin_policy) applies.
|
We had this type of problem, but slightly in reverse to your situation - we were providing the iframed content to sites on other domains, so the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy) was also an issue. After many hours spent trawling google, we eventually found a (somewhat..) workable solution, which you may be able to adapt to your needs.
There is a way around the same origin policy, but it requires changes on both the iframed content and the framing page, so if you haven't the ability to request changes on both sides, this method won't be very useful to you, i'm afraid.
There's a browser quirk which allows us to skirt the same origin policy - javascript can communicate either with pages on its own domain, or with pages it has iframed, but never pages in which it is framed, e.g. if you have:
```
www.foo.com/home.html, which iframes
|-> www.bar.net/framed.html, which iframes
|-> www.foo.com/helper.html
```
then `home.html` can communicate with `framed.html` (iframed) and `helper.html` (same domain).
```
Communication options for each page:
+-------------------------+-----------+-------------+-------------+
| | home.html | framed.html | helper.html |
+-------------------------+-----------+-------------+-------------+
| www.foo.com/home.html | N/A | YES | YES |
| www.bar.net/framed.html | NO | N/A | YES |
| www.foo.com/helper.html | YES | YES | N/A |
+-------------------------+-----------+-------------+-------------+
```
`framed.html` can send messages to `helper.html` (iframed) but *not* `home.html` (child can't communicate cross-domain with parent).
The key here is that `helper.html` can receive messages from `framed.html`, and **can also communicate** with `home.html`.
So essentially, when `framed.html` loads, it works out its own height, tells `helper.html`, which passes the message on to `home.html`, which can then resize the iframe in which `framed.html` sits.
The simplest way we found to pass messages from `framed.html` to `helper.html` was through a URL argument. To do this, `framed.html` has an iframe with `src=''` specified. When its `onload` fires, it evaluates its own height, and sets the src of the iframe at this point to `helper.html?height=N`
[There's an explanation here](http://www.quora.com/How-does-Facebook-Connect-do-cross-domain-communication) of how facebook handle it, which may be slightly clearer than mine above!
---
**Code**
In `www.foo.com/home.html`, the following javascript code is required (this can be loaded from a .js file on any domain, incidentally..):
```
<script>
// Resize iframe to full height
function resizeIframe(height)
{
// "+60" is a general rule of thumb to allow for differences in
// IE & and FF height reporting, can be adjusted as required..
document.getElementById('frame_name_here').height = parseInt(height)+60;
}
</script>
<iframe id='frame_name_here' src='http://www.bar.net/framed.html'></iframe>
```
In `www.bar.net/framed.html`:
```
<body onload="iframeResizePipe()">
<iframe id="helpframe" src='' height='0' width='0' frameborder='0'></iframe>
<script type="text/javascript">
function iframeResizePipe()
{
// What's the page height?
var height = document.body.scrollHeight;
// Going to 'pipe' the data to the parent through the helpframe..
var pipe = document.getElementById('helpframe');
// Cachebuster a precaution here to stop browser caching interfering
pipe.src = 'http://www.foo.com/helper.html?height='+height+'&cacheb='+Math.random();
}
</script>
```
Contents of `www.foo.com/helper.html`:
```
<html>
<!--
This page is on the same domain as the parent, so can
communicate with it to order the iframe window resizing
to fit the content
-->
<body onload="parentIframeResize()">
<script>
// Tell the parent iframe what height the iframe needs to be
function parentIframeResize()
{
var height = getParam('height');
// This works as our parent's parent is on our domain..
parent.parent.resizeIframe(height);
}
// Helper function, parse param from request string
function getParam( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
</script>
</body>
</html>
```
|
If you do not need to handle iframe content from a different domain, try this code, it will solve the problem completely and it's simple:
```
<script language="JavaScript">
<!--
function autoResize(id){
var newheight;
var newwidth;
if(document.getElementById){
newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
}
document.getElementById(id).height= (newheight) + "px";
document.getElementById(id).width= (newwidth) + "px";
}
//-->
</script>
<iframe src="usagelogs/default.aspx" width="100%" height="200px" id="iframe1" marginheight="0" frameborder="0" onLoad="autoResize('iframe1');"></iframe>
```
|
Resizing an iframe based on content
|
[
"",
"javascript",
"iframe",
"widget",
""
] |
Let's say I have a class
```
public class ItemController:Controller
{
public ActionResult Login(int id)
{
return View("Hi", id);
}
}
```
On a page that is not located at the Item folder, where `ItemController` resides, I want to create a link to the `Login` method. So which `Html.ActionLink` method I should use and what parameters should I pass?
Specifically, I am looking for the replacement of the method
```
Html.ActionLink(article.Title,
new { controller = "Articles", action = "Details",
id = article.ArticleID })
```
that has been retired in the recent ASP.NET MVC incarnation.
|
I think what you want is this:
## ASP.NET MVC1
```
Html.ActionLink(article.Title,
"Login", // <-- Controller Name.
"Item", // <-- ActionMethod
new { id = article.ArticleID }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. You need this value
// otherwise you call the WRONG method ...
// (refer to comments, below).
)
```
This uses the following method ActionLink signature:
```
public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string controllerName,
string actionName,
object values,
object htmlAttributes)
```
## ASP.NET MVC2
*two arguments have been switched around*
```
Html.ActionLink(article.Title,
"Item", // <-- ActionMethod
"Login", // <-- Controller Name.
new { id = article.ArticleID }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. You need this value
// otherwise you call the WRONG method ...
// (refer to comments, below).
)
```
This uses the following method ActionLink signature:
```
public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object values,
object htmlAttributes)
```
## ASP.NET MVC3+
*arguments are in the same order as MVC2, however the id value is no longer required:*
```
Html.ActionLink(article.Title,
"Item", // <-- ActionMethod
"Login", // <-- Controller Name.
new { article.ArticleID }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. You need this value
// otherwise you call the WRONG method ...
// (refer to comments, below).
)
```
This avoids hard-coding any routing logic into the link.
```
<a href="/Item/Login/5">Title</a>
```
This will give you the following html output, assuming:
1. `article.Title = "Title"`
2. `article.ArticleID = 5`
3. you still have the following route defined
.
.
```
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
```
|
I wanted to add to [Joseph Kingry's answer](https://stackoverflow.com/a/201341/3834). He provided the solution but at first I couldn't get it to work either and got a result just like Adhip Gupta. And then I realized that the route has to exist in the first place and the parameters need to match the route exactly. So I had an id and then a text parameter for my route which also needed to be included too.
```
Html.ActionLink(article.Title, "Login", "Item", new { id = article.ArticleID, title = article.Title }, null)
```
|
HTML.ActionLink method
|
[
"",
"c#",
".net",
"asp.net-mvc",
"html-helper",
"actionlink",
""
] |
Is there a way to find all the class dependencies of a java main class?
I have been manually sifting through the imports of the main class and it's imports but then realized that, because one does not have to import classes that are in the same package, I was putting together an incomplete list.
I need something that will find dependencies recursively (perhaps to a defined depth).
|
It can be eaily done with just javac. Delete your class files and then compile the main class. javac will recursively compile any classes it needs (providing you don't hide package private classes/interfaces in strangely named files). Of course, this doesn't cover any recursive hacks.
|
You may want to take a look at the `jdeps` command line tool:
<https://docs.oracle.com/javase/8/docs/technotes/tools/unix/jdeps.html>
```
jdeps -cp <your cp> -v <path to your .class file>
```
The command will return a list of the dependencies for that java class file. There are many other options that you can use in your command like `-regex` to find dependencies matching a given pattern
|
How do I get a list of Java class dependencies for a main class?
|
[
"",
"java",
"dependencies",
"dependency-management",
""
] |
I have Slackware 12.1 and wish to try out Eclipse for PHP/HTML/JavaScript development. However, it seems I'm facing myriad of possible options and I'd hate to miss the best thing and give up on Eclipse (I'm currently using [Geany](http://www.geany.org), but I'm missing some stuff like , for example, auto-complete for JavaScript)
I'm currently looking into just installing All-in-one PDT package version 1.0.3 from here:
[<http://www.eclipse.org/pdt/downloads/>](http://www.eclipse.org/pdt/downloads/)
However, that seems to be Eclipse 3.3. There's also Slackware package for 3.4 here:
[<http://repository.slacky.eu/slackware-12.1/development/eclipse/3.4/>](http://repository.slacky.eu/slackware-12.1/development/eclipse/3.4/)
But it says it a "Classic" version. I'm not sure how hard would be to add PHP, HTML, JavaScript support for it.
Note: I don't plan to run PHP through Eclipse's integrated web server or anything like that. I just want a powerful editor.
P.S. Also, recommendations for something better than Eclipse that is for Linux and free are also welcome. I already used Kate, SciTE, Geany, Emacs, Vi and Bluefish, so those are not interesting.
**Important:** whatever you recommend, please explain reasons why. Don't rush to be the fastest gun in the west, as I'll downvote such answers that only say "use this"
|
If you want auto-complete for JavaScript, in that case you should to use some plug-in for Eclipse such as Aptana Studio, but Aptana is more than auto-compete tool for javascript, it has included a lot of unnecessary things that you don't need for regular development.
I have the same problem to find the right solution for JavaScript in Eclipse, Aptana was ok, but I hate the additional features that Aptana includes, I didn't find any good tool which could be added to Eclipse, for JavaScript :( For script languages such as JSP, Eclipse is like a song...nice,sweet and smooth...;)
|
I second Aptana wholeheartedly. Since it is based very closely off of Eclipse, if you ever decide to do coding that Aptana will not cover, you are still used to the general interface of Eclipse.
I don't want to say it is cut down, because it is not. It just has what you need for the languages and technologies you will be using it for. You can still add other plugins to it as well for SVN, CVS, etc. The interface is a bit less crowded as well.
I don't do a whole lot of javascript coding, but man, that is where is stands out from the crowd. It does a fantastic job with Javascript.
Also, you don't have to use Aptana's built in Jetty server to run PHP; you can just tell it where you local Apache server is.
|
Which Eclipse version to install on Linux for PHP development
|
[
"",
"php",
"linux",
"eclipse",
"slackware",
""
] |
Cruisecontrol and Hudson are two popular continuous integration systems. Although both systems are able to do the automated continuous builds nicely, it just seems a lot easier to create a batch or bash build script, then use Windows scheduler or cron to schedule builds.
Are there better continuous integration systems available for C++ projects? Or is just using a script and a scheduler the simpler way?
|
We have been using [CruiseControl](http://cruisecontrol.sourceforge.net/) for CI on a C++ project. While it is the only thing we use ant for, the ant build script for CruiseControl just starts our normal build script, so it is very simple and we haven't really needed to update it in a long while. Therefore the fact that CrusieControl is Java based has not really been an issue at all for us.
The main benefits of using something like cruise control are
* A nice web page showing build status
* Email after each build or after failed builds
* Automatically build after a commit to the source control system
* A firefox plugin to monitor the build status
* Shows the output for any build errors.
* Shows what files have changed since the last build (good for seeing which developer broke the buid)
Of course you can write a script yourself which does all of this, but why do all that work? In the long run the extra initial cost of setting up CruiseControl (or something similar) is probably much less than the cost of maintaining and updating a custom CI build script.
If all you need is to launch a daily build and a simple script started by cron is sufficient for your needs then by all means do that. However, one of the advantages of CI is that you get a build status report after every check in. Writing a script to do that takes more work and CruiseControl already does it.
|
We use [Hudson](http://hudson-ci.org/) for CI and [SonarQube](http://www.sonarqube.org/) for code metrics. They're integrated, and Hudson has a handful of plugins that no cronjob can beat.
One great plugin is CI Game, which keeps a score about who breaks the builds and who commits without breaking it. Hudson has plugins to play with VMWare, Selenium, SVN, CSV, Git. It has RSS syndication, which can help you to automate even more everything else.
Hudson is great...
|
What continuous integration tool is best for a C++ project?
|
[
"",
"c++",
"continuous-integration",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.