Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is there a way of finding the absolute position of an element, i.e. relative to the start of the window, using jQuery? | [`.offset()`](http://docs.jquery.com/CSS/offset) will return the offset position of an element as a simple object, eg:
```
var position = $(element).offset(); // position = { left: 42, top: 567 }
```
You can use this return value to position other elements at the same spot:
```
$(anotherElement).css(position)
``` | Note that `$(element).offset()` tells you the position of an element *relative to the document*. This works great in most circumstances, but in the case of **`position:fixed`** you can get unexpected results.
If your document is *longer than the viewport* and you have scrolled vertically toward the bottom of the document, then your `position:fixed` element's `offset()` value **will be greater than** the expected value by the amount you have scrolled.
If you are looking for a value *relative to the viewport* (window), rather than the document on a position:fixed element, you can subtract the document's `scrollTop()` value from the fixed element's `offset().top` value. Example: `$("#el").offset().top - $(document).scrollTop()`
If the `position:fixed` element's offset parent is the *document*, you want to read `parseInt($.css('top'))` instead. | How do I find the absolute position of an element using jQuery? | [
"",
"javascript",
"jquery",
""
] |
By using sp\_who2 I can get a list of current log-in users and machine names. Some users are using SQL Server log-in user name such as sa. Is there any way I can get the windows log-in user name for the SQL log-in users?
If there is no way to get Windows log-in users from the machine names, can I use WMI class or C# to get find out the Windows log-in user names by their machine names?
My SQL server is Microsoft SQL Server 2005 and Windows is Server 2003. | There is no link between a SQL login and the NT username.
You asked similar here: [How to find out user name and machine name to access to SQL server](https://stackoverflow.com/questions/641515/how-to-find-out-user-name-and-machine-name-to-access-to-sql-server/641620)
The WMI approach will be ambiguous if more than 1 user is logged into the client PC (eg service accounts, remote user via mstsc etc). Any approach like this will require admin rights on the client PC too for the account used.
I doubt you can do it in real time.
All you can do is record the `client_net_address` in `sys.dm_exec_connections` and backtrack from there, perhaps via WMI but not from SQL Server itself.
Do you need the username though? Or just the client PC so you can change the app connection string?
You final solution is to change the sa password and see who calls, if you only have relatively few SQL connections | To get the user and machine name use this:
```
SELECT HOST_NAME() AS HostName, SUSER_NAME() LoggedInUser
``` | How to get Windows Log-in User Name for a SQL Log in User | [
"",
"sql",
"sql-server",
"windows",
"sql-server-2005",
""
] |
If i have:
C:\temp\foo\bar\
(**NOTE:** bar is a directory)
how can i parse out:
**bar** | I figured it out.
```
DirectoryInfo info = new DirectoryInfo(sourceDirectory_);
string currentDirectoryName = info.Name;
``` | Try
```
System.IO.Path.GetFileName("C:\\temp\\foo\\bar");
``` | get directory from full path | [
"",
"c#",
"directory",
""
] |
We have a C++ task that will fork a new process. That process in turn may have several child processes. If the task runs past an allotted time, we will want to kill that forked process.
However, we don't want to orphan the processes it has spawned. We want them all to die. I have used Process Explorer and it has a "Kill Process Tree" option, similar to Windows Task Manager's "End Process Tree", so I'm guessing/assuming there is a public API to do this. Has anyone done this, or know of a reference to a public API that does? | You might want to consider the "Jobs API". [`CreateJobObject`](https://msdn.microsoft.com/en-us/library/ms682409%28VS.85%29.aspx) and friends. You can enforce children processes to stay within the Job, by setting appropriate attribute. Then you can call `TerminateJobObject` whenever you want.
Clarification: this is NOT what Task Manager does. | I suggest going the job object route, as indicated above, it will be the most reliable.
If you can't go the job object route, you can use the toolhelp API to get parent process ID's and build the tree that way. Be cautious though, since Windows doesn't have a strong parent/child relationship and it is possible for PID's to get recycled. You can use `GetProcessTimes` to query the creation time of the process, and check that it is older than the child. If an intermediate process in the tree is terminated, you will not be able to walk the tree further.
```
// Error handling removed for brevity
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
Process32First(snapshot, &process);
do
{
// process.th32ProcessId is the PID.
// process.th32ParentProcessID is the parent PID.
} while (Process32Next(snapshot, &process));
``` | Performing equivalent of "Kill Process Tree" in C++ on windows | [
"",
"c++",
"windows",
"kill",
""
] |
In ASCII, validating a name isn't too difficult: just make sure all the characters are alphabetical.
But what about in Unicode (utf-8) ? How can I make sure there are no commas or underscores (outside of ASCII scope) in a given string?
(ideally in Python) | Just convert bytestring (your utf-8) to unicode objects and check if all characters are alphabetic:
```
s.isalpha()
```
This method is locale-dependent for bytestrings. | Maybe the [unicodedata module](http://docs.python.org/library/unicodedata.html) is useful for this task. Especially the `category()` function. For existing unicode categories look at [unicode.org](http://unicode.org/Public/UNIDATA/UCD.html#General_Category_Values). You can then filter on punctuation characters etc. | Validating a Unicode Name | [
"",
"python",
"unicode",
"validation",
"character-properties",
""
] |
What is the equivalent to [PathCanonicalize](http://msdn.microsoft.com/en-us/library/bb773569(VS.85).aspx) in C#?
Use: I need to take a good guess whether two file paths refer to the same file (without disk access). My typical approach has been throwing it through a few filters like MakeAbsolute and PathCanonicalize, and then do a case-insensitive comparison. | **quick and dirty:**
In the past I have created a [FileInfo](http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx) object from the path string and then used the FullName property. This removes all of the ..\'s and the .\'s.
Of course you could interop:
```
[DllImport("shlwapi", EntryPoint="PathCanonicalize")]
private static extern bool PathCanonicalize(
StringBuilder lpszDst,
string lpszSrc
);
``` | 3 solutions:
Best case scenario, where you are 100% certain the calling process will have full access to the filesystem. **CAVEAT:** permission on a production box can be tricky
```
public static string PathCombineAndCanonicalize1(string path1, string path2)
{
string combined = Path.Combine(path1, path2);
combined = Path.GetFullPath(combined);
return combined;
}
```
But, we're not always free. Often you need to do the string arithmetic without permission. There is a native call for this. **CAVEAT:** resorts to native call
```
public static string PathCombineAndCanonicalize2(string path1, string path2)
{
string combined = Path.Combine(path1, path2);
StringBuilder sb = new StringBuilder(Math.Max(260, 2 * combined.Length));
PathCanonicalize(sb, combined);
return sb.ToString();
}
[DllImport("shlwapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool PathCanonicalize([Out] StringBuilder dst, string src);
```
A third strategy is to trick the CLR. Path.GetFullPath() works just fine on a fictitious path, so just make sure you're always giving it one. What you can do is to swap out the root with a phony UNC path, call GetFullPath(), and then swap the real one back in. **CAVEAT:** this may require a hard sell in code review
```
public static string PathCombineAndCanonicalize3(string path1, string path2)
{
string originalRoot = string.Empty;
if (Path.IsPathRooted(path1))
{
originalRoot = Path.GetPathRoot(path1);
path1 = path1.Substring(originalRoot.Length);
}
string fakeRoot = @"\\thiscantbe\real\";
string combined = Path.Combine(fakeRoot, path1, path2);
combined = Path.GetFullPath(combined);
combined = combined.Substring(fakeRoot.Length);
combined = Path.Combine(originalRoot, combined);
return combined;
}
``` | PathCanonicalize equivalent in C# | [
"",
"c#",
"filenames",
""
] |
I´ve got this in a INSERT statment to MSSQL 2008
> System.Data.SqlClient.SqlException:
> The conversion of a datetime2 data
> type to a datetime data type resulted
> in an out-of-range value. | > Defines a date that is combined with a time of day that is based on 24-hour clock. datetime2 can be considered as an extension of the existing datetime type that has a larger date range, a larger default fractional precision, and optional user-specified precision.
<http://technet.microsoft.com/en-us/library/bb677335.aspx> | SQLServer's datetime datatype is a much smaller range of allowed values than .net datetime datatype. SQLServer's datetime type basically supports the gregorian calendar, so the smallest value you can have is 1/1/1753. In 2008 SQLServer added a datetime2 datatype that supports back to year 1 (there was no year 0). Sounds like you're trying to insert a datetime value that's before 1/1/1753 into a datetime (not datetime2) SQLServer column | What is datetime2? | [
"",
".net",
"sql",
"entity-framework",
"sql-server-2008",
"c#-3.0",
""
] |
How can I check if a client disconnected through Winsock in C++? | [Beej's Network Programming Guide](http://beej.us/guide/bgnet/)
if you call recv in blocking mode and it returns with 0 bytes read, the socket has disconnected, else it wait for bytes to be received.
Look in this [FAQ 2.12](http://tangentsoft.net/wskfaq/newbie.html)
example from select on [this](http://www.codeguru.com/forum/archive/index.php/t-363683.html) page.
```
int nRet;
if(( nRet = select( 0, &fdread, NULL, NULL, NULL )) == SOCKET_ERROR )
{
// Error condition
// Check WSAGetLastError
}
if( nRet > 0 )
{
// select() will return value 1 because i m using only one socket
// At this point, it should be checked whether the
// socket is part of a set.
if( FD_ISSET( s, &fdread ))
{
// A read event has occurred on socket s
}
}
``` | You can only tell if a TCP socket is 'disconnected' by attempting to send data. This is because the design of the protocol is such that it's supposed to allow for temporary outages between peers. So, if you connect from A via R1 via R2 via R3 to B and send data for a while and then stop sending you could unplug R2->R3 (for example) and neither A nor B would notice (or care). If you then plugged R2->R4 and R4->R3 and then tried to send data between A and B then things would 'just work' and you'd never know. If, however, you tried to send data when R2->R3 was disconnected then you'd (eventually, after all the TCP level retries) get an error back.
Now, some operating systems may be able to alert you to the fact that your local network adapter isn't currently connected and you could use that to say "I'm no longer connected to my peers" but I wouldn't advise it.
If having your peers know when connections are 'broken' is important then either use an application level 'ping' message to occasionally send data between the peers or use TCP keep-alive. Personally I'd go for the ping messages...
**Edit:** Of course all that is assuming that you want to know if you can still send data on a connection, after all, you're TOLD when the client is no longer sending because your reads will return 0 bytes and you KNOW when it disconnects its send side because your writes will fail; you also KNOW when you shutdown either the send or recv side of your own end of the connection...
I guess I should have stuck with initial gut reaction response of "define disconnected" ;) | How can I check if a client disconnected through Winsock in C++? | [
"",
"c++",
"winsock",
""
] |
I have a very large loop that loops a 1000 rows. I exit the loop if magic value 1 is found. If magic value 1 is not found but magic value 2 is found then the loop needs to skip to the beginning. Right now I am using a switch, some ifs and a goto. I have read that goto is not the best way. Is there a better way to make this work? | To exit a loop you can use the [break](http://msdn.microsoft.com/en-us/library/adbctzc4(VS.80).aspx) statement, to go onto the next record you can use the [continue](http://msdn.microsoft.com/en-us/library/923ahwt1(VS.80).aspx) statement.
```
for(int i = 0; i < 1000; i++)
{
if(magicValue1)
break;
if(magicValue2)
continue;
}
```
**I AM NOT CONDONING THE USE OF THE GOTO STATEMENT I AM SIMPLY POINTING OUT A POSSIBLE USE CASE**
You can use **goto** jump statement to start/exit a loop, however I would stay away from this option unless you are using **nested looping**. I think the goto statement still has its uses for optimizing, exiting cleanly ect.. but in general it is best to use it **quite** sparingly.
```
for(int i = 0; i < 100; i++)
{
start:
for(int i = 0; i < 10; i++)
{
if(magicValue1)
goto end;
if(magicValue2)
goto start;
}
}
end :
``` | How about this:
```
for(int i = 0; i < 1000; i++) {
if(values[i] == MAGIC_VALUE_1) {
break;
} else if(values[i] == MAGIC_VALUE_2) {
i = 0;
}
}
```
If by "skip to the beginning" you mean "skip this record and process the next one," replace `i = 0` with `continue`. | Looping best practices | [
"",
"c#",
"break",
"continue",
""
] |
I would like to normalize data in a `DataTable insertRows` without a key. To do that I need to identify and mark duplicate records by finding their ID (`import_id`). Afterwards I will select only the distinct ones. The approach I am thinking of is to compare each row against all rows in that DataTable `insertRows`
The columns in the DataTable are not known at design time, and there is no key. Performance-wise, the table would have as much as 10k to 20k records and about 40 columns
How do I accomplish this without sacrificing performance too much?
I attempted using linq but I did not know how to dynamically specify the where criteria
Here I am comparing first and last names in a loop for each row
> ```
> foreach (System.Data.DataRow lrows in importDataTable.Rows)
> {
> IEnumerable<System.Data.DataRow> insertRows = importDataTable.Rows.Cast<System.Data.DataRow>();
>
> var col_matches =
> from irows in insertRows
> where
> String.Compare(irows["fname"].ToString(), lrows["fname"].ToString(), true).Equals(0)
> &&
> String.Compare(irows["last_name"].ToString(), lrows["last_name"].ToString(),true).Equals(0)
>
> select new { import_id = irows["import_id"].ToString() };
> }
> ```
Any ideas are welcome.
How do I find similar column names using linq?>my similar question | The easiest way to get this done without O(n2) complexity is going to be using a data structure that efficiently implements Set operations, specifically a Contains operation. Fortunately .NET (as of 3.0) contains the [HashSet](http://msdn.microsoft.com/en-us/library/bb359438.aspx) object which does this for you. In order to make use of this you're going to need a single object that encapsulates a row in your DataTable.
If DataRow won't work, I recommend converting relevant records into strings, concatenating them then placing those in the HashSet. Before you insert a row check to see if the HashSet already contains it (using Contains). If it does, you've found a duplicate.
**Edit:**
This method is O(n). | I am not sure if I understand the question correctly, but when dealing with System.Data.DataTable the following should work.
```
for (Int32 r0 = 0; r0 < dataTable.Rows.Count; r0++)
{
for (Int32 r1 = r0 + 1; r1 < dataTable.Rows.Count; r1++)
{
Boolean rowsEqual = true;
for (Int32 c = 0; c < dataTable.Columns.Count; c++)
{
if (!Object.Equals(dataTable.Rows[r0][c], dataTable.Rows[r1][c])
{
rowsEqual = false;
break;
}
}
if (rowsEqual)
{
Console.WriteLine(
String.Format("Row {0} is a duplicate of row {1}.", r0, r1))
}
}
}
``` | compare all rows in DataTable - identify duplicate records | [
"",
"c#",
".net",
"asp.net",
"linq",
"normalization",
""
] |
I'm looking for a list numeric type initalization identifiers for both C# and VB.Net.
for example:
```
Dim x = 1D 'Decimal'
Dim y = 1.0 'initializes to float'
```
Here's the list:
The identifiers are case-insensitive
**VB.Net**
```
Int32 = 1, I
Double = 1.0, R, 1.0e5
Decimal = D
Single = F, !
Int16 = S
UInt64 = L, UL
```
**C#** | ## C#
[Section 1.8 of the C# specification](http://msdn.microsoft.com/en-us/library/aa664812(VS.71).aspx) includes these values.
> integer-type-suffix: one of U u L l UL
> Ul uL ul LU Lu lU lu
>
> real-type-suffix: one of F f D d M m
[Section 2.4.4.2](http://msdn.microsoft.com/en-us/library/aa664674(VS.71).aspx) elaborates on this for Integer types:
> The type of an integer literal is
> determined as follows:
>
> * If the literal has no suffix, it has the first of these types in which
> its value can be represented: int,
> uint, long, ulong.
> * If the literal is suffixed by U or u, it has the first of these types in
> which its value can be represented:
> uint, ulong.
> * If the literal is suffixed by L or l, it has the first of these types in
> which its value can be represented:
> long, ulong.
> * If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is
> of type ulong.
[Section 2.4.4.3](http://msdn.microsoft.com/en-us/library/aa691085(VS.71).aspx) elaborates on this for Real types:
> If no real type suffix is specified,
> the type of the real literal is
> double. Otherwise, the real type
> suffix determines the type of the real
> literal, as follows:
>
> * A real literal suffixed by F or f is of type float. For example, the
> literals 1f, 1.5f, 1e10f, and 123.456F
> are all of type float.
> * A real literal suffixed by D or d is of type double. For example, the
> literals 1d, 1.5d, 1e10d, and 123.456D
> are all of type double.
> * A real literal suffixed by M or m is of type decimal. For example, the
> literals 1m, 1.5m, 1e10m, and 123.456M
> are all of type decimal. This literal
> is converted to a decimal value by
> taking the exact value, and, if
> necessary, rounding to the nearest
> representable value using banker's
> rounding (Section 4.1.7). Any scale
> apparent in the literal is preserved
> unless the value is rounded or the
> value is zero (in which latter case
> the sign and scale will be 0). Hence,
> the literal 2.900m will be parsed to
> form the decimal with sign 0,
> coefficient 2900, and scale 3.
## VB
Similarly, the VB specification contains details for both [Integer](http://msdn.microsoft.com/en-us/library/aa711649(VS.71).aspx) and [Floating point](http://msdn.microsoft.com/en-us/library/aa711650(VS.71).aspx) literals.
For integers:
> ShortCharacter ::= S
> IntegerCharacter ::= I
> LongCharacter ::= L
For floating points:
> SingleCharacter ::= F
> DoubleCharacter ::= R
> DecimalCharacter ::= D | Personally, I don't always use the identifiers, for exactly the reasons (memory) raised here. An interesting feature of the C# compiler is that it actually compiles the following to the same thing:
```
static void Foo()
{
var x = 100F;
Console.WriteLine(x);
}
static void Bar()
{
var x = (float)100; // compiled as "ldc.r4 100" - **not** a cast
Console.WriteLine(x);
}
```
I find the second version far more readable. So I use that approach. The only time AFAIK that it does anything different is with decimal with trailing zeros - i.e.
```
static void Foo()
{
var x = 100.00M;
Console.WriteLine(x);
}
static void Bar()
{
var x = (decimal)100.00; // compiled as 100M - extended .00 precision lost
Console.WriteLine(x);
}
``` | List of .Net Numeric Type Initialization Identifiers | [
"",
"c#",
".net",
"vb.net",
""
] |
What's the best way to let a user pick a subdirectory in C#?
For example, an app that lets the user organize all his saved html receipts. He most likely is going to want to be able to select a root subdirectory that the program should search for saved webpages (receipts).
Duplicate:
* [Browse for a directory in C#](https://stackoverflow.com/questions/11767/browse-for-a-directory-in-c) | The [Folder Browser Dialog](http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx) is the way to go.
If you want to set an initial folder path, you can add this to your form load event:
```
// Sets "My Documents" as the initial folder path
string myDocsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
FolderBrowserDialog1.SelectedPath = myDocsPath;
``` | Check the [FolderBrowserDialog](http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx) class.
```
// ...
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
}
``` | What's the best way to let a user pick a subdirectory in C#? | [
"",
"c#",
""
] |
I have two SqlDataSource controls on a page. One loads high level data and the other loads more details based on which high level item you choose. It is a part of a large search that has over 900,000 records and I am looking for ways to speed it up. Whether it is options I can add onto the SqlDataSource, things I can do to the sql query, or use an alternative such as an ObjectDataSource.
I changed the DataSourceMode to DataReader because I heard it was faster and uses less memory. I also noticed that the paging is really slow.
I am doing the following from my this website, <http://mosesofegypt.net/post/2008/02/Building-a-grouping-Grid-with-GridView-and-ASPNET-AJAX-toolkit-CollapsiblePanel.aspx>, but obviously with my data which is over 900,000 records and I am unsure how I can add paging to the second gridview, because right now, it is only on the top-level gridview | I don't think your data source control itself would need to be the target for any optimizations. It is only going to work with the data that you get from it (meaning you should optimize your SQL) or the data put into it before sending it off to SQL (meaning you should optimize your application code). | 1. I would start with server-side paging for your data in asp.net.
2. I would make sure to index your database tables to get maximum performance. Also use query analyzer to see pain points in your query performance.
3. If you are searching I would recommend using Full Text Indexing that SQL server provides. | Tips on speeding up a SqlDataSource? | [
"",
"c#",
"asp.net",
"sql-server",
"t-sql",
"sqldatasource",
""
] |
I'm wishing to aggregate some Blog feeds into an existing PHP-based website. There's tons of free libraries for PHP that consume RSS feeds. But I thought I'd throw out my needs to see if I can get the number to try minimized to one that's popular.
1) I'm wishing to aggregate some top items from up to 3 different RSS feeds into one stream for consumption.
2) In addition, I may want to aggregate stories from the different websites that match a certain "tag".
3) I'd prefer if this ran daily as a chron job and updated some static html include files, as the feed doesn't need to be updated constantly.
4) I'd also like the possibility of the feed writing to a couple different static html includes. So that I can have one Main news section, and then maybe a call-out section on the right that matches a specific tag for the article or something.
So, what's your favorite libraries/code snippets to accomplish some of this.
Thanks,
Todd | Yahoo pipes is an excellent way of aggregating feeds.
There is also functionality to add rules to do operations such as get rid of duplicate entries or filter items matching specific criteria.
For actually parsing the feed, the class library [Simple Pie](http://simplepie.org/) is great. | [SimplePie](http://www.simplepie.org) has performed extremely well for me in every project I've used it in.
In your case its a good match because it fits 2 of your requirements:
1) You can give it an array of feeds which it will treat as one combined feed
2) It has built-in caching
For pulling only items which match a tag, that depends on the site owner enabling this ability (e.g. flickr and YouTube). Otherwise you'll have to use the normal feed and decide which items to keep on your own.
Regarding updating static html files which match certain categories, that's also something you'll need to code yourself. It shouldn't be difficult, and SimplePie will make parsing the feed quite easy. | RSS Feed consumption by PHP | [
"",
"php",
"rss",
""
] |
I want to be able to select all database rows where the month and year are the same as what I am searching for. Since the DATE field has year, month, and day, how do I search with year and month? | ```
SELECT *
FROM myTable
WHERE ( YEAR(myfield) = '2009')
AND ( MONTH(myfield) = '1')
``` | ```
SELECT *
FROM tblTableName
WHERE Month(ColumnDate) = Month(MyDate)
AND Year(ColumnDate) = Year(MyDate)
``` | SQL date selecting | [
"",
"sql",
"mysql",
"date",
""
] |
I have a text file which all contain the following fragments of code in it
```
Lines.Strings = (
'test@test1.com'
'test@test2.org'
'test@test3.org'
'test@test4.com')
```
the e-mail address will change. as will the Lines part of Lines.String it can be called anything EG Test.Strings, or ListBox.Strings
I want to match all and any text inside of this Strings = ( ) block;
here is the code I'm using
```
[a-zA-Z]+\.Strings\s+=\s+[\(]{1}(.+)[\)]{1}
```
but this doesn't catch all of the matches
I want the grouping to stop after the first ) is found. it looks like it's matching any character after the first ( and all the way to the end of the file to the last )
any help would be greatly appreciated.
**EDIT**:
I'm not asking to match "emails"; i want any text between the opening ( and closing )
I think it's called "non-greedy" matching. i only want the match to end after the first ) is found. | This may work better.
```
[a-zA-Z]+\.Strings\s*=\s*\(([^)])+)\)
```
Also, how are you dealing with line breaks? That may be your issue. From the regexp you gave, it looks as if you are concatenating all the lines together with spaces. If not, you need to be thinking in terms of multi-line regular expressions.
In response to your answer to your own question:
```
"[a-zA-Z]+\\.Strings\\s+=\\s+[\\(]{1}(.+?)\\){1}?",
```
is needlessly cluttered, and may not work as you expect for several cases.
* you don't need to write `{1}` since that's the default
* `[\)]` is the same as just `\)`
* you won't match cases where the `=` isn't surrounded by spaces, even though such spaces are generally optional
* Making the final `)` optional and not excluding `)` from your internal pattern means it will be part of your capture.
Fixing these leads to:
```
"[a-zA-Z]+\\.Strings\\s*=\\s*\\(([^)]+)\\)"
```
Which is just what I posted, but with the backslashes doubled for use in a string. | Try
```
/\(([^\)]+)\)/
NODE EXPLANATION
----------------------------------------------------------------------
\( '('
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
[^\)]+? any character except: '\)' (1 or more
times (matching the least amount
possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
\) ')'
----------------------------------------------------------------------
``` | How do I control Regex grouping? | [
"",
"c#",
"regex",
""
] |
I'm toying with the idea for my text input box of clicking on a div containing a selection of "tags" to add meta content. My text input has a width of 35, but I want it to be able to overflow.
I've searched and found methods to focus and position my caret at the end of the updated input content, and chrome and IE behave themselves and auto scroll to show the cursor in the visible area of the input box, but when the text input is full and overflows Firefox 3.0.7 leaves the correctly positioned caret out of view to the right (though if you press right arrow on keyboard you can get to it without disturbing the position).
Any help appreciated. | Thanks, that works for me jtompson. Combined it with an existing script to move the caret to the end of a textinput or textarea seems to cover IE7, FF3, and chrome.
```
function setCaretPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.setSelectionRange(caretPos, caretPos);
elem.focus();
// Workaround for FF overflow no scroll problem
// Trigger a "space" keypress.
var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 0, 32);
elem.dispatchEvent(evt);
// Trigger a "backspace" keypress.
evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 8, 0);
elem.dispatchEvent(evt);
}
else
elem.focus();
}
}
}
setCaretPosition(document.getElementById("searchinput").id, document.getElementById("searchinput").value.length);
``` | See my answer [this question](https://stackoverflow.com/questions/668720/how-do-i-shift-the-visible-text-in-a-narrow-input-element-to-see-the-cursor-at-th/668856#668856). Although it is relatively kludgy, you can trigger an keypress event in FF and the input will scroll to the end (showing the caret where you'd like to see it). | Keeping caret position in a visible position in text input - firefox misbehaves | [
"",
"javascript",
"firefox",
"textinput",
""
] |
I know how I can debug a remote Java VM with Eclipse, but how can I do it with a Java Web Start program. I have a problem that only occurs in Java Web Start. It must be security related.
I need a solution that will work with a current Java VM like 1.6.0\_12. | It's quite the same like with any other Java process you want to debug remotely: You have to set up some arguments for the VM (`-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=n,suspend=y,address=12345`) and then connect to the given port. In Java webstart 6.0 this can be done with the -J option, in earlier version via environment variable JAVAWS\_VM\_ARGS. See details [here](http://java.sun.com/j2se/1.5.0/docs/guide/javaws/developersguide/troubleshooting.03.06.html). | Start the JWS VM manually. This way you can provide the startup parameters to open the debug port. Here is a [description](http://icoloma.blogspot.com/2005/06/how-to-debug-jwsjnlp.html), it goes like this:
```
set JAVAWS_TRACE_NATIVE=1
set JAVAWS_VM_ARGS="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8989,server=y,suspend=n"
javaws http://server:port/descriptor.jnlp
``` | How can I debug applications under Java Web Start (JNLP)? | [
"",
"java",
"debugging",
"jnlp",
"java-web-start",
""
] |
We have a number of plugin applications that can all run independently but also can run within the same host container. Users can run one single host container or multiple ones with one or many plugins.
We have a number of "integration" use cases where people want to either
1. Send data from one plugin to another
2. Send "actions" or "commands" to another app (sometimes with parameters)
We have a couple of options:
1. Have a well known event bus at the container level that all plugins know about and can publish and subscribe well defined messages or objects
2. Embed the dlls of one into another and call the API of one plugin from another
3. create integration plugins that know about the common integration points so each individual plugin is completely standalone and the integration plugin is the only thing that knows about the integration. This was we can ship each individual plugin without any extraneous dependencies.
Thoughts or other suggestions? | The [Smart Client Software Factory](http://www.microsoft.com/downloads/details.aspx?FamilyId=3BE112CC-B2C1-4215-9330-9C8CF9BCC6FA&displaylang=en) is another bit of guidance to consider. It's WinForms for the most part and perhaps slightly more complex than the newer WPF release (which was completely re-architected). However, it would also give you ideas to accomplish your modular goals. The links and documentation do a good job of covering how modules are separate, but can pass data through the common framework. | I would take a look at the new Managed Extensibility Framework (MEF) library currently being developed by Microsoft. See [the Codeplex site](http://www.codeplex.com/MEF). As I understand it correctly VS 2010 will also use this framework to provide extensibility point in Visual Studio. | The best model for integration of plugins | [
"",
"c#",
"integration",
""
] |
How do I ensure that my users can not physically type in http: to bypass my SSL and ensure that every page is https:?
Possibly a redirect on my master page? | This would generally be handled via IIS configuration or with an ISAPI filter, but if you want to do it in the application code, you could put something like this in the Page\_Init event of your master page...
```
If Not Request.IsSecure
Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"))
End If
``` | I would just redirect all http urls to https with a separate page, or use the "require secure channel" option on your IIS configuration, which will display an error if someone tries to access a non-https page.
[Here's](http://blog.kyanmedia.com/archives/2007/6/28/forcing_https_in_iis_60/) a site with a guide to redirecting the error page to the https URL of your site. | Ensure page is only accessed via SSL | [
"",
"c#",
"asp.net",
"ssl",
""
] |
**I imagine that no, they aren't, because every process has its own memory space, of course.**
But how does the whole JVM thing actually work? Is there a separate JVM in a separate process for every Java program that I launch? Do Java programs running in a system share anything at all? Are there differences between OSs and JVM implementations? Can I *make* programs share variables (i. e. directly through the JVM rather than the usual IPC mechanisms)? Are there more exotic one-process JVMs for special purposes?
Generally, what are recommendable reads about the guts of JVMs? The [spec](http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html)? The source code of some implementation? Websites? Books? | > In Java, are static class members
> shared among programs?
A class is defined by its full name and the class loader that loaded it. If the same class is within the same JVM process and the two programs loaded the class through the same class loader then the static members are shared. Classloading rules are of extreme importance.
> I imagine that no, they aren't,
> because every process has its own
> memory space, of course.
If you are using two separate JVMs to launch two apps, you are correct. But take the case of application/servlet containers such as tomcat: they load several apps through the same process (the tomcat host process).
> But how does the whole JVM thing
> actually work? Is there a separate JVM
> in a separate process for every Java
> program that I launch? Do Java
> programs running in a system share
> anything at all?
Every time you type `>java -cp...` at the command line, you are creating a new process. Bear in mind that when you run eclipse or call an ant java task with `fork=true` you are also creating new processes.
> Are there differences between OSs and
> JVM implementations? Can I make
> programs share variables (i. e.
> directly through the JVM rather than
> the usual IPC mechanisms)? Are there
> more exotic one-process JVMs for
> special purposes?
Like a poster said, there are projects like Terracota that facilitate this for you. A general approach for this kind of sharing is a distributed cache. | No, static variables aren't between JVMs. Yes, there's a separate JVM process for each Java app you run.
In some implementations I believe they may share *some* resources (e.g. memory for JITted code of JRE classes) but I'm not sure. I believe there's ongoing work to enable more sharing, but still in a robust way. (You don't really want one JVM crashing to affect others.)
No, you can't make programs share variables transparently.
I believe there are books about the JVM, but I can't recommend any. You'd probably be best off looking for HotSpot white papers for details of that. [This one](http://java.sun.com/products/hotspot/whitepaper.html) is a pretty good starting point. | In Java, are static class members shared among programs? | [
"",
"java",
"jvm",
""
] |
I am of course familiar with the `java.net.URLEncoder` and `java.net.URLDecoder` classes. However, I only need HTML-style encoding. (I don't want `' '` replaced with `'+'`, etc). I am not aware of any JDK built in class that will do just HTML encoding. Is there one? I am aware of other choices (for example, [Jakarta Commons Lang 'StringEscapeUtils'](http://commons.apache.org/lang/api/org/apache/commons/lang3/StringEscapeUtils.html "Jakarta Commons Lang 'StringEscapeUtils'"), but I don't want to add another external dependency to the project where I need this.
I'm hoping that something has been added to a recent JDK (aka 5 or 6) that will do this that I don't know about. Otherwise I have to roll my own. | Apparently, the answer is, "No." This was unfortunately a case where I had to do something and **couldn't** add a new external dependency for it -- in the short term. I agree with everyone that using Commons Lang is the best long-term solution. This is what I will go with once I can add a new library to the project.
It's a shame that something of such common use is not in the Java API. | There isn't a JDK built in class to do this, but it is part of the Jakarta commons-lang library.
```
String escaped = StringEscapeUtils.escapeHtml3(stringToEscape);
String escaped = StringEscapeUtils.escapeHtml4(stringToEscape);
```
Check out the [JavaDoc](http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringEscapeUtils.html#escapeHtml4(java.lang.String))
Adding the dependency is usually as simple as dropping the jar somewhere, and commons-lang has so many useful utilities that it is often worthwhile having it on board. | Is there a JDK class to do HTML encoding (but not URL encoding)? | [
"",
"html",
"java",
"html-encode",
""
] |
I want to implement an intialization mechanism that is annotation-based in Java. Specifically, I have an annotation I've defined:
```
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Initialization {
/**
* If the eager initialization flag is set to <code>true</code> then the
* initialized class will be initialized the first time it is created.
* Otherwise, it will be initialized the first time it is used.
*
* @return <code>true</code> if the initialization method should be called
* eagerly
*/
boolean eager() default false;
}
```
Additionally, I have an interface:
```
public interface SomeKindOfBasicInterface {}
```
I want to find every implementation of the `SomeKindOfBasicInterface` class on my classpath that has the `@Initialization` annotation on a method. I'm looking at Spring's `MetaDataReader` tools, which look like the best way to defer loading the other `SomeKindOfBasicInterface` implementations while I'm doing this... but I'm not sure how to do a search like I'm describing. Any tips? | You could use [Reflections](https://github.com/ronmamo/reflections), which is a Java runtime metadata analysis tool. I've used it to get all subtypes of a given type, but it can handle your case as well. | I would basically create a [BeanPostProcessor](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/BeanPostProcessor.html) implementation, maybe based on the [CommonAnnotationBeanPostProcessor](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.html). Then I'd set up for [component-scan](http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-scanning-autodetection) that scans the classpath and picks up all the beans matching your specification. When the bean is initialized, your postprocessor will be run.
I see I am assuming that you're looking for beans. If that's not the case you may have to scan the classpath yourself. | How can I find all classes on the classpath that have a specific method annotation? | [
"",
"java",
"spring",
"annotations",
""
] |
So let's say I wanna make a dictionary. We'll call it `d`. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:
```
d = {'hash': 'bang', 'slash': 'dot'}
```
Or I could do this:
```
d = dict(hash='bang', slash='dot')
```
Or this, curiously:
```
d = dict({'hash': 'bang', 'slash': 'dot'})
```
Or this:
```
d = dict([['hash', 'bang'], ['slash', 'dot']])
```
And a whole other multitude of ways with the `dict()` function. So obviously one of the things `dict()` provides is flexibility in syntax and initialization. But that's not what I'm asking about.
Say I were to make `d` just an empty dictionary. What goes on behind the scenes of the Python interpreter when I do `d = {}` versus `d = dict()`? Is it simply two ways to do the same thing? Does using `{}` have the *additional* call of `dict()`? Does one have (even negligible) more overhead than the other? While the question is really completely unimportant, it's a curiosity I would love to have answered. | ```
>>> def f():
... return {'a' : 1, 'b' : 2}
...
>>> def g():
... return dict(a=1, b=2)
...
>>> g()
{'a': 1, 'b': 2}
>>> f()
{'a': 1, 'b': 2}
>>> import dis
>>> dis.dis(f)
2 0 BUILD_MAP 0
3 DUP_TOP
4 LOAD_CONST 1 ('a')
7 LOAD_CONST 2 (1)
10 ROT_THREE
11 STORE_SUBSCR
12 DUP_TOP
13 LOAD_CONST 3 ('b')
16 LOAD_CONST 4 (2)
19 ROT_THREE
20 STORE_SUBSCR
21 RETURN_VALUE
>>> dis.dis(g)
2 0 LOAD_GLOBAL 0 (dict)
3 LOAD_CONST 1 ('a')
6 LOAD_CONST 2 (1)
9 LOAD_CONST 3 ('b')
12 LOAD_CONST 4 (2)
15 CALL_FUNCTION 512
18 RETURN_VALUE
```
dict() is apparently some C built-in. A really smart or dedicated person (not me) could look at the interpreter source and tell you more. I just wanted to show off dis.dis. :) | As far as performance goes:
```
>>> from timeit import timeit
>>> timeit("a = {'a': 1, 'b': 2}")
0.424...
>>> timeit("a = dict(a = 1, b = 2)")
0.889...
``` | What's the difference between dict() and {}? | [
"",
"python",
"initialization",
"instantiation",
""
] |
I have a one-function DLL that exports GetHash(). However, the source code for this DLL is lost. I need to integrate this code into my MSVC++ project.
I know that there are some shareware tools for doing this, but I think that I can do it manually.
What do I need to do, to accomplish this manually? | In a project that you build, reference the dll and call the hash function.
Run the code in the debugger and step in and disassemble the function and translate it back into a high level language.
If this isn't good enough, disassemble code into a series of functions you can implement with ASM blocks. | Do you have a LIB file for the DLL? A H(eader) file? Both are needed to link statically, which is the simplest way.
Otherwise, the easiest route is probably just to link it dynamically. (Unless this is a COM DLL -- does you have to RegSvr32 it? If so, you can reference it and call it COM-style.) In order to do so, you use the [LoadLibrary](http://msdn.microsoft.com/en-us/library/ms684175.aspx)() and [GetProcAddress](http://msdn.microsoft.com/en-us/library/ms683212(VS.85).aspx)() to obtain a function pointer. And here's where things get tricky: what calling convention does the function use, what parameters, and what return type? If you have those, you can define an appropriate function pointer type (e.g. "int fphasher\*(char \*)"). Otherwise, prepare for a lot of amusing experimentation or even disassembly listing to get things right...
A DLL viewer like [DllExportViewer](http://www.nirsoft.net/utils/dll_export_viewer.html) can help with getting the function name right, and get some hints whether C++ or C style calling conventions should be used. Caveat: I haven't tested this particular version. | How to recover from lost source code? | [
"",
"c++",
"dll",
"linker",
""
] |
Is this even possible?
The situation is, I don't control the embedded flash, and I have no way of knowing whether it is embedded with wmode=tranparent/opaque or wmode=window. This means in the first 2 situations I can put my html content on top, just by using z-index, but in the last situation (wmode=window) I have no control.
Does anybody know a way to overcome this problem? | You can't, the whole point of wmode=window is to put the plugin in an overlay window that goes on top of the main browser window - it isn't actually possible for the browser to draw on top of it. | Try something called iframe shim. not sure how cross-compatible it is, but it works for me | how to put html content over flash when wmode=window? | [
"",
"javascript",
"flash",
"z-index",
"wmode",
""
] |
I have been a VB.net developer for a long time and changed recently to C#.
When I was using VB.net, to call user settings, I just need to create a new setting using the designer and then call it from code with the My namespace.
Here's the code
`My.settings.anysetting`
I can change or get data from it.
However in C# the My keyword doesn't work, so what can I do to call settings?? | `Settings` are stored under the `Application` folder and as such, use that as their namespace.
```
int myInt = Properties.Settings.Default.myVariable;
Properties.Settings.Default.myVariable = 12;
Properties.Settings.Default.Save();
```
[Using Settings in C#](http://msdn.microsoft.com/en-us/library/aa730869.aspx) | Kinda like this:
```
this.BackColor = Properties.Settings.Default.myColor;
```
Documentation:
<https://msdn.microsoft.com/en-us/library/bb397759(v=vs.110).aspx> | How to use settings in Visual C# | [
"",
"c#",
"vb.net",
"settings",
""
] |
I need to find all matches of word which strictly begins with "$" and contains only digits. So I wrote
```
[$]\d+
```
which gave me 4 matches for
```
$10 $10 $20a a$20
```
so I thought of using word boundaries using \b:
```
[$]\d+\b
```
But it again matched
a$20 for me.
I tried
```
\b[$]\d+\b
```
but I failed.
I'm looking for saying, ACCEPT ONLY IF THE WORD STARTS WITH $ and is followed by DIGITS. How do I tell IT STARTS WITH $, because I think \b is making it assume word boundaries which means surrounded inside alphanumeric characters.
What is the solution? | Not the best solution but this should work. (It does with your test case)
```
(?<=\s+|^)\$\d+\b
``` | Have you tried
> \B\$\d+\b | Finding words strictly starting with $, Regex C# | [
"",
"c#",
"regex",
"cpu-word",
"word-boundary",
""
] |
I am still learning the whole WCF thing, so please bear with me here.
What I have is two self hosted services created using C# and VS 2008:
Service # 1 Adds two numbers and returns the result.
Service # 2 Returns the square of a number.
I want the client to be able to send in two numbers to Service 1, get the sum and then send the sum in to Service 2 and get the square.
I have two generated proxies for both the services, and I am able to use Intellisense on them, so that part supposedly works.
Now how do i configure my app.config file such that I can communicate with both the services? Right now, i get an exception every time I try to do that.
[The client works fine if I only have one of the configurations in the app file at a time, and try to call only that server.]
I suppose this is a very noobish question, and the answer probably is "structure the config file in \_\_\_\_\_ manner", but Google simply does not seem to have an example/guide.
Anyone know how to do this?
Note: [Consume multiple WCF services from one client](https://stackoverflow.com/questions/487662/consume-multiple-wcf-services-from-one-)
client Though sounds like a duplicate is NOT what I am looking for.
**Edit:** Thanks to marc\_s, I got it working
With both the services running in different apps, I did not need to split the server config file, but here is what I did with the client config files: First auto-generated the config files using SvrUtil.exe and then merged them in this way:
```
<bindings>
<wsHttpBinding>
<binding>
...
</binding>
<binding>
...
</binding>
</wsHttpBinding>
</bindings>
```
...
```
<endpoint>
```
... | If you want to run the two services on separate endpoints / ports, do something like this:
**Server-side:**
```
<service name="Service1">
<endpoint address="http://localhost:8001/service1.asmx"
binding="basicHttpBinding"
contract="IService1" />
</service>
<service name="Service2">
<endpoint address="http://localhost:8002/service2.asmx"
binding="basicHttpBinding"
contract="IService2" />
</service>
```
**Client-side:**
```
<client>
<endpoint address="http://localhost:8001/service1.asmx"
binding="basicHttpBinding"
contract="IService1"
name="Service1" />
<endpoint address="http://localhost:8002/service2.asmx"
binding="basicHttpBinding"
contract="IService2"
name="Service2" />
</client>
```
That should give you two separate, individual endpoints on the server and a client that will talk to both.
Marc | I realise you have asked for an App.Config answer but figure this might help. I would normally start by configuring the client connections programatically first, since it's simpler, and once you have got that working you could move it to your App.Config.
Here's an exmaple of how to configure a WCF client.
```
BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress address = new EndpointAddress(serverURL);
MyServiceClient myServiceProxy = new MyServiceClient(binding, address);
```
You could then have something like the below in your App.Config.
```
<client>
<endpoint address="http://localhost/service1.asmx"
binding="basicHttpBinding"
bindingConfiguration="basicHttpBinding"
contract="IService1"
name="Service1" />
<endpoint address="http://localhost/service2.asmx"
binding="basicHttpBinding"
bindingConfiguration="basicHttpBinding"
contract="IService2"
name="Service2" />
</client>
``` | How to consume multiple WCF services from one client | [
"",
"c#",
".net",
"wcf",
"wcf-client",
""
] |
in this text :
```
text text text [[st: aaa bbb ccc ddd eee fff]] text text
text text [[st: ggg hhh iii jjj kkk
lll mmm nnn]] text text text
```
I'm trying to get the text between the [[st: and that ends with ]]
My program should output:
```
aaa bbb ccc ddd eee fff (first match)
ggg hhh iii jjj kkk \n lll mmm nnn(second match)
```
But I can only get it to return the first [[st: and the last ]], so there is just one match instead of two. Any ideas?
Here's my code:
```
package com.s2i.egc.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegex {
/**
* @param args
*/
public static void main(String[] args) {
String bodyText = "text text text [[st: aaa bbb ccc ddd eee fff]] text text text text [[st: ggg hhh iii jjj kkk\n lll mmm nnn]] text text text";
String currentPattern = "\\[\\[st:.*\\]\\]";
Pattern myPattern = Pattern.compile(currentPattern, Pattern.DOTALL);
Matcher myMatcher = myPattern.matcher(bodyText);
int i = 1;
while (myMatcher.find()) {
String match = bodyText.substring(myMatcher.start() + 5, myMatcher.end() - 3);
System.out.println(match + " (match #" + i + ")");
i++;
}
}
}
``` | The quantifier \* (0 or more) is greedy by default, so it matches to the second ]].
Try changing to a reluctant pattern match:
```
String currentPattern = "\\[\\[st:.*?\\]\\]";
``` | You should use lazy mode for the asterisk
```
.*
```
use instead:
```
"\\[\\[st:.*?\\]\\]"
``` | Regex to find strings contained between separators | [
"",
"java",
"regex",
"csv",
""
] |
I'm doing a select box navigator and wondering if it's better to do a javascript redirect or submit a form and redirect from there. Pros and cons of each? | HTTP redirect:
* Pros: you can log user's activity.
* Cons: one extra turnaround cycle until the user gets effectively redirected.
JavaScript redirect:
* Pros: user gets redirected immediately
* Cons: you cannot log user's activity, unless you use AJAX; if user has JavaScript disabled he won't get redirected.
In this case, I tend to use [Unobtrusive JavaScript](http://en.wikipedia.org/wiki/Unobtrusive_JavaScript) to solve this issue: code as if no JavaScript is enabled (i.e. a "Go" button that posts the form); then, after the page loads, Javascript would hide that button, add change functionality to the select box and send an AJAX request to log the activity.
That way you get the best of the two worlds :) | If you mean something like navigating by selecting an item of a list, you could do both:
* Have the form configured with a GET, that points directly to the target page.
* If js is supported, have the "submit" be called when selecting the value. If no js is supported, a select/go/open button should be displayed, allowing the user to still work with the application
**Note:** The approach above goes directly to the target page. This is different than sending a redirect from the server, which incurs in an extra request to be handled, adds extra delay to the operation and more requests to be handled by the server. This is a navigate scenario, there is no need to go server side for this (at least not without additional specific requirements). | Better to Javascript redirect OR form submit? | [
"",
"javascript",
"html",
"redirect",
"submit",
""
] |
I have a small unsorted array and I'd like to find the **index** of a particular value. Does C++ have a built-in sequential search function for this, or do you just write the loop yourself each time it comes up?
I'm specifically using a C-style array like:
```
std::string arr[5] = { "EVEN", "ODD", "NONE", "MARK", "SPACE" };
```
and I need the index of a value that the user supplies. | `std::find()` should work:
```
#include <stdio.h>
#include <algorithm>
#include <string>
using std::string;
std::string arr[5] = { "EVEN", "ODD", "NONE", "MARK", "SPACE" };
int main() {
string* pArrEnd = arr + sizeof( arr)/sizeof(arr[0]);
string* pFound = std::find( arr, pArrEnd, "MARK");
if (pFound == pArrEnd) {
printf( "not found\n");
}
else {
printf( "%s was found at index %d\n", pFound->c_str(), pFound - arr);
printf( "or using STL: %d\n", std::distance( arr, pFound));
}
return 0;
}
``` | Use [`std::find()`](http://en.cppreference.com/w/cpp/algorithm/find) from the STL-*algorithm*-library, or the `find()`-method of your particular container. | Does C++ have a sequential search function? | [
"",
"c++",
"search",
""
] |
I need to write a PHP page which would accept an XML document sent over a POST request like this:
```
POST /mypage.php HTTP/1.1
Host: myhost.com
Content-Type: application/xml
Content-Length: ...
<?xml version="1.0" encoding="utf-8"?>
<data>
...
</data>
```
This is not data from some HTML form, just a plain XML document.
How can I access this XML in my PHP code? | Read from [`php://input`](http://php.net/wrappers.php). For example, you could use:
```
$rawdata = file_get_contents('php://input');
```
or
```
$rootNode = simplexml_load_file('php://input');
```
The alternative, using [`$HTTP_RAW_POST_DATA`](http://php.net/manual/en/reserved.variables.httprawpostdata.php), works, too - but it's slower and needs the PHP configuration [`always_populate_raw_post_data`](http://php.net/manual/en/ini.core.php#ini.always-populate-raw-post-data). | Try the [`$HTTP_RAW_POST_DATA` variable](http://docs.php.net/manual/en/reserved.variables.httprawpostdata.php) or the [`php://input` stream](http://docs.php.net/manual/en/wrappers.php.php). | How to access POST data in PHP? | [
"",
"php",
"http",
"post",
""
] |
I have done this code to login,to retrieve and show a webpage :
```
// login info array
string postData = "user_name=tler";
postData += "&user_password=lodvader";
byte[] data = Encoding.ASCII.GetBytes(postData);
// web request
WebRequest req = WebRequest.Create("http://www.lol.com/login.php");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
// stream response to string
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream(), Encoding.GetEncoding("iso-8859-1"));
string responseString = reader.ReadToEnd();
// retrieve text within title
Regex rx = new Regex(@"(?<=<title>).+?(?=</title>)");
var variable = rx.Matches(responseString);
// output
Console.WriteLine(variable[0]);
Console.ReadLine();
```
But, the following page after login is an html redirect like :
```
<meta http-equiv="refresh" content="3; URL="bb.php">
```
How to follow this link and retrieve next page ? | I have found the time to finish it, here the response ( i tried to be as clear as possible ) :
```
// Cookie for our session
var cookieContainer = new CookieContainer();
// Encode post variables
ASCIIEncoding encoding=new ASCIIEncoding();
byte[] loginDataBytes = encoding.GetBytes("user_name=belaz&user_password=123");
// Prepare our login HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://blabla.fr/verify.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookieContainer;
request.ContentLength = loginDataBytes.Length;
// Write encoded post variable to the stream
Stream newStream = request.GetRequestStream();
newStream.Write(loginDataBytes, 0, loginDataBytes.Length);
newStream.Close();
// Retrieve HttpWebResponse
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Link the response cookie to the domain
cookieContainer.Add(new Uri("http://blabla.fr/"),response.Cookies);
// Prepare our navigate HttpWebRequest, and set his cookie.
HttpWebRequest requestProfile = (HttpWebRequest)WebRequest.Create("http://blabla.fr/bb.php");
requestProfile.CookieContainer = cookieContainer;
// Retrieve HttpWebResponse
HttpWebResponse responseProfile = (HttpWebResponse)requestProfile.GetResponse();
// Retrieve stream response and read it to end
Stream st = responseProfile.GetResponseStream();
StreamReader sr = new StreamReader(st);
string buffer = sr.ReadToEnd();
``` | Just send a new WebRequest to the bb.php file. Make sure that you use the same CookieContainer since I presume that login.php uses cookie-based sessions to remember you. Check out the [HttpWebRequest.CookieContainer](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.cookiecontainer.aspx) property. This requires you to cast your WebRequest to a HttpWebRequest.
Added: (Couldn't write example code in the comment.)
I'm just making code up without proofing now...
```
var cookies = new CookieContainer();
var firstReq = (HttpWebRequest)WebRequest.Create(".../login.php");
firstReq.CookieContainer = cookies;
var secondReq = (HttpWebRequest)WebRequest.Create(".../bb.php");
secondReq.CookieContainer = cookies
``` | How to retrieve an html redirected webpage programmatically? | [
"",
"c#",
"httpwebrequest",
""
] |
When I want to remove a Cookie I try
```
unset($_COOKIE['hello']);
```
I see in my cookie browser from firefox that the cookie still exists. How can I really remove the cookie? | You May Try this
```
if (isset($_COOKIE['remember_user'])) {
unset($_COOKIE['remember_user']);
setcookie('remember_user', '', -1, '/');
return true;
} else {
return false;
}
``` | Set the value to "" and the expiry date to yesterday (or any date in the past)
```
setcookie("hello", "", time()-3600);
```
Then the cookie will expire the next time the page loads. | Remove a cookie | [
"",
"php",
"cookies",
""
] |
I'm about to start creating a new website that has standard user management (customers login and handling (change customer details etc) + my own functionality. I'm looking for the most efficient way to do it. I know PHP/CSS/Jquery quite well.
I have looked into Drupal as a starting point and found it too cumbersome for my needs.
CodeIgniter and PHPcake seems not to be efficient because I'll spend time learning the platform instead of developing (which I would love to do, but not currently).
It seems that what I need is a skeleton of PHP site that simply handles users functionality. Surprisingly I couldn't find one.
Could you recommend a starting point such as an open source website code that I can easily cut the user management part from? Or another option which is more streightforward than learning a new platform/framework? | To be honest, to get started in a framework like CodeIgniter you shouldn't need more than 5 to 15 minutes of learning time (a CI "skeleton" is extremely easy to do).
Yes, it may have plenty of tools/helpers/libraries but for the most part the learning curve is extremely shallow.
As to the users functionality, there are a couple of user-made libraries that may suit your needs - a comprehensive list with detailed functionality can be found here: [what-code-igniter-authentication-library-is-best](https://stackoverflow.com/questions/346980/what-code-igniter-authentication-library-is-best) | Quite honestly, if you are going to use one of the existing platforms out there you are going to have to put the effort in to learning the architecture of it and then adapting to it to further develop on it.
Also, user management is a pain but really shouldn't take you THAT long to implement. If that's all you want, I'd say roll your own because then you are going to be that much more familiar with it. Anything that someone else has written you are going to have to learn about. | Best starting point for a website with user management functionality | [
"",
"php",
"user-management",
"login-script",
""
] |
Can anyone give me a Java regex to identify repeated characters in a string? I am only looking for characters that are repeated immediately and they can be letters or digits.
### Example:
> abccde <- looking for this (immediately repeating c's)
>
> abcdce <- not this (c's seperated by another character) | Try `"(\\w)\\1+"`
The `\\w` matches any word character (letter, digit, or underscore) and the `\\1+` matches whatever was in the first set of parentheses, one or more times. So you wind up matching any occurrence of a word character, followed immediately by one or more of the same word character again.
(Note that I gave the regex as a Java string, i.e. with the backslashes already doubled for you) | ```
String stringToMatch = "abccdef";
Pattern p = Pattern.compile("(\\w)\\1+");
Matcher m = p.matcher(stringToMatch);
if (m.find())
{
System.out.println("Duplicate character " + m.group(1));
}
``` | How can I find repeated characters with a regex in Java? | [
"",
"java",
"regex",
""
] |
I need to parse pretty big XML in PHP (like 300 MB). How can i do it most effectively?
In particular, i need to locate the specific tags and extract their content in a flat TXT file, nothing more. | If it's one or few time job I'd use [XML Starlet](http://xmlstar.sourceforge.net/). But if you really want to do it PHP side then I'd recommend to preparse it to smaller chunks and then processing it. If you load it via [DOM](http://php.net/DOM) as one big chunk it will take **a lot** of memory. Also use CLI side PHP script to speed things up. | You can read and parse XML in chunks with an old-school [SAX-based parsing](http://en.wikipedia.org/wiki/Simple_API_for_XML) approach using PHP's [xml parser functions](http://php.net/manual/en/book.xml.php).
Using this approach, there's no real limit to the size of documents you can parse, as you simply read and parse a buffer-full at a time. The parser will fire events to indicate it has found tags, data etc.
There's a [simple exampl](http://www.php.net/manual/en/example.xml-structure.php)e in the manual which shows how to pick up start and end of tags. For your purposes you might also want to use [xml\_set\_character\_data\_handler](http://www.php.net/manual/en/function.xml-set-character-data-handler.php) so that you pick up on the text between tags also. | Parse big XML in PHP | [
"",
"php",
"xml",
""
] |
Here is an example of an exception happening inside a lock, with a try-catch block.
```
int zero = 0;
int j = 10;
lock (sharedResource.SyncRoot)
{
try
{
j = j / zero;
}
catch (DivideByZeroException e)
{
// exception caught but lock not released
}
}
```
How do I safely release this lock in the catch? | Won't it be released automatically?
From the MSDN lock means
```
System.Threading.Monitor.Enter(x);
try {
...
}
finally {
System.Threading.Monitor.Exit(x);
}
```
So you don't have to bother. | The lock won't be released until you pass out of the scope of the lock(sharedResource.SyncRoot) block. `lock (sharedResource.SyncRoot) {}` is basically identical to:
```
Monitor.Enter(sharedResource.SyncRoot);
try
{
}
finally
{
Monitor.Exit(sharedResource.SyncRoot);
}
```
You can either do the Enter/Exit yourself if you want more control, or just rescope the lock to what you want, like:
```
try
{
lock(sharedResource.SyncRoot)
{
int bad = 2 / 0;
}
}
catch (DivideByZeroException e)
{
// Lock released by this point.
}
``` | In C# how can I safely exit a lock with a try catch block inside? | [
"",
"c#",
""
] |
I have built a table in a class GetData.cs
```
public Table BuildTable()
{
Table tButtons = new Table();
TableRow tRow = new TableRow();
TableCell tCell = new TableCell();
long lColumn = 0;
long lPreviousColumn = 0;
long lRow = 0;
long lPreviousRow = 0;
long lLanguage = 0;
long lPreviousLanguage=0;
OpenConnection();
ButtonData();
Int32 lRowOrd = aReader.GetOrdinal("RowNumber");
Int32 lColOrd = aReader.GetOrdinal("ColumnNumber");
Int32 lLangOrd = aReader.GetOrdinal("Language");
Int32 lLabelOrd = aReader.GetOrdinal("Label");
while (aReader.Read())
{
lRow = IsDbNull(aReader,lRowOrd);//first get our column number
lColumn = IsDbNull(aReader,lColOrd);//first get our column number
lLanguage = IsDbNull(aReader,lLangOrd);//first get our column number
if (lPreviousRow != lRow)//we have a new row
{
if (lPreviousRow != 0)//then we are working on one and need to save it before moving on
{
tButtons.Rows.Add(tRow);//add the new row to the table
}
lPreviousRow = lRow;//remember the value for next time
tRow = new TableRow();
tRow.Visible = true;
//*******put the category titles in here somewhere
}
if (lPreviousColumn != lColumn)//we have a new column
{
if (lPreviousColumn != 0)//then we are working on one and need to save it before moving on
{
tRow.Cells.Add(tCell);//add the new cell to the row
}
lPreviousColumn = lColumn;//remember the value for next time
//*******add the cell colors
if (lPreviousLanguage != lLanguage)//we have a new column
{
lPreviousLanguage = lLanguage;//remember the value for next time
tCell.Text = IsDbNull(aReader,lLabelOrd,"");
//*******add the languages to properties
}
tCell = new TableCell();
tCell.Visible=true;
}
}
CloseConnection();
tButtons.Visible=true;
return tButtons;
}
```
In my Default.aspx.cs page I have
```
GetData Buttons = new GetData();//create a reference to the class
ButtonTable = Buttons.BuildTable();
OutPut.Text = ButtonTable.Rows.Count.ToString();
```
In Default.aspx
```
<asp:Table runat="server" ID="ButtonTable" />
<asp:Label runat="server" ID="OutPut" />
```
Output shows 4 rows, but table is empty.
```
<table id="ButtonTable" border="0"></table>
```
What am I doing wrong? | > What the heck am I missing?
Apparently, a lot. In your markup, you have declared an instance of a [System.Web.UI.WebControls.Table](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.table.aspx). In your instance of the Page class, this will have a variable name of "ButtonTable". It will also be automatically added to the [Page.Controls](http://msdn.microsoft.com/en-us/library/system.web.ui.control.controls.aspx) collection. When the page is going to be rendered, the Controls collection will be iterated and rendered in turn.
In your default.aspx.cs code, you're simply pointing your ButtonTable reference to *a different Table control* - but you're not affecting the Page.Controls collection. When render time comes, it is the (blank) Table defined in the markup that will be rendered - not the result of your BuildTable call.
All of this is a fairly long winded "you're doing it wrong". The answer to *why* you want your table building code in a separate class would shed some light on the "right way". But - and I mean no offense - I think you need to study the basics behind ASP.NET before you go any further.
That being said, the most immediate fix (but likely *not what you really want*) is to add the table to the Controls collection so that it gets rendered:
```
GetData Buttons = new GetData();//create a reference to the class
ButtonTable = Buttons.BuildTable();
this.Controls.Add(ButtonTable);
OutPut.Text = ButtonTable.Rows.Count.ToString();
```
Note that it will render separately from your markup defined ButtonTable, and so will be placed *after* the Output label. That is because it was added after the Output label. | I really suggest you:
* Run it line by line in the debugger to see what's going on
* Refactor it, the code is hard to read. Adding more comments won't solve that.
* Consider what you want to achieve and check if it can fits to databind to a control like ListView.
That said, your code:
```
GetData Buttons = new GetData();
ButtonTable = Buttons.BuildTable(); // this is what's wrong
OutPut.Text = ButtonTable.Rows.Count.ToString();
```
Just assigning the control in the page it's not the way to do it. Either add the returned table to the controls collection, or change BuildTable to receive the table it will load the info into. Never directly assign to the control of the asp.net page, once I had to debug code with some very strange issues and a developer had assigned null to a control (not to a property of the control) which messed up during the asp.net render cycle. | Why does my table have no content in ASP.NET? | [
"",
"c#",
".net",
"asp.net",
"html",
""
] |
I need to compare one given value with a retrieved values. I do this several times in the code. I am not satisfied with how it looks and I am seeking for a some sort of an util function. Anyone wrote one?
Number of values I am comparing with is known at the compile time.
**Update:** I'd like to get rid of containers as I know exact amount of values ( often not more then 3 ) I want to compare with. And it is not so convenient to put items to the container every time.
I don't love **if** neither because it is not obvious as "find".
```
#include <algorithm>
#include <string>
#include <vector>
std::string getValue1()
{
return "test";
}
std::string getValue2()
{
return "the";
}
std::string getValue3()
{
return "world";
}
int main()
{
const std::string value = "the";
// simple if
if ( value == getValue1() ||
value == getValue2() ||
value == getValue3() )
return 1;
// using collections like vector, set
std::vector<std::string> values;
values.push_back( getValue1() );
values.push_back( getValue2() );
values.push_back( getValue3() );
if ( values.end() != std::find( values.begin(), values.end(), value ) )
return 1;
// third option I'd use instead
//
return 0;
}
``` | For your request to do
```
if (InSet(value)(GetValue1(), GetValue2(), GetValue3()))
{
// Do something here...
}
```
Try this:
```
template <typename T>
class InSetHelper
{
const T &Value;
void operator=(const InSetHelper &);
public:
InSetHelper(const T &value) : Value(value) {}
template<class Other, class Another>
bool operator()(const Other &value1, const Another &value2) const
{
return Value == value1 || Value == value2;
}
template<class Other, class Another, class AThird>
bool operator()(const Other &value1, const Another &value2, const AThird &value3) const
{
return Value == value1 || Value == value2 || Value == value3;
}
};
template <typename T>
InSetHelper<T> InSet(const T &value) { return InSetHelper<T>(value); }
```
This syntax might be more clear though:
```
if (MakeSet(GetValue1(), GetValue2(), GetValue3()).Contains(value))
{
// Do something here...
}
template <typename T, typename U, typename V>
class Set3
{
const T& V1;
const U& V2;
const V& V3;
void operator=(const Set3 &);
public:
Set3(const T &v1, const U &v2, const V &v3) : V1(v1), V2(v2), V3(v3) {}
template <typename W>
bool Contains(const W &v) const
{
return V1 == v || V2 == v || V3 == v;
}
};
template <typename T, typename U>
class Set2
{
// as above
};
template <typename T, typename U, typename V>
Set3<T, U, V> MakeSet(const T &v1, const U &v2, const V &v3)
{
return Set3<T, U, V>(v1, v2, v3);
}
template <typename T, typename U>
Set3<T, U> MakeSet(const T &v1, const U &v23)
{
return Set3<T, U, V>(v1, v2);
}
```
If those values are really part of a tree or a linked list, then you have your set/container already, and your best bet is to just use some recursion:
```
parent.ThisOrDescendantHasValue(value);
```
You'd just add this to whatever class parent and child belong to:
```
class Node
{
public:
Value GetValue();
Node *GetChild();
bool ThisOrDescendantHasValue(const Value &value)
{
return GetValue() == value
|| (GetChild() && GetChild->ThisOrDescendantHasValue(value));
}
};
``` | If the values you're looking for are Comparable with operator< (like ints, float and std::strings), then it's faster to use an std::set to put the values there and then check set.find(value) == set.end(). This is because the set will store the values with a certain order that allows for faster lookups. Using an hash table will be even faster. However, for less than 50 values or so you might not notice any difference :) So my rule of thumb would be:
* Less then 5 items: if with multiple ||
* 5 or more: put in a set or hash table | C++ comparing bunch of values with a given one | [
"",
"c++",
""
] |
Sometimes, a certain XMLElement has a value:
```
<CAR>value</CAR>
```
sometimes though it does not in the returend XML:
```
<CAR/>
```
When using the XmlReader, I am not sure yet how to handle this situation. For example I have code that reads each element. But what if car has no value coming back at times? Then my DateTime.Parse bombs out so I'm not quite sure hot to essentially handle these situations and skip it with XmlReader:
```
reader.ReadStartElement("CAR");
// error here since car doesn't have a value this time
_tDate = DateTime.Parse(reader.ReadContentAsString());
```
**EDIT:**
```
if(!reader.IsStartElement())
```
This doesn't work either. After it sees that it's not a start element, I get an error and not sure how to handle skipping it essentially after the if statement
```
if(!reader.IsStartElement())
{
reader.ReadStartElement("CAR");
_tDate = DateTime.Parse(reader.ReadContentAsString());
}
reader. ReadEndElement(); <-- ERROR HERE not sure how to move on
```
**EDIT 2:**
How can I be getting true when the value is `<CAR/>`
```
reader.ReadStartElement("In");
_optedInDate = DateTime.Parse(reader.ReadContentAsString());
_userIsOut = false;
reader.ReadEndElement();
if(reader.IsStartElement("CAR"))
{
reader.ReadStartElement("CAR");
_optedOutDate = DateTime.Parse(reader.ReadContentAsString());
_userIsOptedOut = true;
}
reader.ReadStartElement("COLUMNS");
reader.ReadStartElement("COLUMN");
```
It's clearly NOT a start element but I get true...
**EDIT 3:**
tried this:
```
if((reader.NodeType == XmlNodeType.Element) & (!reader.IsEmptyElement))
{
reader.ReadStartElement("CAR");
_optedOutDate = DateTime.Parse(reader.ReadContentAsString());
_userIsOptedOut = true;
}
reader.ReadStartElement("COLUMNS"); Error Here: Element 'COLUMNS' was not found. Line 12, position 2
```
The nodetype was "whitespace". I can't figure out how the hell to skip that damn `<CAR/>`. | If the reader you are using is an XMLReader then use:
```
XmlReader reader;
reader.IsEmptyElement // to determine if you should try and parse the value.
```
Be aware that you might want something alone the lines of the following to ensure you're reading content...
```
Reader.Read();
Reader.MoveToContent();
``` | Read the content first, then either call `DateTime.Parse` or not depending on whether there's content. If you get "bad" content sometimes which you want to skip, you should look at `DateTime.TryParse` too. As to what exactly you should do in the grander scheme of things if you get an empty element, that entirely depends on your application - we can't really tell you that. | How to handle When XML Element does not have a value | [
"",
"c#",
"xml",
""
] |
I got an object, which is called in my form1-window. How can I change anything from the form1-object from within this object, for example a label or a processbar? | It would be a bad (circular) design to give your object a reference to your form. Use an interface or a delegate (callback).
```
// untested code
class MyObjectClass
{
public delegate void Reportback(int percentage);
public void DoSomething(Reportback callBack) { ...; callback(i*100F/total); ...}
}
class Form1: Form
{
private void reportProgress(int percent) { ...; progressbar1.value = percent; }
void SomeMethod() { myObject1.DoSomething(reportprogress); }
}
``` | Generally speaking, when you find yourself with a need for one object to manipulate the private fields of another, your design needs work.
For instance, an class that's performing some kind of long-running business logic shouldn't be updating a `ProgressBar`. First, that's not its job. Second, that couples the functioning of the business logic to the implementation details of the user interface.
It's much better if the class simply raises events as it performs its long-running task. For instance, look at this class:
```
public class BusinessLogic
{
public event EventHandler ProgressChanged;
private int _Progress;
public int Progress
{
get { return _Progress; }
private set
{
_Progress = value;
EventHandler h = ProgressChanged;
if (h != null)
{
h(this, new EventArgs());
}
}
}
}
```
Whenever any method in this class sets the `Progress` property, the `ProgressChanged` event gets raised. In your form, you can instantiate the object with logic like this:
```
private BusinessLogic Task;
private void Form1_Load(object sender, EventArgs e)
{
Task = new BusinessLogic();
Task.ProgressChanged += Task_ProgressChanged;
}
void Task_ProgressChanged(object sender, EventArgs e)
{
taskProgessBar.Value = ((BusinessLogic) sender).Progress;
}
```
Now, every time a method in the `Task` object sets the `Progress` property, the `ProgressBar` in the form will get updated.
This is quite a bit more code to write than just having the object update the `ProgressBar`, sure. But look what you get out of it. If you have to refactor your form into two forms, and move the task to a new form, you don't have to touch the `BusinessLogic` class. If you move your `ProgressBar` from being a control on the form to being a `ToolStripProgressBar` on a `ToolStrip`, you don't have to touch the `BusinessLogic` class. If you decide that progress reporting isn't important, you don't have to touch the `BusinessLogic` class.
Essentially, this approach protects the `BusinessLogic` class from having to know *anything* about the user interface. This makes it a lot easier to change both the business logic and the user interface as your program evolves. | How can I change components of a form from within another object? | [
"",
"c#",
""
] |
What's the quickest and most efficient way of reading the last line of text from a [very, very large] file in Java? | Have a look at my answer to a [similar question for C#](https://stackoverflow.com/questions/452902/how-to-read-a-text-file-reversely-with-iterator-in-c). The code would be quite similar, although the encoding support is somewhat different in Java.
Basically it's not a terribly easy thing to do in general. As MSalter points out, UTF-8 does make it easy to spot `\r` or `\n` as the UTF-8 representation of those characters is just the same as ASCII, and those bytes won't occur in multi-byte character.
So basically, take a buffer of (say) 2K, and progressively read backwards (skip to 2K before you were before, read the next 2K) checking for a line termination. Then skip to exactly the right place in the stream, create an `InputStreamReader` on the top, and a `BufferedReader` on top of that. Then just call `BufferedReader.readLine()`. | **Below are two functions, one that returns the last non-blank line of a file without loading or stepping through the entire file, and the other that returns the last N lines of the file without stepping through the entire file:**
What tail does is zoom straight to the last character of the file, then steps backward, character by character, recording what it sees until it finds a line break. Once it finds a line break, it breaks out of the loop. Reverses what was recorded and throws it into a string and returns. 0xA is the new line and 0xD is the carriage return.
If your line endings are `\r\n` or `crlf` or some other "double newline style newline", then you will have to specify n\*2 lines to get the last n lines because it counts 2 lines for every line.
```
public String tail( File file ) {
RandomAccessFile fileHandler = null;
try {
fileHandler = new RandomAccessFile( file, "r" );
long fileLength = fileHandler.length() - 1;
StringBuilder sb = new StringBuilder();
for(long filePointer = fileLength; filePointer != -1; filePointer--){
fileHandler.seek( filePointer );
int readByte = fileHandler.readByte();
if( readByte == 0xA ) {
if( filePointer == fileLength ) {
continue;
}
break;
} else if( readByte == 0xD ) {
if( filePointer == fileLength - 1 ) {
continue;
}
break;
}
sb.append( ( char ) readByte );
}
String lastLine = sb.reverse().toString();
return lastLine;
} catch( java.io.FileNotFoundException e ) {
e.printStackTrace();
return null;
} catch( java.io.IOException e ) {
e.printStackTrace();
return null;
} finally {
if (fileHandler != null )
try {
fileHandler.close();
} catch (IOException e) {
/* ignore */
}
}
}
```
**But you probably don't want the last line, you want the last N lines, so use this instead:**
```
public String tail2( File file, int lines) {
java.io.RandomAccessFile fileHandler = null;
try {
fileHandler =
new java.io.RandomAccessFile( file, "r" );
long fileLength = fileHandler.length() - 1;
StringBuilder sb = new StringBuilder();
int line = 0;
for(long filePointer = fileLength; filePointer != -1; filePointer--){
fileHandler.seek( filePointer );
int readByte = fileHandler.readByte();
if( readByte == 0xA ) {
if (filePointer < fileLength) {
line = line + 1;
}
} else if( readByte == 0xD ) {
if (filePointer < fileLength-1) {
line = line + 1;
}
}
if (line >= lines) {
break;
}
sb.append( ( char ) readByte );
}
String lastLine = sb.reverse().toString();
return lastLine;
} catch( java.io.FileNotFoundException e ) {
e.printStackTrace();
return null;
} catch( java.io.IOException e ) {
e.printStackTrace();
return null;
}
finally {
if (fileHandler != null )
try {
fileHandler.close();
} catch (IOException e) {
}
}
}
```
**Invoke the above methods like this:**
```
File file = new File("D:\\stuff\\huge.log");
System.out.println(tail(file));
System.out.println(tail2(file, 10));
```
**Warning**
In the wild west of unicode this code can cause the output of this function to come out wrong. For example "Mary?s" instead of "Mary's". Characters with [hats, accents, Chinese characters](http://en.wikipedia.org/wiki/Diacritic) etc may cause the output to be wrong because accents are added as modifiers after the character. Reversing compound characters changes the nature of the identity of the character on reversal. You will have to do full battery of tests on all languages you plan to use this with.
For more information about this unicode reversal problem read this:
<https://codeblog.jonskeet.uk/2009/11/02/omg-ponies-aka-humanity-epic-fail/> | Quickly read the last line of a text file? | [
"",
"java",
"file",
"io",
""
] |
I really want to use hashsets in my program. Using a dictionary feels ugly. I'll probably start using VS2008 with .Net 3.5 some day, so my ideal would be that even though I can't (or can I?) use [hashsets](http://msdn.microsoft.com/en-us/library/bb359438.aspx) in VS2005, when I start using .NET 3.5, I don't want to have to change much, if anything, in order to switch to using these hashsets.
I am wondering if anyone is aware of an existing hashset implementation designed with this in mind, or a way to use the 3.5 hashset in VS2005. | You can use `HashSet<T>` in a 2.0 application now - just reference System.Core.dll and you should be good to go.
**Note:** This would require you to install the [.NET 3.5 framework](http://www.microsoft.com/downloads/details.aspx?FamilyID=AB99342F-5D1A-413D-8319-81DA479AB0D7&displaylang=en) which is free and separate from Visual Studio. Once you have that installed you will have the new System.Core assembly which contains the `HashSet<T>` type. Since the .NET frameworks versions 2.0 - 3.5 all share the same CLR you can use this assembly in your 2.0 application without any issues. | Here's one I wrote for 2.0 that uses a Dictionary<T, object> internally. It's not an exact match of the 3.5 HashSet<T>, but it does the job for me.
```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
public class HashSet<T> : ICollection<T>, ISerializable, IDeserializationCallback
{
private readonly Dictionary<T, object> dict;
public HashSet()
{
dict = new Dictionary<T, object>();
}
public HashSet(IEnumerable<T> items) : this()
{
if (items == null)
{
return;
}
foreach (T item in items)
{
Add(item);
}
}
public HashSet<T> NullSet { get { return new HashSet<T>(); } }
#region ICollection<T> Members
public void Add(T item)
{
if (null == item)
{
throw new ArgumentNullException("item");
}
dict[item] = null;
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception>
public void Clear()
{
dict.Clear();
}
public bool Contains(T item)
{
return dict.ContainsKey(item);
}
/// <summary>
/// Copies the items of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the items copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional.-or-<paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>.-or-The number of items in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.-or-Type T cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null) throw new ArgumentNullException("array");
if (arrayIndex < 0 || arrayIndex >= array.Length || arrayIndex >= Count)
{
throw new ArgumentOutOfRangeException("arrayIndex");
}
dict.Keys.CopyTo(array, arrayIndex);
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
public bool Remove(T item)
{
return dict.Remove(item);
}
/// <summary>
/// Gets the number of items contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// The number of items contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
public int Count
{
get { return dict.Count; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
/// </returns>
public bool IsReadOnly
{
get
{
return false;
}
}
#endregion
public HashSet<T> Union(HashSet<T> set)
{
HashSet<T> unionSet = new HashSet<T>(this);
if (null == set)
{
return unionSet;
}
foreach (T item in set)
{
if (unionSet.Contains(item))
{
continue;
}
unionSet.Add(item);
}
return unionSet;
}
public HashSet<T> Subtract(HashSet<T> set)
{
HashSet<T> subtractSet = new HashSet<T>(this);
if (null == set)
{
return subtractSet;
}
foreach (T item in set)
{
if (!subtractSet.Contains(item))
{
continue;
}
subtractSet.dict.Remove(item);
}
return subtractSet;
}
public bool IsSubsetOf(HashSet<T> set)
{
HashSet<T> setToCompare = set ?? NullSet;
foreach (T item in this)
{
if (!setToCompare.Contains(item))
{
return false;
}
}
return true;
}
public HashSet<T> Intersection(HashSet<T> set)
{
HashSet<T> intersectionSet = NullSet;
if (null == set)
{
return intersectionSet;
}
foreach (T item in this)
{
if (!set.Contains(item))
{
continue;
}
intersectionSet.Add(item);
}
foreach (T item in set)
{
if (!Contains(item) || intersectionSet.Contains(item))
{
continue;
}
intersectionSet.Add(item);
}
return intersectionSet;
}
public bool IsProperSubsetOf(HashSet<T> set)
{
HashSet<T> setToCompare = set ?? NullSet;
// A is a proper subset of a if the b is a subset of a and a != b
return (IsSubsetOf(setToCompare) && !setToCompare.IsSubsetOf(this));
}
public bool IsSupersetOf(HashSet<T> set)
{
HashSet<T> setToCompare = set ?? NullSet;
foreach (T item in setToCompare)
{
if (!Contains(item))
{
return false;
}
}
return true;
}
public bool IsProperSupersetOf(HashSet<T> set)
{
HashSet<T> setToCompare = set ?? NullSet;
// B is a proper superset of a if b is a superset of a and a != b
return (IsSupersetOf(setToCompare) && !setToCompare.IsSupersetOf(this));
}
public List<T> ToList()
{
return new List<T>(this);
}
#region Implementation of ISerializable
/// <summary>
/// Populates a <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with the data needed to serialize the target object.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> to populate with data. </param><param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext"/>) for this serialization. </param><exception cref="T:System.Security.SecurityException">The caller does not have the required permission. </exception>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null) throw new ArgumentNullException("info");
dict.GetObjectData(info, context);
}
#endregion
#region Implementation of IDeserializationCallback
/// <summary>
/// Runs when the entire object graph has been deserialized.
/// </summary>
/// <param name="sender">The object that initiated the callback. The functionality for this parameter is not currently implemented. </param>
public void OnDeserialization(object sender)
{
dict.OnDeserialization(sender);
}
#endregion
#region Implementation of IEnumerable
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>1</filterpriority>
public IEnumerator<T> GetEnumerator()
{
return dict.Keys.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>2</filterpriority>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
``` | Using HashSet in C# 2.0, compatible with 3.5 | [
"",
"c#",
".net",
"visual-studio-2005",
""
] |
In C# I can do actually this:
```
//This is C#
static T SomeMethod<T>() where T:new()
{
Console.WriteLine("Typeof T: "+typeof(T));
return new T();
}
//And call the method here
SomeMethod<SomeClassName>();
```
But for some reason I can't get it to work in Java.
The thing I want to do is, to create a static method on a superclass, so the subclasses can be converted to XML.
```
//This is Java, but doesn't work
public static T fromXml<T>(String xml) {
try {
JAXBContext context = JAXBContext.newInstance(T.class);
Unmarshaller um = context.createUnmarshaller();
return (T)um.unmarshal(new StringReader(xml));
} catch (JAXBException je) {
throw new RuntimeException("Error interpreting XML response", je);
}
}
//Also the call doesn't work...
fromXml<SomeSubObject>("<xml/>");
``` | ```
public static <T> T fromXml(Class<T> clazz, String xml) {
```
Called as:
```
Thing thing = fromXml(Thing.class, xml);
```
or more explicitly:
```
Thing thing = MyClass.<Thing>fromXml(Thing.class, xml);
```
To be even more confusing you can have constructors that both construct a generic type and have a generic parameter themselves. Can't remember the syntax and have never seen it used in anger (you are probably better off with a static creation method anyway).
The cast `(T)` is unsafe, and you can't write T.class. So include the T.class as an argument (as `JAXBContext.newInstance` does) and throw a relevant exception if the type is wrong.
```
public static <T> T fromXml(Class<T> clazz, String xml) {
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller um = context.createUnmarshaller();
Object obj = um.unmarshal(new StringReader(xml));
try {
return clazz.cast(obj);
} catch (ClassCastException exc) {
throw new RelevantException(
"Expected class "+clazz+
" but was "+obj.getClass()
);
}
} catch (JAXBException exc) {
throw new RelevantException(
"Error unmarshalling XML response",
exc
);
}
}
```
I believe the next version of JAXB (in 6u14?) has some convenience methods for this sort of thing in the `JAXB` class. | Methods like Java's `Collections.emptySet()` have a signature like this:
```
public static final <T> Set<T> emptySet()
```
And are called like this:
```
Set<Foo> foos = Collections.<Foo>emptySet();
```
Mockito's `anyObject()` method is another example. I personally don't find either syntax to be very awesome. Passing the type in as a method argument works but always felt kludgy. Providing the parameter in the way that `emptySet()` does seems cleaner but it's not always apparent that a method allows a type to be specified. | Generic method in Java without generic argument | [
"",
"java",
"generics",
""
] |
Im working on this large DB which has a lot of the business knowledge embedded in the SPs[I know!] and there is a lot of chaining between the SPs. i.e one stored proc calling another.
Im want to find out a list of stored procedures which update a particular column. How would I do that.
Using showplan\_All as outlined in
[SQL Table and column Parser for stored procedures](https://stackoverflow.com/questions/283214/sql-table-and-column-parser-for-stored-procedures) doesnt work for me, because this is a shared dev db.
using a Sp from master db scanning system text as described is not feasible because I dont have access to the master db.
So how can I find this informaion? | Have you tried this : `EXEC sp_depends @objname = [table name of the column you are interested in]`.
So for example, if you had a column named `Price` in a table named `Product`, you would execute this: `EXEC sp_depends @objname = N'Product'`.
Simply executing this would give you list of all sps, views, etc which depend on that particular table.
I use this all the time as I work with a db which has over 400 tables :-)
[sp\_depends page on MSDN](https://msdn.microsoft.com/en-us/library/ms189487.aspx) | From system view **sys.sql\_dependencies** you can get dependencies at column level.
```
DECLARE @Schema SYSNAME
DECLARE @Table SYSNAME
DECLARE @Column SYSNAME
SET @Schema = 'dbo'
SET @Table = 'TableName'
SET @Column = 'ColumnName'
SELECT o.name
FROM sys.sql_dependencies AS d
INNER JOIN sys.all_objects AS o ON o.object_id = d.object_id
INNER JOIN sys.all_objects AS ro ON ro.object_id = d.referenced_major_id
INNER JOIN sys.all_columns AS c ON c.object_id = ro.object_id AND c.column_id = d.referenced_minor_id
WHERE (SCHEMA_NAME(ro.schema_id)=@Schema)
and o.type_desc = 'SQL_STORED_PROCEDURE'
and ro.name = @Table
and c.name = @Column
GROUP BY o.name
``` | How to Find the list of Stored Procedures which affect a particular column? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"stored-procedures",
""
] |
If so how?
I know how to provide exception specifications for members such as
```
class SOMEClass
{
public:
void method(void) throw (SOMEException);
virtual void pure_method(void) = 0;
};
```
So that the `method` throws only `SOMEException`. If I want to ensure that sub-classes of `SOMEClass` throw `SOMEException` for `pure_method`, is it possible to add the exception specification?. Is this approach feasible or do I need to understand more on exceptions and abstract methods to find out why it can(not) be done? | Yes, a pure virtual member can have an exception specification.
I recommend you to read this: <http://www.gotw.ca/publications/mill22.htm> before getting too much involved in exception specifications, though. | ```
virtual void action() throw() = 0;
```
It is possible. But reasonable only for throw() case. Compiler will warn you every time derived class forgets add "throw()" specification on its "action" method declaration. | Is it possible to provide exceptions in C++ virtual(pure) class member? | [
"",
"c++",
"exception-specification",
""
] |
I'm just wondering how the [Vala project](http://en.wikipedia.org/wiki/Vala_(programming_language)) is coming along. I'm not sure if this will be a great new technology or just one that will fall by the wayside. Does anyone know how many people are working on this project and if I can contribute (writing tutorials, reporting/fixing bugs, etc...)? | It's open source, so it cannot die. That said, there are plenty of people (myself included) that love c#, but would also love to be able to get maximum performance from their hardware. This lets you do that while using your favorite language. I can't see something like this dieing.
**Edit**
Also, I don't program for embedded devices, but I imagine with something like this opens up c# and all the benefits it brings to a different class of platform. That's gotta generate some interest. | If you check the metrics for the Vala project you can see that it had a very strong growth pattern from the very start. Not only is it open source but there are more and more developers contributing to it over time, more and more people taking dependencies on it etc.
You can click the links "Very large, active development team" and "Established codebase" to see what these tags mean in terms in numbers compared to other open source projects.
<http://www.ohloh.net/p/vala> | Will Vala survive? | [
"",
"c#",
"c",
"vala",
""
] |
Hi I'm starting out on php and I have the following script
```
<?php
$username = "firstleg_floa";
$password = "**";
$hostname = "***1";
$db = "firstleg_bank";
$guildUser = strtolower('grissiom');
$dbh = mysql_connect( $hostname, $username, $password) or die ("Unable To Connect");
$connectDB = mysql_select_db($db, $dbh);
$results = mysql_query("SELECT * FROM Bank where userId ='" .$guildUser."'");
$i = 0;
$rsArr = array();
While ($row = mysql_fetch_array($results, MYSQL_ASSOC))
{
$rsArr [$i] [0] = $row{'userId'};
$rsArr [$i] [1] = $row{'item'};
$rsArr [$i] [2] = $row{'amount'};
$rsArr [$i] [3] = $row{'position'};
$i++;
}
?>
<?="ghdfdgdfg ". $rsArr[$i][1];}." ----";?>
<? echo $rsArr[$i][0]; ?>
<table>
<tr><td>Item</td><td>Amount</td></tr>
<?for ($x=0;$x <= $i; $x++)
{?>
<tr><td><?=$rsArr[$x][3];?></td><td><?=$rsArr[$x][2];?></td></tr>
<?}?>
</table>
<?php
mysql_close($dbh); ?>
```
and I have the following data in the database
1 - grissiom - Silk Cloth - 100 - 1
with the above data and the above script all I can manage to pull out is the amount(100) and the position(1) how come i am unable to pull anything else out? can someone help me please | after loop is finished $i is equal to 1, but $rsArr[$i] is not defined, so variables $rsArr[$i][0] and $rsArr[$i][1] doensn't exists, try using $rsArr[0][0] and $rsArr[0][1] like this:
```
<?="ghdfdgdfg ". $rsArr[0][1];}." ----";?>
<? echo $rsArr[0][0]; ?>
<table>
<tr><td>Item</td><td>Amount</td></tr>
<?for ($x=0;$x <= $i; $x++)
{?>
<tr><td><?=$rsArr[$x][3];?></td><td><?=$rsArr[$x][2];?></td></tr>
<?}?>
</table>
``` | It could be because you're using curly braces instead of square. The row returned by `mysql_fetch_array()` is a PHP array, not an object or string. | php + mysql rows only returning int | [
"",
"php",
"mysql",
""
] |
Let's say I have a socket connection, and the 3rd party listener on the other side expects to see data flowing in a very structured manner. For example, it looks for an unsigned byte that denotes a type of message being sent, followed by an unsigned integer that denotes the length of message, then another unsigned byte which is really a bit field with some flags set or unset and etc...
How would I do this in python? I'm just wondering how to reliably generate this data and make sure I'm sending it correctly (i.e. that I'm really sending an unsigned byte rather than say a signed integer or worse, a string). | Use the [struct](http://docs.python.org/library/struct.html) module to build a buffer and write that. | A very elegant way to handle theses transitions between Python objects and a binary representation (both directions) is using the [Construct library](http://construct.wikispaces.com/).
In their documentation you'll find many nice examples of using it. I've been using it myself for several years now for serial communications protocols and decoding binary data. | Writing binary data to a socket (or file) with Python | [
"",
"python",
""
] |
I want to either enable or disable a button from another file,what should I do?
This is the form class declaration:
```
public partial class Form1 : Form
```
I tried with
```
Form.btnName.enabled = false/true
```
but there's no btnName member.
Thanks in advance! | You need to expose the btnName member to other classes by making it public or using a property of sorts. For example add the following code to Form1
```
public Button ButtonName { get { return btnName; } }
```
Now you can use form.ButtonName for any instance of Form1 | Simply expose a public method:
```
public void EnableButton(bool enable)
{
this.myButton.Enabled = enable;
}
```
Correction:
```
public void EnableButton()
{
this.myButton.Enabled = true;
}
``` | C#: How to access a button outside the form class | [
"",
"c#",
".net",
"winforms",
""
] |
I would be certain that this question addresses something that would have been brought up in a previous question, but I was unable to find it.
There is a method in a C# class that takes as a parameter a generic List of a Base Class. I need to pass a list of an inherited class and do not know exactly how to do this. I am getting an error in my attempts. Below is sample code to illustrated this:
```
public class A
{
public static void MethodC(List<A>)
{
// Do Something here with the list
}
}
public Class B : A
{
// B inherits from A, A is the Base Class
}
// Code utilizing the above method
List<B> listOfB = new List<B>();
A.MethodC( (List<A>) listOfB ); // Error: this does not work
A.MethodC( listOfB.ToList<typeof(A)>() ); // Error: this does not work
A.MethodC( listOfB.ConvertAll<A>(typeof(A)) ); // Error: this does not work
// how can I accomplish this? It should be possible I would think
```
Note: Here is my final working Method as a reference. I got an even better solution to my problem, but technically it wasn't an answer to the question, since my question was phrased impropertly.
```
public static DataTable
ObjectCollectionToDataTable<GLIST>
(List<GLIST> ObjectCollection) where GLIST
: BaseBusinessObject
{
DataTable ret = null;
if (ObjectCollection != null)
{
foreach ( var b in ObjectCollection)
{
DataTable dt = b.ToDataTable();
if (ret == null)
ret = dt.Clone();
if (dt.Rows.Count > 0)
ret.Rows.Add(dt.Rows[0].ItemArray);
}
}
return ret;
}
``` | If you have linq available you can do
```
var ListOfA = ListOfB.Cast<A>().ToList();
``` | You cannot do that. To understand why it is not allowed, imagine what would happen if `Add` was called on a `List<Derived>` after it had been cast to a `List<Base>`.
Also, the answers implying that C# 4.0 will be different are wrong. List will never be modified to allow you to do this. Only `IEnumerable` will - because it does not allow items to be added to the collection.
Update: The reason it works in the solution you've gone for is because you're no longer passing the same list. You're creating a whole new list which is a copy of the original. This is why I asked about modifying the list; if `MethodC` makes changes to the number of items on the list, those changes would be made to a copy, not the original list.
I think the ideal solution for you is as follows:
```
public abstract class A
{
public void MethodC<TItem>(List<TItem> list) where TItem : A
{
foreach (var item in list)
item.CanBeCalled();
}
public abstract void CanBeCalled();
}
public class B : A
{
public override void CanBeCalled()
{
Console.WriteLine("Calling into B");
}
}
class Program
{
static void Main(string[] args)
{
List<B> listOfB = new List<B>();
A a = new B();
a.MethodC(listOfB);
}
}
```
Notice how, with this solution, you can pass a `List<B>` directly to `MethodC` without needing to do that weird conversion on it first. So no unnecessary copying.
The reason this works is because we've told `MethodC` to accept a list of anything that is derived from `A`, instead of insisting that it must be a list of `A`. | Converting a List of Base type to a List of Inherited Type | [
"",
"c#",
"generic-list",
""
] |
What value do you think named and default parameters will add in C#.Net 4.0?
What would be a good use for these (that hasn't already been achieved with overloading and overriding)? | It can make constructors simpler, especially for immutable types (which are important for threading) - [see here for a full discussion](http://marcgravell.blogspot.com/2008/11/immutability-and-optional-parameters.html). Not as nice as it *should* be perhaps, but nicer than having lots of overloads. You obviously can't use object initializers with immutable objects, so the usual:
```
new Foo {Id = 25, Name = "Fred"}
```
isn't available; I'll settle for:
```
new Foo (Id: 25, Name: "Fred")
```
This can be extended to the general idea of simplifying overloads, but in *most* cases I'd prefer overloads that advertise the legal combinations. Constructors are a bit different, IMO, since you are just (typically) defining the initial state.
The COM side of things is also important to a lot of people, but I simply don't use much COM interop - so this isn't *as* important to me.
---
Edit re comments; why didn't they just use the same syntax that attributes use? Simple - it can be ambiguous with other members / variables (which isn't an issue with attributes); take the example:
```
[XmlElement("foo", Namespace = "bar")]
```
which uses one regular parameter (to the ctor, "foo"), and one named assignment. So suppose we use this for regular named arguments:
```
SomeMethod("foo", SecondArg = "bar");
```
(which could also be a constructor; I've used a method for simplicity)
Now... what if we have a variable or a property called `SecondArg`? This would be ambiguous between using `SecondArg` as a named argument to `SomeMethod`, and *assigning "bar" to `SecondArg`, and passing "bar" as a regular argument*.
To illustrate, this is legal in C# 3.0:
```
static void SomeMethod(string x, string y) { }
static void Main()
{
string SecondArg;
SomeMethod("foo", SecondArg = "bar");
}
```
Obviously, SecondArg could be a property, field, varialble, etc...
The alternative syntax doesn't have this ambiguity.
---
```
[AttributeUsage(AttributeTargets.Class)]
public sealed class SomeAttribute : Attribute
{
public SomeAttribute() { }
public SomeAttribute(int SomeVariable)
{
this.SomeVariable = SomeVariable;
}
public int SomeVariable
{
get;
set;
}
}
/* Here's the true ambiguity: When you add an attribute, and only in this case
* there would be no way without a new syntax to use named arguments with attributes.
* This is a particular problem because attributes are a prime candidate for
* constructor simplification for immutable data types.
*/
// This calls the constructor with 1 arg
[Some(SomeVariable: 3)]
// This calls the constructor with 0 args, followed by setting a property
[Some(SomeVariable = 3)]
public class SomeClass
{
}
```
--- | It will help to dodge the problem of providing a decent API to work with Office applications! :)
Some parts of the Office API are okay, but there are edge cases that were clearly designed for use from a language with optional/named parameters. So that's why C# has to have them. | C# .Net 4.0 Named and Default Parameters | [
"",
"c#",
"c#-4.0",
""
] |
This is very similar to question [653714](https://stackoverflow.com/questions/653714/how-to-select-into-temp-table-from-stored-procedure), but for MySQL instead of SQL Server.
Basically, I have a complicated select that is the basis for several stored procedures. I would like to share the code across the stored procedures, however, I'm not sure how to do this. One way I could do this is by making the shared select a stored procedure and then calling that stored procedure from the other ones. I can't figure out how to work with the result set of the nested stored procedure. If I could put them in a temp table I could use the results effectively, but I can't figure out how to get them in a temp table. For example, this does not work:
```
CREATE TEMPORARY TABLE tmp EXEC nested_sp();
``` | The problem is, Stored Procedures don't really return output directly. They can execute select statements inside the script, but have no return value.
MySQL calls stored procedures via `CALL StoredProcedureName();` And you cannot direct that output to anything, as **they don't return anything** (unlike a function).
[MySQL Call Command](http://dev.mysql.com/doc/refman/5.1/en/call.html) | You cannot "SELECT INTO" with stored procedures.
Create the temporary table first and have your stored procedure to store the query result into the created temporary table using normal "INSERT INTO". The temporary table is visible as long as you drop it or until the connection is closed. | MySQL How to INSERT INTO [temp table] FROM [Stored Procedure] | [
"",
"sql",
"mysql",
"stored-procedures",
""
] |
I've written a filter class to add a P3P header to every page. I added this to my web.xml:
```
<filter>
<filter-name>AddP3pHeaderFilter</filter-name>
<filter-class>com.mycompany.AddP3pHeaderFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AddP3pHeaderFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
It adds the header to every page request, but it doesn't work when the user first logs in. The user submits the form to `j_security_check`, but the response doesn't include the header. How can I make my filter apply to the login request? | [Doesn't work in Tomcat.](http://faq.javaranch.com/java/ServletsFaq#7)
I ended up having to use Tomcat valves. | The login request forwards to the appropriate page. By default, filters only apply to REQUEST dispatches. You need to modify the web.xml as follows:
```
<filter>
<filter-name>AddP3pHeaderFilter</filter-name>
<filter-class>com.mycompany.AddP3pHeaderFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AddP3pHeaderFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
```
**EDIT:** I thought this had fixed it, but I was mistaken. | Java servlet filter not working on login | [
"",
"java",
"servlets",
"servlet-filters",
""
] |
Is it possible to find the memory address of a JavaScript variable? The JavaScript code is part of (embedded into) a normal application where JavaScript is used as a front end to C++ and does not run on the browser. The JavaScript implementation used is SpiderMonkey. | If it would be possible at all, it would be very dependent on the javascript engine. The more modern javascript engine compile their code using a just in time compiler and messing with their internal variables would be either bad for performance, or bad for stability.
If the engine allows it, why not make a function call interface to some native code to exchange the variable's values? | It's more or less impossible - Javascript's evaluation strategy is to always use call by value, but in the case of Objects (including arrays) the value passed is a reference to the Object, which is not copied or cloned. If you reassign the Object itself in the function, the original won't be changed, but if you reassign one of the Object's properties, that will affect the original Object.
That said, what are you trying to accomplish? If it's just passing complex data between C++ and Javascript, you could use a JSON library to communicate. Send a JSON object to C++ for processing, and get a JSON object to replace the old one. | How can I get the memory address of a JavaScript variable? | [
"",
"javascript",
"spidermonkey",
"memory-address",
""
] |
How do I generate random floats in C++?
I thought I could take the integer rand and divide it by something, would that be adequate enough? | `rand()` can be used to generate pseudo-random numbers in C++. In combination with `RAND_MAX` and a little math, you can generate random numbers in any arbitrary interval you choose. This is sufficient for learning purposes and toy programs. If you need *truly* random numbers with normal distribution, you'll need to employ a more advanced method.
---
This will generate a number from 0.0 to 1.0, inclusive.
```
float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
```
This will generate a number from 0.0 to some arbitrary `float`, `X`:
```
float r2 = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/X));
```
This will generate a number from some arbitrary `LO` to some arbitrary `HI`:
```
float r3 = LO + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(HI-LO)));
```
---
Note that the `rand()` function will often not be sufficient if you need truly random numbers.
---
Before calling `rand()`, you must first "seed" the random number generator by calling `srand()`. This should be done once during your program's run -- not once every time you call `rand()`. This is often done like this:
```
srand (static_cast <unsigned> (time(0)));
```
In order to call `rand` or `srand` you must `#include <cstdlib>`.
In order to call `time`, you must `#include <ctime>`. | C++11 gives you a lot of new options with [`random`](http://en.cppreference.com/w/cpp/numeric/random). The canonical paper on this topic would be [N3551, Random Number Generation in C++11](http://isocpp.org/blog/2013/03/n3551-random-number-generation)
To see why using `rand()` can be problematic see the [rand() Considered Harmful](https://learn.microsoft.com/en-us/events/goingnative-2013/rand-considered-harmful) presentation material by *Stephan T. Lavavej* given during the *GoingNative 2013* event. The slides are in the comments but here is a [direct link](http://sdrv.ms/1e11LXl).
I also cover `boost` as well as using `rand` since legacy code may still require its support.
The example below is distilled from the cppreference site and uses the [std::mersenne\_twister\_engine](http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine) engine and the [std::uniform\_real\_distribution](http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution) which generates numbers in the `[0,10)` interval, with other engines and distributions commented out (*[see it live](http://rextester.com/PQDR43690)*):
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
//
// Engines
//
std::mt19937 e2(rd());
//std::knuth_b e2(rd());
//std::default_random_engine e2(rd()) ;
//
// Distribtuions
//
std::uniform_real_distribution<> dist(0, 10);
//std::normal_distribution<> dist(2, 2);
//std::student_t_distribution<> dist(5);
//std::poisson_distribution<> dist(2);
//std::extreme_value_distribution<> dist(0,2);
std::map<int, int> hist;
for (int n = 0; n < 10000; ++n) {
++hist[std::floor(dist(e2))];
}
for (auto p : hist) {
std::cout << std::fixed << std::setprecision(1) << std::setw(2)
<< p.first << ' ' << std::string(p.second/200, '*') << '\n';
}
}
```
output will be similar to the following:
```
0 ****
1 ****
2 ****
3 ****
4 *****
5 ****
6 *****
7 ****
8 *****
9 ****
```
The output will vary depending on which distribution you choose, so if we decided to go with [std::normal\_distribution](http://en.cppreference.com/w/cpp/numeric/random/normal_distribution) with a value of `2` for both *mean* and *stddev* e.g. `dist(2, 2)` instead the output would be similar to this (*[see it live](http://rextester.com/KIZ75365)*):
```
-6
-5
-4
-3
-2 **
-1 ****
0 *******
1 *********
2 *********
3 *******
4 ****
5 **
6
7
8
9
```
The following is a modified version of some of the code presented in `N3551` (*[see it live](http://rextester.com/JGIZ32198)*) :
```
#include <algorithm>
#include <array>
#include <iostream>
#include <random>
std::default_random_engine & global_urng( )
{
static std::default_random_engine u{};
return u ;
}
void randomize( )
{
static std::random_device rd{};
global_urng().seed( rd() );
}
int main( )
{
// Manufacture a deck of cards:
using card = int;
std::array<card,52> deck{};
std::iota(deck.begin(), deck.end(), 0);
randomize( ) ;
std::shuffle(deck.begin(), deck.end(), global_urng());
// Display each card in the shuffled deck:
auto suit = []( card c ) { return "SHDC"[c / 13]; };
auto rank = []( card c ) { return "AKQJT98765432"[c % 13]; };
for( card c : deck )
std::cout << ' ' << rank(c) << suit(c);
std::cout << std::endl;
}
```
Results will look similar to:
> 5H 5S AS 9S 4D 6H TH 6D KH 2S QS 9H 8H 3D KC TD 7H 2D KS 3C TC 7D 4C QH QC QD JD AH JC AC KD 9D 5C 2H 4H 9C 8C JH 5D 4S 7C AD 3S 8S TS 2C 8D 3H 6C JS 7S 6S
**Boost**
Of course [Boost.Random](http://www.boost.org/doc/libs/1_55_0/doc/html/boost_random.html) is always an option as well, here I am using [boost::random::uniform\_real\_distribution](http://www.boost.org/doc/libs/1_50_0/doc/html/boost/random/uniform_real_distribution.html):
```
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real_distribution.hpp>
int main()
{
boost::random::mt19937 gen;
boost::random::uniform_real_distribution<> dist(0, 10);
std::map<int, int> hist;
for (int n = 0; n < 10000; ++n) {
++hist[std::floor(dist(gen))];
}
for (auto p : hist) {
std::cout << std::fixed << std::setprecision(1) << std::setw(2)
<< p.first << ' ' << std::string(p.second/200, '*') << '\n';
}
}
```
**rand()**
If you must use `rand()` then we can go to the *C FAQ* for a guides on [How can I generate floating-point random numbers?](http://c-faq.com/lib/fprand.html) , which basically gives an example similar to this for generating an on the interval `[0,1)`:
```
#include <stdlib.h>
double randZeroToOne()
{
return rand() / (RAND_MAX + 1.);
}
```
and to generate a random number in the range from `[M,N)`:
```
double randMToN(double M, double N)
{
return M + (rand() / ( RAND_MAX / (N-M) ) ) ;
}
``` | Random float number generation | [
"",
"c++",
"random",
"floating-point",
""
] |
Was the creator of this construct a baseball fan? | See Stroustrup's book "The Design & Evolution of C++" - basically, "raise" was already taken. | From <http://www.cs.bgu.ac.il/~frankel/TechRep/pdfs/TR-08-03.pdf>
> MacLISP was first to introduce
> catch/throw as an exception handling
> mechanism for handling exceptional
> conditions[9]
> ...
> [9]Moon, D. A. The MacLisp Reference Manual. MIT Project MAC, April 1974.
-Adam | What is the origin of the throw/catch exception naming? | [
"",
"c++",
"exception",
""
] |
I'm *trying* to run javascript from a windows command line via script
cscript //NoLogo test.js
However, I can't find any predefined objects which are available. I'm totally at a loss - Can't get hello world to work:
`System.print("Hello, World!")`
results in `"System" is undefined`
Is there another way I should be running this - like through .NET runtime?
Thanks
jeff | You are using the Windows Scripting Host.
You can say things like:
```
WScript.Echo("Hello, World.");
```
It's all COM-based, so you instantiate ActiveX controls to do anything useful:
```
var y = new ActiveXObject("Scripting.Dictionary");
y.add ("a", "test");
if (y.Exists("a"))
WScript.Echo("true");
```
Or:
```
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
// Get a File object to query.
f1 = fso.GetFile("c:\\detlog.txt");
// Print information.
Response.Write("File last modified: " + f1.DateLastModified);
```
See [Windows Script Host](http://msdn.microsoft.com/en-us/library/9bbdkx3k(VS.85).aspx). | If you really want to run JavaScript in a shell, then you should consider installing Node.js
<http://javascript.cs.lmu.edu/notes/commandlinejs/> | windows command line javascript | [
"",
"javascript",
"windows",
"command-line",
""
] |
I have a service that runs and I'd like to receive notification when:
a) the network is connected.
b) when a user logs in to the machine.
How can I do this? (C# .NET 2.0) | ```
//using Microsoft.Win32;
//using System.Net.NetworkInformation;
public class SessionChanges
{
public SessionChanges()
{
NetworkChange.NetworkAvailabilityChanged +=
new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
}
void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLogon)
{
//user logged in
}
}
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
if (e.IsAvailable)
{
//a network is available
}
}
}
``` | To be notified when any user logs in to the machine, call `WTSRegisterSessionNotification`, passing `NOTIFY_FOR_ALL_SESSIONS`, and listen for the `WM_WTSSESSION_CHANGE` message in the message loop.
In the message, cast the `wParam` to the `Microsoft.Win32.SessionSwitchReason` enum to find out what happened, and pass the `lParam` to `WTSQuerySessionInformation` to find the username.
```
[DllImport("Wtsapi32.dll", CharSet=.CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WTSRegisterSessionNotification(IntPtr hWnd, int dwFlags);
//Pass this value in dwFlags
public const int NOTIFY_FOR_ALL_SESSIONS = 0x1;
//Listen for this message
public const int WM_WTSSESSION_CHANGE = 0x02B1;
//Call this method before exiting your program
[DllImport("Wtsapi32.dll", CharSet=.CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WTSUnRegisterSessionNotification(IntPtr hWnd);
``` | How to receive event when network is connected and also when user logs in | [
"",
"c#",
".net",
"events",
"networking",
""
] |
I know how to do it in WinForms
```
byte[] binaryData = Convert.FromBase64String(bgImage64);
image = Image.FromStream(new MemoryStream(binaryData));
```
but how do i do the same thing in WPF? | ```
byte[] binaryData = Convert.FromBase64String(bgImage64);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = new MemoryStream(binaryData);
bi.EndInit();
Image img = new Image();
img.Source = bi;
``` | Expanding on Josh's answer above - here's one that uses a ValueConverter so you can use binding instead of setting the image source in the code-behind.
Base64ImageConverter.cs
```
public class Base64ImageConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string s = value as string;
if (s == null)
return null;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = new MemoryStream(System.Convert.FromBase64String(s));
bi.EndInit();
return bi;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
```
ImageData.cs (used as a data source)
```
public class ImageData
{
public string Base64ImageData { get; set; }
public ImageData()
{
this.Base64ImageData = "iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAgMSURBVHja7Jl7jFXFHcc/55y5j32C+wCVXV6KwAIrbUBQeUhiixQEiYrUGNC0Bq2CFqsNjSYUrQg+Uk1JbW0VW0I3BCGgFSlYQKBSqKK8W6lCgQ0s7sKye++eOefMTP+4d+/ee3eRpa3ipvySyZnc+5s5v+/vOb85ljGGjkw2HZwuArgI4P8dgAU4QCT57EikACmAwv3ff6SuqF8vSh74HiYa5Y1lf2PJkr+QSLECCFjxq6kcve9RLMcG4VD2y4VMvqcqbT+X0u7duH9yBb22vIX7+Sm6zJzB1DnrvzQEK1feXySATge/dRtjwiepX7qc/BvHMGXKEIYN682GDfupqTkNOFiRMHkjh2M5FpZtQyjMyJF9AA3AgME9uO5SG7H9fczQoZSMHYMWghEjDn0pwm/e/AlAJwFEFr22DR4eyw39YjS8vgRn4EB6TB7PtLuvZ+2a3WzctAd8D/V5LZZwwHHQQUBt7WlyCgu4bXwFvf++g9j2Q+TeMZlInys4cbKRqqXvU1sbwxiwrDSnNalHBhkDxhhs2zqr4MZA5845aG0AIiLxo2Hn9gPszS/kO2MmUr5nGydfWESnSeMZN24Q5eVFOI6NURqMBq0RwqH/oJ58u3eY3HdX4XbpQvHMGejCAtat28f69fvwA0lI5LQOPItMUIDWBqU0va7sypHDtRitsZIMzfzNc6V0MwAEgFYenqc5+Vk1r3xWzbR7x1FxfD+n3lhJ54kTGDiwD6amBuP7GMfCMgn13TkgQsOfNxIePYrcId/AB1at2Ml7G/dkxppprf2URpPPvLwwoZBgQr9cltfHqI9J4vEA08yRZi7PUzQfgSygb3Cy9gA5UfA8tDZorQmFRMtLtMH2JcfmPp8IYsfhsp8+hvF8CIdBOOD7ba6d9fjb5/RnrQ2DKssYd6mkYPM63KEjWC9L+ev2Q7TlTZ065fDBB/9i7dqH+gmAw9MeIGdQBepMwxe/yRiMH4AfUD3nKTJ12Tb5urJdQblj+yH6XFvCqO7dOSQdNm35FGGZDDdrywKJGHAlJt6EiTedo2pYLTLr9p1iPVudk8cYgxAOp6KdePJId64uKSI30kBDQxO2bbcBIEApnRYDnoeKxVHnAmAnUyhgAtUuAK7w28Xn+5oVbx/A930++ccJhHCSQibeo5TCcRK1NhRyMgF0f/VFrHAYKxxGK4WtAoRoKcyBsTC+z7GHHwfHBiEoe/k5TEMjRic2sqLRNtfKWW+ed473PIXnqaR1NEoZ+leWc/BANSrQSQBpLnT9na9TXl5EY6ME4JEf38JNN/YF4PTy1QS7dlI4fXrC1YQDgcYKCUTP8gTPstXEd2yjcPp0Fu+Msep361LChMO5rQQMAo3j2K3926SFVXKenx8lEg0xfXAev6jJpbbexXX9lAXsRBZwaGpqIhrNYdZD4xh7Y1+8Tw9T/cOfoDZu4J/9R2BFImjpoV2JlhLjuix49h3q6mJ0vn08OYMqqX1iHpPqP+bmW65B+gIpPVw3SI2mJp/GRkmf/t3w/IB43M/435WZ88aYR+8ruzDnughFi19idn+Pq68uozGWBSAIPCorr2RJ1f3cPKGSM6vXcGLGTHLLLuOd677Lg4u2o4IA7boYKcGV6ECzfNk27rrrFT7ceYxLpk2l20sLMFs2M23vKn7+2ChKepQhpY+UPq70iURCFBXnM2NoLpeX5hGNCqQMUjzSTfK6CX7lK9b/aT+7qj06X3UVR1zByrf2IV0PnQ5g5qybWLjwdgoaT3H0B7MJllZx+r7ZPHq4Kwvmr0aeiWN7XsKFmiTGkyilcKXNkaN13D39N8yf/0dk18voXvUqQcUAurwwjxevdVIajcU8+vTtypOjcyh++VkeH+gxZEgPYnGPpqZMC0gZIN2AJtdHCIuavBLuPt6PvaGuFOY4xOOSID0GJk0cTOO7mzg+byEF13yT9cMm88xzW4nXnUqetANCwsZID4QNRhMOCzwZpBx28eINbN16kKd+diuDH7yX+PChnHjiaaQcmHLxtWv2MmRiGVMqKtjjhli2YjchW39hNVHK8Ovff4jn+ezedZRwyCEIdOq8ZAF9KyrmHgjamRb/UzLGEAqHuOeOSt7bUc0NQ8uoenMvdXUxHOf8+yohHPbtm5uoxEppamtjrTqd//rCJWsTx7F55sUtSOmxdetBQklttnef9ENdSXF+WiHTmuz7of/JbZHJTp8qmVpFsnip89onXURt0gqZUq0BfO37yfRKHAQK27baZ86vAQlhp6wp0tF0JCtkWKAFAB0XgDGk2rQLSYEf4AjRZh+Q3X6mnYUSQdwyOMsze95eXs4yb+HTSiOlz/DR/bBsiyCp1NZrE6c8rdMAKKVSDXRz3jIZedC0kdOyc2X2muz8l75Xq/sILinKo0evUuaPK6b/FUUUF+UmrWBayZFo7FWmBcBkaAVjsrSUNWj9G+fB2zx8X+H5AUOG9+IPtxZy+dM/4rcjA8aOrcDzFVq38R5MpgUSvm9lmeyrGY5jIxyH1Ss+5v1jitLhwzno5fLakg+xk16RvSbhQiYTgGVduMA1xlBQGKGmuIzRNcP4KL8nl5fmpLTcVmuecS9kzIUtYJZloZXm+Ze34boeuz46QjjstNnQt4BOS6PNm3wd8no0Gkq1nWcTKV1Wu9mEFxrAeVtM63QXSvhTQUG0w33gEM0XL2fO1HfEDzTKAroCg4DSDib8SWC3lWx6C5LPjkQSaLAufqm/COAigIsALij9ewBzvhamSg2pRgAAAABJRU5ErkJggg==";
}
}
```
Window1.xaml
```
<Window x:Class="ImageFromData.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ImageFromData"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<local:Base64ImageConverter x:Key="Base64ImageConverter"/>
<local:ImageData x:Key="ImageData"/>
</Window.Resources>
<Grid DataContext="{StaticResource ImageData}">
<Image Source="{Binding Base64ImageData, Converter={StaticResource Base64ImageConverter}}"/>
</Grid>
</Window>
```
(root namespace for project is ImageFromData) | How do i read a base64 image in WPF? | [
"",
"c#",
".net",
"wpf",
""
] |
We all know that generic List<> does not box value types. Why on the following code snippet the rects[1] is not affected by Inflate method?
If there is no boxing and I want to afect the rect[1] I need to write three lines of code as it is shown - commented. Can someone please explain this?
```
List<Rectangle> rects = new List<Rectangle>();
for (int i = 0; i < 5; i++)
{
rects.Add(new Rectangle(1, 1, 1, 1));
}
foreach (Rectangle item in rects)
{
Console.WriteLine(item);
}
//Rectangle r = rects[1];
//r.Inflate(100, 100);
//rects[1] = r;
rects[1].Inflate(100, 100);
foreach (Rectangle item in rects)
{
Console.WriteLine(item);
}
``` | It isn't boxing - simply that when you get the rectangle out, you are manipulating a standalone **copy** of the rectangle.
This is one of the side effect of having mutable value-types (structs). And the reason you shouldn't write your own mutable structs - it is too easy to lose data.
Since you can't make the pre-built rectangle immutable, I'm afraid you're going to have to copy it out; mutate it; and put it back in. | Yes, the value of the `Rectangle` will be copied to your local variable if you do that.
It's not called boxing. It's just normal copying, since `Rectangle` is a value type. | List<Rectangle> - behaves like there is a boxing | [
"",
"c#",
"list",
"value-type",
""
] |
To be clear, I'm referring to the usage of [stackoverflow's forked WMD](http://github.com/derobins/wmd/tree/master), *not* the [original version from attacklab](http://wmd-editor.com/).
I'd like to use the forked version, however it seems that the div id's which are used by the script to identify the page elements to WMDify are hardcoded in `wmd.js:66`:
```
// A collection of the important regions on the page.
// Cached so we don't have to keep traversing the DOM.
wmd.PanelCollection = function(){
this.buttonBar = doc.getElementById("wmd-button-bar");
this.preview = doc.getElementById("wmd-preview");
this.output = doc.getElementById("wmd-output");
this.input = doc.getElementById("wmd-input");
};
```
If I just wanted to use different region names I'd be fine on my own—but I want to use **a variable number** of WMD editors on a single page. I'd need a way to tell each instance of WMD about the page regions it should affect, but I don't see any 'hooks' for that.
The not-seeing is likely a product of my almost complete lack of js knowledge. The Right Thing To Do™ is to just learn javascript properly, but I'm in the middle of a project with a deadline. I'd really like to use this version of WMD but I need some clues on how to go about modifying the WMD script, or perhaps simply an example of how to call it in such a fashion that I can speficy which div id's to use.
Clues appreciated! | I had similar problems so I re-factored WMD to be able to do just that.
[my version of wmd](http://moowmd.awardspace.info/)
Recently, I rechecked this. The version in Google code supports multiple versions on a page.
[google code fork](http://code.google.com/p/pagedown/) and is the latest out there. | On a "project with a deadline" it is allowed to hack around some constraints. In this case I would just make multiple copies of the WMD editor script (or generate it on the server side) and replace the IDs by your needed identifiers. That way you can immediately deploy multiple WMDs on a single page.
You just have to be really clear about one thing: You **are** accruing [technical debt](http://en.wikipedia.org/wiki/Technical_debt) ("the eventual consequences of slapdash software architecture and hasty software development") on your project there. You **will** have to revisit this to pay back this debt or you will drown in interest payments when doing maintenance. | Multiple WMD editors (SO forked version) on one page? | [
"",
"javascript",
"wmd",
""
] |
Lets say I have something like this:
```
<tr>
<td><input type="text" /></td>
<td>Somevalue</td>
<td><intput type="text /></td>
</tr>
```
I am in the event handler for a keypress in the first text box. I want to find the next td which has a text box in it if it exists using jQuery. | Something like this should work (assuming `this` is the input).
```
var next = $(this).parent().next("td > input[type='text']");
``` | tj111's answer does not work for me.
May be that is because of newer version of jQuery. I came up with this:
```
var next = $(this).parent().nextAll().has("input[type='text']").first();
``` | jQuery - Find the next element which has a specific child | [
"",
"javascript",
"jquery",
""
] |
Currently the project I'm working with does not have completely fixed models (due to an external influence) and hence I'd like some flexibility in writing them. Currently they are replicated across three different layers of the application (db, web api and client) and each has similar logic in it (ie. validation).
I was wondering if there is an approach that would allow me to write a model file (say in ruby), and then have it convert that model into the necessary c# files. Currently it seems I'm just writing a lot of boilerplate code that may change at any stage, whereas this generated approach would allow me to focus on much more important things.
Does anyone have a recommendation for something like this, a dsl/language I can do this in, and does anyone have any experience regarding something like this? | This can be easily done with [ANTLR](http://antlr.org/). If the output is similar enough you can simply use the text templating mechanism—otherwise it can generate an abstract syntax tree for you to traverse. | I have seen a system that used partial classes and partial methods to allow for regeneration of code without affecting custom code. The "rules engine" if you will was completely generated from a Visio state diagram. This is basically poor mans workflow but very easy to modify. The Viso diagram was exported to XML which was read in using powershell and T4 to generate the classes.
The above example is of an external DSL. I.E. external to the programming language that the application runs in. You could on the other hand create an internal DSL which is implemented and used in a programming language.
This and the previous [article on DSLSs](http://code-magazine.com/Article.aspx?quickid=0903061) from Code-Magazine are quite good.
In the above link Neal Ford shows you how to create an internal DSL in C# using a fluent interface.
One thing he hasn't mentioned yet is that you can put this attribute [EditorBrowsable(EditorBrowsableState.Never)] on your methods so that they don't appear to intellisense. This means that you can hide the non-DSL (if you will) methods on the class from the user of the DSL making the fluent API much more discoverable.
You can see a fluent interface being written live in this video series by [Daniel Cazzulino](http://www.viddler.com/explore/dcazzulino/) on writing an IoC container with TDD
On the subject of external DSLs you also have the option of [Oslo (CTP at the moment)](http://www.microsoft.com/downloadS/details.aspx?familyid=F2F4544C-626C-44A3-8866-B2A9FE078956&displaylang=en) which is quite powerful in it's ability to let you create external DSLs that can be executed directly rather than for the use of code generation which come to think of it isn't really much of a DSL at all. | Using a DSL to generate C# Code | [
"",
"c#",
".net",
"code-generation",
"dsl",
""
] |
In my current project I've been inherited with lots of long (1200+ lines) SQL Server stored procedures with some horrible indentation and formatting which makes them almost unreadable. Is there some tool that I can use to automatically format these and make them more readable? I don't want to go through it manually and indent it. | Here's a couple -- no idea how well they work, unfortunately...
<http://www.wangz.net/gsqlparser/sqlpp/sqlformat.htm> (free)
<http://www.sqlinform.com/> (free for personal use) | Try using [ApexSQL Refactor](http://www.apexsql.com/sql_tools_refactor.aspx). It integrates into SSMS and it’s a free tool. Good thing about it is that it allows to save formatting options and share them with the team so all of you use the same settings for code. | Need a tool to automatically indent and format SQL Server stored procedures | [
"",
"sql",
"sql-server",
"stored-procedures",
"formatting",
""
] |
It's a Java web application on Websphere6.1, Solaris 10, JDK 1.5.0\_13. We set the maximum heap size to 1024m. jmap shows the heap status is healthy. The heap memory usage is only 57%. No OutOfMemory at all.
But we saw very high RSS (3GB) for this java process from ps. pmap shows a block of 1.9G private memory.
```
3785: /dmwdkpmmkg/was/610/java/bin/java -server -Dwas.status.socket=65370 -X
Address Kbytes RSS Anon Locked Pgsz Mode Mapped File
...
0020A000 2008 2008 2008 - 8K rwx-- [ heap ]
00400000 1957888 1957888 1957888 - 4M rwx-- [ heap ]
8D076000 40 40 40 - 8K rw--R [ stack tid=10786 ]
...
```
Is it a C heap memory leak in native code? What approach is recommended to find out the root cause? | This [Troubleshooting Memory Leaks](http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/memleaks.html) document from Sun may help you with finding the problem why your high RSS, specially in section 3.4.
As you are running Websphere, maybe you can use the *-memorycheck* on your VM. For details see [here](http://publib.boulder.ibm.com/infocenter/javasdk/tools/index.jsp?topic=/com.ibm.java.doc.igaa/_1vg000121410cbe-1195c23a635-7ffd_1001.html).
It's not necessarily a leak in native code. If you look [here](https://bugs.java.com/bugdatabase/view_bug?bug_id=5004956), on Solaris there might be an issue with files being kept open.
It's just a bunch of links and hints, but maybe helpful to track down your problem. | This might happen even when there isn't a native memory leak (like unclosed zip resources).
I ran in to the same problem. This is a known problem with glibc >= 2.10
The cure is to set this env variable
`export MALLOC_ARENA_MAX=4`
IBM article about setting MALLOC\_ARENA\_MAX
<https://www.ibm.com/developerworks/community/blogs/kevgrig/entry/linux_glibc_2_10_rhel_6_malloc_may_show_excessive_virtual_memory_usage?lang=en>
Google for MALLOC\_ARENA\_MAX or search for it on SO to find a lot of references.
You might want to tune also other malloc options to optimize for low fragmentation of allocated memory:
```
# tune glibc memory allocation, optimize for low fragmentation
# limit the number of arenas
# requires glibc >= 2.16 since there was a bug in
# MALLOC_ARENA_TEST parameter handling that cause MALLOC_ARENA_MAX not to work
export MALLOC_ARENA_MAX=2
# disable dynamic mmap threshold, see M_MMAP_THRESHOLD in "man mallopt"
export MALLOC_MMAP_THRESHOLD_=131072
export MALLOC_TRIM_THRESHOLD_=131072
export MALLOC_TOP_PAD_=131072
export MALLOC_MMAP_MAX_=65536
```
You can call the native malloc\_info function to get information about memory allocations. Here is an example of [using JNA to call the native malloc\_info method](https://github.com/lhotari/java-buildpack-diagnostics-app/blob/907d204f21d011f0272c9d47cac9375e5395574b/src/main/groovy/io/github/lhotari/jbpdiagnostics/MallocInfo.java#L20-L28). | How can a Java process with -Xmx1024m occupy 3GB resident memory? | [
"",
"java",
"memory-leaks",
""
] |
After Xcode has finished building is there a way to make it copy the executable to specific directory
> ~/Sites/cgi-bin/
I have the target `Installation Directory` set to the correct folder, with `skip installation` **unchecked**, but no luck.
Is there something i'm missing? | Check the "Deployment Postprocessing" build setting in your target's Release configuration. Installation is normally done only with a command-line xcodebuild install, but setting Deployment Postprocessing makes it install on every build.
Ensure your user account has write privileges in the directory you want to install in, because the IDE normally doesn't run with root privileges. | In **build phases** down right corner Add Build Phase run script, add such as
mv -f ${SYMROOT}/debug/projectname ~/Library/projectname | Mac OSX - Xcode Installation Directory | [
"",
"c++",
"xcode",
"macos",
""
] |
I am trying to assign some javascript variables in a Django template.
I am having a problem where the values I am assigning are being written to the page properly (I can see them in the page source), but still come up as `null`.
I am doing this:
```
<script type="text/javascript">
var coords = [];
{% for i in item_list %}
coords.push([ {{i.x}}, {{i.y}} ]);
{% endfor %}
</script>
```
This is the page source that is produced:
```
coords.push([ -320.435118373, -149.333637576 ]);
coords.push([ -120.41321373 , -329.312376 ]);
...
```
It seems to be perfectly valid javascript, however, using Firebug to view the value of `coords`, this is what is produced:
```
[[null, null], [null, null], [null, null]...[null, null]]
```
So it's apparent that each of the `push()` calls is going off correctly and a new array of size 2 is being added each time. However, for some reason, the numeric literals all evaluate to `null`.
Does anyone know how I can get these values to be used properly?
**UPDATE:** It appears that the values in the array are fine until I pass them into the jQuery flot plugin:
```
$.plot($('#mapWrapper'), coords, options);
```
So I guess this doesn't have anything to do with the way I am using the Django templates after all. Still, I am curious as to what the problem is with `$.plot`. | Looks like I was missing one small thing. I was using a data series which was an array of arrays. Actually, the jquery flot plugin is expecting an array of series, which are arrays of arrays, so I needed a triple-nested array.
Changing from this:
```
$.plot($('#mapWrapper'), coords, options);
```
to this:
```
$.plot($('#mapWrapper'), [coords], options);
```
fixed the problem.
Thanks to all who looked at this. | I've tried this out in a test app and it works fine (with item\_list being a list of dicts with floats as the "x" and "y" elements). There must be something else you're doing that you're not showing here.
I wonder if maybe it's a weird encoding issue, maybe you're using weird unicode characters without realizing it? | Django templates: insert values for javascript variables | [
"",
"javascript",
"jquery",
"django",
"django-templates",
"flot",
""
] |
How do I pass a property to a Java process, started as a Windows service using Wrapper.exe?
The target code calls:
```
System.getProperty("ADMIN_USERNAME");
``` | <http://wrapper.tanukisoftware.org/doc/english/prop-java-additional-n.html>
You can set "additional parameters" that will go to the JVM (as opposed to your main class), and -DADMIN\_USERNAME=gandalf should work there.
```
wrapper.java.additional.1=-Xrs
wrapper.java.additional.2=-Dprop=TRUE
wrapper.java.additional.3=-DADMIN_USERNAME=gandalf
```
**Update:** You must start with *additional.1* and count up without gaps (This is a convention for shoe-horning lists into Java properties syntax). | You can set certain properties in the wrapper config file, see this link:
<http://wrapper.tanukisoftware.org/doc/english/properties.html>
I believe you can also configure the wrapper to startup java and pass additional properties using the java "-Dproperty=value" syntax | How to pass a system property using Wrapper.exe | [
"",
"java",
"windows-services",
"wrapper",
""
] |
Today, I found something in legacy code. It has "static new" for one function. It looks like this.
```
class Foo
{
public static void Do()
{
Console.WriteLine("Foo.Do");
}
}
class Bar: Foo
{
public static new void Do()
{
Console.WriteLine("Bar.Do");
}
}
```
I don't understand the ***static new*** modifier for the **Do** method in class **Bar**. In C#, static method can only be invoked with class name instead of object name. So, I don't think there is any difference between having the "new" and not.
Generally, if some syntax is unnecessary, C# just treat it is error.
Anybody has any idea about why C# allows such syntax? | If you remove the **new** from your code you get:
> warning CS0108: 'Bar.Do()' hides inherited member 'Foo.Do()'. Use the new keyword if hiding was intended.
The C# compiler just warns you that you might be doing something you did not intend and asks you to insert the **new** keyword to confirm that you know what you are doing. Besides suppressing the warning, it has no other effects. | That applies only for external callers. Remember that you can call a static method of the base class, so something like this is valid:
```
class Foo
{
public static void Do() { Console.WriteLine("Foo.Do"); }
}
class Bar : Foo // :Foo added
{
public static void Something()
{
Do();
}
}
```
This is why the warning tells you to put the new, you want to avoid any confusion when doing this:
```
class Foo
{
public static void Do() { Console.WriteLine("Foo.Do"); }
}
class Bar : Foo // :Foo added
{
public static void Something()
{
Do();
}
public static new void Do() { Console.WriteLine("Bar.Do"); }
}
``` | What is the point of "static new" modifier for a function? | [
"",
"c#",
"static",
"new-operator",
"modifier",
""
] |
PHP 5.2.8 is refusing to load `php_pgsql.dll`, with the following error:
> Warning: PHP Startup: Unable to load dynamic library 'D:\PHP\ext\php\_pgsql.dll' - The specified module could not be found.
>
> in Unknown on line 0
The .dll exists in PHP/ext/.
Has anyone else had this problem with PHP on Windows before? | Check out the info on the PHP PostgreSQL installation page: <http://us.php.net/manual/en/pgsql.installation.php>
> On a Windows server, configured with Apache, adding the following line to httpd.conf to load libpq.dll can save you a lot of time :
>
> ```
> LoadFile "C:/Program Files/PostgreSQL/8.4/bin/libpq.dll"
> ```
>
> Note that you will have to change your folder accordingly to the installation path and version of PostgreSQL you have installed. Also note that having Apache and PostgreSQL on the same server for production environments is not recommended.
This fixed my setup instantly. | This happened to me also with PHP 5.4.1
Copying the offending DLL everywhere didn't work, and I don't have PostgreSQL installed in the server, but I also planned to use PHP against different Postgres versions, so the only solution I found that worked was to put in httpd.conf a line like this:
```
LoadFile "C:/Program Files/PostgreSQL/8.4/bin/libpq.dll"
```
And referring to the libpq.dll that comes bundled with PHP, like this:
```
LoadFile "C:/php/libpq.dll"
```
After that it worked fine to me. | PHP not loading php_pgsql.dll on Windows | [
"",
"php",
"windows",
"postgresql",
""
] |
I have a program that requires fast performance. Within one of its inner loops, I need to test the type of an object to see whether it inherits from a certain interface.
One way to do this would be with the CLR's built-in type-checking functionality. The most elegant method there probably being the 'is' keyword:
```
if (obj is ISpecialType)
```
Another approach would be to give the base class my own virtual GetType() function which returns a pre-defined enum value (in my case, actually, i only need a bool). That method would be fast, but less elegant.
I have heard that there is an IL instruction specifically for the 'is' keyword, but that doesn't mean it executes fast when translated into native assembly. Can anyone share some insight into the performance of 'is' versus the other method?
**UPDATE:** Thanks for all the informed answers! It seem a couple helpful points are spread out among the answers: Andrew's point about 'is' automatically performing a cast is essential, but the performance data gathered by Binary Worrier and Ian is also extremely useful. It would be great if one of the answers were edited to include *all* of this information. | Using `is` can hurt performance if, once you check the type, you cast to that type. `is` actually casts the object to the type you are checking so any subsequent casting is redundant.
If you are going to cast anyway, here is a better approach:
```
ISpecialType t = obj as ISpecialType;
if (t != null)
{
// use t here
}
``` | I'm with [Ian](https://stackoverflow.com/questions/686412/c-is-keyword-performance/686456#686456), you probably don't want to do this.
However, just so you know, there is very little difference between the two, over 10,000,000 iterations
* The enum check comes in at **700**
milliseconds (approx)
* The IS check comes in at **1000**
milliseconds (approx)
I personally wouldn't fix this problem this way, but if I was forced to pick one method it would be the built in IS check, the performance difference isn't worth considering the coding overhead.
My base and derived classes
```
class MyBaseClass
{
public enum ClassTypeEnum { A, B }
public ClassTypeEnum ClassType { get; protected set; }
}
class MyClassA : MyBaseClass
{
public MyClassA()
{
ClassType = MyBaseClass.ClassTypeEnum.A;
}
}
class MyClassB : MyBaseClass
{
public MyClassB()
{
ClassType = MyBaseClass.ClassTypeEnum.B;
}
}
```
**JubJub: As requested more info on the tests.**
I ran both tests from a console app (a debug build) each test looks like the following
```
static void IsTest()
{
DateTime start = DateTime.Now;
for (int i = 0; i < 10000000; i++)
{
MyBaseClass a;
if (i % 2 == 0)
a = new MyClassA();
else
a = new MyClassB();
bool b = a is MyClassB;
}
DateTime end = DateTime.Now;
Console.WriteLine("Is test {0} miliseconds", (end - start).TotalMilliseconds);
}
```
Running in release, I get a difference of 60 - 70 ms, like Ian.
**Further Update - Oct 25th 2012**
After a couple of years away I noticed something about this, the compiler can choose to omit `bool b = a is MyClassB` in release because b isn't used anywhere.
This code . . .
```
public static void IsTest()
{
long total = 0;
var a = new MyClassA();
var b = new MyClassB();
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10000000; i++)
{
MyBaseClass baseRef;
if (i % 2 == 0)
baseRef = a;//new MyClassA();
else
baseRef = b;// new MyClassB();
//bool bo = baseRef is MyClassB;
bool bo = baseRef.ClassType == MyBaseClass.ClassTypeEnum.B;
if (bo) total += 1;
}
sw.Stop();
Console.WriteLine("Is test {0} miliseconds {1}", sw.ElapsedMilliseconds, total);
}
```
. . . consistently shows the `is` check coming in at approx 57 milliseconds, and the enum comparison coming in at 29 milliseconds.
**NB** *I'd still prefer the `is` check, the difference is too small to care about* | C# 'is' operator performance | [
"",
"c#",
"performance",
"clr",
"gettype",
""
] |
I was looking through a [Findbugs](http://findbugs.sourceforge.net/) report on my code base and one of the patterns that was triggered was for an empty `synchronzied` block (i.e. `synchronized (var) {}`). The [documentation says](http://findbugs.sourceforge.net/bugDescriptions.html#ESync_EMPTY_SYNC):
> Empty synchronized blocks are far more
> subtle and hard to use correctly than
> most people recognize, and empty
> synchronized blocks are almost never a
> better solution than less contrived
> solutions.
In my case it occurred because the contents of the block had been commented out, but the `synchronized` statement was still there. In what situations could an empty `synchronized` block achieve correct threading semantics? | An empty synchronized block will wait until nobody else is using that monitor.
That may be what you want, but because you haven't protected the subsequent code in the synchronized block, nothing is stopping somebody else from modifying what ever it was you were waiting for while you run the subsequent code. That's almost never what you want. | How an empty `synchronized` block can ‘achieve correct threading’ I explain in sections one and two. How it can be a ‘better solution’ I explain in section three. How it can nevertheless be ‘subtle and hard to use correctly’ I show by example in the fourth and final section.
## 1. Correct threading
In what situations might an empty `synchronized` block enable correct threading?
Consider an example.
```
import static java.lang.System.exit;
class Example { // Incorrect, might never exit
public static void main( String[] _args ) { new Example().enter(); }
void enter() {
new Thread( () -> { // A
for( ;; ) {
toExit = true; }})
.start();
new Thread( () -> { // B
for( ;; ) {
if( toExit ) exit( 0 ); }})
.start(); }
boolean toExit; }
```
The code above is incorrect. The runtime might isolate thread A’s change to the boolean variable `toExit`, effectively hiding it from B, which would then loop forever.
It can be corrected by introducing empty `synchronized` blocks, as follows.
```
import static java.lang.System.exit;
class Example { // Corrected
public static void main( String[] _args ) { new Example().enter(); }
void enter() {
new Thread( () -> { // A
for( ;; ) {
toExit = true;
synchronized( o ) {} }}) // Force exposure of the change
.start();
new Thread( () -> { // B
for( ;; ) {
synchronized( o ) {} // Seek exposed changes
if( toExit ) exit( 0 ); }})
.start(); }
static final Object o = new Object();
boolean toExit; }
```
## 2. Basis for correctness
How do the empty `synchronized` blocks make the code correct?
The Java memory model guarantees that an ‘unlock action on monitor m *synchronizes-with* all subsequent lock actions on m’ and thereby *happens-before* those actions ([§17.4.4](https://docs.oracle.com/javase/specs/jls/se18/html/jls-17.html#jls-17.4.4)). So the *unlock* of monitor `o` at the tail of A’s `synchronized` block *happens-before* its eventual *lock* at the head of B’s `synchronized` block. And because A’s *write* to the variable precedes its unlock and B’s lock precedes its *read*, the guarantee extends to the write and read operations: *write happens-before read*.
Now, ‘[if] one action happens-before another, then the first is visible to and ordered before the second’ ([§17.4.5](https://docs.oracle.com/javase/specs/jls/se18/html/jls-17.html#jls-17.4.5)). It is this visibility guarantee that makes the code correct in terms of the memory model.
## 3. Comparative utility
How might an empty `synchronized` block be a better solution than the alternatives?
#### Versus a non-empty `synchronized` block
One alternative is a *non*-empty `synchronized` block. A non-empty `synchronized` block does two things: a) it provides the ordering and visibility guarantee described in the previous section, effectively forcing the exposure of memory changes across all threads that synchronize on the same monitor; and b) it makes the code within the block effectively atomic among those threads; the execution of that code will not be interleaved with the execution of other block-synchronized code.
An empty `synchronized` block does only (a) above. In situations where (a) alone is required and (b) could have significant costs, the empty `synchronized` block might be a better solution.
#### Versus a `volatile` modifier
Another alternative is a `volatile` modifier attached to the declaration of a particular variable, thereby forcing exposure of its changes. An empty `synchronized` block differs in applying not to any particular variable, but to all of them. In situations where a wide range of variables have changes that need exposing, the empty `synchronized` block might be a better solution.
Moreover a `volatile` modifier forces exposure of each separate write to the variable, exposing each across all threads. An empty `synchronized` block differs both in the timing of the exposure (only when the block executes) and in its extent (only to threads that synchronize on the same monitor). In situations where a narrower focus of timing and extent could have significant cost benefits, the empty `synchronized` block might be a better solution for that reason.
## 4. Correctness revisited
Concurrent programming is difficult. So it should come as no surprise that empty `synchronized` blocks can be ‘subtle and hard to use correctly’. One way to misuse them (mentioned by Holger) is shown in the example below.
```
import static java.lang.System.exit;
class Example { // Incorrect, might exit with a value of 0 instead of 1
public static void main( String[] _args ) { new Example().enter(); }
void enter() {
new Thread( () -> { // A
for( ;; ) {
exitValue = 1;
toExit = true;
synchronized( o ) {} }})
.start();
new Thread( () -> { // B
for( ;; ) {
synchronized( o ) {}
if( toExit ) exit( exitValue ); }})
.start(); }
static final Object o = new Object();
int exitValue;
boolean toExit; }
```
Thread B’s statement “`if( toExit ) exit( exitValue )`” assumes a synchrony between the two variables that the code does not warrant. Suppose B happens to read `toExit` and `exitValue` after they’re written by A, yet before the subsequent execution of both `synchronized` statements (A’s then B’s). Then what B sees may be the updated value of the first variable (`true`) together with the *un*-updated value of the second (zero), causing it to exit with the wrong value.
One way to correct the code is through the mediation of final fields.
```
import static java.lang.System.exit;
class Example { // Corrected
public static void main( String[] _args ) { new Example().enter(); }
void enter() {
new Thread( () -> { // A
for( ;; ) if( !state.toExit() ) {
state = new State( /*toExit*/true, /*exitValue*/1 );
synchronized( o ) {} }})
.start();
new Thread( () -> { // B
for( ;; ) {
synchronized( o ) {}
State state = this.state; /* Local cache. It might seem
unnecessary when `state` is known to change once only,
but see § Subtleties in the text. */
if( state.toExit ) exit( state.exitValue ); }})
.start(); }
static final Object o = new Object();
static record State( boolean toExit, int exitValue ) {}
State state = new State( /*toExit*/false, /*exitValue*/0 ); }
```
The revised code is correct because the Java memory model guarantees that, when B reads the new value of `state` written by A, it will see the fully initialized values of the final fields `toExit` and `exitValue`, both being implicitly final in the declaration of `State`. ‘A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.’ ([§17.5](https://docs.oracle.com/javase/specs/jls/se18/html/jls-17.html#jls-17.5))
Crucial to the general utility of this technique (though irrelevant in the present example), the specification goes on to say: ‘It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are.’ So the guarantee of synchrony extends deeply into data structures.
#### Subtleties
Local caching of the `state` variable by thread B (example above) might seem unnecessary when `state` is known to change once only. While it has its original value, the statement “`if( state.toExit ) exit( state.exitValue )`” will short circuit and read it once only; otherwise it will have its final value and be guaranteed not to change between the two reads. But as Holger points out, there is no such guarantee.
Consider what could happen if we leave the caching out.
```
new Thread( () -> { // B
for( ;; ) {
synchronized( o ) {}
// State state = this.state;
//// not required when it’s known to change once only
if( state.toExit ) exit( state.exitValue ); }})
.start(); }
```
‘An implementation is free to produce any code it likes, as long as all resulting executions of a program produce a result that can be predicted by the memory model. *This provides a great deal of freedom for the implementor to perform a myriad of code transformations, including the reordering of actions and removal of unnecessary synchronization*.’ ([§17.4](https://docs.oracle.com/javase/specs/jls/se18/html/jls-17.html#jls-17.4))
Seeing therefore that “`if( state.toExit ) exit( state.exitValue )`” lies outside of the synchronized block, and that `state` is a non-volatile variable, the following transformation would be valid.
```
new Thread( () -> { // B
for( ;; ) {
synchronized( o ) {}
// State state = this.state;
//// not required when it’s known to change once only
State s = state;
if( state.toExit ) exit( s.exitValue ); }})
.start(); }
```
This might actually be how the code executes. Then the first read of `state` (into `s`) might yield its original value, while the next read yields its final value, causing the program to exit unexpectedly with a value of 0 instead of 1. | In what situations could an empty synchronized block achieve correct threading semantics? | [
"",
"java",
"multithreading",
"findbugs",
"synchronized",
""
] |
What is the purpose and effect of the `true` and `false` **operators** in C#? The [official documentation](http://msdn.microsoft.com/en-us/library/eahhcxk2(VS.71).aspx) on these is hopelessly non-explanatory. | The true and false operators can be overloaded, to allow a class to represent its own state as true or false, for example:
```
public class MyClass
{
//...
public static bool operator true(MyClass op)
{
// Evaluation code...
}
public static bool operator false(MyClass op)
{
// Evaluation code...
}
}
```
And you will be able to use the operator in boolean expressions:
```
MyClass test = new MyClass(4, 3);
if (test)
Console.WriteLine("Something true");
else
Console.WriteLine("Something false");
string text = test ? "Returned true" : "Returned false";
``` | **You would overload the `true` or `false` operators if you were defining a specialized boolean value.** This is not typically needed, however, which is why they don't seem useful. For example, in a fuzzy-logic boolean class, you might have something like this:
```
// Represents a boolean that can store truth values in a range from [0, 1], with
// a value of one indicating complete metaphysical certitude and a value of
// zero indicating complete impossibility.
public class FuzzyBoolean {
// ...
public static bool operator true(FuzzyBoolean fb) {
return fb.TruthValue > 0;
}
public static bool operator false(FuzzyBoolean fb) {
return fb.TruthValue == 0;
}
// ...
}
```
Note that if you overload `true`, you must also overload `false` (and vice versa).
Of course, there are also the `true` and `false` *literals*, the two literal values you can assign to a boolean instance. Don't confuse these with the operators mentioned above. A more substantial example of how you'd use this, involving booleans in a database, is given in the MSDN docs [**here**](http://msdn.microsoft.com/en-us/library/aa664483%28VS.71%29.aspx). | What are true and false operators in C#? | [
"",
"c#",
"operators",
""
] |
I have the following dynamic SQL in one of my package bodies
```
OPEN ccur for
'select c.category
from test_category c
where c.deptid='||PI_N_Dept ||
' and c.category not in ('|| sExcludeCategories ||')';
```
`sExcludeCategories` will contain a set of integers separated by comma. I would like to eliminate this dynamic SQL statement. Are there any smart ways to accomplish this?? | I'm guessing you know you can bind a variable to `PI_N_Dept` to remove that piece of dynamic sql. Unfortunately for your `IN` clause and `sExcludeCategories` you can't bind a variable for a list in Oracle (at least up to 9.2 as far as i know)
You do have a few choices. Your current solution is the easiest. Another solution is to change the procedure to accept multiple variables and create a list of AND statements.
```
'select c.category
from test_category c
where c.deptid= :PI_N_Dept
and c.category <> :sExcludeCategory1
and c.category <> :sExcludeCategory2
and c.category <> :sExcludeCategory3
';
```
or have a fixed list of IN values
```
'select c.category
from test_category c
where c.deptid= :PI_N_Dept
and c.category not in (:sExcludeCategory1 , :sExcludeCategory2, :sExcludeCategory3)';
```
You'll have to be careful in the case where you only want 2 categories. The third will have to be set to some value not in c.category (NB: be careful and test null values here)
Another solution is presented in [Ask Tom](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:110612348061). This looks quite simple, though i haven't tested it. It works by creating a function str2tbl() which allows you to pass a series of numbers separated by commas and creating a 'table' via dual to do a IN.
```
create or replace type myTableType as table of number;
create or replace function str2tbl( p_str in varchar2 ) return myTableType
as
l_str long default p_str || ',';
l_n number;
l_data myTableType := myTabletype();
begin
loop
l_n := instr( l_str, ',' );
exit when (nvl(l_n,0) = 0);
l_data.extend;
l_data( l_data.count ) := ltrim(rtrim(substr(l_str,1,l_n-1)));
l_str := substr( l_str, l_n+1 );
end loop;
return l_data;
end;
```
Your example would look something like
```
'select c.category
from test_category c
where c.deptid= :PI_N_Dept
and c.category not in ( select * from INLIST ( select cast( str2tbl( :sExcludeCategories ) as mytableType ) from dual ) )';
```
This would only work if `sExcludeCategories` was a list of numbers. You'd have to change str2tbl to handle quotes if they are included in the variable (and you cant change it) plus change the type of `myTableType` to `varchar2(10)` or something more appropriate.
Overall, if the original sql not effecting performance then for simplicity sake i'd leave it as dynamic SQL. It's much less of a head ache to maintain. Otherwise test out the str2tbl. It should work in Oracle 8 and above.
**PS**: Just for completeness, i came across [this nice article on binding vars](http://www.akadia.com/services/ora_bind_variables.html) that covers the simple problems like though not using variables for IN clauses. | I don't know oracle, but in SQL Server, it is fairly common to obtain a "split" udf ([like so](https://stackoverflow.com/questions/2647/split-string-in-sql/2677#2677) - just one of many, many versions available) that turns the CSV into a column of values, and join (etc) to it. Does pl-sql have anything similar? | How can I get rid of dynamic SQL | [
"",
"sql",
"oracle",
"plsql",
""
] |
I found that quite a few "toolbar" in web page is implemented with HTML tag **UL** and **LI** with style "***float:left***".
Fore example, with the help of FireBug it is easy to find this pattern in <http://www.yahoo.com/>.
Is there any reason for that? I don't think that UL and LI are invented to create toolbar. | HTML was intended for *semantics* (what things mean), not *presentation* (what they look like). Since `<ul>` represents an *unordered list*, and since a toolbar is conceptually just a list of items, this is sensible. Even StackOverflow does it!
```
<div class="nav">
<ul>
<li><a href="/questions">Questions</a></li>
<li><a href="/tags">Tags</a></li>
<li><a href="/users">Users</a></li>
<li><a href="/badges">Badges</a></li>
<li><a href="/unanswered">Unanswered</a></li>
</ul>
</div>
``` | `UL` and `LI` are for lists. And you are listing a bunch of links (sub-navigation, tools(?), etc.) | Why is it common to create toolbar with tag <UL> and <LI>? | [
"",
"javascript",
"html",
"tags",
"html-lists",
""
] |
I'd like to know some best practice when designing c++ classes.
To put it in context, I have a c++ class named Vec3.
```
class Vec3{
private:
float elements[3];
public:
Vec3(Vec3 v1){...}
Vec3(int x, int y, int z){...}
Vec3 add(Vec3 v1){...}
Vec3 add(int x, int y, int z){...}
...
Vec3 multiply(Vec3 v1){...}
...
int dotProduct(Vec3 v1){...}
Vec3 normalize(){...}
....
int operator[](int pos){...}
};
```
So, I have this class that does computing over a Vector of size 3.
I'd like to know what's better. Working with pointers or not.
Should I return pointer and have my parameters as Pointers or not.
Vec3 add(Vec3 v1) or Vec3\* add(Vec3 v1) or Vec3\* add(Vec3\* v1) or ....
Now I'm confused, I don't know if I should use pointer or not in my class. I guess there is always a way to send my arguments to function that don't handle pointers...
```
Vec3* v2 = new Vec3(1,1,1);
Vec3 sum = v1.add(*v2);
```
And there is a solution that is probably the best of all I can come up with..
having both functions
```
Vec3 add(Vec3 v2){...}
Vec3* add(Vec3* v2){...}
```
But I fear this will lead to duplicate code and may be overhead.
Thank you for answers...btw, I could use a template to change the size of the Vector but I prefer to keep my Vec3 class alone and create a Vec4 class or name it Quaternion.
***EDIT***
Here is the solution I came with. Feel free to comment or modify or reuse the code.
One thing. I just want to mention that, in my case, This class is supposed to be transparent. Just like we add numbers.
```
int i = 10;
int j = 15;
int k = i + k;
```
If the add overload modify the object that is calling the function in this case i.
I would endup with a k being a reference to i and i being equal to 25. But what we really want here is a k equal to 25 and i,k unchanged.
Thats how my class work. Vec3 k = i + k will not modify i or k because we are creating a new number from these values. The only case where I return a reference is for +=, -=, ++, --..., set([XYZ])? and normalize.
It could be fun to do something like myvec.setX(10).normalize().scale(10)
NOTE: scale should return a reference. I didn't see it but I guess it should be better this way.
```
Vec3 t = myvec.normalize().scale(100).copy();
```
<http://pastebin.com/f413b7ffb>
Thank you all, I'll be working on the Matrix class now. | These are the rules I usually stick to. Note 'usually', sometimes there are reasons for doing things differently...
For parameters I don't intend to modify I pass by value if they aren't too large since they will be copied. If they are a bit large or aren't copyable, you could use a const reference or a pointer (I prefer const reference).
For parameters I do intend to modify, I use a reference.
For return values I will return a copy whenever possible. Some times it's handy to return a reference (this works well for a single function for get/set where you don't need to do any special processing when the item is fetched or set).
Where pointers really shine in my opinion is for instance variables where I want control over when it is constructed or destructed.
Hope that helps. | Since the int's are primtives, leave them as is. for anything with vec3's use references.
eg.
```
Vec3 add(const Vec3 &v1){...}
```
In C you'd use a pointer, but in c++ a reference is usually better for objects. | C++ class best practice | [
"",
"c++",
"class",
""
] |
I've created some foreign keys without an explicit name.
Then I've found SQL generated crazy names like `FK__Machines__IdArt__760D22A7`. Guess they will be generated with different names at different servers.
Is there any nice function to drop the unnamed FK constraints passing as arguments the tables and the fields in question? | There is not a built in procedure to accomplish this, but you can build your own using the information in the information\_schema views.
Table based example
```
Create Proc dropFK(@TableName sysname)
as
Begin
Declare @FK sysname
Declare @SQL nvarchar(4000)
Declare crsFK cursor for
select tu.Constraint_Name from
information_schema.constraint_table_usage TU
LEFT JOIN SYSOBJECTS SO
ON TU.Constraint_NAME = SO.NAME
where xtype = 'F'
and Table_Name = @TableName
open crsFK
fetch next from crsFK into @FK
While (@@Fetch_Status = 0)
Begin
Set @SQL = 'Alter table ' + @TableName + ' Drop Constraint ' + @FK
Print 'Dropping ' + @FK
exec sp_executesql @SQL
fetch next from crsFK into @FK
End
Close crsFK
Deallocate crsFK
End
``` | For dropping an individual unnamed default constrain on a column use the following code:
```
DECLARE @ConstraintName VARCHAR(256)
SET @ConstraintName = (
SELECT obj.name
FROM sys.columns col
LEFT OUTER JOIN sys.objects obj
ON obj.object_id = col.default_object_id
AND obj.type = 'F'
WHERE col.object_id = OBJECT_ID('TableName')
AND obj.name IS NOT NULL
AND col.name = 'ColunmName'
)
IF(@ConstraintName IS NOT NULL)
BEGIN
EXEC ('ALTER TABLE [TableName] DROP CONSTRAINT ['+@ConstraintName+']')
END
```
If you want to do this for a default column, which is probably more common than the original question and I'm sure a lot of people will land on this from a Google search, then just change the line:
```
obj.type = 'F'
```
to
```
obj.type = 'D'
``` | Dropping unnamed constraints | [
"",
"sql",
"sql-server",
""
] |
I've been running some metrics on my Java project and apparently there are a lot of dependency cycles between packages. I didn't really know how to organize stuff into packages, so I just did what made sense to me, which is apparently wrong.
My project is a neural network framework. Neural networks have Neurons, which are connected to each other with Connections. They need to depend on each other. However, there are also different types of Neurons, so I thought it'd be a good idea to put them all in there own 'neurons' package. Obviously a Connection isn't a Neuron so it shouldn't be in the package, but since they refer to each other, I now have a circular dependency.
This is just an example, but I have more situations like this. How do you handle these kinds of situations?
Also, I read that classes in a package higher up in the package hierarchy are not supposed to refer to classes in packages that are deeper. This would mean that a NeuralNetwork class in package 'nn' can not refer to the Neuron in package 'nn.neurons'. Do you guys follow this principle? And what if I would move NeuralNetwork to 'nn.networks' or something? In that case, it would refer to a sibling package instead of a child. Is that better practice? | The [antcontrib VerifyDesign task](http://ant-contrib.sourceforge.net/tasks/tasks/verifydesign.html) will help you do what you want:
> For example, if there are three
> packages in one source tree
>
> ```
> * biz.xsoftware.presentation
> * biz.xsoftware.business
> * biz.xsoftware.dataaccess
> ```
>
> and naturally presentation should only
> depend on business package, and
> business should depend on dataaccess.
> If you define your design this way and
> it is violated the build will fail
> when the verifydesign ant task is
> called. For example, if I created a
> class in biz.xsoftware.presentation
> and that class depended on a class in
> biz.xsoftware.dataaccess, the build
> would fail. This ensures the design
> actually follows what is documented(to
> some degree at least). This is
> especially nice with automated builds
So once you have decided how things should be organized you can enforce the requirements at compile time. You also get fine-granied control so you can allow certain cases to break these "rules". So you can allow some cycles.
Depending on how you want to do things, you might find that "utils" package makes sense.
For the particular case that you cite... I might do something like this:
* package nn contains Nueron and Connection
* package nn.neurons contains the subclasses of Nueron
Neuron and Connection are both high-level concepts used in the NeuralNetowrk, so putting them all together makes sense. The Neuron and Connection classes can refer to each other while the Connection class has no need to know about the Neuron subclasses. | First of all, you are rightfully concerned because circular dependencies between packages are bad. Problems that come out of it grow in importance with the size of the project, but no reason to tackle this situation on time.
You should organize your classes by placing classes that you reuse together in the same package. So, if you have for example AbstractNeuron and AbstractConnection, you’d place them in the same package. If you now have implementations HumanNeuron and HumanConnection, you’d place these in the same package (called for example \*.network.human). Or, you might have only one type of connection, for example BaseConnection and many different Neurons. The principle stays the same. You place BaseConnection together with BaseNeuron. HumanNeuron in its own package together with HumanSignal etc. VirtualNeuron together with VirtualSignal etc.
You say: “Obviously a Connection isn't a Neuron so it shouldn't be in the package..”. This is not that obvious, nor correct to be exact.
You say you placed all your neurons in the same package. Neither this is correct, unless you reuse all your implementations together. Again, take a look at scheme I described above. Either your project is so small you place all in the single package, or you start organizing packages as described.
For more details take a look at [The Common Reuse Principle](http://www.objectmentor.com/resources/articles/granularity.pdf):
THE CLASSES IN A PACKAGE ARE REUSED TOGETHER. IF YOU
REUSE ONE OF THE CLASSES IN A PACKAGE, YOU REUSE THEM
ALL. | How to organize packages (and prevent dependency cycles)? | [
"",
"java",
"dependencies",
"package",
"project-organization",
""
] |
I need to get unmanaged Windows C++ clients to talk to a WCF service. C++ clients could be running on Win2000 and later. I have a control over both WCF service and which C++ API is being used. Since it's for a proprietary application, it is preferable to use Microsoft stuff where possible, definitely not GNU licensed APIs. Those of you who have it working, can you share a step-by-step process how to make it working?
I have researched following options so far:
* WWSAPI - not good, will not work on Win 2000 clients.
* ATL Server, used [following guide](http://icoder.wordpress.com/2007/07/25/consuming-a-wcf-service-with-an-unmanaged-c-client-with-credential-passing/) as a reference. I followed the steps outlined (remove policy refs and flatten WSDL), however the resulting WSDL is still not usable by sproxy
Any more ideas? Please answer only if you actually have it working yourself.
***Edit1***: I apologize for anyone who I might have confused: what I was looking for was a way to call WCF service from client(s) where no .NET framework is installed, so using .NET-based helper library is not an option, it must be pure unmanaged C++ | For those who are interested, I found one semi-working ATL Server solution. Following is the host code, notice it is using BasicHttpBinding, it's the only one which works with ATL Server:
```
var svc = new Service1();
Uri uri = new Uri("http://localhost:8200/Service1");
ServiceHost host = new ServiceHost(typeof(Service1), uri);
var binding = new BasicHttpBinding();
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService1), binding, uri);
endpoint.Behaviors.Add(new InlineXsdInWsdlBehavior());
host.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetEnabled = true });
var mex = host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
host.Open();
Console.ReadLine();
```
code for InlineXsdInWsdlBehavior could be found [here](http://www.winterdom.com/weblog/2006/10/03/InlineXSDInWSDLWithWCF.aspx) . One important change needs to be done to the InlineXsdInWsdlBehavior in order for it to work properly with sproxy when complex types are involved. It is caused by the bug in sproxy, which does not properly scope the namespace aliases, so wsdl cannot have repeating namespace aliases or sproxy will crap out. Here's the functions which needs to change:
```
public void ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext context)
{
int tnsCount = 0;
XmlSchemaSet schemaSet = exporter.GeneratedXmlSchemas;
foreach (WsdlDescription wsdl in exporter.GeneratedWsdlDocuments)
{
//
// Recursively find all schemas imported by this wsdl
// and then add them. In the process, remove any
// <xsd:imports/>
//
List<XmlSchema> importsList = new List<XmlSchema>();
foreach (XmlSchema schema in wsdl.Types.Schemas)
{
AddImportedSchemas(schema, schemaSet, importsList, ref tnsCount);
}
wsdl.Types.Schemas.Clear();
foreach (XmlSchema schema in importsList)
{
RemoveXsdImports(schema);
wsdl.Types.Schemas.Add(schema);
}
}
}
private void AddImportedSchemas(XmlSchema schema, XmlSchemaSet schemaSet, List<XmlSchema> importsList, ref int tnsCount)
{
foreach (XmlSchemaImport import in schema.Includes)
{
ICollection realSchemas = schemaSet.Schemas(import.Namespace);
foreach (XmlSchema ixsd in realSchemas)
{
if (!importsList.Contains(ixsd))
{
var new_namespaces = new XmlSerializerNamespaces();
foreach (var ns in ixsd.Namespaces.ToArray())
{
var new_pfx = (ns.Name == "tns") ? string.Format("tns{0}", tnsCount++) : ns.Name;
new_namespaces.Add(new_pfx, ns.Namespace);
}
ixsd.Namespaces = new_namespaces;
importsList.Add(ixsd);
AddImportedSchemas(ixsd, schemaSet, importsList, ref tnsCount);
}
}
}
}
```
Next step is to generate C++ header:
```
sproxy.exe /wsdl http://localhost:8200/Service1?wsdl
```
and then C++ program looks like this:
```
using namespace Service1;
CoInitializeEx( NULL, COINIT_MULTITHREADED );
{
CService1T<CSoapWininetClient> cli;
cli.SetUrl( _T("http://localhost:8200/Service1") );
HRESULT hr = cli.HelloWorld(); //todo: analyze hr
}
CoUninitialize();
return 0;
```
Resulting C++ code handles complex types pretty decently, except that it cannot assign NULL to the objects. | The basic idea is to write the WCF code for your clients in C# (it's just easier this way) and use a C++ bridge DLL to bridge the gap between your unmanaged C++ code and the managed WCF code written in C#.
Here is the step-by-step process using Visual Studio 2008 along with .NET 3.5 SP1.
1. The first thing to do is create the WCF Service and a means to host it. If you already have this, skip to Step 7 below. Otherwise, create a Windows NT Service following the steps from [here](https://stackoverflow.com/questions/593454/easiest-language-to-create-a-windows-service/593803#593803). Use the default names offered by VS2008 for the project and any classes that are added to the project. This Windows NT Service will host the WCF Service.
* Add a WCF Service named HelloService to the project. To do this, right-click the project in the Solution Explorer window and select the Add|New Item... menu item. In the Add New Item dialog, select the C# WCF Service template and click the Add button. This adds the HelloService to the project in the form of an interface file (`IHelloService.cs`), a class file (`HelloService.cs`), and a default service configuration file (`app.config`).
* Define the HelloService like this:
```
[ServiceContract]
public interface IHelloService
{
[OperationContract]
string SayHello(string name);
}
public class HelloService : IHelloService
{
public string SayHello(string name)
{
return String.Format("Hello, {0}!", name);
}
}
```
* Modify the Service1 class created in Step 1 above to look like this:
```
using System.ServiceModel;
using System.ServiceProcess;
public partial class Service1 : ServiceBase
{
private ServiceHost _host;
public Service1()
{
InitializeComponent();
}
protected override void OnStart( string [] args )
{
_host = new ServiceHost( typeof( HelloService ) );
_host.Open();
}
protected override void OnStop()
{
try {
if ( _host.State != CommunicationState.Closed ) {
_host.Close();
}
} catch {
}
}
}
```
* Build the project.
* Open the Visual Studio 2008 command prompt. Navigate to the output directory for the project. Type the following: `installutil WindowsService1.exe' This installs the Windows NT Service on your local machine. Open the Services control panel and start the Service1 service. It is important to do this in order for Step 9 below to work.
7. Open another instance of Visual Studio 2008 and create an MFC application, which is about as far away as you can get from WCF. As an example, I simply created a dialog MFC application and added a Say Hello! button to it. Right-click the project in the Solution Explorer and select the Properties menu option. Under the General settings, change the Output Directory to ..\bin\Debug. Under the C/C++ General settings, add ..\HelloServiceClientBridge to the Additional Include Directories. Under the Linker General settings, add ..\Debug to the Additional Library Directories. Click the OK button.
* From the File menu, select the Add|New Project... menu item. Select the C# Class Library template. Change the name to HelloServiceClient and click the OK button. Right-click the project in the Solution Explorer and select the Properties menu option. In the Build tab, change the output path to ..\bin\Debug so the assembly and app.config file will be in the same directory as the MFC application. This library will contain the service reference, i.e., the WCF proxy class, to the WCF Hello Service hosted in the Windows NT Service.
* In the Solution Explorer, right-click the References folder for the HelloServiceClient project and select the Add Service Reference... menu option. In the Address field, type the address of Hello Service. This should be equal to the base address in the app.config file created in Step 2 above. Click the Go button. The Hello Service should show up in the Services list. Click the OK button to automatically generate the
proxy class(es) for the Hello Service. ***NOTE:*** *I seem to always run into compilation problems with the Reference.cs file generated by this process. I don't know if I'm doing it wrong or if there is a bug, but the easiest way to fix this is modify the Reference.cs file directly. The problem is usually a namespacing issue and can be fixed with minimal effort. Just be aware that this is a possibility. For this example, I've changed the HelloServiceClient.ServiceReference1 to simply HelloService (along with any other required changes).*
* To allow the MFC Application to interact with the WCF service, we need to build a managed C++ "bridge" DLL. From the File menu, select the Add|New Project... menu item. Select the C++ Win32 Project template. Change the name to HelloServiceClientBridge and click the OK button. For the Application Settings, change the Application Type to DLL and check the Empty project checkbox. Click the Finish button.
* The first thing to do is modify the project properties. Right-click the project in the Solution Explorer and select the Properties menu option. Under the General settings, change the Output Directory to ..\bin\Debug and change the Common Language Runtime Support option to Common Language Runtime Support (/clr). Under the Framework
and References settings, add a reference to the .NET System, System.ServiceModel, and mscorlib assemblies. Click the OK button.
* Add the following files to the HelloServiceClientBridge project - HelloServiceClientBridge.h, IHelloServiceClientBridge.h, and HelloServiceClientBridge.cpp.
* Modify the IHelloServiceClientBridge.h to look like this:
```
#ifndef __IHelloServiceClientBridge_h__
#define __IHelloServiceClientBridge_h__
#include <string>
#ifdef HELLOSERVICECLIENTBRIDGE_EXPORTS
#define DLLAPI __declspec(dllexport)
#else
#define DLLAPI __declspec(dllimport)
#pragma comment (lib, "HelloServiceClientBridge.lib") // if importing, link also
#endif
class DLLAPI IHelloServiceClientBridge
{
public:
static std::string SayHello(char const *name);
};
#endif // __IHelloServiceClientBridge_h__
```
* Modify the HelloServiceClientBridge.h to look like this:
```
#ifndef __HelloServiceClientBridge_h__
#define __HelloServiceClientBridge_h__
#include <vcclr.h>
#include "IHelloServiceClientBridge.h"
#ifdef _DEBUG
#using<..\HelloServiceClient\bin\Debug\HelloServiceClient.dll>
#else
#using<..\HelloServiceClient\bin\Release\HelloServiceClient.dll>
#endif
class DLLAPI HelloServiceClientBridge : IHelloServiceClientBridge
{ };
#endif // __HelloServiceClientBridge_h__
```
* The syntax for the .cpp file uses managed C++, which takes some getting used to. Modify the HelloServiceClientBridge.cpp to look like this:
```
#include "HelloServiceClientBridge.h"
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace System::ServiceModel;
using namespace System::ServiceModel::Channels;
std::string IHelloServiceClientBridge::SayHello(char const *name)
{
std::string rv;
gcroot<Binding^> binding = gcnew WSHttpBinding();
gcroot<EndpointAddress^> address = gcnew EndpointAddress(gcnew String("http://localhost:8731/Design_Time_Addresses/WindowsService1/HelloService/"));
gcroot<HelloService::HelloServiceClient^> client = gcnew HelloService::HelloServiceClient(binding, address);
try {
// call to WCF Hello Service
String^ message = client->SayHello(gcnew String(name));
client->Close();
// marshal from managed string back to unmanaged string
IntPtr ptr = Marshal::StringToHGlobalAnsi(message);
rv = std::string(reinterpret_cast<char *>(static_cast<void *>(ptr)));
Marshal::FreeHGlobal(ptr);
} catch (Exception ^) {
client->Abort();
}
return rv;
}
```
* The only thing left to do is update the MFC application to invoke the SayHello() WCF
service call. On the MFC form, double-click the Say Hello! button to generate the ButtonClicked event handler. Make the event handler look like this:
```
#include "IHelloServiceClientBridge.h"
#include <string>
void CMFCApplicationDlg::OnBnClickedButton1()
{
try {
std::string message = IHelloServiceClientBridge::SayHello("Your Name Here");
AfxMessageBox(CString(message.c_str()));
} catch (...) {
}
}
```
* Run the application and click the Say Hello! button. This will cause the application to
invoke the SayHello() method of the WCF Hello Service hosted in the Windows NT Service (which should still be running, by the way). The return value is then displayed in a message box.
Hopefully you can extrapolate from this simple example to fit your needs. If this does not work, please let me know so I can fix the post. | Create WCF service for unmanaged C++ clients | [
"",
"c++",
"wcf",
"web-services",
"soap",
"wsdl",
""
] |
I have a gigantic QuickBooks SDK .XSD schema file which defines XML requests/responses that I can send/receive from QuickBooks.
I'd like to be able to easily generate Java classes from these .XSD files, which I could then use to marshal XML to Java objects, and Java objects to XML.
Is there an easy way to do this...?
Ideally, it would not require any libraries external to the basic Java distro at run-time. But I'm flexible... | [JAXB](http://jaxb.java.net/) does EXACTLY what you want. It's built into the JRE/JDK starting at 1.6 | To expand on the "use JAXB" comments above,
In Windows
`"%java_home%\bin\xjc" -p [your namespace] [xsd_file].xsd`
e.g.,
`"%java_home%\bin\xjc" -p com.mycompany.quickbooks.obj quickbooks.xsd`
Wait a bit, and if you had a well-formed XSD file, you will get some well-formed Java classes | Generate Java classes from .XSD files...? | [
"",
"java",
"xml",
"xsd",
""
] |
Is there a function in Python to list the attributes and methods of a particular object?
Something like:
```
ShowAttributes ( myObject )
-> .count
-> .size
ShowMethods ( myObject )
-> len
-> parse
``` | You want to look at the [`dir()`](http://diveintopython.net/power_of_introspection/built_in_functions.html) function:
```
>>> li = []
>>> dir(li)
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
```
> `li` is a list, so `dir(li)` returns a list of all the methods of a list. Note that the returned list contains the names of the methods as strings, not the methods themselves.
---
**Edit in response to comment:**
No this will show all inherited methods as well. Consider this example:
**test.py:**
```
class Foo:
def foo(): pass
class Bar(Foo):
def bar(): pass
```
**Python interpreter:**
```
>>> from test import Foo, Bar
>>> dir(Foo)
['__doc__', '__module__', 'foo']
>>> dir(Bar)
['__doc__', '__module__', 'bar', 'foo']
```
---
**You should note that** [Python's documentation](http://docs.python.org/library/functions.html) states:
> **Note:** Because `dir()` is supplied
> *primarily as a convenience for use at
> an interactive prompt*, it tries to
> supply an interesting set of names
> more than it tries to supply a
> rigorously or consistently defined set
> of names, *and its detailed behavior
> may change across releases*. For
> example, metaclass attributes are not
> in the result list when the argument
> is a class.
Therefore it's not safe to use in your code. Use `vars()` instead. `Vars()` doesn't include information about the superclasses, you'd have to collect them yourself.
---
If you're using `dir()` to find information in an interactive interpreter, consider the use of `help()`. | Don't dir() and vars() suit you? | Is there a function in Python to list the attributes and methods of a particular object? | [
"",
"python",
""
] |
I was reading the answers to this question [C++ pros and cons](https://stackoverflow.com/questions/385297/whats-wrong-with-c-compared-to-other-languages) and got this doubt while reading the comments.
> programmers frequently find it confusing that "this" is a pointer but not a reference. another confusion is why "hello" is not of type std::string but evaluates to a char const\* (pointer) (after array to pointer conversion) – Johannes Schaub - litb Dec 22 '08 at 1:56
>
> That only shows that it doesn't use the same conventions as other (later) languages. – le dorfier Dec 22 '08 at 3:35
>
> I'd call the "this" thing a pretty trivial issue though. And oops, thanks for catching a few errors in my examples of undefined behavior. :) Although I don't understand what info about size has to do with anything in the first one. A pointer is simply not allowed to point outside allocated memory – jalf Dec 22 '08 at 4:18
>
> Is this a constant poiner? – yesraaj Dec 22 '08 at 6:35
>
> this can be constant if the method is const int getFoo() const; <- in the scope of getFoo, "this" is constant, and is therefore readonly. This prevents bugs and provides some level of guarantee to the caller that the object won't change. – Doug T. Dec 22 '08 at 16:42
>
> you can't reassign "this". i.e you cannot do "this = &other;", because this is an rvalue. but this is of type T\*, not of type T const . i.e it's a non-constant pointer. if you are in a const method, then it's a pointer to const. T const . but the pointer itself is nonconst – Johannes Schaub - litb Dec 22 '08 at 17:53
>
> think of "this" like this: #define this (this\_ + 0) where the compiler creates "this\_" as a pointer to the object and makes "this" a keyword. you can't assign "this" because (this\_ + 0) is an rvalue. of course that's not how it is (there is no such macro), but it can help understand it – Johannes Schaub - litb Dec 22 '08 at 17:55
My question is, why is `this` a pointer a not a reference? Any particular reason for making it a pointer?
---
Some further arguments why `this` being a reference would make sense:
* Consider `Item 1` from `More Effective C++` : use references when it is guaranteed that we have a valid object i.e. not a NULL (my interpretation).
* Furthermore, references are considered safer than pointers (because we can't screw the memory up with a stray pointer).
* Thirdly, the syntax for accessing references (`.`) is a little bit nicer and shorter than accessing pointers (`->` or `(*)`). | When the language was first evolving, in early releases with real users, there were no references, only pointers. References were added when operator overloading was added, as it requires references to work consistently.
One of the uses of `this` is for an object to get a pointer to itself. If it was a reference, we'd have to write `&this`. On the other hand, when we write an assignment operator we have to `return *this`, which would look simpler as `return this`. So if you had a blank slate, you could argue it either way. But C++ evolved gradually in response to feedback from a community of users (like most successful things). The value of backward compatibility totally overwhelms the minor advantages/disadvantages stemming from `this` being a reference or a pointer. | A little late to the party... Straight from the horse's mouth, [here's what Bjarne Stroustrup has to say](http://www.stroustrup.com/bs_faq2.html#this) (which is essentially repeated in or taken from the "Design and Evolution of C++" book):
> Why is "`this`" not a reference?
>
> Because "this" was introduced into C++ (really into C with Classes) before references were added. Also, I chose "`this`" to follow Simula usage, rather than the (later) Smalltalk use of "self". | Why is 'this' a pointer and not a reference? | [
"",
"c++",
"pointers",
"reference",
"this",
"c++-faq",
""
] |
Is there a way to do form filling with XPS documents in C#? | Here's how you do it.
First, you create an object (POCO is fine) that contains the form fields you wish to have the user fill in for your form. Next, you create your form as a FixedDocument. It should have Bindings that work against your POCO. Then you create a Window that is set up so that the user can enter values for those fields.
Bind the POCO (plain old CLR object) to the TextBoxes in the Window. After the user has entered the form data, take your now filled-in object and set it as the DataContext of the FixedDocument. Create an XpsWriter and Write your FixedDocument to your output (file, printer, etc).
I'd give you code, but since I'm actually doing this (or something relatively similar) for work I don't think I can. I can tell you that the hardest part is dealing with the XPS document. You can judge relative to your experiences there. | It wouldn't be an ideal solution. The reason is that text in XPS is represented by [Glyphs](http://msdn.microsoft.com/en-us/library/system.windows.documents.glyphs.aspx), in which characters (roughly speaking) are specified as indexes into a particular typeface's table of character shapes, rather than in something handy like Unicode. And the `Glyphs` have to be specifically positioned, each character offset from the string origin. If a string has to wrap onto multiple lines, that has to be done by putting in many separate `Glyphs` objects, all individually positioned. It's not a logical format, but a physical one, and it isn't particularly amenable to being altered after it's generated.
You'd be much better off defining the template document as a [FlowDocument](http://msdn.microsoft.com/en-us/library/aa970909.aspx). That's a much more logically manipulable format, rather than a physical "frozen" format. (An XPS document is technically a [FixedDocument](http://msdn.microsoft.com/en-us/library/system.windows.documents.fixeddocument.aspx)). You can then freeze a `FlowDocument` into a `FixedDocument` to export it as XPS, when it has been filled in.
[Read more about Flow Documents.](http://msdn.microsoft.com/en-us/library/aa970909.aspx) | XPS form filling | [
"",
"c#",
"xps",
""
] |
I have a class with a lot of built-in type members with read/write access. Should I make them public members and provide get/set methods for each one? How about structures? | If there are [invariants](http://en.wikipedia.org/wiki/Class_invariant) you need to preserve, then yes. Otherwise, don't bother. | The whole reason to have accessors (getters) and modifiers (setters) is to provide yourself with an extra level of indirection.
This extra level of indirection allows you to provide a read only view of your variable to a public interface, while not allowing your data member to be changed. You could still use a private or protected setter.
Setters allow you to do special error checking, validation and corrections when a value is set. For example setDirectory(const std::string &strPath), you could make sure there is a terminating slash if the user didn't specify one. This ensures that your class state will always be valid.
Getters can also shield your members from having them exposed to allow pointers to them. By not allowing pointers to them from the outside, you can ensure that if your object goes out of scope it won't lead to a crash.
The extra level of indirection for getters/setters also allow you to be able to change the data member that they encapsulate.
With a getter you can also obtain different views of your data, example: getMinutes, when your data member is actually stored in seconds.
This is not the reason to use them, but a nice side effect of using getters and setters is that you can set a breakpoint inside your modifier for example to see exactly when it is changed.
Whether you should use them or not is a judgement call based on your need. If you have so many members that it is a huge pain to provide getters and settings you could consider storing the data members in a struct and using that struct inside your class instead. You could even provide getters/setters for an object for the whole struct at once. | Accessors vs. public members | [
"",
"c++",
"class",
"member",
""
] |
I am trying to use a return type of `const MyClass * const`. However, I get a warning:
> Warning: #815-D: type qualifier on return type is meaningless.
Is this not a valid type? I want a pointer than cannot be changed, and I want the thing it points to to not be changed either. | The pointer itself has value type, so it doesn't make sense to make it const. What the caller function does with the returned value can't be restricted by the called function. This is akin to trying to define something like:
```
const int getInt();
```
getInt(), in this case, just returns an int value (not a reference). It goes to a register, then the caller function receives it and does whatever it wants with it. | I agree with Juliano's answer, you want the constness of the pointer to be at the call site.
A better way to do what you are looking for is to have your function return a const reference to the object:
```
const MyClass& getMyClass()
{
return myClass;
}
```
By definition references can't be modified, so you'd be better off.
Of course this won't work if your function is attempting to **create** a MyClass object. In that case you can just move the extra const to the call site.
```
// function definition
const MyClass* createMyClass()
{
return new MyClass("I Love C++");
}
// use of a const pointer to a MyClass which is const
const MyClass* const myClassInstance = creatMyClass();
``` | Why does the compiler warn about const on a return type being meaningless? | [
"",
"c++",
"constants",
"const-correctness",
""
] |
I have a report that I currently allow the user to choose an output option (HTML or PDF) when they are supplying the report parameters (date range, filters, etc.).
I want to change the report such that it always does HTML and puts a link on the rendered HTML page so the user can grab the PDF if they want it.
How do I modify my IIS6/IIS7 configuration, user permissions, etc. to allow my site to write the PDF to the filesystem? Any C# code would be appreciated.
I plan on creating PDFs with random filenames and adding a process to cleanup old PDFs so I don't have a disk space issue. This is a lightly used web application so I'm not worried about having lots of old PDF files hanging around. | In IIS 6 Manager, go to Application Pools and get the properties of the Application Pool your web site is running under (if you're not sure, it's on the web site Properties dialog > Home Directory tab). Go to the identity tab and see what user account that app pool is running under.
Then go to the target folder you want to write the PDF to, right-click and go to Properties > Security > Add and add "write" for the account listed for the app pool. | n IIS 6 Manager, go to Application Pools and get the properties of the Application Pool your web site is running under (if you're not sure, it's on the web site Properties dialog > Home Directory tab). Go to the identity tab and see what user account that app pool is running under.
Then go to the target folder you want to write the PDF to, right-click and go to Properties > Security > Add and add "write" for the account listed for the app pool. | ASP.NET Writing PDF to filesystem | [
"",
"c#",
".net",
"asp.net",
"iis",
"file-permissions",
""
] |
I am an absolute novice at reflection in C#. I want to use reflection to access all of private fields in a class, including those which are inherited.
I have succeeded in accessing all private fields excluding those which are inherited, as well as all of the public and protected inherited fields. However, I have not been able to access the private, inherited fields. The following example illustrates:
```
class A
{
private string a;
public string c;
protected string d;
}
class B : A
{
private string b;
}
class test
{
public static void Main(string[] Args)
{
B b = new B();
Type t;
t = b.GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance);
foreach(FieldInfo fi in fields){
Console.WriteLine(fi.Name);
}
Console.ReadLine();
}
}
```
This fails to find the field B.a.
Is it even possible to accomplish this? The obvious solution would be to convert the private, inherited fields to protected fields. This, however, is out of my control at the moment. | As Lee stated, you can do this with recursion.
```
private static void FindFields(ICollection<FieldInfo> fields, Type t) {
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (var field in t.GetFields(flags)) {
// Ignore inherited fields.
if (field.DeclaringType == t)
fields.Add(field);
}
var baseType = t.BaseType;
if (baseType != null)
FindFields(fields, baseType);
}
public static void Main() {
var fields = new Collection<FieldInfo>();
FindFields(fields, typeof(B));
foreach (FieldInfo fi in fields)
Console.WriteLine(fi.DeclaringType.Name + " - " + fi.Name);
}
``` | I haven't tried it, but you should be able to access the base type private members through the Type.BaseType property and recursively accumulate all the private fields through the inheritence hierarchy. | C#: Accessing Inherited Private Instance Members Through Reflection | [
"",
"c#",
"reflection",
""
] |
I'm finding massive performance differences between similar code in C and C#.
The C code is:
```
#include <stdio.h>
#include <time.h>
#include <math.h>
main()
{
int i;
double root;
clock_t start = clock();
for (i = 0 ; i <= 100000000; i++){
root = sqrt(i);
}
printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);
}
```
And the C# (console app) is:
```
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
DateTime startTime = DateTime.Now;
double root;
for (int i = 0; i <= 100000000; i++)
{
root = Math.Sqrt(i);
}
TimeSpan runTime = DateTime.Now - startTime;
Console.WriteLine("Time elapsed: " + Convert.ToString(runTime.TotalMilliseconds/1000));
}
}
}
```
With the above code, the C# completes in 0.328125 seconds (release version) and the C takes 11.14 seconds to run.
The C is being compiled to a Windows executable using mingw.
I've always been under the assumption that C/C++ were faster or at least comparable to C#.net. What exactly is causing the C code to run over 30 times slower?
EDIT:
It does appear that the C# optimizer was removing the root as it wasn't being used.
I changed the root assignment to `root +=` and printed out the total at the end.
I've also compiled the C using cl.exe with the /O2 flag set for max speed.
The results are now:
3.75 seconds for the C
2.61 seconds for the C#
The C is still taking longer, but this is acceptable. | Since you never use 'root', the compiler may have been removing the call to optimize your method.
You could try to accumulate the square root values into an accumulator, print it out at the end of the method, and see what's going on.
Edit : see [Jalf's answer](https://stackoverflow.com/questions/686483/c-vs-c-big-performance-difference/686617#686617) below | You must be comparing debug builds. I just compiled your C code, and got
```
Time elapsed: 0.000000
```
If you don't enable optimizations, any benchmarking you do is completely worthless. (And if you do enable optimizations, the loop gets optimized away. So your benchmarking code is flawed too. You need to force it to run the loop, usually by summing up the result or similar, and printing it out at the end)
It seems that what you're measuring is basically "which compiler inserts the most debugging overhead". And turns out the answer is C. But that doesn't tell us which program is fastest. Because when you want speed, you enable optimizations.
By the way, you'll save yourself a lot of headaches in the long run if you abandon any notion of languages being "faster" than each others. C# no more has a speed than English does.
There are certain things in the C language that would be efficient even in a naive non-optimizing compiler, and there are others that relies heavily on a compiler to optimize everything away. And of course, the same goes for C# or any other language.
The execution speed is determined by:
* the platform you're running on (OS, hardware, other software running on the system)
* the compiler
* your source code
A good C# compiler will yield efficient code. A bad C compiler will generate slow code. What about a C compiler which generated C# code, which you could then run through a C# compiler? How fast would that run? Languages don't have a speed. Your code does. | C# vs C - Big performance difference | [
"",
"c#",
"c",
"performance",
""
] |
In Django model QuerySets, I see that there is a `__gt` and `__lt` for comparative values, but is there a `__ne` or `!=` (**not equals**)? I want to filter out using a not equals. For example, for
```
Model:
bool a;
int x;
```
I want to do
```
results = Model.objects.exclude(a=True, x!=5)
```
The `!=` is not correct syntax. I also tried `__ne`.
I ended up using:
```
results = Model.objects.exclude(a=True, x__lt=5).exclude(a=True, x__gt=5)
``` | You can use [Q objects](https://docs.djangoproject.com/en/stable/topics/db/queries/#complex-lookups-with-q) for this. They can be negated with the `~` operator and combined much like normal Python expressions:
```
from myapp.models import Entry
from django.db.models import Q
Entry.objects.filter(~Q(id=3))
```
will return all entries except the one(s) with `3` as their ID:
```
[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]
``` | Your query appears to have a double negative, you want to exclude all rows where `x` is not 5, so in other words you want to include all rows where `x` *is* 5. I believe this will do the trick:
```
results = Model.objects.filter(x=5).exclude(a=True)
```
To answer your specific question, there is no "not equal to" [field lookup](http://docs.djangoproject.com/en/stable/ref/models/querysets/#field-lookups) but that's probably because Django has both [`filter`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#filter) and [`exclude`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#exclude) methods available so you can always just switch the logic around to get the desired result. | How do I do a not equal in Django queryset filtering? | [
"",
"python",
"django",
"django-models",
"django-queryset",
""
] |
I'm trying to access the parent window document from a popup.
```
<script type='text/javascript'>
$(document).ready(function(){
var summary = window.parent.document.getElementById('summary');
var content = summary.innerHTML;
});
</script>
```
Is it even possible? Is there a jQuery specific way to do it?
Thanks | You want `window.opener` not `window.parent` (that's for frames). | You can use context to accessed it:
```
<script type="text/javascript">
$(document).ready(function(){
var content = $("#summary",window.opener.document).html();
});
</script>
``` | Reference parent window document | [
"",
"javascript",
"jquery",
"dom",
""
] |
I have an application that builds dynamic parameterized SQL queries. The following query returns an inner exception of "syntax error at or near "="...
I am thinking it is in the way that I am assigning the parameter to the column name but, I'm not sure. Code follows.
```
SELECT TOP 50 77 AS Repository, DocID, LastFileDate, ImageCount,
LockedUserID, DocClass, Offline, FileType, OrigFileName, C_CredCardSSN, C_CredCardName,C_CredCardDocType, C_CredCardDocDate, C_CredCardStatus
FROM D77
WHERE C_CredCardSSN
LIKE C_CredCardSSN = @sp1%
ORDER BY C_CredCardSSN,C_CredCardName
```
**EDIT:** Thanks to everyone. All of these answers helped. =) | Try just
```
WHERE C_CredCardSSN LIKE @sp1
```
or
```
WHERE C_CredCardSSN LIKE @sp1+'%'
```
depending on why you had a "%" there (thanks to Joel Coehoorn's comment for pointing out the "%" I'd missed).
Or (in response to your comment) maybe:
```
WHERE C_CredCardSSN LIKE ''+@sp1
``` | The LIKE statement should look like this:
```
WHERE C_CredCardSSN LIKE @sp1 + '%'
``` | Parameterized SQL Query error | [
"",
"asp.net",
"sql",
"parameterized",
""
] |
I have a List containing a bunch of strings that can occur more than once. I would like to take this list and build a dictionary of the list items as the key and the count of their occurrences as the value.
Example:
```
List<string> stuff = new List<string>();
stuff.Add( "Peanut Butter" );
stuff.Add( "Jam" );
stuff.Add( "Food" );
stuff.Add( "Snacks" );
stuff.Add( "Philosophy" );
stuff.Add( "Peanut Butter" );
stuff.Add( "Jam" );
stuff.Add( "Food" );
```
and the result would be a Dictionary containing:
```
"Peanut Butter", 2
"Jam", 2
"Food", 2
"Snacks", 1
"Philosophy", 1
```
I have a way to do this, but it doesn't seem like I'm utilizing the good stuff in C# 3.0
```
public Dictionary<string, int> CountStuff( IList<string> stuffList )
{
Dictionary<string, int> stuffCount = new Dictionary<string, int>();
foreach (string stuff in stuffList) {
//initialize or increment the count for this item
if (stuffCount.ContainsKey( stuff )) {
stuffCount[stuff]++;
} else {
stuffCount.Add( stuff, 1 );
}
}
return stuffCount;
}
``` | You can use the group clause in C# to do this.
```
List<string> stuff = new List<string>();
...
var groups =
from s in stuff
group s by s into g
select new {
Stuff = g.Key,
Count = g.Count()
};
```
You can call the extension methods directly as well if you want:
```
var groups = stuff
.GroupBy(s => s)
.Select(s => new {
Stuff = s.Key,
Count = s.Count()
});
```
From here it's a short hop to place it into a `Dictionary<string, int>`:
```
var dictionary = groups.ToDictionary(g => g.Stuff, g => g.Count);
``` | I would have made a specialized List, that backed by the Dictionary and the add method would test for membership and increase count if found.
sorta like:
```
public class CountingList
{
Dictionary<string, int> countingList = new Dictionary<string, int>();
void Add( string s )
{
if( countingList.ContainsKey( s ))
countingList[ s ] ++;
else
countingList.Add( s, 1 );
}
}
``` | Building a dictionary of counts of items in a list | [
"",
"c#",
"list",
"dictionary",
""
] |
Is there a way to create a *modeless* dialog box in C++ MFC which always stays on top of the other windows in the application? I'm thinking sort of like the Find dialog in Visual Studio 2005 - where it stays on top, but you can still edit the underlying text.
(If it makes any difference, it's not MDI; it's a dialog-based app) | *Note: This does not work under Windows 10, and may not work under Windows 7 and 8 (Reports vary).*
From [Nish](http://www.voidnish.com/Articles/ShowArticle.aspx?code=dlgboxtricks):
> ###Making your dialog stay on top
>
> Haven't you seen programs which have
> an "always-stay-on-top" option? Well
> the unbelievable thing is that you can
> make your dialog stay on top with just
> one line of code. Simply put the
> following line in your dialog class's
> OnInitDialog() function.
>
> ```
> SetWindowPos(&this->wndTopMost,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
> ```
>
> Basically what we are doing is to use
> the SetWindowPos function to change
> the Z-order of our dialog window. We
> make our dialog stay on top of all
> other windows by moving it to the top
> of the Z-order. Now even when you
> activate some other window, our window
> will stay on top. But I'd advise you
> to make sure you know exactly what you
> are doing when you do this, for it
> might annoy people if they can't get
> your window out of the way when they
> want to do that.
As you mentioned in the comments, the above line makes the window sit on top of every application. You'll need to do
```
SetWindowPos(&this->wndTop,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
```
To make a window sit on top of only your application. | The accepted answer fails for Windows 7 or above. (Or perhaps its me)
But making the modeless dialog as popup instead of child solves it.
It now gets positioned wrt main dialog window but you can write code to constrain anywhere.
Using the no border or top bar makes it a simple window. | Always-in-front dialogs | [
"",
"c++",
"mfc",
"dialog",
"modeless",
"always-on-top",
""
] |
I know this sounded stupid. But I gotta be doing something wrong here.
Say,
```
struct lala
{
private bool state1;
public lala(bool state1)
{
this.state1 = state1;
}
public void SetState1ToTrue()
{
this.state1 = true;
}
public bool GetState1()
{
return this.state1;
}
}
```
Then somewhere...
```
List<lala> lalas = new List<lala>();
lalas.Add(new lala(false));
lalas.Add(new lala(false));
lalas[0].SetState1ToTrue();
// Why is it False???
Console.WriteLine(lalas[0].GetState1());
```
Are there any workarounds to this except changing it to:
```
List<lala> lalas = new List<lala>();
lalas.Add(new lala(false));
lalas.Add(new lala(false));
lala newLala = lalas[0];
newLala.SetState1ToTrue();
lalas[0] = newLala;
// It's True, finally.
Console.WriteLine(lalas[0].GetState1());
```
Which looked awful, unelegant and wasted 2 lines of code. If there's any Linq-ish or Functional Programming-ish way in say 1 line of code that would be awesome. | The problem is in this line:
```
lalas[0].SetState1ToTrue();
```
The first part, lalas[0], retrieves the first lala from the list, and does so as a new copy of it in an implicit variable. So your SetState1ToTrue operates on a lala that is then immediately discarded, and the one in the list remains the same. It's the same as doing this:
```
lala newLala = lalas[0];
newLala.SetState1ToTrue();
```
If you make lala a class not a struct, so that it becomes a reference type, then the temporary variable (explicit or implicit) is a reference to the lala within the list. | Structs are value types, so they are passed by value. That means that lalas[0] gives you a copy of the struct in lalas. You are changing a copy, so the original is unchanged. | Why state in a structs in a List cannot be change? | [
"",
"c#",
""
] |
Here's the script that's builds/sends the email:
```
$boundary = md5(date('U'));
$to = $email;
$subject = "My Subject";
$headers = "From: myaddress@mydomain.com" . "\r\n".
"X-Mailer: PHP/".phpversion() ."\r\n".
"MIME-Version: 1.0" . "\r\n".
"Content-Type: multipart/alternative; boundary=--$boundary". "\r\n".
"Content-Transfer-Encoding: 7bit". "\r\n";
$text = "You really ought remember the birthdays";
$html = '<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
$message = "Multipart Message coming up" . "\r\n\r\n".
"--".$boundary.
"Content-Type: text/plain; charset=\"iso-8859-1\"" .
"Content-Transfer-Encoding: 7bit".
$text.
"--".$boundary.
"Content-Type: text/html; charset=\"iso-8859-1\"".
"Content-Transfer-Encoding: 7bit".
$html.
"--".$boundary."--";
mail("toAddress@example.com", $subject, $message, $headers);
```
It sends the message just fine, and my recipient receives it, but they get the whole thing in text/plain instead of in multipart/alternative. Viewing the source of the received message gives this (lots of cruft removed):
```
Delivered-To: myrecipient@example.com
Received: by 10.90.100.4 with SMTP id x4cs111413agb;
Wed, 25 Mar 2009 16:39:32 -0700 (PDT)
Received: by 10.100.153.6 with SMTP id a6mr85081ane.123.1238024372342;
Wed, 25 Mar 2009 16:39:32 -0700 (PDT)
Return-Path: <xxx@xxxx.com>
--- snip ---
Date: Wed, 25 Mar 2009 17:37:36 -0600 (MDT)
Message-Id: <200903252337.n2PNbaw2019541@www.xxxxxxx.com>
To: trevor@saturdayplace.com
Subject: My Subject
From: me@mydomain.com
X-Mailer: PHP/4.3.9
MIME-Version: 1.0
Content-Type: text/plain;
boundary="--66131caf569f63b24f43d529d8973560"
Content-Transfer-Encoding: 7bit
X-OriginalArrivalTime: 25 Mar 2009 23:38:30.0531 (UTC) FILETIME=[CDC4E530:01C9ADA2]
X-TM-AS-Product-Ver: SMEX-8.0.0.1181-5.600.1016-16540.005
X-TM-AS-Result: No--4.921300-8.000000-31
X-TM-AS-User-Approved-Sender: No
X-TM-AS-User-Blocked-Sender: No
Multipart Message coming up
--66131caf569f63b24f43d529d8973560
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
You really ought remember the birthdays
--66131caf569f63b24f43d529d8973560
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
--66131caf569f63b24f43d529d8973560--
```
It looks like the content-type header is getting changed along the way from multipart/alternative to text/plain. I'm no sysadmin, so if this is a sendmail issue I'm in way over my head. Any suggestions? | The line
```
"Content-Type: multipart/alternative; boundary=--$boundary". "\r\n".
```
should be
```
"Content-Type: multipart/alternative; boundary=$boundary". "\r\n".
```
You don't include the dashes in the header. | To get this to work properly for me, I also needed to add a "\r\n" at the end of each header line, two of them ("\r\n\r\n") at the end of the lines before the text and html bodies, and one at the end of each body. This results in something like this:
```
$message = "Multipart Message coming up" . "\r\n\r\n".
"--".$boundary."\r\n".
"Content-Type: text/plain; charset=\"iso-8859-1\""."\r\n".
"Content-Transfer-Encoding: 7bit"."\r\n".
$text."\r\n".
"--".$boundary."\r\n".
"Content-Type: text/html; charset=\"iso-8859-1\""."\r\n".
"Content-Transfer-Encoding: 7bit"."\r\n".
$html."\r\n".
"--".$boundary."--";
``` | Problems with sending a multipart/alternative email with PHP | [
"",
"php",
"email",
""
] |
I have a MySQL database that I'm working with, but when I try to update a row in it, it doesn't work. Here's the update code I'm working with:
```
mysql_query("UPDATE offtopic SET next = '$insert' WHERE id = '$id'");
``` | First of all, you should make it a bit more safe:
```
mysql_query(sprintf("UPDATE offtopic SET next = '%s' WHERE id = '%s'",
mysql_real_escape_string($insert),
mysql_real_escape_string($id));
```
Now, is your `id` actually string, and not numeric? If its numeric, you should rather have:
```
mysql_query(sprintf("UPDATE offtopic SET next = '%s' WHERE id = %d",
mysql_real_escape_string($insert), $id);
``` | your syntax is correct, so it might be an error with the variables or your field names.
Try this:
```
$sql = "UPDATE offtopic SET next = '$insert' WHERE id = '$id'";
if (!mysql_query($sql)) {
echo "MySQL Error: " . mysql_error() . "<br />" . $sql;
}
```
That might show you some useful information to help you debug. | How do I update MySQL row in PHP? | [
"",
"php",
"mysql",
""
] |
I have a Java Maven project with about 800 source files (some generated by javacc/JTB) which is taking a good 25 minutes to compile with javac.
When I changed my pom.xml over to use the Eclipse compiler, it takes about 30 seconds to compile.
Any suggestions as to why javac (1.5) is running so slowly? (I don't want to switch over to the Eclipse compiler permanently, as the plugin for Maven seems more than a little buggy.)
I have a test case which easily reproduces the problem. The following code generates a number of source files in the default package. If you try to compile ImplementingClass.java with javac, it will seem to pause for an inordinately long time.
```
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class CodeGenerator
{
private final static String PATH = System.getProperty("java.io.tmpdir");
private final static int NUM_TYPES = 1000;
public static void main(String[] args) throws FileNotFoundException
{
PrintStream interfacePs = new PrintStream(PATH + File.separator + "Interface.java");
PrintStream abstractClassPs = new PrintStream(PATH + File.separator + "AbstractClass.java");
PrintStream implementingClassPs = new PrintStream(PATH + File.separator + "ImplementingClass.java");
interfacePs.println("public interface Interface<T> {");
abstractClassPs.println("public abstract class AbstractClass<T> implements Interface<T> {");
implementingClassPs.println("public class ImplementingClass extends AbstractClass<Object> {");
for (int i=0; i<NUM_TYPES; i++)
{
String nodeName = "Node" + i;
PrintStream nodePs = new PrintStream(PATH + File.separator + nodeName + ".java");
nodePs.printf("public class %s { }\n", nodeName);
nodePs.close();
interfacePs.printf("void visit(%s node, T obj);%n", nodeName);
abstractClassPs.printf("public void visit(%s node, T obj) { System.out.println(obj.toString()); }%n", nodeName);
}
interfacePs.println("}");
abstractClassPs.println("}");
implementingClassPs.println("}");
interfacePs.close();
abstractClassPs.close();
implementingClassPs.close();
}
}
``` | You get the same behaviour with JDK 1.6, including update 14, build 04, using G1 doesn't change the behaviour, (though G1 appears to work really well).
Monitoring javac with jvisualvm, repeated thread dumps show the main thread spending lots of time in
```
at com.sun.tools.javac.code.Types.isSubSignature(Types.java:1846)
at com.sun.tools.javac.code.Symbol$MethodSymbol.overrides(Symbol.java:1108)
at com.sun.tools.javac.code.Symbol$MethodSymbol.implementation(Symbol.java:1159)
at com.sun.tools.javac.comp.Check.checkCompatibleConcretes(Check.java:1239)
at com.sun.tools.javac.comp.Check.checkCompatibleSupertypes(Check.java:1567)
at com.sun.tools.javac.comp.Attr.attribClassBody(Attr.java:2674)
at com.sun.tools.javac.comp.Attr.attribClass(Attr.java:2628)
at com.sun.tools.javac.comp.Attr.attribClass(Attr.java:2564)
at com.sun.tools.javac.main.JavaCompiler.attribute(JavaCompiler.java:1036)
at com.sun.tools.javac.main.JavaCompiler.compile2(JavaCompiler.java:765)
at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:730)
at com.sun.tools.javac.main.Main.compile(Main.java:353)
at com.sun.tools.javac.main.Main.compile(Main.java:279)
at com.sun.tools.javac.main.Main.compile(Main.java:270)
at com.sun.tools.javac.Main.compile(Main.java:69)
at com.sun.tools.javac.Main.main(Main.java:54)
```
and churning through a large number of short lived instances of these classes:
```
com.sun.tools.javac.code.Types$Subst
com.sun.tools.javac.util.List
com.sun.tools.javac.code.Types$MethodType
```
I suspect the code is churning through `com.sun.tools.javac.comp.Check.checkCompatibleConcretes` comparing each method with every other method
That method's javadoc:
```
/** Check that a class does not inherit two concrete methods
* with the same signature.
*/
```
It may be that eclipse's compiler either doesn't perform that check, or doesn't perform it in the same way. | Sun has confirmed to me by email that this is a new bug ([6827648](https://bugs.java.com/bugdatabase/view_bug?bug_id=6827648) in their bug database). | Why is javac 1.5 running so slowly compared with the Eclipse compiler? | [
"",
"java",
"eclipse",
"maven-2",
"javac",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.