Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am running static code analysis with FxCop 1.36 and I keep getting [warning CA1034](http://msdn.microsoft.com/en-us/library/ms182162.aspx): NestedTypesShouldNotBeVisible.
I would understand if the parent class were declared as internal or private, but it is public. Why would it be bad for TimerReset to be declared public?
Am I missing something, or is this something that can be ignored?
Thanks for any input!
Here is an excerpt of the code causing this warning:
```
namespace Company.App.Thing
{
public partial class Page : XtraPage
{
public delegate void TimerResetDelegate(object sender, EventArgs e);
private TimerResetDelegate _timerReset;
public Page()
{
InitializeComponent();
}
public TimerResetDelegate TimerReset
{
set
{
if (null != (_timerReset = value))
{
checkBox.Click += new EventHandler(_timerReset);
textField.Click += new EventHandler(_timerReset);
textField.KeyDown += new KeyEventHandler(_timerReset);
TimeField.Click += new EventHandler(_timerReset);
TimeField.KeyDown += new KeyEventHandler(_timerReset);
}
}
}
}
}
``` | Generally speaking, Nested Types are harder to 'discover'.
E.g. To use your nested type, I will have to write following
```
Page.TimerResetDelegate timer = new Page.TimerResetDelegate();
```
Even though above is valid C# code, it doesn't read like the usual type usage.
Nested Types are generally used when you want to define a type to be used internally and you would avoid code like above. This is the reason why FxCop is giving you warning. If you want, you can ignore it. Personally, I would keep my Nested types as private. If I expect caller to make use of the type, I will move them to a proper namespace. | > Why would it be bad for TimerReset to be declared public?
Exactly as the [description states](http://msdn.microsoft.com/en-us/library/ms182162.aspx):
> Nested types are useful for encapsulating private implementation details of the containing type. Used for this purpose, nested types should not be externally visible.
Since you're exposing `TimerResetDelegate` publically with `TimerReset`, I guess it's not an implementation detail.
> Do not use externally visible nested types for logical grouping or to avoid name collisions; instead, use namespaces.
Which makes it look like you're using a nested type for grouping. As FxCop states, use a namespace instead.
> Nested types include the notion of member accessibility, which some programmers do not understand clearly.
Since `TimerResetDelegate` is a delegate, this doesn't really apply.
Move `TimerResetDelegate` to it's own TimeResetDelegate.cs file, and put it in your `Company.App.Thing` namespace. Then, it's no longer nested.
Of course, it'd be even better to just go with [EventHandler](http://msdn.microsoft.com/en-us/library/system.eventhandler.aspx) instead of defining your own delegate type. | FxCop - CA1034 error - WHY? | [
"",
"c#",
"static-analysis",
"fxcop",
""
] |
I have a query that returns data in the following form
```
attribute value
--------- ----------
petid 1000
name buttercup
species cat
age 10
owner Bob Dole
```
Basically I want to go through every row and return the fields name and species in a single string, so here the result would be
```
buttercup cat
```
Any ideas how I could do this? | Try this. I've only tried it with SQL Serer 2008, but maybe it will work:
```
DECLARE @Concat nvarchar(50)
SET @Concat=N''
SELECT @Concat = @Concat + Value + N' '
FROM dbo.AttributeValue
WHERE Attribute IN (N'name', N'species')
SELECT @Concat
``` | Okay - Now I think I understand the data format...
Here is the code to create the sample set (just to make sure I've got it right)
```
CREATE TABLE MyTable
(
attribute varchar(20),
value varchar(20)
)
INSERT INTO MyTable VALUES('petid','1000')
INSERT INTO MyTable VALUES('name','buttercup')
INSERT INTO MyTable VALUES('species','cat')
INSERT INTO MyTable VALUES('age','10')
INSERT INTO MyTable VALUES('owner','Bob Dole')
```
Here is my answer:
```
SELECT a.value + ' ' +b.value
FROM MyTable AS a
INNER JOIN MyTable AS b ON a.attribute='name' AND b.attribute = 'species'
``` | Concatenating Columns from a Result Set in SQL Server 2000 | [
"",
"sql",
"sql-server-2000",
""
] |
In my particular case, we've got a db table that, among other fields, has an "Image" field. We'd like to append ".jpg" to every row in this table for this column. To keep it simple we'll say it just has two columns...an ID column and an Image column. (bonus points for skipping rows that have an empty string for "Image".)
The question title is a bit more open ended because I can imagine someone wanting to just about anything to all rows. ("update all rows so that column 'X' has its values divided by 2", "update all rows so that column 'Y' is prepended with this path", etc.)
Although I'm using SQL server, I suspect that the answers will be pretty universal...but if your particular answer is not, don't let that stop you from responding...but please do add in your post what system it is for. | You mean like this? This works in SQL Server.
```
UPDATE [table]
SET [image] = [image] + '.jpg'
WHERE ISNULL([image], '') <> ''
```
If you want this to be repeatable:
```
UPDATE [table]
SET [image] = [image] + '.jpg'
WHERE ISNULL([image], '') <> ''
AND [image] NOT LIKE '%.jpg'
``` | like this
```
update Table
set image = image + '.jpg'
where image <> ''
```
or
```
update Table
set image = image + '.jpg'
where rtrim(image) <> ''
```
or
```
update Table
set image = image + '.jpg'
where rtrim(coalesce(image,'')) <> ''
``` | How does one modify all DB column data based on current data? | [
"",
"sql",
""
] |
SQL 2000
The NED table has a foreign key to the SIGN table NED.RowID to SIGN.RowID
The SIGN table has a foreign key to the NED table SIGN.SignID to NED.SignID
The RowID and SignID are clustered primary keys that are GUIDs (not my choice)
The WHERE clause is:
```
FROM
[SIGN] A
INNER JOIN NED N ON A.SIGNID = N.SIGNID
INNER JOIN Wizard S ON A.WizardID = S.WizardID
INNER JOIN [Level] SL ON N.LevelID = SL.LevelID
LEFT JOIN Driver DSL ON SL.LevelID = DSL.LevelID
AND DSL.fsDeptID = @fsDeptID
INNER JOIN [Character] ET ON S.CharacterID = ET.CharacterID
INNER JOIN Town DS ON A.TownID = DS.TownID
WHERE
(A.DeptID = @DeptID OR
S.DeptID = @DeptID
AND
A.[EndTime] > @StartDateTime AND A.[StartTime] < @EndDateTime
AND
A.NEDStatusID = 2
```
Why is there an INDEX SCAN on the SIGN table for this query? What would cause an index scan on a clustered index? Thanks | Here's a good blog post about when SQL Server reaches the "tipping point" and switches from an index seek to an index/table scan:
<http://www.sqlskills.com/BLOGS/KIMBERLY/post/The-Tipping-Point-Query-Answers.aspx>
You may want to look at the way your queries are filtering, as the tipping point is often much fewer rows than people expect. | A clustered index scan is how SQL Server designates a full table scan on a table with a clustered index. This is because you don't have enough indexes on the SIGN table to satisfy the WHERE clause, or because it decided that the SIGN table is small enough (or the indexes not selective enough) that a table scan would be more efficient.
Just by examining the query, you'd probably have to index the DeptID column as well as some combination of StartTime, EndTime and NEDStatusID to avoid the table scan. If the reason you're asking is because you're having performance problems, you can also run the Index Tuning Wizard (now the Database Engine Tuning Advisor in the SQL2005+ client tools) and have it give some advice on which indexes to create to speed up your query. | Why is there a scan on my clustered index? | [
"",
"sql",
"sql-server",
"clustered-index",
""
] |
i have a php page,
on that page i have text boxes and a submit button,
this button runs php in a section:
> if(isset($\_POST['Add'])){code}
This works fine here and in that section $name,$base,$location etc are calculated and used. but that section of code generates another submit button that drives another section of code.
it is in this second section of code that i wish to add data to the DB.
Now i already know how to do this, the problem is that the variables $name and so forth have a value of NULL at this point.. but they can only be called after the first code section has been run where they gain value.
**How do i maintain these values until the point where i add them?**
Resources:
the page feel free to try it out:
location mustbe of the form 'DNN:NN:NN:NN' where D is "D" and N is a 0-9 integer
<http://www.teamdelta.byethost12.com/postroute.php>
the code of the php file as a text file!
<http://www.teamdelta.byethost12.com/postroute.php>
lines 116 and 149 are the start of the 2 button run sections! | I think you are looking for PHP's session handling stuff ...
As an example, first page:
```
session_start(); # start session handling.
$_SESSION['test']='hello world';
exit();
```
second page:
```
session_start(); # start session handling again.
echo $_SESSION['test']; # prints out 'hello world'
```
Behind the scenes, php has set a cookie in the users browser when you first call session start, serialized the $\_SESSION array to disk at the end of execution, and then when it receives the cookie back on the next page request, it matches the serialised data and loads it back as the $\_SESSION array when you call session\_start();
Full details on the session handling stuff:
<http://uk.php.net/manual/en/book.session.php> | Around the add-button you are creating a second form. If you want to have the data within this form then you will have to create hidden input fields. Because you are sending a second form here. Or you are moving the add button up to the other form.
Or as others are mentioning.. Save the values into a session. | Variable persistence in PHP | [
"",
"php",
"variables",
"persistence",
""
] |
The documentation of [CharUnicodeInfo.GetUnicodeCategory](http://msdn.microsoft.com/en-us/library/system.globalization.charunicodeinfo.getunicodecategory.aspx) says:
> Note that [*CharUnicodeInfo*.GetUnicodeCategory](http://msdn.microsoft.com/en-us/library/system.globalization.charunicodeinfo.getunicodecategory.aspx) does not always return the same [UnicodeCategory](http://msdn.microsoft.com/en-us/library/system.globalization.unicodecategory.aspx) value as the [*Char*.GetUnicodeCategory](http://msdn.microsoft.com/en-us/library/system.char.getunicodecategory.aspx) method when passed a particular character as a parameter.
>
> The [*CharUnicodeInfo*.GetUnicodeCategory](http://msdn.microsoft.com/en-us/library/system.globalization.charunicodeinfo.getunicodecategory.aspx) method is **designed to reflect the current version of the Unicode standard**. In contrast, although the [*Char*.GetUnicodeCategory](http://msdn.microsoft.com/en-us/library/system.char.getunicodecategory.aspx) method usually reflects the current version of the Unicode standard, it might return a character's category based on a previous version of the standard, or it might return a category that differs from the current standard to preserve backward compatibility.
So, which version of the Unicode standard is reflected by [*CharUnicodeInfo*.GetUnicodeCategory](http://msdn.microsoft.com/en-us/library/system.globalization.charunicodeinfo.getunicodecategory.aspx) and [*Char*.GetUnicodeCategory](http://msdn.microsoft.com/en-us/library/system.char.getunicodecategory.aspx) in which version of the .NET Framework? | The documentation for the [String Class](http://msdn.microsoft.com/en-us/library/system.string.aspx) states the Unicode version that the .NET Framework 4 and 4.5 conform to:
[**.NET Framework 4**](http://msdn.microsoft.com/en-us/library/system.string%28v=vs.100%29.aspx)
> In the .NET Framework 4, sorting, casing, normalization, and Unicode character information is synchronized with Windows 7 and conforms to the Unicode 5.1 standard.
[**.NET Framework 4.5**](http://msdn.microsoft.com/en-us/library/system.string%28v=vs.110%29.aspx)
> In the .NET Framework 4.5 running on the Windows 8 operating system, sorting, casing, normalization, and Unicode character information conforms to the Unicode 6.0 standard. On other operating systems, it conforms to the Unicode 5.0 standard. | As far as I can tell, the unicode version isn't stored. The character lookup is implemented by storing the character info in an embedded resource called "charinfo.nlp" in mscorlib.dll, and this is used as a lookup table internally. There is a "version" property on the header to this lookup table data, but it is "0" in the binary data (offset 0x20), so I'm not sure what that's a version of, or if it's just not implemented. | Unicode versions in .NET | [
"",
"c#",
".net",
"vb.net",
"string",
"unicode",
""
] |
```
join_strings(string $glue, string $var, string $var2 [, string $...]);
```
I am looking for something that would behave similar to the function I conceptualized above. A functional example would be:
```
$title = "Mr.";
$fname = "Jonathan";
$lname = "Sampson";
print join_strings(" ", $title, $fname, $lname); // Mr. Jonathan Sampson
```
After giving the documentation a quick look-over, I didn't see anything that does this. The closest I can think of is implode(), which operates on arrays - so I would have to first add the strings into an array, and then implode.
Is there already a method that exists to accomplish this, or would I need to author one from scratch?
**Note**: I'm familiar with concatenation (.), and building-concatenation (.=). I'm not wanting to do that (that would take place within the function). My intentions are to write the $glue variable only once. Not several times with each concatenation. | you can use join or implode, both do same thing
and as you say it needs to be an array which is not difficult
```
join($glue, array($va1, $var2, $var3));
``` | You can use [`func_get_args()`](http://www.php.net/manual/en/function.func-get-args.php) to make [`implode()`](http://www.php.net/manual/en/function.implode.php) (or its alias [`join()`](http://www.php.net/manual/en/function.join.php)) bend to your will:
```
function join_strings($glue) {
$args = func_get_args();
array_shift($args);
return implode($glue, $args);
}
```
As the documentation for `func_get_args()` notes, however:
> Returns an array in which each element is a copy of the corresponding member of the current user-defined function's argument list.
So you still end up making an array out of the arguments and then passing it on, except now you're letting PHP take care of that for you.
Do you have a more convincing example than the one in your question to justify not simply using `implode()` directly?
The only thing you're doing now is saving yourself the trouble to type `array()` around the variables, but that's actually shorter than the `_strings` you appended to the function name. | PHP Function to Join Strings? | [
"",
"php",
"string",
"concatenation",
""
] |
Before, I had this:
```
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var optPrompt = "- Select One -";
var subCats;
var parentCats;
var nextBtn;
var ParentChanged = function() {
ClearDescription();
if (this.selectedIndex == 0) {
$(subCats).html($("<option>").text(optPrompt));
}
$.getJSON('<%=Url.Action("GetChildCategories") %>', { parentId: $(this).val() },
function(data) {
subCats.options.length = 0;
$("<option>").text(optPrompt).appendTo(subCats);
$(data).each(function() {
$("<option>").attr("value", this.ID).text(this.Name).appendTo(subCats);
});
});
}
var DisplayDescription = function(catId) {
$.ajax({
url: '<%=Url.Action("GetDescription") %>',
data: { categoryId: catId },
dataType: 'html',
success: function(data) {
$("p#categoryDescription").html(data);
}
});
}
var ChildChanged = function() {
var catSelected = this.selectedIndex != 0;
if (!catSelected) ClearDescription();
else DisplayDescription($(this).val());
}
var ClearDescription = function() {
$("p#categoryDescription").html('');
}
$(function() {
parentCats = $("select#Category").get(0);
subCats = $("select#Subcategory").get(0);
nextBtn = $("input#nextButton").get(0);
$(parentCats).change(ParentChanged);
$(subCats).change(ChildChanged);
});
</script>
</head>
```
Then I put all of my inline script into a file (myScript.js) and changed my HTML to this:
```
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/Scripts/myScript.js" type="text/javascript"></script>
</head>
```
And now nothing is working. I opened up my page in IE7 and it had a page error that read:
> Line: 54
> Error: Unknown name.
Line 54 happens to be the last line of my external javascript file.
What am I doing wrong? | Am I right in saying that this is ASP.Net? If it is, inline scripts like:
```
<%=Url.Action("GetDescription") %>
```
cannot go in the external JavaScript file. | Did you put the < script > tag inside your myScript.js? If yes, remove them.
Your myScript.js should start with
var optPrompt = "- Select One -"; | Javascript File References Problem (with jQuery) | [
"",
"javascript",
"jquery",
"html",
"filereference",
""
] |
Is there a way to get the modification time of a file (either `ctime` or `mtime` should work) that is accessed locally through JavaScript?
I want to go to `file:///home/me/mtime.html` and have the JavaScript tell me that `/home/me/file.txt` was modified 2 minutes ago or something. I Understand that JavaScript has limited file access due to security problems, but is there some trick since it is all done locally.
Thanks. | Firefox has a set of components under its XPCOM (ActiveX competitor technology) that could be used to do the same thing.
Probably something like this (untested):
```
function getLastModifiedTime(filePath)
{
try
{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
catch (e)
{
throw new Error("Permission to read file was denied.");
}
var file = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
file.initWithPath( filePath );
return file.lastModifiedTime;
}
```
As for Safari.... no idea. Maybe a signed java applet? | Here is some javascript using ActiveX that I think might help you out:
```
<script language=jscript runat=server>
var thisfile = <File_Path>;
thisfile = Server.MapPath(thisfile);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fs = fso.GetFile(thisfile);
var dlm = fs.DateLastModified;
Response.Write("Last modified: " + dlm);
</script>
```
If you need how long ago it was modified you would need some other javascript to subtract dlm from the current time. | Access local file modification time in JavaScript | [
"",
"javascript",
"file",
""
] |
I'll write a application but I've never experienced to allow people to use my application programming interface before.I mean how kinda design I should make to let people use my methods from outside world like API.
Please some one show me a way.I am kinda new to this. | 1. Expose as little as you can. Every bit you publish, will return to you x100 in next version. Keeping compatibility is very hard.
2. Create abstractions for everything you publish. You will definitely change your internals, but your existing users should stay compatible.
3. Mark everything as internal. Even the main method of your application. Every single method that could be used, will be used.
4. Test your public API the same way you would for interfaces. Integration tests and so on. Note that your API will be used in unpredictable ways.
5. Maximize convention over configuration. This is required. Even if your API is a single method you will still need to support this. Just makes your life easier.
6. Sign, and strong name your assemblies, this is good practice.
7. Resolve as many FxCop and StyleCop errors as possible.
8. Check your API is compatible with the Naming Guidelines of your platform.
9. Provide as many examples as you can, and remember that most of the usage of your API will be Ctrl+C and Ctrl+V from these examples.
10. Try to provide documentation. Check that you do not have GhostDoc-style auto-generated documentation. Everybody hates this.
11. Include information on how to find you.
12. Do not bother with obfuscation. This will help you and your users.
ADDED
13. API should have as less dependencies as you can. For example, dependecies on the IoC containers should be prohibited. If your code uses it internally. Just ilmerge them into your assemblies. | It may not be the funniest reading, and certainly not the only reading to do on the subject, but while designing your class library (your API), do check in with the [Design Guidelines for Developing Class Libraries](http://msdn.microsoft.com/en-us/library/ms229042.aspx) every now and then, it's a good idea to have a design that corresponds a bit with the .NET Framework iteself. | Writing API in C# for My Application | [
"",
"c#",
"api",
""
] |
Is it possible to implement a p2p using just PHP? Without Flash or Java and obviously without installing some sort of agent/client on one's computer.
so even though it might not be "true" p2p, but it'd use server to establish connection of some sort, but rest of communication must be done using p2p
i apologize for little miscommunication, by "php" i meant not a php binary, but a php script that hosted on web server remote from both peers, so each peer have nothing but a browser. | No.
You could write a P2P client / server in PHP — but it would have to be installed on the participating computers.
You can't have PHP running on a webserver cause two other computers to communicate with each other without having P2P software installed.
You can't even use JavaScript to help — the same origin policy would prevent it.
JavaScript running a browser could use a PHP based server as a middleman so that two clients could communicate — but you aren't going to achieve P2P.
---
Since 2009 (when this answer was originally written), the WebRTC protocol was written and achieved [widespread support](https://caniuse.com/?search=WebRTC) among browsers.
This allows you to perform [peer-to-peer between web browsers](https://developer.mozilla.org/en-US/docs/Web/Guide/API/WebRTC/Peer-to-peer_communications_with_WebRTC) but you need to write the code in JavaScript (WebAssembly might also be an option and one that would let you write PHP.)
You also need a [bunch of non-peer server code](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Protocols) to support WebRTC (e.g. for allow peer discovery and proxy data around firewalls) which you could write in PHP. | > without installing some sort of
> agent/client on one's computer
Each computer would have to have the PHP binaries installed.
**EDIT**
I see in a different post you mentioned browser based. Security restrictions in javascript would prohibit this type of interaction | Is it possible to have a peer to peer communication using nothing but PHP | [
"",
"php",
"p2p",
""
] |
I would like to see how a large (>40 developers) project done with Python looks like:
* how the code looks like
* what folder structure they use
* what tools they use
* how they set up the collaboration environment
* what kind of documentation they provide
It doesn't matter what type of software it is (server, client, application, web, ...) but I would prefer something mature (version 1.0 already done) | [Chandler](http://chandlerproject.org/) is a really huge one that had problems because of its size and the developers working on it, so you can learn from their failures. There's a [book](http://www.dreamingincode.com/) written about it too.
[Wingware Python IDE](http://www.wingware.com/) is a huge project, unfortunately it's closed source. But I think it's still interesting to see what a large desktop application is like in Python. | The [Django](http://www.djangoproject.com/) web framework.
Also, [Twisted Matrix](http://twistedmatrix.com/trac/).
I am not sure about the exact number of developers, though. | Can you point me to a large Python open-source project? | [
"",
"python",
"open-source",
""
] |
I am building a small app as a service in django and now is the time to integrate it on some clients PHP web app.
Our client *A* from domain www.a.com handles his own authentication for his users and probably use cookies for sessions.
How could i make logged in users from his domain also logged in on my Django app dommain www.b.com/clientA/ ?
I see how i can make them reloggin on my domain and use an authbackend checking credential with domain A but that means the user will have to enter his login/pass twice: on www.a.com and www.b.com.
Accessing cookie from domain www.a.com is impossible for security reasons i think.
How would you handle this ? | You are correct in assuming cookies from another domain cannot be accessed. However, if it's on a subdomain, you should be able to access the cookies if they're set correctly.
If you absolutely must have them on completely separate domains, it's going to be a bit tricky. If you can't modify the existing PHP code, you can pretty much forget it.
One option would be using OpenID - that may be the simplest way to tackle this, as there are OpenID libraries available for PHP and Python. OpenID would allow you to have a single-sign on like authentiction, and since it's already used on various sites it is proven and works.
Another option is writing a custom single sign-on system.
The basic idea is that when a user arrives at your site, you direct them to a login site. This can be either in the PHP or Python end of things, or separate. Here, the user will sign in, and then the login generates a secret key - this can be a hash, random string, whatever as long as it's not predictable - and the user is redirected back to the main site with the key.
The main site then sees the user has a key, and sends a request to the login site behind the scenes to verify the user's key.
Now the user is logged in at one site. When the user visits the second site, it too redirects the user to the login site. Since the user had already logged in, the login site simply redirects the user back with a new secret key, and the second site verifies it from the login site and now the user is logged in without having to input their credentials another time. | Ok, this is how to authenticate a Django user from PHP, or how to "read" a Django password from PHP.
I think OpenID is the best solution but I had to authenticate Django users in a PHP app sharing the same database today and this is how I solved:
```
<?php
/* Generates crypted hash the same way as Django does */
function get_hexdigest($algorithm, $salt, $raw_password) {
if (!array_in($algorithm, array('md5', 'sha1'))) {
return false;
}
return $algorithm($salt.$raw_password);
}
/* Checks if password matches the same way Django does */
function check_password($raw_password, $django_password) {
list($algorithm, $salt, $hsh) = explode('$', $django_password);
return get_hexdigest($algoritm, $salt, $raw_password) === $hsh;
}
?>
```
The key is to understand the format in which Django saves the passwords, which is:
[algorithm]$[salt]$[hash]
So for example I had an "admin" user with password "admin" and the password field in the auth\_user row was:
```
sha1$63a11$85a93f217a72212b23fb0d5b95f3856db9575c1a
```
The algorithm is "sha1", the salt, which was generated randomly is "63a11" and the crypted hash is "85a93f217a72212b23fb0d5b95f3856db9575c1a".
So who do you produce the crypted hash in PHP? You simple concatenate the salt and the raw password and hash it with the algorithm, in this case, sha1:
```
<?php
$salt = '63a11';
$pass = 'admin';
echo sha1($salt.$pass); // prints "85a93f217a72212b23fb0d5b95f3856db9575c1a"
?>
```
That wasn't difficult! I got it by reading the relevant code in the Django sources. | Django single sign on and Php site: cross domain login? | [
"",
"php",
"django",
"authentication",
""
] |
I have two MySQL (MyISAM) tables:
```
Posts: PostID(primary key), post_text, post_date, etc.
Comments: CommentID(primary key), comment_text, comment_date, etc.
```
I want to delete all the comments in the "Comments" table belonging to a particular post, when the corresponding post record is deleted from the "Posts" table.
I know this can be achieved using cascaded delete with InnoDB (by setting up foreign keys). But how would I do it in MyISAM using PHP? | ```
DELETE
Posts,
Comments
FROM Posts
INNER JOIN Comments ON
Posts.PostID = Comments.PostID
WHERE Posts.PostID = $post_id;
```
Assuming your Comments table has a field PostID, which designates the Post to which a Comment belongs to. | Even without enforceable foreign keys, the method to do the deletion is still the same. Assuming you have a column like `post_id` in your Comments table
```
DELETE FROM Comments
WHERE post_id = [Whatever Id];
DELETE FROM Posts
WHERE PostID = [Whatever Id];
```
What you *really* lose with MyISAM is the ability to execute these two queries within a transaction. | Deleting related records in MySQL | [
"",
"php",
"mysql",
"database",
"myisam",
""
] |
Is the indexOf(String) method case sensitive? If so, is there a case insensitive version of it? | The `indexOf()` methods are all case-sensitive. You can make them (roughly, in a broken way, but working for plenty of cases) case-insensitive by converting your strings to upper/lower case beforehand:
```
s1 = s1.toLowerCase(Locale.US);
s2 = s2.toLowerCase(Locale.US);
s1.indexOf(s2);
``` | > Is the indexOf(String) method case sensitive?
Yes, it is case sensitive:
```
@Test
public void indexOfIsCaseSensitive() {
assertTrue("Hello World!".indexOf("Hello") != -1);
assertTrue("Hello World!".indexOf("hello") == -1);
}
```
> If so, is there a case insensitive version of it?
No, there isn't. You can convert both strings to lower case before calling indexOf:
```
@Test
public void caseInsensitiveIndexOf() {
assertTrue("Hello World!".toLowerCase().indexOf("Hello".toLowerCase()) != -1);
assertTrue("Hello World!".toLowerCase().indexOf("hello".toLowerCase()) != -1);
}
``` | indexOf Case Sensitive? | [
"",
"java",
"case-sensitive",
""
] |
I was just wondering if anyone had any success in getting `XMLBeans` (or any other generator) to work on android. It would be very nice if I could use it because I have a very large schema that I would rather not write all the classes by hand.
I had asked about this on the android developers mailing list, but no one responded. This tells me that either they don't care, or no one feels like telling me its not possible.
If anyone knows of anything else like `XMLBeans` that works for android, please let me know. It would be very helpful.
Thanks,
Robbie | If you're looking to do class generation and DOM parsing, XMLBeans is probably pretty heavy-weight for a mobile device running android. All of the code generated by XMLBeans makes synchronized calls into an underlying data store that I've seen as a hot spot several times when profiling.
I can't suggest any alternatives, but I would be wary of using this even if you *could* get it to work, because of the afore mentioned performance issue. | You can use Castor . Just be sure, in Android 2.1, not to use default android SAXParser. You'll get namespace errors. You do this by defining the parser to be, for example, Xerces (and the you add the required JARS), in core.properties .
In android 2.2 it may be ok.
Note that if you create an xmlcontext for the unmarsheler with xerces, it still won't work, as the mapping itself would be parsed with android's SAX. It must be done at core (top level properties file) so that even the mapping is parsed by xerces.
finally - performance is as slow as you can expect... :(
Good luck
SM | Using XMLBeans on Android | [
"",
"java",
"xml",
"android",
"xmlbeans",
""
] |
I've got a PHP application I wrote earlier that I'd like to add a RESTful API to. I'd also like to expand the site to behave more like a Rails application in terms of the URLs you call to get the items in the system.
Is there any way to call items in PHP in a Railsy way without creating all kinds of folders and index pages? How can I call information in PHP without using a GET query tag? | If you have some form of mod\_rewrite going you can do this quite easily with a .htaccess file.
If you have something like this:
```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
```
It will check that the file you are trying to access doesn't exist already. (Say you had a file hello.html that you still needed people to access via <http://yoursite.com/hello.html>)
Then if the file doesn't already exist it will load your index.php file with the rest of the URL stored in the url variable.
This means you can call something like this <http://yoursite.com/pages/edit/24> and it will load index.php with /pages/edit/24 inside the url variable.
That should get you started and you won't need all kinds of folders and index pages, just mod\_rewrite, .htaccess file and an index.php that will be used to load whatever you need. | You also might consider to use one of the PHP frameworks with built-in REST support, for example [CakePHP](http://cakephp.org "CakePHP"). | Creating a RESTful API and website with PHP | [
"",
"php",
"ruby-on-rails",
"url",
"rest",
"get",
""
] |
I would like to extract the year from the current date using Python.
In C#, this looks like:
```
DateTime a = DateTime.Now()
a.Year
```
What is required in Python? | It's in fact almost the same in Python.. :-)
```
import datetime
year = datetime.date.today().year
```
Of course, date doesn't have a time associated, so if you care about that too, you can do the same with a complete datetime object:
```
import datetime
year = datetime.datetime.today().year
```
(Obviously no different, but you can store datetime.datetime.today() in a variable before you grab the year, of course).
One key thing to note is that the time components can differ between 32-bit and 64-bit pythons in some python versions (2.5.x tree I think). So you will find things like hour/min/sec on some 64-bit platforms, while you get hour/minute/second on 32-bit. | ```
import datetime
a = datetime.datetime.today().year
```
or even (as [Lennart suggested](https://stackoverflow.com/questions/1133147/how-to-extract-the-year-from-a-python-datetime-object#comment950702_1133171))
```
a = datetime.datetime.now().year
```
or even
```
a = datetime.date.today().year
``` | How to extract the year from a Python datetime object? | [
"",
"python",
"datetime",
""
] |
I have a process which iterates String instances.
Each iteration does few operations on the String instance.
At the end the String instance is persisted.
Now, I want to add for each iteration a check if the String instance might be spam.
I only have to verify that the String instance is not "adult materials" spam.
Any recommendations? | This is a *very* hard problem that the industry is constantly trying to solve. The best thing for you to do is to try and use an existing solution like [Classifier4J](http://classifier4j.sourceforge.net/) along with a black-list datasource to identify spam. | You need to apply some Bayesian logic, which is what, among other things, [Classifier4J](http://classifier4j.sourceforge.net/) that Andrew mentioned is doing beneath the covers.
Paul Graham wrote a good article about this a few years back - <http://www.paulgraham.com/spam.html>. | Easiest Way to Check if a Java String Instance Might Hold Spam Data | [
"",
"java",
"spam-prevention",
""
] |
I'm trying to load binary file using `fstream` in the following way:
```
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
basic_fstream<uint32_t> file( "somefile.dat", ios::in|ios::binary );
vector<uint32_t> buffer;
buffer.assign( istream_iterator<uint32_t, uint32_t>( file ), istream_iterator<uint32_t, uint32_t>() );
cout << buffer.size() << endl;
return 0;
}
```
But it doesn't work. In Ubuntu it crashed with `std::bad_cast` exception. In MSVC++ 2008 it just prints 0.
I know that I could use `file.read` to load file, but I want to use iterator and `operator>>` to load parts of the file. Is that possible? **Why** the code above doesn't work? | 1. `istream_iterator` wants `basic_istream` as argument.
2. It is impossible to overload `operator>>` inside `basic_istream` class.
3. Defining global `operator>>` will lead to compile time conflicts with class member `operator>>`.
4. You could specialize `basic_istream` for type `uint32_t`. But for specialization you should rewrite all fuctionons of `basic_istream` class. Instead you could define dummy class `x` and specialize `basic_istream` for it as in the following code:
```
using namespace std;
struct x {};
namespace std {
template<class traits>
class basic_istream<x, traits> : public basic_ifstream<uint32_t>
{
public:
explicit basic_istream<x, traits>(const wchar_t* _Filename,
ios_base::openmode _Mode,
int _Prot = (int)ios_base::_Openprot) : basic_ifstream<uint32_t>( _Filename, _Mode, _Prot ) {}
basic_istream<x, traits>& operator>>(uint32_t& data)
{
read(&data, 1);
return *this;
}
};
} // namespace std
int main()
{
basic_istream<x> file( "somefile.dat", ios::in|ios::binary );
vector<uint32_t> buffer;
buffer.assign( istream_iterator<uint32_t, x>( file ), istream_iterator<uint32_t, x>() );
cout << buffer.size() << endl;
return 0;
}
``` | You can reload operator>> to read integers properly. Of course all it will do is read() 4 bytes. But that's what all other operators>> are eventually doing anyway.
Here is example (no error checking, assuming endianess is same as current compiler uses, etc)
```
std::istream& operator>>(std::istream& in, uint32_t& data)
{
in.read(&data, sizeof(data));
return in;
}
```
Tailor for your own flavor of integers (might have to read one byte at a time and shift assign them, look at the file in hex editor if you don't know byte order), add error checking, and you should be able to use your existing code.
EDIT: ah, and yes, make sure this shadows provided stl operator that reads integer -- might have to derive your own class from the stream you are using and use that instead of std::istream& in, just so compiler knows who to check first. | Load binary file using fstream | [
"",
"c++",
"stl",
"file-io",
"filestream",
"fstream",
""
] |
I would like to be able to use a Dataset as an in-memory datastore.
I want to be able to use SELECT, INSERT, UPDATE, and DELETE, CREATE TABLE, DROP TABLE, ALTER TABLE ADD COLUMN, ALTER TABLE DROP COLUMN, and support for Constraints PRIMARY KEY, UNIQUE, NOT NULL, FOREIGN KEY, REFERENCES. | Someone has made this a reality in the form of a commercial product. <http://www.queryadataset.com>
It supports all of the features that I originally asked about
<http://www.queryadataset.com/Documentation/Expressions/tabid/80/Default.aspx>. | If you want to test your database commands on an in-memory data store, DataSet is not the way to go, as its not an in-memory relational database engine. As others have said, you can do all sorts of querying on a DataSet, but not DDL commands. I have looked at various in-memory or embedded database engines (SqlLite, HSQL, Firebird) but never came close to finding a good way to unit test Sql Server code in memory, generally due to the limitations of those engines (e.g. no stored procedures).
If you need an embedded database for your application, have a look at those products.
If you need to test Sql Server commands, you'll have to run them on an instance of Sql Server (consider Express, lightweight and free). | How can I execute SQL statements against a Dataset | [
"",
".net",
"sql",
"dataset",
""
] |
Is there a way I can create my own Linq Clauses? I have been looking into extension methods and it's not quite what I am looking for.
I was thinking something like the where, the select or the from clause. I want to use my code like such
```
var blah = from bleep in bloops
where bleep == razzie
myclause bleep.property
select bleep;
``` | You cannot change the way the compiler interprets query statements. These are referred to as query comprehensions - and the rules for translating these are built directly into the C# compiler. Every query is translated into an appropriate sequence of calls to into the extensions methods within the Linq library.
If you use tools like Reflector, you will see the corresponding sequence of extension method calls that such expressions are translated into.
The rules for query comprehensions are fully documented in the [C# 3.0 specification](http://msdn.microsoft.com/en-us/library/ms364047(VS.80).aspx).
While I agree that there are some specific cases where it might be useful to extend the query syntax in the language, I suspect that it requires a significant amount of sophisticated compile-time processing to convert them into appropriate function call syntax. I don't think that in most cases it would be easy to just inject processing for special cases without affecting how the entire expression is transformed.
In the meantime, realize that you can use chaining and regular extensions methods to expand on the capabilities of Linq. | To do that, you need access to the C# compiler source code. I would stick with the Extension methods. If you have a copy of [Reflector](http://www.red-gate.com/products/reflector/), you can peer into System.Data.Linq, and see how the original extension methods were written. | How do I make my own Linq Clauses? | [
"",
"c#",
".net",
"linq",
".net-3.5",
""
] |
```
List<int> a = new List<int>{ 1,1,2,2,3,4,5 };
```
What's the quickest way to do this with LINQ?
I'm new to LINQ | The key here is using [`Enumerable.GroupBy`](http://msdn.microsoft.com/en-us/library/bb534501.aspx) and the aggregation method [`Enumerable.Count`](http://msdn.microsoft.com/en-us/library/bb535181.aspx):
```
List<int> list = new List<int>() { 1,1,2,2,3,4,5 };
// group by value and count frequency
var query = from i in list
group i by i into g
select new {g.Key, Count = g.Count()};
// compute the maximum frequency
int whatsTheFrequencyKenneth = query.Max(g => g.Count);
// find the values with that frequency
IEnumerable<int> modes = query
.Where(g => g.Count == whatsTheFrequencyKenneth)
.Select(g => g.Key);
// dump to console
foreach(var mode in modes) {
Console.WriteLine(mode);
}
``` | Jason's answer is correct, but you can perform this operation in one LINQ operation.
```
List<int> list = new List<int>() { 1, 1, 2, 2, 3, 4, 5 };
// return most frequently occurring items
var query = from i in list
group i by i into g
let maxFreq = (from i2 in list
group i2 by i2 into g2
orderby g2.Count() descending
select g2.Count()).First()
let gCount = g.Count()
where gCount == maxFreq
select g.Key;
// dump to console
foreach (var mode in query)
{
Console.WriteLine(mode);
}
``` | Find the most frequent numbers in an array using LINQ | [
"",
"c#",
"linq",
""
] |
I came across the following code snippet and needed to predict the output. My answer was 220 but was told its wrong. Could someone tell me the correct output and please explain why.
```
using System;
class pointer
{
public static void Main()
{
int ptr1=0;
int* ptr2=&ptr1;
*ptr2=220;
Console.WriteLine(ptr1);
}
}
```
EDIT:
Thank you everybody for the explanatory answers. The correct answer is definitely 220 if and only if the above block of code (which is C# code, Sorry for not mentioning it in the question) was declared as unmanaged. Thank you for all your answers. Every one of em was really informative and helpful. | The answer is that it does not compile. You will get the following error:
*error CS0214: Pointers and fixed size buffers may only be used in an unsafe contex*
If, however, you write this:
```
int ptr1 = 0;
unsafe {
int* ptr2 = &ptr1;
*ptr2 = 220;
}
Console.WriteLine(ptr1);
```
Then you will indeed get 220.
You can also create an entire unsafe method, rather than creating specific unsafe blocks:
```
public unsafe void Something() {
/* pointer manipulation */
}
```
**Note**: you also have to compile with the /unsafe switch (check "Allow unsafe code" in the project properties in Visual Studio)
**Edit**: Have a look at [Pointer fun with binky](http://www.youtube.com/watch?v=UvoHwFvAvQE) for a short, funny, yet informative video on pointers. | The result is 220, below is a C# code snippet to test it (don't have C++ here)
```
using System;
internal class Pointer {
public unsafe void Main() {
int ptr1 = 0;
int* ptr2 = &ptr1;
*ptr2 = 220;
Console.WriteLine(ptr1);
}
}
```
The steps:
* PTR1 is assigned value 0
* PTR2 is pointing to the address space of PTR1
* PTR2 is assigned value 220 (but is pointing to the address space of PTR1)
* So when PTR1 is now requested the value is also 220.
Ask your teacher to get me an A as well ;) | Unsafe C# code snippet with pointers | [
"",
"c#",
"pointers",
""
] |
I've got a group of data that looks like this:
```
001 001 One
001 002 Two
001 003 Three
002 001 One
002 002 Two
002 003 Three
...
```
Now, certainly, I could create an array of string[x][y] = z, but this array has to be resizable, and i'd prefer to use the string representations of the indexers than convert to numeric. The reason is that i will need to look up the data by string, and i don't see the point in needless string->number conversions.
My first thought was this:
```
Dictionary<string, Dictionary<string, string>> data;
data = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> subdata = Dictionary<string, string>();
subdata.Add(key, string);
data.add(key2, subdata);
```
and this works, but is somewhat cumbersome. It also feels wrong and kludgy and not particularly efficient.
So what's the best way to store this sort of data in a collection?
I also thought of creating my own collection class, but I'd rather not if I don't have to. I'd rather just use the existing tools. | This is pretty common request, and most people end up writing some variation of a Tuple class. If you're using ASP.Net, you can utilize the `Triple` class that's already available, otherwise, write something like:
```
public class Tuple<T, T2, T3>
{
public Tuple(T first, T2 second, T3 third)
{
First = first;
Second = second;
Third = third;
}
public T First { get; set; }
public T2 Second { get; set; }
public T3 Third { get; set; }
}
```
There's a generic three-tuple class, so you can create a new `List<Tuple<string, string, string>>()` and create your tuples and add them. Expand on that basic class with some indexing functionality and you're up up and away.
Edit: A list with a dictionary doesn't seem like the correct approach, because each dictionary is only holding one value. There is no multi-entry relationship between the key and values - there is simply one multi-part key and one associated value. The data is equivalent to a database row (or tuple!).
Edit2: Here's an indexable list class you could use for convenience.
```
public class MyTupleList : List<Tuple<string, string, string>>
{
public Tuple<string, string, string> this[string first, string second]
{
get
{
return (this.Find(x => x.First == first && x.Second == second));
}
set
{
this[first, second] = value;
}
}
}
``` | I think this really depends on what you are modelling here. If you're planning to use an object-oriented approach, you shouldn't be thinking of these as arbitrary items inside a data structure.
I'm guessing from looking at this that the first two columns are serving as a "key" for the other items. Define a simple struct, and create a dictionary of like so:
```
struct Key {
public int Val1 { get; set; }
public int Val2 { get; set; }
}
....
Dictionary<Key, string> values;
```
Obviously Key and the items inside it should be mapped to something closer to what you are representing. | What is the collection equivalent of a multi-dimensional array? | [
"",
"c#",
"collections",
""
] |
I'm trying to run a stored procedure from my website that disables a trigger. Here is the code for the trigger:
```
CREATE PROCEDURE [dbo].[DisableMyTrigger]
AS
BEGIN
alter table dbo.TableName DISABLE TRIGGER TriggerName
END
```
I've also set the permissions on the stored procedure with:
```
Grant Exec on dbo.DisableMyTrigger To DBAccountName
```
DBAccountName is and has been able to run other stored procedures as well as dynamic SQL statements without issue.
Here is the code from my CFM page:
```
<cfstoredproc datasource="myDatasource" procedure="DisableMyTrigger" />
```
And here is the error I'm getting:
```
[Macromedia][SequeLink JDBC Driver][ODBC Socket][Microsoft][SQL Native Client][SQL Server]Cannot find the object "TableName" because it does not exist or you do not have permissions.
``` | Does DBAccountName have permissions to TableName? These can be granted or revoked separately from the overall schema (dbo).
I'm not a dba, but is DBAccountName allowed to execute DDL statements? (so it can do things like disable triggers programmatically) | Its because your connected to the wrong db Catalog (assuming SQL Server). Your connected to the database but your connected to the "default" catalog, which is probably "master"
I think you can put something in the beginning of your procedure like :
**use DBName;**
and that will connect you to the proper catalog. | What Access Rights am I Missing on my Stored Procedure | [
"",
"sql",
"sql-server-2005",
"stored-procedures",
"coldfusion",
""
] |
Here's some C# source code which implements an unmanaged DLL (advapi32).
```
public void AddPrivileges(string account, string privilege)
{
IntPtr pSid = GetSIDInformation(account);
LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
privileges[0] = InitLsaString(privilege);
uint ret = Win32Sec.LsaAddAccountRights(lsaHandle, pSid, privileges, 1);
if (ret == 0)
return;
if (ret == STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
{
throw new OutOfMemoryException();
}
int error = Win32Sec.LsaNtStatusToWinError((int)ret);
throw new Win32Exception(error);
}
```
The variable values at runtime are as follows:
```
privilege: "SeServiceLogonRight"
account: "named"
ret: 3221225485 (STATUS_INVALID_PARAMETER)
error: 87
```
When caught, the message within the Win32Exception is: "The parameter is incorrect"
The code is running on Windows Web Server 2008. I can verify that the account does exist, and this code works fine on another server... I'm not sure if this could have been caused by Windows 2008 SP2. I'm thinking that I've forgotten to install something, but I can't think what...
The code is from: <http://weblogs.asp.net/avnerk/archive/2007/05/10/granting-user-rights-in-c.aspx> | I couldn't get this to work, so instead I used the source code from the CodeProject project, [LSA Functions - Privileges and Impersonation](http://www.codeproject.com/KB/cs/lsadotnet.aspx) which works nicely. | Following the provided link through to the code at <http://www.hightechtalks.com/csharp/lsa-functions-276626.html>
```
IntPtr GetSIDInformation(string account)
{
LSA_UNICODE_STRING[] names = new LSA_UNICODE_STRING[1];
LSA_TRANSLATED_SID2 lts;
IntPtr tsids = IntPtr.Zero;
IntPtr tdom = IntPtr.Zero;
names[0] = InitLsaString(account);
lts.Sid = IntPtr.Zero;
Console.WriteLine("String account: {0}", names[0].Length);
int ret = Win32Sec.LsaLookupNames2(lsaHandle, 0, 1, names, ref tdom, ref tsids);
if (ret != 0)
{
throw new Win32Exception(Win32Sec.LsaNtStatusToWinError(ret));
}
lts = (LSA_TRANSLATED_SID2) Marshal.PtrToStructure(tsids,
typeof(LSA_TRANSLATED_SID2));
Win32Sec.LsaFreeMemory(tsids);
Win32Sec.LsaFreeMemory(tdom);
return lts.Sid;
}
```
*lts* (an LSA\_TRANSLATED\_SID2 struct) contains a pointer that points at memory that is freed by the call to *Win32Sec.LsaFreeMemory*. Using the pointer after the memory is freed is bad practice and will have unpredictable results -- it might even "work".
Tweaking the code at the link by using the SecurityIdentifier class (.Net 2 and above) along a little cleanup of unneeded code avoids the memory problem.
```
using System;
namespace Willys.LsaSecurity
{
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using LSA_HANDLE = IntPtr;
[StructLayout(LayoutKind.Sequential)]
struct LSA_OBJECT_ATTRIBUTES
{
internal int Length;
internal IntPtr RootDirectory;
internal IntPtr ObjectName;
internal int Attributes;
internal IntPtr SecurityDescriptor;
internal IntPtr SecurityQualityOfService;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct LSA_UNICODE_STRING
{
internal ushort Length;
internal ushort MaximumLength;
[MarshalAs(UnmanagedType.LPWStr)]
internal string Buffer;
}
sealed class Win32Sec
{
[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
internal static extern uint LsaOpenPolicy(
LSA_UNICODE_STRING[] SystemName,
ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
int AccessMask,
out IntPtr PolicyHandle
);
[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
internal static extern uint LsaAddAccountRights(
LSA_HANDLE PolicyHandle,
IntPtr pSID,
LSA_UNICODE_STRING[] UserRights,
int CountOfRights
);
[DllImport("advapi32")]
internal static extern int LsaNtStatusToWinError(int NTSTATUS);
[DllImport("advapi32")]
internal static extern int LsaClose(IntPtr PolicyHandle);
}
sealed class Sid : IDisposable
{
public IntPtr pSid = IntPtr.Zero;
public SecurityIdentifier sid = null;
public Sid(string account)
{
sid = (SecurityIdentifier) (new NTAccount(account)).Translate(typeof(SecurityIdentifier));
Byte[] buffer = new Byte[sid.BinaryLength];
sid.GetBinaryForm(buffer, 0);
pSid = Marshal.AllocHGlobal(sid.BinaryLength);
Marshal.Copy(buffer, 0, pSid, sid.BinaryLength);
}
public void Dispose()
{
if (pSid != IntPtr.Zero)
{
Marshal.FreeHGlobal(pSid);
pSid = IntPtr.Zero;
}
GC.SuppressFinalize(this);
}
~Sid()
{
Dispose();
}
}
public sealed class LsaWrapper : IDisposable
{
enum Access : int
{
POLICY_READ = 0x20006,
POLICY_ALL_ACCESS = 0x00F0FFF,
POLICY_EXECUTE = 0X20801,
POLICY_WRITE = 0X207F8
}
const uint STATUS_ACCESS_DENIED = 0xc0000022;
const uint STATUS_INSUFFICIENT_RESOURCES = 0xc000009a;
const uint STATUS_NO_MEMORY = 0xc0000017;
IntPtr lsaHandle;
public LsaWrapper()
: this(null)
{ }
// // local system if systemName is null
public LsaWrapper(string systemName)
{
LSA_OBJECT_ATTRIBUTES lsaAttr;
lsaAttr.RootDirectory = IntPtr.Zero;
lsaAttr.ObjectName = IntPtr.Zero;
lsaAttr.Attributes = 0;
lsaAttr.SecurityDescriptor = IntPtr.Zero;
lsaAttr.SecurityQualityOfService = IntPtr.Zero;
lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
lsaHandle = IntPtr.Zero;
LSA_UNICODE_STRING[] system = null;
if (systemName != null)
{
system = new LSA_UNICODE_STRING[1];
system[0] = InitLsaString(systemName);
}
uint ret = Win32Sec.LsaOpenPolicy(system, ref lsaAttr,
(int) Access.POLICY_ALL_ACCESS, out lsaHandle);
if (ret == 0)
return;
if (ret == STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
{
throw new OutOfMemoryException();
}
throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int) ret));
}
public void AddPrivileges(string account, string privilege)
{
uint ret = 0;
using (Sid sid = new Sid(account))
{
LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
privileges[0] = InitLsaString(privilege);
ret = Win32Sec.LsaAddAccountRights(lsaHandle, sid.pSid, privileges, 1);
}
if (ret == 0)
return;
if (ret == STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
{
throw new OutOfMemoryException();
}
throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int) ret));
}
public void Dispose()
{
if (lsaHandle != IntPtr.Zero)
{
Win32Sec.LsaClose(lsaHandle);
lsaHandle = IntPtr.Zero;
}
GC.SuppressFinalize(this);
}
~LsaWrapper()
{
Dispose();
}
// helper functions
static LSA_UNICODE_STRING InitLsaString(string s)
{
// Unicode strings max. 32KB
if (s.Length > 0x7ffe)
throw new ArgumentException("String too long");
LSA_UNICODE_STRING lus = new LSA_UNICODE_STRING();
lus.Buffer = s;
lus.Length = (ushort) (s.Length * sizeof(char));
lus.MaximumLength = (ushort) (lus.Length + sizeof(char));
return lus;
}
}
}
``` | Why might LsaAddAccountRights return STATUS_INVALID_PARAMETER? | [
"",
"c#",
"advapi32",
""
] |
I just started to use django. I came across forms and I need to know which one is the better way to validate a forms. Would it be using django forms or should we use javascript or some client side scripting language to do it? | You should ALWAYS validate your form on the server side, client side validation is but a convenience for the user only.
That being said, Django forms has a variable form.errors which shows if certain form fields were incorrect.
{{ form.name\_of\_field.errors }} can give you each individual error of each field that's incorrectly filled out. See more here:
<http://docs.djangoproject.com/en/dev/topics/forms/> | There's a pluggable Django app ([django-ajax-forms](http://code.google.com/p/django-ajax-forms/)) that helps validate forms on the client side through JavaScript. But as AlbertoPL says, use client side validation only as a usability measure (e.g. telling a user that his desired username is already taken without reloading the registration page). There are all kind of ways to sidestep client side validation, in most cases as simple as deactivating JavaScript.
Generally speaking: presume all data coming from the outside as faulty until validated. | Form validation in django | [
"",
"python",
"django",
"django-forms",
""
] |
I have some negative values coming back from a query. I would like them to just be zero.
How do I write a condition in my sql query that returns zero if the value is below a certain value.
sol:
```
CASE WHEN CONVERT(float,dt.FQI53X02_101) < 1.3 THEN 0 ELSE CONVERT(float,dt.FQI53X02_101) END AS FQI53X02_101
``` | You dont use If-Then-Else in the actual query (you can use them but thats something else)...
What you use is a Case statement... Try this
```
Select
Case When [Value] < 0 Then 0 Else [Value] End
From
Example
``` | If you want it as part of your query, wrap the return inside a CASE statement. Example from MSDN is below
```
SELECT 'Price Category' =
CASE
WHEN price IS NULL THEN 'Not yet priced'
WHEN price < 10 THEN 'Very Reasonable Title'
WHEN price >= 10 and price < 20 THEN 'Coffee Table Title'
ELSE 'Expensive book!'
END,
CAST(title AS varchar(20)) AS 'Shortened Title'
FROM titles
ORDER BY price
``` | How do I create an If-Then-Else in T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I understand the basics of pixel tracking, I'm able to insert a pixel that references an image on my tracking domain to other websites.
However, how do I increment that actual pixel count on my tracking domain? Is there some kind of log that tells me every time that pixel image was served up? Am i able to do something like:
```
<img src="http://www.foo.com/serveImage/getImage.php?id=5123" />
```
then have the getImage page, serve up the image, and increment based on the id that was passed in? or is there a better way to achieve this?
Thank you in advance. | if you want to just output a gif this is a quick simple way, just make sure your script doesn't output anything else before or after:
```
header("Content-type: image/gif");
header("Content-length: 43");
$fp = fopen("php://output","wb");
fwrite($fp,"GIF89a\x01\x00\x01\x00\x80\x00\x00\xFF\xFF",15);
fwrite($fp,"\xFF\x00\x00\x00\x21\xF9\x04\x01\x00\x00\x00\x00",12);
fwrite($fp,"\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02",12);
fwrite($fp,"\x44\x01\x00\x3B",4);
fclose($fp);
``` | this is my track code:
```
<?php
$id = $_GET['site_id'];
// do track
$imageFile = 'images/pixel.jpg';
$im = imagecreatefromjpeg($imageFile);
header('Content-type: image/jpeg');
imagejpeg($im);
?>
``` | How to use Pixel Tracking across domains in PHP | [
"",
"php",
"cross-domain",
"tracking",
"pixel",
"code-metrics",
""
] |
I have a table containing multiple records for different transactions i.e.
```
ID Date REF
1 01/09/2008 A
1 11/09/2008 A
1 01/10/2008 A
2 01/09/2008 A
2 01/10/2008 A
2 01/11/2008 B
2 01/12/2008 B
```
and I'm looking to summarise the data so that I have the average days for each id and ref...
i.e.
```
ID Ref Avg_Days
1 A 15
2 A 30
2 B 30
```
Thanks in advance if anyone can help | Average day difference is a `SUM` of differences divided by `COUNT(*)`
`SUM` of differences is in fact difference between `MIN` and `MAX`:
```
SELECT id, ref, DATEDIFF(day, MIN(date), MAX(date)) / NULLIF(COUNT(*) - 1, 0)
FROM mytable
GROUP BY
id, ref
``` | Something like this... not really sure how this info will help you with anything though.... need more info as to what your trying to average the days for.
```
SELECT ID, REF, AVG(DATEPART(day, [Date]))
FROM dbo.Table1
GROUP BY ID, REF
```
Reference:
[AVG](http://msdn.microsoft.com/en-us/library/ms177677.aspx),
[DATEPART](http://msdn.microsoft.com/en-us/library/ms174420.aspx) | SQL To find difference between multiple rows | [
"",
"sql",
"difference-between-rows",
""
] |
I work for an Architecture firm and I am creating a plug-in for a 3D modeling program to assist design. I have a **Building** class, and a **Floor** class. The building contains a reference to a **FloorList** collection of floors. I'm trying to figure out what to base the **FloorList** collection off of so that I can minimize the amount of work I need to do to create an interface to edit the collection.
The **Floor** collection represents a series of building floors that are stacked on top of one another. Each **Floor** has a **Floor.Height** property that is read write, and an **Floor.Elevation** property that is read only and set by totaling the floor heights below the current **Floor**. So, whenever a **Floor** is added, removed, moved, or changed in the collection the **Floor.Elevation** properties need to be updated.
In addition, I want to create a UI to edit this collection. I was thinking of using a **DataGrid** control where each **Floor** is listed with its **Height** and other properties as a row of the control. The user should be able to add, remove, and re order floors using the control. I'd like setting this up to be as easy and flexible as possible. Meaning I'd like to simply be able to bind the collection of Floors to the **DataGrid** and have the columns of the **DataGrid** populate based on the properties of the **Floor** class. If possible I'd like to be able to utilize the built in Add/Remove UI interface of the DataGrid control with out having to mess with setting up a bunch of event relationships between my collection and the **DataGrid**.
To complicate things further in the future I'll need to be able to allow the user to dynamically add custom properties to the **Floors** that I'll want them to be able to see and edit in the **DataGrid** as well. I think I'd end up doing that by having **Floor** class implement **IExtenderProvider**. So ultimately the **DataGrid** would look something like this:
```
Initial Properties Future Custom User Properties
Height Elevation ProgramType UnitType UnitCount
15' 70' Residential Luxury 5
15' 55' Residential Luxury 5
15' 40' Residential Budget 10
20' 20' Retail N/A 2
20' 0' Retail N/A 3
```
My question now is what should I base my **FloorList** collection off of to allow for this functionality? The options I'm considering are as follows.
**1) Inherit from List(Floor)**
* Methods such as Add/Remove are not vitrual and thus I can't not override them to update the elevations
**2) Implement IList(Floor)**
* OnChange event is not built in so if the lists changes the DataGrid will not update (I think?)
* I think this is probably the best option but what would I need to do the ensure that changes to the **FloorList** collection or **DataGrid** are synced with one another?
**3) Inherit from BindingList(Floor)**
* Method like Add/Remove are not virtual so I can't modify them to update the floor elevations.
**4) Implement IBindingList**
* IBindinglist is not generic and I only want my collection to contain **Floor** objects | You should use BindingList for your collection or implement IBindingList as this will notify back the DataGridView about any changes in the list.
Then implement INotifyPropertyChanged interface for Floor class, this will allow for a TwoWay binding mode between your individual Floor items and the DataGridView.
Eric, you could also do something like this
```
public class MyFloorCollection : BindingList<Floor>
{
public MyFloorCollection()
: base()
{
this.ListChanged += new ListChangedEventHandler(MyFloorCollection_ListChanged);
}
void MyFloorCollection_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
Floor newFloor = this[e.NewIndex] as Floor;
if (newFloor != null)
{
newFloor.HeightChanged += new Floor.HeightChangedEventHandler(newFloor_HeightChanged);
}
}
}
void newFloor_HeightChanged(int newValue, int oldValue)
{
//recaluclate
}
}
```
Of course you can create your own **HeightChangedEvent** and subscribe to that, that way you dont have to go by property names in an if statement.
So your Floor class will look like this
```
public class Floor : INotifyPropertyChanged
{
private int _height;
public int Height
{
get { return _height; }
set
{
if (HeightChanged != null)
HeightChanged(value, _height);
_height = value;
OnPropertyChanged("Height");
}
}
public int Elevation { get; set; }
private void OnPropertyChanged(string property)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(property));
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
public delegate void HeightChangedEventHandler(int newValue, int oldValue);
public event HeightChangedEventHandler HeightChanged;
}
```
this way you only have to subscribe to your HeightChanged variable, instead of to PropertyChanged. PropertyChanged will be consumed by the DataGridView to keep a TwoWay binding. I do believe this way is cleaner.
You can also change the delegate and pass the item as the sender.
```
public delegate void HeightChangedEventHandler(Floor sender, int newValue, int oldValue);
```
EDIT: To unsubscribe from HeightChanged event you need to override RemoveItem
```
protected override void RemoveItem(int index)
{
if (index > -1)
this[index].HeightChanged -= newFloor_HeightChanged;
base.RemoveItem(index);
}
``` | Implement IList(Floor), and have your new collection also implement [INotifyPropertyChanged](http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx) interface. | Creating a custom collection that can be bound to a DataGrid | [
"",
"c#",
"list",
"collections",
"binding",
"bindinglist",
""
] |
i want to build a site similar to www.omegle.com. can any one suggest me some ideas.
I think its built usning twisted , orbiter comet server. | Twisted is a good choice. I used it a few years ago to build a server for a browser-based online game I wrote - it kept track of clients, served them replies to Ajax requests, and used HTML5 Server-Sent DOM Events as well. Worked rather painlessly thanks to Twisted's good HTTP library.
For a Python web framework, I personally favor Django. It's quick to get going with it, and it has a lot of functionality out of the box ("batteries included" as it says on their site I think). Pylons is another popular choice. | You can use [Nevow](http://www.divmod.org/trac/wiki/DivmodNevow), which is a web framework that is built on top of [Twisted](http://twistedmatrix.com/). The documentation for Nevow includes a fully functional [two-way chat application](http://divmod.org/trac/browser/trunk/Nevow/doc/howto/chattutorial/index.xhtml?rev=16627) including examples of how to write [unit tests](http://divmod.org/trac/browser/trunk/Nevow/nevow/test/test_howtolistings.py#L175) for it. | Chat comet site using python and twisted | [
"",
"python",
"twisted",
"orbited",
""
] |
I'm thinking of using Java to write a program that I might try to sell one day. I'm new to Java so I have to ask, what types of tools/software/etc will I need (from development, to distribution, to user-friendly installation on users' machines) that have licenses that must be considered to make sure they allow sales and closed source code, etc.?
Should we assume the user already runs at least one Java app, and therefore has a fairly recent version of Java on their machine?
Also, do you have any recommendations for specific tools that are definitely suitable for this purpose? | It's very rare to see any development tools that restrict the way you can use software created using them. The only exception to that are libraries, and that is not a problem with standard Java libraries. Tools, IDE and so on - regardless of whether they're free or not - will not affect how you can distribute your code.
There are some weird exceptions, like BitKeeper source control software, the license of which prohibits anyone using it from trying to create software that could compete with BitKeeper - which is why I advise to stay as far away from the thing, and the company behind it, as possible. In the end, if you want to be absolutely legally clear, you'll have to hire a lawyer and have him go through licenses and EULAs for all software you're going to use in your development process, because of stuff like this.
Some specific data points: Java itself is okay (both compiler and libraries); both Ant and Maven are okay; and Eclipse and NetBeans are okay. | For development, you will likely need an IDE. The top picks are:
* Eclipse (most features)
* IntelliJ (non-free)
* Netbeans (easiest to learn, imo)
* A few others with much lower popularity
For a free installation program, I've had the best experiences with IzPack, but there are others available. Similarly, to convert to a .exe for easy launching, I recommend Launch4J.
I don't think that its safe to assume that users have Java installed. Many will, but the versions will vary fairly widely, and the few that don't will tend to cause problems. Obviously, this may vary depending upon your intended audience (and how much control you have over them). | Java licensing for commercial distribution | [
"",
"java",
"licensing",
"distribution",
"software-distribution",
""
] |
I have an enum declaration like this:
```
public enum Filter
{
a = 0x0001;
b = 0x0002;
}
```
What does that mean? They are using this to filter an array. | It just means that if you do Filter->a, you get 1. Filter->b is 2.
The weird hex notation is just that, notation.
EDIT:
Since this is a 'filter' the hex notation makes a little more sense.
By writing 0x1, you specify the following bit pattern:
```
0000 0001
```
And 0x2 is:
```
0000 0010
```
This makes it clearer on how to use a filter.
So for example, if you wanted to filter out data that has the lower 2 bits set, you could do:
```
Filter->a | Filter->b
```
which would correspond to:
```
0000 0011
```
The hex notation makes the concept of a filter clearer (for some people). For example, it's relatively easy to figure out the binary of 0x83F0 by looking at it, but much more difficult for 33776 (the same number in base 10). | It means they're the integer values assigned to those names. Enums are basically just named numbers. You can cast between the underlying type of an enum and the enum value.
For example:
```
public enum Colour
{
Red = 1,
Blue = 2,
Green = 3
}
Colour green = (Colour) 3;
int three = (int) Colour.Green;
```
By default an enum's underlying type is `int`, but you can use any of `byte`, `sbyte`, `short`, `ushort`, `int`, `uint`, `long` or `ulong`:
```
public enum BigEnum : long
{
BigValue = 0x5000000000 // Couldn't fit this in an int
}
``` | enum with value 0x0001? | [
"",
"c#",
"enums",
""
] |
Ok, I have this prototype that was written by someone else in C# and I'm trying to put it into Objective-C. Now, I haven't had any formal experience with C# yet, so I don't know everything about it yet. I understand what the first three variables are, but I'm running into problems with what the fourth and fifth lines (c\_data) are doing. Is the fourth declaring a method and then the fifth defining it or what's happening? Thanks for your help!
```
public class c_data {
public double value;
public int label;
public int ID;
public c_data() { }
public c_data(double val) {
value = val;
}
}
``` | The fourth and fifth lines are constructors in C#. They are the equivalent to [[c\_data alloc] init] chains in objective-c. C# allows you to overload constructors based on the parameters they take. This is equivalent to having two different initialization methods in Objective-C:
```
@interface CData : NSObject
{
double value;
int label;
int ID;
}
@property double value;
@property int label;
@property int ID;
-(id) init;
-(id) initWithValue:(double)value;
@end
``` | The 4th line is a parameterless constructor and the 5th line is a parameterfull constructor. | Help with understanding C# code and porting to Objective-C | [
"",
"c#",
"objective-c",
"methods",
"declaration",
"porting",
""
] |
I'm writing a library and I want to put documentation in my functions so that it will show up in intellisense, kind of like how the intellisense for the built in functions shows descriptions for each of the parameters and for the function itself. How do you put the documentation in? Is it through comments in the function or is it in some separate file? | Use XML comments above the function signature.
```
/// <summary>
/// Summary
/// </summary>
/// <param name="param1">Some Parameter.</param>
/// <returns>What this method returns.</returns>
```
The [GhostDoc](http://submain.com/products/ghostdoc.aspx) plugin can help generate these for you. | To auto-generate the three-slash comment section on top of an existing method, just place the cursor on an empty line, right above the method definition and type three forward slashes ("///"). Visual Studio will auto-generate a three-slash comment that corresponds to your method. It will have placeholders for the summary, each parameter (if any) and the return value (if any). You just have to fill-in the blanks.
I would recommend you don't try to write these description blocks by hand and not to copy from one method to another. Third-party tools are also not necessary to generate them (at least in Visual Studio 2010). | Where do you put the function documentation so that it shows up on intellisense? | [
"",
"c#",
".net",
"intellisense",
""
] |
For the last couple of years I've had my head in Python, where there are numerous choices for simple, minimal frameworks that allow me to stand up a website or service easily (eg. web.py). I'm looking for something similar in Java.
What is the simplest, least-moving-parts way of standing up simple services using Java these days? I'm looking for something as simple as:
* the ability to receive HTTP requests
* the ability to dispatch those requests to handlers (preferably a regular expression based url to handler mapping facility)
* the ability to set HTTP headers and generally fully control the request/response
Bonus points if the framework plays well with Jython.
[Update] Thanks for the responses, some of these look quite interesting. I'm not seeing the url dispatch capability in these, however. I'm looking for something similar to Django's url.py system, which looks like:
```
urlpatterns = patterns('',
(r'^articles/2003/$', 'news.views.special_case_2003'),
(r'^articles/(\d{4})/$', 'news.views.year_archive'),
(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)
```
Where you specify a url regular expression along with the handler that handles it. | I liked to worth the [Simple HTTP](http://www.simpleframework.org/) Server from the Simple Framework. It offers [a nice Tutorial](http://www.simpleframework.org/doc/tutorial/tutorial.php) about how to start as well. | there are several alternatives:
* servlets
* [restlet](http://www.restlet.org/): lightweight REST framework
* jax-rs: using [jersey](http://jersey.java.net/) or the restlet module implementing the jax-rs specs
* [grizzly](https://grizzly.dev.java.net/): NIO based server (with HTTP support + handlers)
* [apache mina](http://mina.apache.org/): event-driven, async server (with HTTP support)
all these frameworks come with a built-in server.
EDIT
jax-rs has a similar approach using url templates:
```
@Path("/users/{username}")
public class UserResource {
@GET
@Produces("text/xml")
public String getUser(@PathParam("username") String userName) {
}
}
```
then put your handlers in an Application object:
```
public class MyApplicaton extends Application {
public Set<Class> getClasses() {
Set<Class> s = new HashSet<Class>();
s.add(UserResource.class);
return s;
}
}
```
another example with JAX-RS:
```
@GET
@Produces("application/json")
@Path("/network/{id: [0-9]+}/{nid}")
public User getUserByNID(@PathParam("id") int id, @PathParam("nid") String nid) {
}
```
EDIT 2
Restlet supports a centralized configurations like Django, in your Application object:
```
// Attach the handlers to the root router
router.attach("/users/{user}", account);
router.attach("/users/{user}/orders", orders);
router.attach("/users/{user}/orders/{order}", order);
``` | Simple Java stand-alone server container/framework? | [
"",
"java",
""
] |
I'm new to C# and learning new words. I find it difficult to understand what's the meaning of these two words when it comes to programming c#.
I looked in the dictionary for the meaning and here's what I got:
**Implicit**
> "Something that is implicit is expressed in an indirect way."
>
> "If a quality or element is implicit in something, it is involved in it or is shown by it;"
**Explicit**
> "Something that is explicit is expressed or shown clearly and openly, without any attempt to hide anything"
>
> "If you are explicit about something, you speak about it very openly and clearly."
I would like to understand it in C#.
Thanks for your help.
Cheers
---
additional info:
Here is a part of sentence in the book what I'm reading now which has this word "implicit"
> "This means that Area and Occupants inside `AreaPerPerson( )` **implicitly** refer to the copies of those variables found in the object that invokes `AreaPerPerson( )`"
I quite don't understand what this sentence here trying to say. | The [`implicit`](http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx) and [`explicit`](http://msdn.microsoft.com/en-us/library/xhbhezf4.aspx) keywords in C# are used when declaring conversion operators. Let's say that you have the following class:
```
public class Role
{
public string Name { get; set; }
}
```
If you want to create a new `Role` and assign a `Name` to it, you will typically do it like this:
```
Role role = new Role();
role.Name = "RoleName";
```
Since it has only one property, it would perhaps be convenient if we could instead do it like this:
```
Role role = "RoleName";
```
This means that we want to *implicitly* convert a string to a `Role` (since there is no specific cast involved in the code). To achieve this, we add an implicit conversion operator:
```
public static implicit operator Role(string roleName)
{
return new Role() { Name = roleName };
}
```
Another option is to implement an explicit conversion operator:
```
public static explicit operator Role(string roleName)
{
return new Role() { Name = roleName };
}
```
In this case, we cannot implicitly convert a string to a `Role`, but we need to cast it in our code:
```
Role r = (Role)"RoleName";
``` | In general
* Implicit: something is being done for you automatically.
* Explicit: you've written something in the source code to indicate what you want to happen.
For example:
```
int x = 10;
long y = x; // Implicit conversion from int to long
int z = (int) y; // Explicit conversion from long to int
```
Implicit and explicit are used quite a lot in different contexts, but the general meaning will always be along those lines.
Note that occasionally the two can come together. For instance:
```
int x = 10;
long y = (long) x; // Explicit use of implicit conversion!
```
(An explicit conversion is one which *has* to be stated explicitly; an implicit version is one which *can* be used implicitly, i.e. without the code having to state it.) | explicit and implicit c# | [
"",
"c#",
"dictionary",
"implicit",
"explicit",
""
] |
Say there are two arrays:
```
String[] title = { "One","Two","three","Four"};
String[] user = { "rob","","john",""};
```
I need to filter out the above array when the `user` value is Empty then join or zip the two together. Final Output should be like:
```
{ "One:rob", "three:john" }
```
How can this be done using LINQ? | It sounds like you actually want to "zip" the data together (not join) - i.e. match pairwise; is that correct? If so, simply:
```
var qry = from row in title.Zip(user, (t, u) => new { Title = t, User = u })
where !string.IsNullOrEmpty(row.User)
select row.Title + ":" + row.User;
foreach (string s in qry) Console.WriteLine(s);
```
using the `Zip` operation from [here](http://blogs.msdn.com/ericlippert/archive/2009/05/07/zip-me-up.aspx):
```
// http://blogs.msdn.com/ericlippert/archive/2009/05/07/zip-me-up.aspx
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>
(this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector)
{
if (first == null) throw new ArgumentNullException("first");
if (second == null) throw new ArgumentNullException("second");
if (resultSelector == null) throw new ArgumentNullException("resultSelector");
return ZipIterator(first, second, resultSelector);
}
private static IEnumerable<TResult> ZipIterator<TFirst, TSecond, TResult>
(IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector)
{
using (IEnumerator<TFirst> e1 = first.GetEnumerator())
using (IEnumerator<TSecond> e2 = second.GetEnumerator())
while (e1.MoveNext() && e2.MoveNext())
yield return resultSelector(e1.Current, e2.Current);
}
``` | For a start, you need a `Zip` operator to zip the two arrays together. Here's an abbreviated version of the code from [Eric Lippert's blog](http://blogs.msdn.com/ericlippert/archive/2009/05/07/zip-me-up.aspx) (no error checking in this version, just for brevity):
```
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>
(this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector)
{
using (IEnumerator<TFirst> e1 = first.GetEnumerator())
using (IEnumerator<TSecond> e2 = second.GetEnumerator())
while (e1.MoveNext() && e2.MoveNext())
yield return resultSelector(e1.Current, e2.Current);
}
```
Note that `Zip` will be in the standard libraries for .NET 4.0.
Then you need to just apply a filter and a projection. So we'd get:
```
var results = title.Zip(user, (Title, User) => new { Title, User })
.Where(x => x.Title != "")
.Select(x => x.Title + ":" + x.User);
``` | LINQ "zip" in String Array | [
"",
"c#",
"linq",
""
] |
Currently ive got some reference counted classes using the following:
```
class RefCounted
{
public:
void IncRef()
{
++refCnt;
}
void DecRef()
{
if(!--refCnt)delete this;
}
protected:
RefCounted():refCnt(0){}
private:
unsigned refCnt;
//not implemented
RefCounted(RefCounted&);
RefCounted& operator = (RefCounted&};
};
```
I also have a smart pointer class that handles reference counting , all though its not uniformly used (eg in one or two bits of performance critical code, where I minimised the number of IncRef and DecRef calls).
```
template<class T>class RefCountedPtr
{
public:
RefCountedPtr(T *p)
:p(p)
{
if(p)p->IncRef();
}
~RefCountedPtr()
{
if(p)p->DecRef();
}
RefCountedPtr<T>& operator = (T *newP)
{
if(newP)newP->IncRef();
if(p) p ->DecRef();
p = newP;
return *this;
}
RefCountedPtr<T>& operator = (RefCountedPtr<T> &newP)
{
if(newP.p)newP.p->IncRef();
if(p) p ->DecRef();
p = newP.p;
return *this;
}
T& operator *()
{
return *p;
}
T* operator ->()
{
return p;
}
//comparison operators etc and some const versions of the above...
private:
T *p;
};
```
For the general use of the classes themselves I plan to use a reader/writer locking system, however I dont really want to have to get a writer lock for every single IncRef and DecRef call.
I also just thought of a scenario where the pointer may be invalidated just before the IncRef call, consider:
```
class Texture : public RefCounted
{
public:
//...various operations...
private:
Texture(const std::string &file)
{
//...load texture from file...
TexPool.insert(this);
}
virtual ~Texture()
{
TexPool.erase(this);
}
freind CreateTextureFromFile;
};
Texture *CreateTexture(const std::string &file)
{
TexPoolIterator i = TexPool.find(file);
if(i != TexPool.end())return *i;
else return new Texture(file);
}
```
```
ThreadA ThreadB
t = CreateTexture("ball.png");
t->IncRef();
...use t... t2 = CreateTexture("ball.png");//returns *t
... thread suspended...
t->DecRef();//deletes t ...
... t2->IncRef();//ERROR
```
So I guess I need to change the ref counting model entirely, the reason I added a ref after the return in the design was to support things like the following:
```
MyObj->GetSomething()->GetSomethingElse()->DoSomething();
```
rather than having to:
```
SomeObject a = MyObj->GetSomething();
AnotherObject *b = a->GetSomethingElse();
b->DoSomething();
b->DecRef();
a->DecRef();
```
Is there a clean way for fast reference counting in c++ in a multi threaded environment? | Make the reference counting atomic and you won't need any lock. In Windows ::InterlockedIncrement and ::InterlockedDecrement can be used. In C++ 0x, you have atomic<>. | Unless you know it's a specific bottleneck I'd just use [`boost::shared_ptr`](http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/shared_ptr.htm)
It is very fast however there is a bit of extra overhead in the extra control block being allocated. On the other hand it has many benefits:
* It is portable
* It is correct
* You don't have to waste your mental cycles on it leaving you time to actually get stuff done
* It is fast
* It is industry standard and other programmers will immediately understand it.
* It forces you to use `boost` which if you aren't you should be
Also note, you probably won't want a reader\writer lock for a ref counted object. The contention is minimal and the extra overhead will completely overwhelm any benefits you would have. The shared pointer is implemented with a chip level atomic int operation, this is significantly better than a normal mutex which is significantly faster than a reader\writer lock. | C++: Multi threading and reference counting | [
"",
"c++",
"multithreading",
"reference-counting",
""
] |
Whats is the difference between:
List<MyType> myList;
and
myList : List<MyType>
Its obvious that the first one is list and second one is a class. But my question is what's the advantage of second over first one. | The latter gives you the ability to have a function which takes a myList, instead of just a List. This also means that if the type of myList changes (perhaps to a sorted list) you don't have to change your code anywhere. So instead of declaring `List<myType>` everwhere, and then having to change them, if you had `MyList` objects everywhere, you're golden.
Its also a syntactic difference. Does myList *have* a list, or *is it* a list?
I would lean towards having a `MyList : List<MyType>` if it is used commonly throughout your program. | **List<MyType> myList** is an instance of the generic type List that can contain items that are of MyType (or of any types derived from MyType)
```
var myTypeInstance = new MyType();
var myList = new List<MyType>;
myList.Add(myTypeInstance);
```
**myList : List<MyType>** is a new type that inherits from List from which you can then make multiple instances:
```
var myTypeInstance = new MyType();
var myCollectionVariable = new myList();
myCollectionVariable.Add(myTypeInstance);
```
The main advantage of the latter over the former is if you wanted to have some methods that act on a List you can put them on your class, rather than storing them in a "helper" or "utility" library, for example:
```
class myList : List<MyType>
{
public void DoSomethingToAllMyTypesInList()
{
...
...
}
}
``` | Why Create a Class Derived from a Generic List (.NET)? | [
"",
"c#",
".net",
"generics",
""
] |
1.
I know that it is possible to initialise an array of structures in the declaration. For example:
```
struct BusStruct
{
string registration_number;
string route;
};
struct BusStruct BusDepot[] =
{
{ "ED3280", "70" },
{ "ED3536", "73" },
{ "FP6583", "74A" },
};
```
If the structure is changed into a class, like this:
```
class BusClass
{
protected:
string m_registration_number;
string m_route;
public:
// maybe some public functions to help initialisation
};
```
Is it possible to do the same as for the structure (i.e. declare and initialise an array of classes at the same time)?
2.
Am I correct to think that it is not possible to declare and initialise `vector<BusStruct>` or `vector<BusClass>` at the same time? | > Is it possible to do the same as for the structure (i.e. declare and initialise an array of classes at the same time)?
Not unless you create a suitable constructor:
```
class BusClass
{
protected:
string m_registration_number;
string m_route;
public:
// maybe some public functions to help initialisation
// Indeed:
BusClass(string const& registration_number,
string const& route)
:m_registration_number(registration_number),
m_route(route) { }
};
```
Or you make all members public and omit the constructor, in which case you can use the same initialization syntax as for the struct. But i think that's not what you intended.
> Am I correct to think that it is not possible to declare and initialise `vector<BusStruct>` or `vector<BusClass>` at the same time?
No it's not possible with current C++. You can however use libraries that make this possible. I recommend [*Boost.Assign*](http://www.boost.org/doc/libs/1_39_0/libs/assign/doc/index.html) for that. For that, however, your class has to have a constructor, and likewise your struct too - Or you need to create some kind of factory function
```
BusStruct make_bus(string const& registration_number,
string const& route) { ... }
```
If you want to keep the struct initializable with the brace enclosed initializer list in other cases. | 1. No, you would not be able to initialize classes the way you can with structures. But you can write the class constructor inside the array declaration.
2. C++ has no built in way of initializing vectors, unless you want to load the vector from an array that you have initialized. | Declare and initialise an array of struct/class at the same time | [
"",
"c++",
"class",
"struct",
"initialization",
""
] |
Are there any benefits to using the 'window' prefix when calling javascript variables or methods in the window object? For example, would calling 'window.alert' have an advantage over simply calling 'alert'?
I can imagine using the prefix could give a small performance boost when the call is made from inside some function/object, however I rarely see this in people's code. Henceforth this question. | I doubt there is any measurable performance benefit. After all the scope chain would be scanned for the identifier `window` first then the window object would be scanned for the desired item. Hence more likely it would be deterimental to performance.
Using window prefix is useful if you have another variable in scope that would hide the item you may want to retrieve from the window. The question is can you always know when this might be? The answer is no. So should you always prefix with window? What would you code look like if you did that. Ugly. Hence don't do it unless you know you need to. | This is useful when attempting to test global object values. For example, if `GlobalObject` is not defined then this throws an error:
```
if(GlobalObject) { // <- error on this line if not defined
var obj = new GlobalObject();
}
```
but this does not throw an error:
```
if(window.GlobalObject) { // Yay! No error!
var obj = new GlobalObject();
}
```
Similarly with:
```
if(globalValue == 'something') // <- error on this line if not defined
if(window.globalValue == 'something') // Hurrah!
```
and:
```
if(globalObj instanceof SomeObject) // <- error on this line if not defined
if(window.globalObj instanceof SomeObject) // Yippee! window.prop FTW!
```
I would not expect to see a significant performance difference, and the only other reason you might do this is to ensure that you are actually getting a value from the global scope (in case the value has been redefined in the current scope). | Benefit of using 'window' prefix in javascript | [
"",
"javascript",
"window",
"namespaces",
""
] |
In Python I have a list of strings, some of which may be the empty string. What's the best way to get the first non-empty string? | ```
next(s for s in list_of_string if s)
```
Thanks to [Stephan202](https://stackoverflow.com/users/74939/stephan202) for this Python 3 version. | To remove all empty strings,
`[s for s in list_of_strings if s]`
To get the first non-empty string, simply create this list and get the first element, or use the lazy method as suggested by wuub. | Get first non-empty string from a list in python | [
"",
"python",
"string",
"list",
""
] |
Here is some code outlining a problem I've been wrestling with. The final problem (as far as g++ is concerned at the moment) is that: "error: 'Foo-T' was not declared in this scope" when performing the Bar::Bar(...) constructor routine. Otherwise, the problem I'm attempting to learn my way through is one of setting base-class member types based on arguments passed to a derived-class constructor using templates. If there were a way to set the base-class member type (T Foo-T) simply by passing arguments to the derived-class constructor, I would prefer that. As of now I can't see a way past using both the template argument and a matching derived-class constructor argument to accomplish this task. Can you spot anything in the following code that I can be doing better to achieve the same goals? I'm rather new to generic-coding and templates.
```
#include <iostream>
typedef int a_arg_t;
typedef double b_arg_t;
typedef std::string foo_arg_t;
class TypeA {
public:
TypeA ();
TypeA (a_arg_t a) {
/* Do sosmething with the parameter passed in */
}
};
class TypeB {
public:
TypeB ();
TypeB (b_arg_t b) {
/* typeB's constructor - do something here */
}
};
// The base-class with a member-type to be determined by the template argument
template <class T>
class Foo {
public:
Foo (const foo_arg_t foo_arg) : _foo_arg(foo_arg) // initialize something here
{
/* do something for foo */
}
T Foo_T; // either a TypeA or a TypeB - TBD
foo_arg_t _foo_arg;
};
// the derived class that should set the basse-member type (T Foo_T)
template <class T>
class Bar : public Foo<T> {
public:
Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
: Foo<T>(bar_arg) // base-class initializer
{
// the initialization of Foo_T has to be done outside the initializer list because it's not in scsope until here
Foo_T = TypeA(a_arg); // if an a_arg_t is passed in, then we set the Foo_T to TypeA, etc.
}
Bar (const foo_arg_t bar_arg, const b_arg_t b_arg)
: Foo<T>(bar_arg)
{
Foo_T = TypeB(b_arg);
}
};
int main () {
b_arg_t b_arg;
a_arg_t a_arg;
foo_arg_t bar_arg;
Bar<TypeA> a (bar_arg, a_arg); // try creating the derived class using TypeA
Bar<TypeB> b (bar_arg, b_arg); // and another type for show
return 0;
}
``` | The Foo\_T type will not be looked up in the base class when used in the derived (Bar) constructor.
```
Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
: Foo<T>(bar_arg) // base-class initializer
{
Foo_T = TypeA(a_arg); TypeA, etc. // Won't compile, per the standard
}
```
This is per the C++ standard, which says unqualified names are generally non-dependent, and should be looked up when the template is fully defined.
Since a template base class definition is not known at that time (there could be fully specialised instances of the template being pulled in later in the compilation unit), unqualified names are never resolved to names in dependent base classes.
If you need a name from a base class when templates are involved, you have to either fully qualify them, or make them implicitly dependent in your derived class.
```
Foo< T >::Foo_T = TypeA(a_arg); // fully qualified will compile
```
or, make it dependent
```
this->Foo_T = TypeA(a_arg);
```
Since the `this` makes it template dependent, resolving the type is postponed till "phase 2" of template instantiation (and then, the base class is also fully known)
Note that if you wanted to use a function from the base class, you could have also added a using declaration..
(inside Bar())
```
some_foo_func(); // wouldn't work either
using Foo<T>::some_foo_func;
some_foo_func(); // would work however
``` | Sorry to be unhelpful, but I also do not see a way around this without doing exactly what you stated:
> As of now I can't see a way past using
> both the template argument and a
> matching derived-class constructor
> argument to accomplish this task.
You will likely have to specialize a bit:
```
template<>
Bar<TypeA>::Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
: Foo<TypeA>(bar_arg) // base-class initializer
{
// the initialization of Foo_T has to be done outside the initializer list because it's not in scsope until here
Foo_T = TypeA(a_arg); // if an a_arg_t is passed in, then we set the Foo_T to TypeA, etc.
}
template< class T>
Bar<T>::Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
: Foo<T>(bar_arg) // base-class initializer
{
// Throw exception?
}
template<>
Bar<TypeB>::Bar (const foo_arg_t bar_arg, const b_arg_t b_arg)
: Foo<TypeB>(bar_arg)
{
Foo_T = TypeB(b_arg);
}
template< class T >
Bar<T>::Bar (const foo_arg_t bar_arg, const b_arg_t b_arg)
: Foo<T>(bar_arg)
{
// Throw exception ?
}
```
Unfortunately, I do not have access to a compiler at the moment to check this code so be wary.
---
In answer to your question/comment. I got the following to compile:
```
#include <iostream>
typedef int a_arg_t;
typedef double b_arg_t;
typedef std::string foo_arg_t;
class TypeA {
public:
TypeA () {}
TypeA (a_arg_t a) {}
};
class TypeB {
public:
TypeB () {}
TypeB (b_arg_t b) {}
};
template <class T>
class Foo {
public:
Foo (const foo_arg_t foo_arg) : _foo_arg(foo_arg) {}
T Foo_T; // either a TypeA or a TypeB - TBD
foo_arg_t _foo_arg;
};
// the derived class that should set the basse-member type (T Foo_T)
template <class T>
class Bar : public Foo<T> {
public:
Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
: Foo<T>(bar_arg) // base-class initializer
{
Foo<T>::Foo_T = TypeA(a_arg);
}
Bar (const foo_arg_t bar_arg, const b_arg_t b_arg)
: Foo<T>(bar_arg)
{
Foo<T>::Foo_T = TypeB(b_arg);
}
};
int main () {
b_arg_t b_arg;
a_arg_t a_arg;
foo_arg_t bar_arg;
Bar<TypeA> a (bar_arg, a_arg); // try creating the derived class using TypeA
Bar<TypeB> b (bar_arg, b_arg); // and another type for show
return 0;
}
``` | Initializing template base-class member types in derived-class initializer lists | [
"",
"c++",
"inheritance",
"templates",
"initialization",
""
] |
I have 3 textboxes, and on the `keyup` event for all 3, I want to call the same function?
In the below code, I am tring to bind `keyup` event to `CalculateTotalOnKeyUpEvent` function to a textbox named `compensation`, but it doesn't work:
```
$("#compensation").bind("keyup", CalculateTotalOnKeyUpEvent(keyupEvent));
function CalculateTotalOnKeyUpEvent(keyupEvent) {
var keyCode = keyupEvent.keyCode;
if (KeyStrokeAllowdToCalculateRefund(keyCode)) {
CalculateTotalRefund();
}
};
``` | You need do like this:
```
// Edit according to request in the comment:
// in order to select more than one element,
// you need to specify comma separated ids.
// Also, maybe you need to consider to use a CSS class for the selected elements,
// then it could be just $(".className")
$("#element1, #element2, ....").bind("keyup", CalculateTotalOnKeyUpEvent);
```
You need to pass the function as a parameter, you do not need to pass the function as it was declared. | ```
$("#txt1, #txt2, #txt3").keyup(fn);
``` | JQuery, bind same function to 3 different textboxs' keyup event | [
"",
"javascript",
"jquery",
"events",
"bind",
""
] |
I see this parameter in all kinds of places (forums, etc.) and the common answer it help highly concurrent servers. Still, I cannot find an official documentation from sun explaining what it does. Also, was it added in Java 6 or did it exist in Java 5?
(BTW, a good place for many hotspot VM parameters is [this page](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp))
**Update:** Java 5 does not boot with this parameter. | In order to optimise performance, the JVM uses a "pseudo memory barrier" in code to act as a fencing instruction when synchronizing across multiple processors. It is possible to revert back to a "true" memory barrier instruction, but this can have a noticeable (and bad) effect upon performance.
The use of `-XX:+UseMembar` causes the VM to revert back to true memory barrier instructions. This parameter was originally intended to exist temporarily as a verification mechanism of the new pseudo-barrier logic, but it turned out that the new pseudo-memory barrier code introduced some synchronization issues. I believe these are now fixed, but until they were, the acceptable way to get around these issues was to use the reinstated flag.
The bug was introduced in 1.5, and I believe the flag exists in 1.5 and 1.6.
I've google-fu'ed this from a variety of mailing lists and JVM bugs:
* <https://bugs.java.com/bugdatabase/view_bug?bug_id=6546278>
* [The obligatory Wikipedia link to memory barriers (fencing instructions)](http://en.wikipedia.org/wiki/Memory_barrier)
* [A classic post from Raymond Chen](http://blogs.msdn.com/oldnewthing/archive/2004/05/28/143769.aspx)
* [SO question on fencing](https://stackoverflow.com/questions/286629/what-is-a-memory-fence) | butterchicken only explains half of the story, I would like to augment more detail to kmatveev's answer. Yes, the option is for thread state changes, and (pseudo) memory barriers are used to ensure that the change is visible from other threads, especially VM thread. Thread states used in OpenJDK6 are as follows:
```
// _thread_new : Just started, but not executed init. code yet (most likely still in OS init code)
// _thread_in_native : In native code. This is a safepoint region, since all oops will be in jobject handles
// _thread_in_vm : Executing in the vm
// _thread_in_Java : Executing either interpreted or compiled Java code (or could be in a stub)
...
_thread_blocked = 10, // blocked in vm
```
Without UseMembar option, in Linux, Hotspot uses memory serialize page instead of memory barrier instruction. Whenever a thread state transition happens, the thread writes to a memory address in memory serialize page with volatile pointer. When the VM thread needs to look at up-to-date state of all the threads, VM changes the protection bits for the memory serialize page to read only and then recovers it to read/write to serialize state changes. More detailed mechanism is introduced in the following page:
<http://home.comcast.net/~pjbishop/Dave/Asymmetric-Dekker-Synchronization.txt> | What is Java's -XX:+UseMembar parameter | [
"",
"java",
"concurrency",
"jvm",
"jvm-arguments",
""
] |
I am wondering if it is viable to store cached items in Session variables, rather than creating a file-based caching solution? Because it is once per user, it could reduce some extra calls to the database if a user visits more than one page. But is it worth the effort? | If the data you are caching *(willing to cache)* does not depend on the user, why would you store in the session... which is attached to a user ?
Considering sessions are generally stored in files, it will not optimise anything in comparaison of using files yourself.
And if you have 10 users on the site, you will have 10 times the same data in cache ? I do not think this is the best way to cache things ;-)
For data that is the same fo all users, I would really go with another solution, be it file-based or not (even for data specific to one user, or a group of users, I would probably not store it in session -- except if very small, maybe)
Some things you can look about :
* Almost every framework provides some kind of caching mecanism. For instance :
+ [`PEAR::Cache_Lite`](http://pear.php.net/package/Cache_Lite/)
+ [`Zend_Cache`](http://framework.zend.com/manual/en/zend.cache.html)
* You can store cached data using lots of backend ; for instance :
+ files
+ shared memory (using something like [`APC`](http://www.php.net/apc), for example)
+ If you have several servers and loads of data, [`memcached`](http://www.danga.com/memcached/)
+ (some frameworks provide classes to work with those ; switching from one to the other can even be as simple as changing a couple of lines in a config file ^^ )
Next question is : what do you need to cache ? For how long ? but that's another problem, and only you can answer that ;-) | It can be, but it depends largely on what you're trying to cache, as well as some other circumstances.
* Is the information likely to change?
* Is it a problem if slightly outdated information is shown?
* How heavy is the load the query imposes on the database?
* What is the latency to the database server? (shouldn't be an issue on local network)
* Should the information be cached on a per user basis, or globally for the entire application?
* Amount of data involved
* etc.
Performance gain can be significant in some cases. On a particular ASP.NET / SQL Server site I've worked on, adding a simple caching mechanism (at application level) reduced the CPU load on the web server by a factor 3 (!) and at the same time prevented a whole bunch of database timeout issues when accessing a certain table.
It's been a while since I've done anything serious in PHP, but I think your only option there is to do this at the session level. Most of my considerations above are still valid however. As for effort; it should take very little effort to implement, assuming your code is sufficiently structured. | Is a Session-Based Cache Solution Viable? | [
"",
"php",
"session",
"caching",
""
] |
My colleague and I have been having a discussion about what Collections should be called.
For example:
Class Product - Collection - Class Products
or
Class Product - Collection - Class ProductCollection
I've had a look around to see if I can see any guidelines or reasons for using one or the other but nothing seems to spring out. The framework seems to use both variants for example. The argument I can see is that a class that has a collection of products variable should be called Products but it should be of type ProductCollection.
Which is correct if any?
In the same vane is there a standard for the naming of return variable for a function. e.g. retVal?
We mainly code in C#, although I'm not sure that affects my question. | I would say that with generics there should rarely ever be a reason to create a custom collection type. But if you must I would say that `ProductCollection` would best fit the naming conventions of the framework.
Still, consider using a `List<Product>` or `Collection<Product>` or better yet `IList<Product>` or `ICollection<Product>`.
**Edit:** *This is in response to MrEdmundo's comments below.*
In your case you have two choices. The most obvious choice would be to use inheritance like this:
```
class Ball { }
class BallCollection : List<Ball>
{
public String Color { get; set; }
public String Material { get; set; }
}
```
I say obvious because it *seems* like the best idea at first glance but after a bit of thought it becomes clear that this is not the best choice. What if you or Microsoft creates a new `SuperAwesomeList<T>` and you want to use that to improve the performance of your `BallCollection` class? It would be difficult because you are tied to the `List<T>` class through inheritance and changing the base class would potentially break any code that uses `BallCollection` as a `List<T>`.
So what is the better solution? I would recommend that in this case you would be better off to favor *composition* over inheritance. So what would a composition-based solution look like?
```
class Ball { }
class BallCollection
{
public String Color { get; set; }
public String Material { get; set; }
public IList<Ball> Balls { get; set; }
}
```
Notice that I have declared the `Balls` property to be of type `IList<T>`. This means that you are free to implement the property using whatever type you wish as long as that type implements `IList<T>`. This means that you can freely use a `SuperAwesomeList<T>` at any point which makes this type significantly more scalable and much less painful to maintain. | **Products** is certainly not correct IMHO. A non-static class name should represent a noun (not plural), because you should be able to say "*x is a [classname]*".
Obviously, **Products** doesn't fit in that scheme. **ProductCollection** does:
Illustration:
```
var products = new Products(); // products is a Products
var products = new ProductCollection(); // products is a ProductCollection
```
Which one "sounds right" ?
Another thing about naming collection classes: I usually try to name collection classes in such way that it is clear what kind of collection it is.
For example:
* class **ProductCollection**: can only be enumerated and the Count retrieved (i.e. only implements ICollection interface(s))
* class **ProductList**: a list that can be manipulated using Add(), Insert(), etc. (i.e. implements IList interface(s))
* class **ProductDictionary**: a dictionary of products accessible by some key (i.e. implements IDictionary interface(s))
The last one can be ambiguous if there could be a doubt what the key of the dictionary is, so it's better to specify what the key type is (like ProductDictionaryByString). But to be honest, I rarely name it this way because most of the time the key will be a string anyway. | .NET Collection Naming Convention | [
"",
"c#",
".net",
"naming-conventions",
""
] |
Using JavaScript, how can i open a new window (loading, say, <http://www.google.com> in the process) and inject/insert this code into its body:
```
<script type="text/javascript">alert(document.title);</script>
```
I know how to open a new window, but i don't know how to add the script to the new window and run it:
```
var ww = window.open('http://www.google.com');
``` | **No**. This would violate the [**same origin policy**](http://en.wikipedia.org/wiki/Same_origin_policy) implemented by most (all?) browsers to protect their users.
Imagine if this were possible: You could convince users to come to your site, open a new window with, say, their bank's website loaded into it, and inject code to steal their credentials. Then proceed to steal their money, identity, etc...
Not good, eh? So be very, very glad it isn't possible.
---
### See also: [Same-origin policy for DOM access in the Browser Security Handbook](http://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_DOM_access) | This worked on the firebug console:
```
>>> var x = window.open("");
Window opened
>>> x
Window about:blank
>>> x.document
Document about:blank
>>> x.document.write("<script type='text/javascript'>alert('h1');</script>");
Alert popped up
``` | How can I load a web page into a new window and inject JavaScript code into it? | [
"",
"javascript",
"code-injection",
""
] |
I can't really seem to find any good .NET Micro Framework Tutorials on google. Does anyone know of any? | Have a look here: <http://informatix.miloush.net/microframework/>, this site contains many examples, articles and resources you will find handy when developing for Micro Framework.
On that website there's a feed which aggregates all the feeds from all the blogs targeting .net micro framework, so you can stay in touch with the latest news from this field.
And if you are seriously interested in developing for this platform, you should get the book called Expert .NET Micro Framework. It is an excellent introduction with many examples and how-tos. | Check Scott's Hanselminutes Session at <http://www.hanselman.com/blog/HanselminutesOn9TheNETMicroFrameworkWithColinMiller.aspx> | .NET Micro Framework Tutorials? | [
"",
"c#",
".net",
".net-micro-framework",
""
] |
I'm using PHP5 here. I have made a login system that check's the username and password against the records in the database. I want to use sessions to store the logged value. For example, when I reach the zone where I "log in" the user succesfully:
```
if($errors = 0) {
$_SESSION['logged'] = "1";
}
```
The problem is that I want the `$_SESSION['logged']` to stay active for let's say 5 minutes so when I do a `if($_SESSION['logged'] == "1")` after this time to return false. Also, I would like to delete this session after the user closes the browser. Basically, I want a session configuration so that the user can safely leave his desk and when him or somebody presses refresh after 10 minutes or enters again after the browser has been closed, the session to be already removed, and the access to be restricted.
Can anybody help? Thanks. | Use [`session_set_cookie_params()`](https://www.php.net/manual/en/function.session-set-cookie-params.php) to change the lifetime of the session cookie. Note that by default, it is set to **`0`** which means that the cookie is set until the user exits the browser. You can do this in the following way:
```
/* Set to 0 if you want the session
cookie to be set until the user closes
the browser. Use time() + seconds
otherwise. */
session_set_cookie_params(0);
session_start();
```
Then check for the last activity time, updated each time someone visits a page.
```
if(($_SESSION['lastActivity'] + 300) < time()) {
// timeout, destroy the session.
session_destroy();
unset($_SESSION);
die('Timeout!');
} else {
$_SESSION['lastActivity'] = time();
}
``` | Instead of setting it to one, why don't you set `$_SESSION['logged_time'] = time();` and then check the time against time() in your application?
If you'd like to actually expire the entire session, the exact specifics can change depending on your session handler, but for the default session handler (and any other well behaved session handler) you'll want to check out <https://www.php.net/manual/en/session.configuration.php> | PHP session lifetime problem | [
"",
"php",
"session",
""
] |
I am having some weird issue here. I have a database table which has huge value stored on a column. My application (C#) is reading this value and keeping in a *double* type. This application will insert the same value to another table. Note : I am not doing any calculations/processing on the value read from the first table. It is just kept for updating the second table.
Issue here is, the second table is getting slightly different value than in the first table. Looks like the number is rounding off when I keep in the double type.
Here is an example of values.
Original Value : **18014398509481984**
Value copied to new table : **18014398509482000**
The values looks different, but both are same in reality. I did a google search with ***18014398509481984 - 18014398509482000*** as a search term and it returned result ***0***, which means both are same.
**Questions**:
1 - If both are same, why the second value looks different? I can see ***1984*** turned into ***2000***.
2 - Why the conversion happens?
3 - How can I avoid this type of conversions?
Any help would be great! | Try using a `System.Decimal` to store the value from the first table, instead of a `System.Double`. `System.Double` doesn't seem to contain enough significant digits to store that large of a value accurately. | A double precision value is accurate only to 15 or 16 decimal digits (see [here](http://en.wikipedia.org/wiki/Double_precision_floating-point_format) for an explanation). If you need to store more than this, then you will have to use a different number format. If you want to work with very big integers without losing accuracy, then there are various classes out there to help you like [this one](http://www.codeplex.com/biginteger).
If you're getting a value out of SQL, make sure that your target data type in .NET matches - SQL bigint for C# long for example - to avoid rounding issues like this. | Large numbers rounding off [c#] | [
"",
"c#",
"math",
"double",
"rounding",
""
] |
I have a TextBox and would like to forward a KeyPress-event from another Form.
So far I have my Form:
```
private readonly Action<KeyPressEventArgs> m_KeyPress;
public KeyboardForm( Action<KeyPressEventArgs> keyPress )
{
m_KeyPress = keyPress;
}
protected override void OnKeyPress( KeyPressEventArgs e )
{
m_KeyPress( e );
base.OnKeyPress( e );
}
```
And a derived TextBox, which initializes the Form:
```
var keyboardForm = new KeyboardForm( OnKeyPress );
keyboardForm.Show();
```
Now, the OnKeyPress-method gets called as expected (of the Form, then of the TextBox). But nevertheless nothing happens ... when I press 'a' I expected an 'a' to appear in my TextBox ...
Does anyone have an idea what's the problem here?
It is not working with `KeyDown`, too, and attaching to the regular exposed event `KeyPress` does not help me either. I think, that the problem is the explicit call of `OnKeyPress`. Is it allowed? | Form1:
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Form2 f = new Form2();
f.mEvent += new Form2.TestEvent(f_mEvent);
f.Show();
}
void f_mEvent(KeyPressEventArgs e)
{
textBox1.Text += e.KeyChar;
}
}
```
Form2:
```
public partial class Form2 : Form
{
public delegate void TestEvent(KeyPressEventArgs e);
public event TestEvent mEvent;
public Form2()
{
InitializeComponent();
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (mEvent != null)
{
mEvent(e);
}
base.OnKeyPress(e);
}
}
``` | This should do what you want. Make the text of the buttons on the Keyboard Form based on the [SendKey characters](http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send.aspx). For example, if you want lower case a, just put "a" for the keyboard button text. If you want a backspace button, just put "backspace" as the text of the button. All the keyboard buttons Click events can register for the ButtonClick function
Keyboard Form:
```
public partial class KeyboardForm : Form
{
public delegate void ButtonPressed(string keyPressed);
public event ButtonPressed ButtonPressedEvent;
public KeyboardForm()
{
InitializeComponent();
}
private void ButtonClick(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{
if ((ButtonPressedEvent != null))
{
ButtonPressedEvent("{"+button.Text+"}");
}
}
}
}
```
Form with textbox that the user types things into:
```
public partial class Form1 : Form
{
private KeyboardForm mKeyboardForm = new KeyboardForm();
private bool mIsKeyboardCode = false;
public Form1()
{
InitializeComponent();
mKeyboardForm.ButtonPressedEvent += new KeyboardForm.ButtonPressed(KeyboardFormButtonPressedEvent);
}
void KeyboardFormButtonPressedEvent(string keyPressed)
{
mIsKeyboardCode = true;
textBox1.Focus();
SendKeys.SendWait(keyPressed.ToString());
mKeyboardForm.Focus();
mIsKeyboardCode = false;
}
private void TextBoxKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ControlKey)
{
if (!mKeyboardForm.Visible)
{
mKeyboardForm.Show(this);
e.Handled = true;
}
}
else if (!mIsKeyboardCode)
{
mKeyboardForm.Hide();
}
}
}
```
Note: I did not use an extended textbox with a form inside of it. I dont think its a good design to have a form be shown/hidden from a custom textbox. | Forward a KeyPress-event | [
"",
"c#",
"events",
""
] |
I'm fixing some PHP scripts and I'm missing ruby's pretty printer. i.e.
```
require 'pp'
arr = {:one => 1}
pp arr
```
will output {:one => 1}. This even works with fairly complex objects and makes digging into an unknown script much easier. Is there some way to duplicate this functionality in PHP? | Both [`print_r()`](http://www.php.net/manual/en/function.print-r.php) and [`var_dump()`](http://www.php.net/manual/en/function.var-dump.php) will output visual representations of objects within PHP.
```
$arr = array('one' => 1);
print_r($arr);
var_dump($arr);
``` | This is what I use to print my arrays:
```
<pre>
<?php
print_r($your_array);
?>
</pre>
```
The magic comes with the `pre` tag. | Is there a pretty print for PHP? | [
"",
"php",
"pretty-print",
""
] |
I need to do a Bin deployment on our ISP, Network Solutions. They have NET Framework 3.5 SP1 installed on their servers, but NOT ASP.NET MVC.
I need to point my application to a directory called **cgi-bin** instead of bin. Network Solutions says that this is the only directory they have marked for execution as medium trust. I need to put the System.Web.Mvc DLL and the application DLL there, and I need my ASP.NET MVC application to find them in that directory.
It goes without saying that they won't put them in the GAC for me.
How do I tell my application to look in the cgi-bin directory instead of the bin directory for the DLL's?
---
**Solution is posted below.** | After tinkering for awhile, I finally decided to deploy to an actual bin directory that I created (a procedure that Network Solutions says will not work) following [Phil Haacked's instructions](http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx) exactly, and it appears to be working.
I did have to apply the routing patch described in [ASP.NET MVC: Default page works, but other pages return 404 error](https://stackoverflow.com/questions/1169492/asp-net-mvc-default-page-works-but-other-pages-return-404-error/1169555#1169555), because Network Solutions is still running IIS6.
For those who are interested, you can specify a different bin directory in web.config like this:
```
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="SomeFolder/bin" />
</assemblyBinding>
</runtime>
```
I tried this with Network Solution's cgi-bin directory and my application did indeed find the mvc dll's. | You should be able to set the output directory or your project to cgi-bin if you want. If you right-click your project and click on Properties. From there you should be able to select Build in the left list of options and set the output directory to whatever you want. | How do I deploy an ASP.NET MVC application if the ISP doesn't use a BIN directory? | [
"",
"c#",
"asp.net-mvc",
"dll",
""
] |
Here is my shortened code snippet:
```
$(document).ready(function() {
$.get("/Handlers/SearchData.ashx",
function(data) {
json = $.evalJSON(data);
});
//do some other stuff
//use json data
alert(json == null);
});
```
Alert says true because evalJson is not done processing JSON data yet (21kb gzipped). I need to wait somehow for it to finish before using that data - exactly what I'd do with DoEvents in a while loop. | There is no equivalent to DoEvents, but you can put the code that depends on your JSON data into a function and call it from the AJAX callback. You can also use the $.getJSON method so you don't have to eval the JSON yourself.
```
$(document).ready(function() {
$.getJSON("/Handlers/SearchData.ashx",
function(data) {
json = data;
stuffToDoAfterIHaveData();
});
//do some other stuff
});
//use json data
function stuffToDoAfterIHaveData() {
alert(json == null);
}
```
Alternatively, jQuery offers a way to make AJAX requests synchronous (i.e. they halt code execution until the response comes back). You can use `$.ajaxSetup({ async: false });` or you can call the `$.ajax` method directly and pass `async:false` in the options object. | Instead of executing evalJSON yourself, why not let jQuery figure out when it's done:
```
$.ajax({
url:"/Handlers/SearchData.ashx",
type: "get",
dataType: "json",
success:function(d) {
//d now contains a JSON object, not a string.
alert(d==null);
}
});
``` | Javascript DoEvents equivalent? | [
"",
"asp.net",
"javascript",
"jquery",
""
] |
Is it possible to disable a browser cookie using selenium, RC specifically? If so, what is the api call or sequence of calls to make this happen. There is a feature being tested where theres a need to verify the behavior when cookies are enabled or disabled. Thanks | As specified in the comment. If you are using FF, you could specify the profile to be used.
The way to do it it so specify the browserStartCommand (3rd argument of the `DefaultSelenium` constructor) to something similar to:
```
*custom "C:/Program Files/Mozilla Firefox/firefox.exe" -no-remote -profile "C:/Some/Path/To/Mozilla/Firefox/Profiles/selenium"
```
And this profile you could have the cookies disabled. | There's an easier way with using only a default profile, if on Selenium 2.x.
```
FirefoxProfile profile=new FirefoxProfile();
profile.setPreference("network.cookie.cookieBehavior",2);
``` | Selenium RC - disabling browser cookie | [
"",
"java",
"browser",
"cookies",
"junit",
"selenium",
""
] |
The system I'm running on is Windows XP, with JRE 1.6.
I do this :
```
public static void main(String[] args) {
try {
System.out.println(new File("C:\\test a.xml").toURI().toURL());
} catch (Exception e) {
e.printStackTrace();
}
}
```
and I get this : `file:/C:/test%20a.xml`
How come the given URL doesn't have two slashes before the `C:` ? I expected `file://C:...`. Is it normal behaviour?
---
**EDIT :**
From Java source code : java.net.URLStreamHandler.toExternalForm(URL)
```
result.append(":");
if (u.getAuthority() != null && u.getAuthority().length() > 0) {
result.append("//");
result.append(u.getAuthority());
}
```
It seems that the Authority part of a file URL is null or empty, and thus the double slash is skipped. So what is the authority part of a URL and is it really absent from the file protocol? | That's an interesting question.
First things first: I get the same results on JRE6. I even get that when I lop off the toURL() part.
[RFC2396](http://www.ietf.org/rfc/rfc2396.txt) does not actually require two slashes. According to section 3:
> The URI syntax is dependent upon the
> scheme. In general, absolute URI are
> written as follows:
>
> ```
> <scheme>:<scheme-specific-part>
> ```
Having said that, RFC2396 has been superseded by [RFC3986](http://www.faqs.org/rfcs/rfc3986.html), which states
> The generic URI syntax consists of a
> hierarchical sequence of omponents
> referred to as the scheme, authority,
> path, query, and fragment.
>
> ```
> URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
>
> hier-part = "//" authority path-abempty
> / path-absolute
> / path-rootless
> / path-empty
> ```
>
> The scheme and path components are
> required, though the path may be empty
> (no characters). When authority is
> present, the path must either be empty
> or begin with a slash ("/") character.
> When authority is not present, the
> path cannot begin with two slash
> characters ("//"). These restrictions
> result in five different ABNF rules
> for a path (Section 3.3), only one of
> which will match any given URI
> reference.
So, there you go. Since file URIs have no authority segment, they're forbidden from starting with //.
However, that RFC didn't come around until 2005, and Java references RFC2396, so I don't know why it's following this convention, as file URLs before the new RFC have always had two slashes. | To answer why you can have both:
```
file:/path/file
file:///path/file
file://localhost/path/file
```
[RFC3986 (3.2.2. Host)](https://www.rfc-editor.org/rfc/rfc3986#section-3.2.2) states:
> "If the URI scheme defines a default for host, then that default applies when the host subcomponent is undefined or when the registered name is empty (zero length). For example, the "file" URI scheme is defined so that no authority, an empty host, and "localhost" all mean the end-user's machine, whereas the "http" scheme considers a missing authority or empty host invalid."
So the "file" scheme translates `file:///path/file` to have a context of the end-user's machine even though the authority is an empty host. | Java : File.toURI().toURL() on Windows file | [
"",
"java",
"url",
"uri",
"filepath",
"file-uri",
""
] |
An application I've been working with is failing when I try to serialize types.
A statement like
```
XmlSerializer lizer = new XmlSerializer(typeof(MyType));
```
produces:
```
System.IO.FileNotFoundException occurred
Message="Could not load file or assembly '[Containing Assembly of MyType].XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified."
Source="mscorlib"
FileName="[Containing Assembly of MyType].XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
FusionLog=""
StackTrace:
at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
```
I don't define any special serializers for my class.
How can I fix this problem? | Believe it or not, this is normal behaviour. An exception is thrown but handled by the XmlSerializer, so if you just ignore it everything should continue on fine.
I have found this very annoying, and there have been many complaints about this if you search around a bit, but from what I've read Microsoft don't plan on doing anything about it.
You can avoid getting Exception popups all the time while debugging if you switch off first chance exceptions for that specific exception. In Visual Studio, go to *Debug* -> *Exceptions* (or press `Ctrl` + `Alt` + `E`), *Common Language Runtime Exceptions* -> *System.IO* -> *System.IO.FileNotFoundException*.
You can find information about another way around it in the blog post *[C# XmlSerializer FileNotFound exception](https://www.rickvandenbosch.net/blog/c-xmlserializer-filenotfound-exception/)* (which discusses Chris Sells' tool *XmlSerializerPreCompiler*). | Like Martin Sherburn said, this is normal behavior. The constructor of the XmlSerializer first tries to find an assembly named [YourAssembly].XmlSerializers.dll which should contain the generated class for serialization of your type. Since such a DLL has not been generated yet (they are not by default), a FileNotFoundException is thrown. When that happenes, XmlSerializer's constructor catches that exception, and the DLL is generated automatically at runtime by the XmlSerializer's constructor (this is done by generating C# source files in the %temp% directory of your computer, then compiling them using the C# compiler). Additional constructions of an XmlSerializer for the same type will just use the already generated DLL.
> **UPDATE:** Starting from .NET 4.5, `XmlSerializer` no longer performs code generation nor does it perform compilation with the C# compiler in order to create a serializer assembly at runtime, unless explicitly forced to by setting a configuration file setting ([useLegacySerializerGeneration](http://msdn.microsoft.com/en-US/library/system.xml.serialization.configuration.xmlserializersection.uselegacyserializergeneration.aspx)). This change removes the dependency on `csc.exe` and improves startup performance. *Source: [.NET Framework 4.5 Readme](http://download.microsoft.com/download/1/1/C/11CC285A-F710-4B77-AC98-E17E3CA1C009/Net%20Framework%204.5%20Readme_enu.htm), section 1.3.8.1.*
The exception is handled by XmlSerializer's constructor. There is no need to do anything yourself, you can just click 'Continue' (F5) to continue executing your program and everything will be fine. If you're bothered by the exceptions stopping the execution of your program and popping up an exception helper, you either have 'Just My Code' turned off, or you have the FileNotFoundException set to break execution when thrown, instead of when 'User-unhandled'.
To enable 'Just My Code', go to Tools >> Options >> Debugging >> General >> Enable Just My Code. To turn off breaking of execution when FileNotFound is thrown, go to Debug >> Exceptions >> Find >> enter 'FileNotFoundException' >> untick the 'Thrown' checkbox from System.IO.FileNotFoundException. | XmlSerializer giving FileNotFoundException at constructor | [
"",
"c#",
"xml-serialization",
""
] |
I have a file in my project which I need to compile using an external tool, and the output of that is a pair of .c and .h files.
Whats the best way to integrate this into my Eclipse-CDT build?
* Ideally I can reference the external tool using a relative path
* Ideally Eclipse will know if I change this file that it needs to re-run the external tool
I've tried out adding something to the 'Builders' section under Project Properties with mixed results.
thx
* Alex | I got this working well by adding a **'Builder'** of type **'Program'**.
1. Right click on the project
2. Click "Properties", "Builders"
3. Click "New", "Program", ...
4. Add the location of the file you want to execute, as well as any command line arguments. | I'm using [cmake](http://www.cmake.org/) with eclipse cdt
it provides an generator to generate the whole eclipse cdt project
you just have to setup your CMakeLists.txt file and then run the following command in your project directory:
`cmake -G"Eclipse CDT4 - Unix Makefiles" -D CMAKE_BUILD_TYPE=Debug .`
after that eclipse uses the cmake generated make file and regenerates it when you change the CMakeLists.txt
there exists [tutorial](http://www.paraview.org/Wiki/CMake:Eclipse_UNIX_Tutorial) for cmake and cdt
you have to check whether cmake suits your needs | Eclipse-CDT: Whats the best way to add a custom build step? | [
"",
"c++",
"build-process",
"eclipse-cdt",
""
] |
I'm researching alternatives to the federally backed [CONNECT adapter](http://www.connectopensource.org/display/Gateway/CONNECT+Community+Portal) for building a custom adapter to connect to the Nationwide Health Information Network (NHIN). Is CONNECT the only available solution, or are there other solutions as well? | I don't see any alternative currently. I also don't see much of a prospect for one, when CONNECT is addressing an incredibly complex challenge, has broad governmental support, is open source, and is actively being developed. | Very late answer, but there is an alternative now: <http://aurionproject.org/>
This is indeed based on CONNECT, however. | Alternatives to CONNECT adapter to interface with NHIN network? | [
"",
"java",
"adapter",
"connect",
""
] |
How to find what are all tables has binary data and display the table name ? | For MySql you want the INFORMATION\_SCHEMA COLUMNS table:
<http://dev.mysql.com/doc/refman/5.1/en/columns-table.html>
If you need to find all of the tables which have binary columns, then you can create a query joining with the INFORMATION\_SCHEMA TABLES table:
<http://dev.mysql.com/doc/refman/5.1/en/tables-table.html> | you need to select the system tables (in msssql 2000 - syscolumns) or system management views (in mssql 2005 or 2008 - sys.columns) to find the columns with system\_type\_id you need to find, and then find the corresponding table joining sys.columns and sys.objects by object\_id field. | find the tables has binary data | [
"",
"sql",
"mysql",
"database",
""
] |
I have the following setup, and I need to know how to persist state.
1.) An external web page uses ajax to load and display a .jsp file, which contains javascript.
2.) Once this rendering is complete, javascript in the .jsp file must be called to perform an action based on the results that occurred during rendering. Specifically, the document does action on $(document).ready, and those actions dictate what must be done on later function calls.
The question I have is this: How do I persist the data and state created when the page is loaded? I tried something like this:
External:
ajax to test.jsp
Internal test.jsp
```
var saveMe = {};
function getsCalled()
{
saveMe = {'a':function(){return false;}};
}
function needsData()
{
//???
}
```
Later...
External:
```
needsData();
```
Nothing I seem to attempt is working. What would be the best way to persist state in this situation? | Making the variable a member of the function object worked swimmingly. | If you want to know about scoping read [this](http://www.crockford.com/javascript/private.html). It might help you to work out what is going on. | JavaScript variable scoping - persisting state? | [
"",
"javascript",
"jquery",
"jquery-ui",
"persistence",
"scope",
""
] |
Let's say I have something like this:
```
d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }
```
What's the easiest way to **progammatically** get that into a file that I can load from python later?
Can I somehow save it as python source (from within a python script, not manually!), then `import` it later?
Or should I use JSON or something? | Use the [pickle](http://docs.python.org/library/pickle.html) module.
```
import pickle
d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }
afile = open(r'C:\d.pkl', 'wb')
pickle.dump(d, afile)
afile.close()
#reload object from file
file2 = open(r'C:\d.pkl', 'rb')
new_d = pickle.load(file2)
file2.close()
#print dictionary object loaded from file
print new_d
``` | Take your pick: [Python Standard Library - Data Persistance](http://docs.python.org/library/persistence.html). Which one is most appropriate can vary by what your specific needs are.
[`pickle`](http://docs.python.org/library/pickle.html) is probably the simplest and most capable as far as "write an arbitrary object to a file and recover it" goes—it can automatically handle custom classes and circular references.
For the best pickling performance (speed and space), use `cPickle` at `HIGHEST_PROTOCOL`. | Easiest way to persist a data structure to a file in python? | [
"",
"python",
"file",
"persistence",
""
] |
I'm quite new to Linq and have had some problems updating my dabase.
I don't know if it is actually happening for be using a global data context or I'm missing something.
I have my typed DataContex and one Static Public Var to initialize it located within the namespace AlpaCommon, like following:
My partial datacontext\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
```
// partial datacontext class
namespace
AlpaCommon
{
public partial class AlpaDataContext : System.Data.Linq.DataContext
{
//Insert method is working...
public void InsertAnimal2(Animal instance)
{
Animais.InsertOnSubmit(instance);
SubmitChanges();
}
//Delete method is working...
public void DeleteAnimal2(int animalID)
{
var animal = (from a in Animais where a.AnimalID == animalID select a).First();
Animais.DeleteOnSubmit(animal);
SubmitChanges();
}
//Update method IS NOT working...
public void UpdateAnimal2(Animal newAnimal)
{.
var animal = (from a in Animais where a.AnimalID == newAnimal.AnimalID select a).First();
animal = newAnimal;
SubmitChanges();
}
```
This is where I'm instanciating the datacontext e other variables I'll need in the whole app\*\*\*\*\*\*\*\*\*\*\*\*\*
```
//global DataContext instance
namespace AlpaCommon
{
public static class Globals
{
public static AlpaDataContext db = new AlpaDataContext();
```
This is the call to the update method \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
```
using AlpaCommon;
namespace Animais
{
public partial class Altera : System.Web.UI.Page
{
protected void btnUpdate_Click(object sender, EventArgs e)
{
try
{
//cria um novo Objeto do tipo Animal
Animal animalAltera = new Animal();
//set new values
animalAltera.AnimalID = Convert.ToInt32(Request.Params["AnimalID"]);
animalAltera.Castrado = CastradoCheckBox.Checked;
animalAltera.DisponivelAdocao = DisponivelCheckBox.Checked;
animalAltera.Adotado = AdotadoCheckBox.Checked;
animalAltera.Nome = NomeTextBox.Text;
animalAltera.Tipo = TipoDropDownList.SelectedValue;
animalAltera.Sexo = SexoDropDownList.SelectedValue;
animalAltera.Descricao = DescricaoTextBox.Text;
animalAltera.Local = LocalTextBox.Text;
animalAltera.Foto = AlteraFoto();
AlpaCommon.Globals.db.UpdateAnimal2(animalAltera);
redirect = redirectSucesso;
}
catch
{
redirect = redirectErro;
}
finally
{
Helper.Redirect(redirect);
}
}
```
---
I'm not catching any exception, it just does not update the database. Am I missing something in my updating or calling method? I'm looking forward for suggestions.
Thank you
Josimari Martarelli | The problem is in your animal = newAnimal; statement in UpdateAnimal2. Remember that animal in that context is just a reference, and you're just assigning that reference to an animal that is not connected to your DataContext. Get the animal from your dataContext first instead of calling animalAltera = new Animal(); THEN, call SubmitChanges(). Or, you could use the Attach() method of the DataContext to attach your new Animal() object and then submit. | In your UpdateAnimal2() method, note that the DataContext is associated with *animal* prior to its assignment. The DataContext remains associated with that *animal* after the assignment, but the variable simply points to a different object. The DataContext knows nothing about this new object, and in fact, would have problems handling it if that object was created by a different DataContext. Instead, you should assign all of *animal's* properties to match the properties of *newAnimal*. An assignment does not accomplish anything in this context. | Link to Sql - Problems on Updating Database | [
"",
"c#",
"asp.net",
"linq-to-sql",
""
] |
Many times I hear that F# is not suited to particular tasks, such as UI. "Use the right tool" is a common phrase.
Apart from missing tools such as a WinForms/WPF/ORM designer, I'm not sure what exactly is missing in F# -- honestly! Yet, particularly with UI, I'm told that C# just does it better. So, what are the actual differences and omissions in F# when using it imperatively?
Here is a list I came up with:
* Lots of missing tool support
* F# is still beta
* Your developers don't know F#
+ I'd like to not consider those points, as they aren't really intrinsic to F#
* Mutables need "mutable" or need to be ref, ref needs ! to dereference
* Mutables assign with <- and ref uses := ( they're both 1 more character than just = )
* val needs DefaultValueAttribute to get a default value
* F# doesn't emit implicit interfaces
* Protected members are more difficult to deal with
* No automatic properties
* Implemented virtual members on abstract classes require two definitions
* Quotations-to-LINQ-Expression-Trees produces trees slightly different than C#/VB (annoying for APIs that expect their Expressions in a specific format)
* No stackalloc
* F# doesn't have the ?: conditional operator
* Pointers might be considered more cumbersome in F#
* Delegates/events might possibly be considered more cumbersome (I'd argue they're easier, but at a minimum they're different)
* No automatic type conversions (like int to float, or implicit casts)
* No special syntax support for Nullable (C#'s ? type annotation and ?? operator, as well as using operators on nullables.)
* No automatic upcasting to common base class or boxing (ex: let x : obj = if true then 1 else "hi" // this won't typecheck)
* Values can't be discarded without a warning ("ignore" to get around it)
* Doesn't have C-style syntax :)
To the question: Which of these are a hindrance to writing imperative or OO code? Why (short examples)? Which ones did I miss? What are the best workarounds, and why are they not enough?
*Please note*, I'm not talking about writing so-called idiomatic F#, and I'm certainly not talking about functional programming. I'm more interested along the lines of "If I were to force myself to write UI or imperative/OO code in F#, using F# OO/imperative features and class types, what hurts the most?"
**Bonus**
If you don't know F# but use C# or VB.NET and think it's a better tool for some situations, please indicate the specific language features and syntax you find appealing. | With regards to OO stuff, my list might be
* You mentioned some things about interfaces and virtuals that can be annoyances or hindrances; lack of auto-props you mentioned is also a shame
* OO frameworks sometimes require many mutually recursive classes, which F# currently forces you to put in one file (in a 'type ... and ... and ...' block)
* If you need to call two different base constructors in a derived class, you have to use the 'explicit' class syntax (as mentioned [here](http://cs.hubfs.net/forums/thread/11173.aspx))
That said, F# has strengths in the OO department too, like type inference, local functions, succinct syntax, ... so overall I might call it a wash in the 'heavily OO' department.
(I have done almost no UI programming of any kind, so am not qualified to weigh in there.)
(EDIT: I also want to interject that, even though you're explicitly choosing to exclude 'tooling' from the question, I think tooling matters a bit, and in this respect the other managed VS languages excel.) | I'm not a huge fan of this question as it complains about F# not supporting idiomatic C#. For example, I don't think it's fair to criticize F# for using <- and := for variable assignment because the language makes things immutable by default.
Regardless, there are several imperative / object-oriented things you can do in C# that you simply cannot in F#.
* F# doesn't not support nested classes. In C# you can declare a class within the body of another class as a mechanism for scoping types. F# does not support this.
* F# doesn't allow you to implement the same generic interface twice. For example, in C# you can implement `IComparable<int>` and `IComparable<string>` on the same type.
* In F# you must have architectural layering. Due to F#'s type inference you can only use classes that have been declared 'before' or in the same 'block' of type declarations. In C# however you can have any class reference any other. (This actually enforces some good programming practices.)
* F# doesn't have 'native' support for LINQ, as in no from keyword. However, you can use LINQ APIs and lambda expressions to achieve the same result.
Things that F# can do that C# can't:
* Discriminated unions. This makes it trivial to create tree-like data structures in F#, where in C# you'd have to resort to a complex type hierarchy.
* Asynchronous workflows. This feature of the F# library makes asynchronous and parallel programming much more paletable by abstracting away all the pain associated with the APM.
* Pattern matching and active patterns.
* Units of measure for eliminating bugs associated with using the wrong units. (E.g., adding 'feet' to 'meters'.)
* etc.
You shouldn't focus on what F# 'can't do like C#' because the whole point of learning F# is to be presented with a new way to think about problem solving. If you write idiomatic C# code in F# you aren't actually gaining anything.
AFAIK F# isn't missing any 'must haves' for .NET / COM interop. In F# you can do things like have out and byref parameters, declare string literals, and support putting attributes on just just about anything. | What is F# lacking for OO or imperative? | [
"",
"c#",
"oop",
"f#",
"user-interface",
"language-design",
""
] |
I just want to know what's the lambda expression of `Select * from TableName`.
Like in plain LINQ it will be `var res=from s in db.StudentDatas select s`;
here `StudentData` is name of the table.
Thanks. | The lambda expression isn't needed:
```
var res = db.StudentDatas;
```
You could use one but it would be rather pointless:
```
var res = db.StudentDatas.Select(s => s);
``` | The compiler will translate it to something along these lines:
```
db.StudentDatas.Select(s => s)
```
The translation to SQL is done by the Base Class Library. SQL, of course, does not use lambda expressions... | Lambda Expression of Select * from TableName | [
"",
"c#",
"linq",
"c#-3.0",
""
] |
I'm new to C++ and there's something I just completely don't get. In C#, if I want to use an external library, log4net for example, I just add a reference to the log4net DLL and its members are automatically available to me (and in IntelliSense). How do I do that in non-managed C++? | Often, the library comes with 1) a header file (.h) and 2) a .lib file in addition to the .dll.
The header file is #include'ed in your code, to give you access to the type and function declarations in the library.
The .lib is linked into your application (project properties -> linker -> input, additional dependencies).
The .lib file usually contains simple stubs that automatically load the dll and forward function calls to it.
If you don't have a .lib file, you'll instead have to use the LoadLibrary function to dynamically load the DLL. | The basic concept is the following:
There are 2 types of libraries: static & dynamic. The difference between them is that static libraries, during the linking build step, embed their compiled code in your executable (or dll); dynamic libs just embed pointers to the functions and instructions that some dll should be loaded when program is going to be loaded. This is realized for you by the linker.
Now you can decide which of those two you are going to use. DLLs have many advantages and disadvantages. If developing a huge application it might be worthy to consider using DLLs with delay loading instead of static lib's. Some libs are simply delivered to you as DLLs and you have no choice. Anyway the easiest way for a beginner would be to use static libraries. That would make your deployment and test much easier, since, when dealing with DLL you have to ensure that they are found at runtime (even when using debugger), this involves either copying everything in one directory or dealing with path variables.
Usually a DLL provider (if it is intended that you should be able to deal with the library) delivers you a header file(s) and a .lib which contains the calls into the desired DLL. Some vendors (e.g. boost) only require you to include the header file and the lib is automatically linked to your executable (can be achieved through compiler prorietary pragma directive). If it is not the case you must go into the project settings of the C++ project (project properties/Configuration Properties/Linker/Input) and enter the lib file name into the "Additional Dependencies" row, e.g. `iced.lib; iceutild.lib`. You can also put fully qualified path names there. Be aware that you have to enter the lib file names for both configurations (Debug, Release). This is the procedure you do with static libraries and Dll equally. The only difference that DLL will require a DLL lib to be either in you app-directory or in one of the path-directories.
After that step, you still might get compiler errors if you try to link incompatible libraries. There are many reasons, why they can be incompatible. But try to first link the lib this way and see if works. If not, post again your errors here ;)
Include file(s) is(are) used to be included in places, where you would like to use smth. from the lib. Just include it and the compiler will know that the symbols must come either from another (compiled) compilation unit (compiled cpp-file=>object file) or the .lib. It will make the look up and notify you if the required symbols are not found.
Good Luck,
Ovanes
P.S. This might be hard in the beginning, but when you get used to it, it will be easy. | How to "add reference" in C++ | [
"",
"c++",
"visual-studio",
"dll",
""
] |
If I have `int x[10]` and `int *y`, how can I tell the difference between the two?
I have two ideas:
> 1. sizeof() is different.
> 2. &x has different type --- `int (*p)[10] = &x` works but not `int **q
> = &x`.
Any others?
In some template library code, I need to determine whether a pointer is a "real" pointer or degenerated from an array. I can't look at source code as the library user does not exist until I write the library. ... I can work around this by rewriting the code, so now this is only a theoretical exercise. | The `sizeof` idea is not very good, because if the array happens to have a single element, and the element type happens to be the same size as a pointer, then it will be the same size as the size of a pointer.
The type matching approach looks more promising, and could presumably be used to pick a template specialization (if that's what you're up to). | There is no general method - you either already know the type because you have just declared the object, or the type will have decayed to a pointer and been lost. Please explain what problem you are trying to solve by differentiating between them. | array of integers vs. pointer to integer in c++ | [
"",
"c++",
"arrays",
"pointers",
""
] |
I came across this code while working through code-analysis warnings on our code base. I want to change the name, but not if it will cause a serialization issue. While it looks to me like there is no point in it being serializable, I just wanted to check to make sure I'm not missing something before I strip the attribute.
```
[Serializable]
public class FileIsNotReadonlyVerifier : IFileVerifier
{
#region IFileVerifier Members
public void Verify(FileInfo file, FlatFileTrafficSystem system)
{
if ((file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
throw new VerificationException(Resources.VerificationException_FileIsReadonly);
}
}
#endregion
}
``` | Your class isn't sealed; if the intention is that somebody could subclass it and need to serialize it, then perhaps add `[Serializable]`.
**However**; I *wouldn't* add `[Serializable]` "just because"; serialization (like threading or inheritance) is something that should be **planned, designed and tested**. If you don't currently serialize the type or foresee a *need* to serialize it, then the chances are that you haven't designed/tested it adequately for those scenarios (which is 100% correct; you don't waste time writing unnecessary code).
If somebody else uses your class and wants to be serializable, they can do that by marking their local field as `[NonSerialized]` and handling it manually (perhaps in the callbacks).
Note also that in many ways `BinaryFormatter` (which is the main consumer of `[Serializable]`) *itself* has design issues and is fairly brittle. There are contract-based serializers that offer far more stability. | Yes please mark this as serializable.The reason being that if you don't anyone who uses your type will be unable to serialize an instance of this class.
```
[Serializable]
public class MyType {
// Breaks serialization.
private readonly FileIsNotReadonlyVerifier _verifier;
// Might work, might break. Depends on the implementation. Have to use
// another context variable to serialize / deserialize this.
private readonly IFileVerifier _otherVerifier;
}
```
The only way to make it work in this case is to make the variable non-serializable, use another variable to track the state, and override the special serialization methods with fixup logic.
I've run into this problem several times and it's extremely frustrating. Most notably I've run into it in places where people were creating custom string comparers which had no members. In order to serialize my types I had to jump through a lot of hoops. Very frustrating. | Is it pointless to mark a class with no properties as Serializable? | [
"",
"c#",
"serialization",
""
] |
I'm using Tangosol Coherence v3.2.2b371. Can I cache objects that do not implement *Serializable* through the *NamedCache* api? Or this depends on configuration?
---
Edit: For clarification, I'm trying to cache compiled *javax.xml.xpath.XPathExpression* objects. | To store an object in the cache it must be serializable but does not have to implement Serializable. Specifically, it can use [POF](https://docs.oracle.com/cd/E24290_01/coh.371/e22837/api_pof.htm#COHDG5182) which is more efficient in time and memory than Serializable.
POF does require some additional configuration, which is described in the article I linked to. | I'm guessing (just guessing) that the answer is "no". However, do take a look at the PortableObject interface. This is supposed to be an alternative to java.io.Serializable, but for performance reasons. You should check whether it can be used to replace Serializable interface.
[PortableObject JavaDoc](http://download.oracle.com/otn_hosted_doc/coherence/350/com/tangosol/io/pof/PortableObject.html) | Can Tangosol Coherence cache non-serializable objects? | [
"",
"java",
"caching",
"oracle-coherence",
""
] |
Is there any way to determine in Javascript if an object was created using [object-literal](http://www.brainonfire.net/blog/javascript-object-literal-namespace/) notation or using a constructor method?
It seems to me that you just access it's parent object, but if the object you are passing in doesn't have a reference to it's parent, I don't think you can tell this, can you? | I just came across this question and thread during a sweet hackfest that involved a grail quest for evaluating whether an object was created with {} or new Object() (i still havent figured that out.)
Anyway, I was suprised to find the similarity between the isObjectLiteral() function posted here and my own isObjLiteral() function that I wrote for the Pollen.JS project. I believe this solution was posted prior to my Pollen.JS commit, so - hats off to you! The upside to mine is the length... less then half (when included your set up routine), but both produce the same results.
Take a look:
```
function isObjLiteral(_obj) {
var _test = _obj;
return ( typeof _obj !== 'object' || _obj === null ?
false :
(
(function () {
while (!false) {
if ( Object.getPrototypeOf( _test = Object.getPrototypeOf(_test) ) === null) {
break;
}
}
return Object.getPrototypeOf(_obj) === _test;
})()
)
);
}
```
Additionally, some test stuff:
```
var _cases= {
_objLit : {},
_objNew : new Object(),
_function : new Function(),
_array : new Array(),
_string : new String(),
_image : new Image(),
_bool: true
};
console.dir(_cases);
for ( var _test in _cases ) {
console.group(_test);
console.dir( {
type: typeof _cases[_test],
string: _cases[_test].toString(),
result: isObjLiteral(_cases[_test])
});
console.groupEnd();
}
```
Or on jsbin.com...
<http://jsbin.com/iwuwa>
Be sure to open firebug when you get there - debugging to the document is for IE lovers. | What you want is:
```
Object.getPrototypeOf(obj) === Object.prototype
```
This checks that the object is a plain object created with either `new Object()` or `{...}` and not some subclass of `Object`. | How to determine if an object is an object literal in Javascript? | [
"",
"javascript",
"oop",
"object-literal",
""
] |
I have created the following LINQ query to demonstrate the problem:
```
string[] dateStrings = new string[] { "2009-07-20 13:00:00", "2009-07-20 16:00:00", "2009-07-20 09:00:00" };
DateTime dateValue = DateTime.MinValue;
var results =
from dateString in dateStrings
where DateTime.TryParse(dateString, out dateValue)
orderby dateValue descending
select dateValue;
```
You'd expect the result to be a list of DateTimes in the reversed order:
20-7-2009 16:00:00
20-7-2009 13:00:00
20-7-2009 9:00:00
However all I get is this:
20-7-2009 9:00:00
20-7-2009 9:00:00
20-7-2009 9:00:00
What am I doing wrong?
If you remove the orderby statement you'll notice a normal list of DateTime's. | Where is dateValue declared? Observe that it can only hold one value.
Try this instead:
```
string[] dateStrings = new string[] { "2009-07-20 13:00:00",
"2009-07-20 16:00:00", "2009-07-20 09:00:00" };
var results =
dateStrings.Select(s =>
{
DateTime v;
bool parsed = DateTime.TryParse(s, out v);
return new {Parsed = parsed, Value = v };
})
.Where(x => x.Parsed)
.Select(x => x.Value)
.OrderByDescending(d => d);
``` | try the method
```
var results =
from dateString in dateStrings
orderby (Convert.ToDateTime(dateString)) descending
select (Convert.ToDateTime(dateString));
``` | LINQ Orderby clause is causing weird results | [
"",
"c#",
"linq",
""
] |
Is there a quick and dirty mapping of MIME types to extensions in PHP that I can make use of? | Not built-in, but it's not terribly hard to roll your own:
```
function system_extension_mime_types() {
# Returns the system MIME type mapping of extensions to MIME types, as defined in /etc/mime.types.
$out = array();
$file = fopen('/etc/mime.types', 'r');
while(($line = fgets($file)) !== false) {
$line = trim(preg_replace('/#.*/', '', $line));
if(!$line)
continue;
$parts = preg_split('/\s+/', $line);
if(count($parts) == 1)
continue;
$type = array_shift($parts);
foreach($parts as $part)
$out[$part] = $type;
}
fclose($file);
return $out;
}
function system_extension_mime_type($file) {
# Returns the system MIME type (as defined in /etc/mime.types) for the filename specified.
#
# $file - the filename to examine
static $types;
if(!isset($types))
$types = system_extension_mime_types();
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(!$ext)
$ext = $file;
$ext = strtolower($ext);
return isset($types[$ext]) ? $types[$ext] : null;
}
function system_mime_type_extensions() {
# Returns the system MIME type mapping of MIME types to extensions, as defined in /etc/mime.types (considering the first
# extension listed to be canonical).
$out = array();
$file = fopen('/etc/mime.types', 'r');
while(($line = fgets($file)) !== false) {
$line = trim(preg_replace('/#.*/', '', $line));
if(!$line)
continue;
$parts = preg_split('/\s+/', $line);
if(count($parts) == 1)
continue;
$type = array_shift($parts);
if(!isset($out[$type]))
$out[$type] = array_shift($parts);
}
fclose($file);
return $out;
}
function system_mime_type_extension($type) {
# Returns the canonical file extension for the MIME type specified, as defined in /etc/mime.types (considering the first
# extension listed to be canonical).
#
# $type - the MIME type
static $exts;
if(!isset($exts))
$exts = system_mime_type_extensions();
return isset($exts[$type]) ? $exts[$type] : null;
}
``` | You could use [`mime_content_type`](http://php.net/manual/en/function.mime-content-type.php) but it is deprecated. Use [`fileinfo`](http://www.php.net/manual/en/ref.fileinfo.php) instead:
```
function getMimeType($filename) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $filename);
finfo_close($finfo);
return $mime;
}
``` | How do I determine the extension(s) associated with a MIME type in PHP? | [
"",
"php",
"mime",
"mime-types",
"filenames",
"file-type",
""
] |
First question on SO and it's a real RTM candidate. But I promise you I've looked and can't seem to find it. I'll happily do a #headpalm when it turns out to be a simple thing that I missed.
Trying to figure out Zend Framework and came across the following syntax:
```
$this->_session->{'user_id'}
```
I have never seen the curly braces syntax used to access what appears to be a member variable. How is it different than
```
$this->_session->user_id
```
I'm assuming that the \_session is irrelevant, but including it in the question since it may not be.
Are the curly braces just a cleanliness convention that attempts to wrap the compound variable name user\_id? Or is it some kind of a special accessor?
Any pointers into TFM so I can R up would be humbly appreciated.
Many thanks. Please be gentle. | Curly braces are used to explicitly specify the end of a variable name. For example:
```
echo "This square is {$square->width}00 centimeters broad.";
```
So, your case is really a combination of two special cases. You're allowed to access class variables using curly braces and like so:
```
$class->{'variable_name'} // Same as $class->variable_name
$class->{'variable' . '_name'} // Dynamic values are also allowed
```
And in your case, you're just surrounding them with the curly brace syntax.
See the [PHP manual](http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex), "complex (curly) syntax." | I know the syntax just when using [variable variables](http://docs.php.net/manual/en/language.variables.variable.php):
```
$userProp = 'id';
$this->_session->{'user_'.$userProp};
``` | PHP curly brace syntax for member variable | [
"",
"php",
"syntax",
"variables",
"curly-braces",
""
] |
I need to load and use CSV file data in C++. At this point it can really just be a comma-delimited parser (ie don't worry about escaping new lines and commas). The main need is a line-by-line parser that will return a vector for the next line each time the method is called.
I found this article which looks quite promising:
<http://www.boost.org/doc/libs/1_35_0/libs/spirit/example/fundamental/list_parser.cpp>
I've never used Boost's Spirit, but am willing to try it. But only if there isn't a more straightforward solution I'm overlooking. | If you don't care about escaping comma and newline,
AND you can't embed comma and newline in quotes (If you can't escape then...)
then its only about three lines of code (OK 14 ->But its only 15 to read the whole file).
```
std::vector<std::string> getNextLineAndSplitIntoTokens(std::istream& str)
{
std::vector<std::string> result;
std::string line;
std::getline(str,line);
std::stringstream lineStream(line);
std::string cell;
while(std::getline(lineStream,cell, ','))
{
result.push_back(cell);
}
// This checks for a trailing comma with no data after it.
if (!lineStream && cell.empty())
{
// If there was a trailing comma then add an empty element.
result.push_back("");
}
return result;
}
```
I would just create a class representing a row.
Then stream into that object:
```
#include <iterator>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
class CSVRow
{
public:
std::string_view operator[](std::size_t index) const
{
return std::string_view(&m_line[m_data[index] + 1], m_data[index + 1] - (m_data[index] + 1));
}
std::size_t size() const
{
return m_data.size() - 1;
}
void readNextRow(std::istream& str)
{
std::getline(str, m_line);
m_data.clear();
m_data.emplace_back(-1);
std::string::size_type pos = 0;
while((pos = m_line.find(',', pos)) != std::string::npos)
{
m_data.emplace_back(pos);
++pos;
}
// This checks for a trailing comma with no data after it.
pos = m_line.size();
m_data.emplace_back(pos);
}
private:
std::string m_line;
std::vector<int> m_data;
};
std::istream& operator>>(std::istream& str, CSVRow& data)
{
data.readNextRow(str);
return str;
}
int main()
{
std::ifstream file("plop.csv");
CSVRow row;
while(file >> row)
{
std::cout << "4th Element(" << row[3] << ")\n";
}
}
```
But with a little work we could technically create an iterator:
```
class CSVIterator
{
public:
typedef std::input_iterator_tag iterator_category;
typedef CSVRow value_type;
typedef std::size_t difference_type;
typedef CSVRow* pointer;
typedef CSVRow& reference;
CSVIterator(std::istream& str) :m_str(str.good()?&str:nullptr) { ++(*this); }
CSVIterator() :m_str(nullptr) {}
// Pre Increment
CSVIterator& operator++() {if (m_str) { if (!((*m_str) >> m_row)){m_str = nullptr;}}return *this;}
// Post increment
CSVIterator operator++(int) {CSVIterator tmp(*this);++(*this);return tmp;}
CSVRow const& operator*() const {return m_row;}
CSVRow const* operator->() const {return &m_row;}
bool operator==(CSVIterator const& rhs) {return ((this == &rhs) || ((this->m_str == nullptr) && (rhs.m_str == nullptr)));}
bool operator!=(CSVIterator const& rhs) {return !((*this) == rhs);}
private:
std::istream* m_str;
CSVRow m_row;
};
int main()
{
std::ifstream file("plop.csv");
for(CSVIterator loop(file); loop != CSVIterator(); ++loop)
{
std::cout << "4th Element(" << (*loop)[3] << ")\n";
}
}
```
Now that we are in 2020 lets add a CSVRange object:
```
class CSVRange
{
std::istream& stream;
public:
CSVRange(std::istream& str)
: stream(str)
{}
CSVIterator begin() const {return CSVIterator{stream};}
CSVIterator end() const {return CSVIterator{};}
};
int main()
{
std::ifstream file("plop.csv");
for(auto& row: CSVRange(file))
{
std::cout << "4th Element(" << row[3] << ")\n";
}
}
``` | My version is not using anything but the standard C++11 library. It copes well with Excel CSV quotation:
```
spam eggs,"foo,bar","""fizz buzz"""
1.23,4.567,-8.00E+09
```
The code is written as a finite-state machine and is consuming one character at a time. I think it's easier to reason about.
```
#include <istream>
#include <string>
#include <vector>
enum class CSVState {
UnquotedField,
QuotedField,
QuotedQuote
};
std::vector<std::string> readCSVRow(const std::string &row) {
CSVState state = CSVState::UnquotedField;
std::vector<std::string> fields {""};
size_t i = 0; // index of the current field
for (char c : row) {
switch (state) {
case CSVState::UnquotedField:
switch (c) {
case ',': // end of field
fields.push_back(""); i++;
break;
case '"': state = CSVState::QuotedField;
break;
default: fields[i].push_back(c);
break; }
break;
case CSVState::QuotedField:
switch (c) {
case '"': state = CSVState::QuotedQuote;
break;
default: fields[i].push_back(c);
break; }
break;
case CSVState::QuotedQuote:
switch (c) {
case ',': // , after closing quote
fields.push_back(""); i++;
state = CSVState::UnquotedField;
break;
case '"': // "" -> "
fields[i].push_back('"');
state = CSVState::QuotedField;
break;
default: // end of quote
state = CSVState::UnquotedField;
break; }
break;
}
}
return fields;
}
/// Read CSV file, Excel dialect. Accept "quoted fields ""with quotes"""
std::vector<std::vector<std::string>> readCSV(std::istream &in) {
std::vector<std::vector<std::string>> table;
std::string row;
while (!in.eof()) {
std::getline(in, row);
if (in.bad() || in.fail()) {
break;
}
auto fields = readCSVRow(row);
table.push_back(fields);
}
return table;
}
``` | How can I read and parse CSV files in C++? | [
"",
"c++",
"parsing",
"text",
"csv",
""
] |
We use SQL Server 2005. All our data access is done through stored procedures. Our selection stored procedures always return multiple result sets.
For instance:
```
CREATE PROCEDURE hd_invoice_select(@id INT) AS
SELECT * FROM Invoice WHERE InvoiceID = @id
SELECT * FROM InvoiceItem WHERE InvoiceID = @id
SELECT * FROM InvoiceComments WHERE InvoiceID = @id
RETURN
```
Our application's data access layer builds an object graph based on the results (O/R Mapper style).
The problem I have is that we have many different invoice selection stored procs. They all return the same structure, only for different selection criteria. For instance, I also have:
```
CREATE PROCEDURE hd_invoice_selectAllForCustomer(@customerID INT) AS
SELECT * FROM Invoice WHERE CustomerID = @customerID
SELECT * FROM InvoiceItem WHERE InvoiceID IN
(SELECT InvoiceID FROM Invoice WHERE CustomerID = @customerID)
SELECT * FROM InvoiceComments WHERE InvoiceID = @id
(SELECT InvoiceID FROM Invoice WHERE CustomerID = @customerID)
RETURN
```
and I have many others including:
```
hd_invoice_selectActive()
hd_invoice_selectOverdue()
hd_invoice_selectForMonth(@year INT, @month INT)
```
and I have the same pattern for a lot of concepts (Customers, Employees, etc)
We end up copying a lot of code and maintenance is really hard. When the "structure" of a concept changes, we have to go and fix all procs and it's very error prone.
So my question is: What is the best way to reuse the code in the scenario?
We came up with a solution that uses temp tables. But it's not very elegant. I'll let you share your ideas and if necessary I will post the detail of my solution in an upcoming post to get your comments on that approach.
Thanks | Posting this as a second answer because it is a different approach. If you are using SQL Server 2008:
```
CREATE TYPE InvoiceListTableType AS TABLE
(
InvoiceId INT
);
GO
CREATE PROCEDURE hd_invoice_selectFromTempTable
(
@InvoiceList InvoiceListTableType READONLY
)
AS
BEGIN
SELECT * FROM Invoice WHERE InvoiceID IN
(SELECT InvoiceId FROM @InvoiceList)
SELECT * FROM InvoiceItem WHERE InvoiceID IN
(SELECT InvoiceId FROM @InvoiceList)
SELECT * FROM InvoiceComments WHERE InvoiceID IN
(SELECT InvoiceId FROM @InvoiceList)
RETURN
END
GO
CREATE PROCEDURE hd_invoice_select(@id INT) AS
BEGIN
DECLARE @InvoiceList AS InvoiceListTableType;
SELECT id AS ID
INTO @InvoiceList
EXEC hd_invoice_selectFromTempTable(@InvoiceList)
RETURN
END
GO
CREATE PROCEDURE hd_invoice_selectAllForCustomer(@customerID INT) AS
BEGIN
DECLARE @InvoiceList AS InvoiceListTableType;
SELECT invoiceID as ID
INTO @InvoiceList
FROM Invoice WHERE CustomerID = @customerID
EXEC hd_invoice_selectFromTempTable(@InvoiceList)
RETURN
END
GO
CREATE PROCEDURE hd_invoice_selectAllActive AS
BEGIN
DECLARE @InvoiceList AS InvoiceListTableType;
SELECT invoiceID as ID
INTO @InvoiceList
FROM Invoice WHERE Status = 10002
EXEC hd_invoice_selectFromTempTable(@InvoiceList)
RETURN
END
GO
``` | The "best" way for this specific scenario would be to use some sort of code generation. Come up with some sort of convention and plug it into a code generator. | How to reuse code in SQL stored procedures? | [
"",
"sql",
"sql-server",
"code-reuse",
""
] |
When you need to check/have combinations of array elements, how can you avoid nesting foreach?
Example code:
```
$as = array($optionA1, $optionA2)
$bs = array($optionB1, $optionB2)
$cs = array($optionC1, $optionC2)
foreach ($as as $a) {
foreach ($bs as $b) {
foreach ($cs as $c) {
$result = $this->method($a, $b, $c);
if ($result) etc
}
}
}
```
Anyone with alternative approaches that can avoid nesting? | You could write your own Iterator class which implements the [Iterator interface](http://php.net/manual/en/class.iterator.php). You could then have its constructor accept the three arrays and then you can use it to loop over every combination with foreach.
However I think this would be significantly slower, so I would avoid it. It would be interesting to know the reasons you want to avoid the nested foreach loops? | Logically, you have to iterate through each item somehow. You're just shuffling around the process.
If multiple for loops look ugly, maybe you should put your arrays into their own classes, that have their own encapsulated 'checks'. | combinations: avoiding multiple nested foreach | [
"",
"php",
"nested",
"foreach",
"nested-loops",
""
] |
I need to get the company name and its ticker symbol in different arrays. Here is my data which is stored in a txt file:
```
3M Company MMM
99 Cents Only Stores NDN
AO Smith Corporation AOS
Aaron's, Inc. AAN
```
and so on
How would I do this using regex or some other techniques? | Iterate over each line, and collect the data with a regular expression:
```
^(.+?)\s+([A-Z]+)$
```
The backreference `$1` will contain the company name, `$2` will contain the ticker symbol.
You can also split the string in two with a two or three-space delimiter and trim the resulting two strings. This only works if you are sure the company name and ticker symbol are always separated by enough spaces, and the company name itself doesn't contain that amount of spaces. | Is the format of the text file imposed on you? If you have the choice, I'd suggest you don't use spaces to separate the fields in the text file. Instead, use | or $$ or something you can be assured won't appear in the content, then just split it to an array. | Parse lines of a text file where values are separated by a varying number of whitespace characters | [
"",
"php",
"regex",
"string",
"text-parsing",
"array-column",
""
] |
I am writing an app where the user should be able to alter the action of a button.
The user should right-click a button, and choose an option from a pop-up context menu. Once the choice has been made the button will perform a different action when the user uses a normal click.
I've already gotten the "Click" event working for a normal button click, however the "MouseClick" event handler isn't working correctly.
The "MouseClick" event gets activated on regular left-clicks, but never get's called for right-click.
Is there some default event handling being performed that is ignoring that right-click? | If you want to display a context menu with actions to choose from it should be enough to assign a `ContextMenuStrip` to the [`ContextMenuStrip`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.contextmenustrip.aspx) property. There is usually no need to manually handle the mouse events for that. | I'm sorry to say that this would be a serious UI blooper. Perhaps it would make more sense to add a small combobox next to the button.
Perhaps something like this?
<http://www.codeproject.com/KB/buttons/SplitButton.aspx> | Use right-click with Windows Forms Button | [
"",
"c#",
".net",
"user-interface",
"events",
"button",
""
] |
I'm really baffled by this. Have I managed to do something to cause this, or is it an unclosed namespace block in boost, or some bug in VS c++ 2008? I'm definitely sure I've closed all my own namespaces properly, all includes are outside of and above them, and all my header files got include guards.
[alt text http://lowtown.se/stuffs/superboost.png](http://lowtown.se/stuffs/superboost.png)
The boost/function.hpp is only included in this header. Two other headers in my library includes the boost/cstdint.hpp but they don't have this problem. | Visual C++'s intellisense is a bit quirky. Sometimes it screws up. That doesn't mean there is a problem in your code. Always take C++ intellisense with a grain of salt. | Sometimes intellisense does that. If you use Visual Assist X it will fix that, but it is a very expensive program :( | Namespace loop or code leak in boost::function? | [
"",
"c++",
"visual-studio-2008",
"boost",
"namespaces",
""
] |
How can I convert the following?
2934 (integer) to B76 (hex)
Let me explain what I am trying to do. I have User IDs in my database that are stored as integers. Rather than having users reference their IDs I want to let them use the hex value. The main reason is because it's shorter.
So not only do I need to go from integer to hex but I also need to go from hex to integer.
Is there an easy way to do this in C#? | ```
// Store integer 182
int intValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
```
from <http://www.geekpedia.com/KB8_How-do-I-convert-from-decimal-to-hex-and-hex-to-decimal.html>
---
**HINT (from the comments):**
Use `.ToString("X4")` to get exactly 4 digits with leading 0, or `.ToString("x4")` for lowercase hex numbers (likewise for more digits). | Use:
```
int myInt = 2934;
string myHex = myInt.ToString("X"); // Gives you hexadecimal
int myNewInt = Convert.ToInt32(myHex, 16); // Back to int again.
```
See *[How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/bb311038.aspx)* for more information and examples. | Convert integer to hexadecimal and back again | [
"",
"c#",
"hex",
"type-conversion",
""
] |
I got sick of writing queries in my PHP as:
```
"WHERE '" . Database::escape($var) . "'";
```
The escape() function just calls mysql\_real\_escape\_string() - but it's there so I can extend support to other databases later.
Having to single quote strings in the query was making my code more cluttered. So my idea was to create an other function in my database class to 'prepare' a variable for a query:
```
static public function prepare($var)
{
if (is_object($var) || is_array($var) ) {
return " '" . Database::escape(serialize($var)) . "' ";
} else if (is_bool($var)) {
return ' ' . (int)$var . ' ';
} else if (is_int($var)) {
return ' ' . $var . ' ';
} else if (is_string($var) || is_float($var)) {
return " '" . Database::escape($var) . "' ";
} else {
throw new Exception('Unsupported variable type [' . gettype($var) . ']');
}
}
```
Now the benefit here is that, I don't need to worry about which variables I pass to a query. However it raises two questions:
1. Am I handling each variable type properly?
2. For what reason (if any) should I not do this? | You are looking for a) pepared statements and b) a database abstraction layer (like PDO).
What you are trying to do on your own has been solved already, you should not roll your own implementation.
If you go down that road you'll notice that this:
```
"... WHERE '" . Database::escape($var) . "'"
```
is pointless and dangerous. A clear separation of SQL code and parameters requires you to be more explicit and gets you on the safe side against SQL injection the same time:
```
"--- WHERE SomeField = ?" /* the parameter (?) will be filled elsewhere */
```
It's worth noting that true vendor-independence in the database field is somewhere between hard and impossible, depending on your needs and priorities. So trying to write portable SQL *could* turn out as an exercise in futility unless you are willing to sacrifice a lot. For MySQL it starts even with the LIMIT clause, which you will find impossible to port to, say, SQL Server. | You probably shouldn't be doing this. Here's why: [mysqli::prepare](https://www.php.net/manual/en/mysqli.prepare.php) or [PDO::prepare](http://il.php.net/manual/en/pdo.prepare.php)
As for your function itself, what happens if you have something stored in a string (say `"5"`) that you want to store as an int? It'll still quote it anyway. | Function to escape different variable types in MySQL Query | [
"",
"php",
"mysql",
""
] |
Is there a simple way of escaping the magic characters used for variable substitution in a [buildout](http://www.buildout.org/) configuration, such that the string is left alone. In other words, where I say:
```
[part]
attribute = ${variable}
```
I don't actually want it to expand ${variable} but leave it as the literal value.
In practice the specific problem I am encountering is not in the buildout configuration file itself, but in a template file processed by the recipe 'collective.recipe.template'. This uses the same variable substitution engine from buildout that is used in the configuration files. Problem is that the file I want to use as a template already uses '${variable}' syntax for its own purposes in conjunction with the application configuration system which ultimately consumes the file.
The only way I have found to get around the problem is to use something like:
```
[server-xml]
recipe = collective.recipe.template
input = templates/server.xml.in
output = ${product:build-directory}/conf/server.xml
dollar = $
```
In the template input file then have:
```
${dollar}{variable}
```
instead of:
```
${variable}
```
that it already had.
What this is doing is cause a lookup of 'dollar' attribute against the section using the template and replace it with '$'.
Rather than have to do that, was sort of hoping that one could do:
```
\${variable}
```
or perhaps even:
```
$${variable}
```
and eliminate the need to have to have a dummy attribute to trick it into doing what I want.
Looking at the source code for buildout, the way it matches variable substitution doesn't seem to provide an escape mechanism.
If there is indeed no way, then perhaps someone knows of an alternate templating recipe for buildout that can do variable expansion, but provides an escape mechanism for whatever way it indicates variables, such that one can avoid problems where there may be a clash between the templating systems expansion mechanism and literal data in the file being templated. | I am afraid your analysis of the buildout variable substitution code (which collective.recipe.template relies on) is correct. There is no syntax for escaping a `${section:variable}` variable substitution and your solution of providing a `${dollar}` substitution is the best workaround I can think of.
You could of course also propose a patch to the zc.buildout team to add support for escaping the variable substitution syntax. :-) | since version 1.7 of collective.recipe.template you can use genshi text templates, but since version 1.8 its useful because of some fixes made.
```
recipe = collective.recipe.template[genshi]:genshi
...
mymessage = Hello
```
so the input-file it looks like
```
The message in $${:mymessage} is: ${options['mymessage']}
```
genshi allows escaping of the dollar, see <http://genshi.edgewall.org/wiki/Documentation/templates.html#escaping>
More details of how to use teh recipe with genshi at <http://pypi.python.org/pypi/collective.recipe.template#genshi-text-templates> | Preventing variable substitutions from occurring with buildout | [
"",
"python",
"buildout",
""
] |
A small program of mine just broke because, it seems, the site I was programmatically browsing now assumes a Java request comes from a mobile phone, and the link I was looking for is not on their mobile page.
So I want to fake an Internet Explorer access. How do I do that with java.net? | IIRC, set `"http.agent"` system property through `System`, `-D` on the command line, in your JNLP file or elsewhere. | Assuming you're using java.net.URLConnection, then call setRequestProperty(String,String) to set the request header to a value that IE would use. For example, to fake IE6:
```
URL url = new URL("http://google.com");
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 1.2.30703)");
```
and then use the connection object as before.
But java.net is horrible. Use Apache Commons HttpClient instead, it's much nicer.
Even better, use a framework designed for navigating websites, like HtmlUnit | How do I fake an specific browser client when using Java's Net library? | [
"",
"java",
"http",
"http-headers",
""
] |
I have a large 2GB file with 1.5 million listings to process. I am running a console app that performs some string manipulation then uploads each listing to the database.
1. I created a LINQ object and clear the object by assigning it to a new LinqObject() for each listing (loop).
2. When the object is complete, I add it to a list.
3. When the list reaches 100 objects, I submitAll on the entire list, clear the list, then repeat.
My memory usage continues to grow as the program runs. Is there anything I should be doing to keep memory usage down? I tried GC.collect. I think I want to use dispose..
Thanks in advance for looking. | It's normal for the memory usage of a program to increase when it's working. You should not try to force the garbage collector to reduce the memory usage to try to save resources, this will most likely waste resources instead.
Contrary to one's first reaction, high memory usage is not a performance problem as long as there are any free memory left at all. Having a lot of unused memory doesn't increase the performance a bit. If you try to reduce the memory usage only to keep it down, you are just wasting CPU time doing cleanup that is not needed.
If you are running out of free memory or if some other application needs it, the garbage collector will do the appropriate cleanup. In almost every situation the garbage collector will know much more about the current memory situatiuon than you can possibly anticipate when writing the code.
If you are using objects that implement the IDisposable interface, you should call the Dispose method to free unmanaged resources, but all other objects are handled by the garbage collector. Managed objects normally don't leak memory at all. | Do you *need* your memory usage to stay low? Absent an actual functional problem, high memory usage in and of itself is not an issue. | C# .NET Linq Memory Cleanup or Leak? | [
"",
"c#",
".net",
"memory",
"garbage-collection",
"dispose",
""
] |
When using nosetests for Python it is possible to disable a unit test by setting the test function's `__test__` attribute to false. I have implemented this using the following decorator:
```
def unit_test_disabled():
def wrapper(func):
func.__test__ = False
return func
return wrapper
@unit_test_disabled
def test_my_sample_test()
#code here ...
```
However, this has the side effect of calling wrapper as the unit test. Wrapper will always pass but it is included in nosetests output. Is there another way of structuring the decorator so that the test will not run and does not appear in nosetests output. | I think you will also need to rename your decorator to something that has not got test in. The below only fails on the second test for me and the first does not show up in the test suite.
```
def unit_disabled(func):
def wrapper(func):
func.__test__ = False
return func
return wrapper
@unit_disabled
def test_my_sample_test():
assert 1 <> 1
def test2_my_sample_test():
assert 1 <> 1
``` | Nose already has a builtin decorator for this:
```
from nose.tools import nottest
@nottest
def test_my_sample_test()
#code here ...
```
Also check out the other goodies that nose provides: <https://nose.readthedocs.org/en/latest/testing_tools.html> | Disabling Python nosetests | [
"",
"python",
"nosetests",
""
] |
There are thousand articles how to use LineBreakMeasurer to draw multi-line text but there is none about drawing multi-line text taking into account also \n(when you want to force a new line at a specific position in text and not only when the right - or left - margin ends).
The secret seems to lie in BreakIterator, but I couldn't find an implementation which handles \n. | Tokenize the text first, then just apply the LineBreakMeasureCode to each token. | Instead of `LineBreakMeasurer`'s (`LBM`'s) `nextLayout(float)` method, use the overloaded `LBM.nextLayout(float, int, boolean)` method. This allows you to limit the text that `LBM` will include in the returned `TextLayout`. In your case, you'll instruct it not to go beyond the next newline.
This code snippet should give you the idea. First use `LBM.nextOffset` to "peek" which character index would be the end of the next layout. Then iterate over your string content up to that offset to see if you find any newline characters. If you do, then use that found limit as the second argument to `nextLayout(float, int, boolean)` which will tell `LBM` not to exceed the newline:
```
int next = lineMeasurer.nextOffset(formatWidth);
int limit = next;
if (limit < totalLength) {
for (int i = lineMeasurer.getPosition(); i < next; ++i) {
char c = string.charAt(i);
if (c == '\n') {
limit = i;
break;
}
}
}
TextLayout layout = lineMeasurer.nextLayout(formatWidth, limit, false);
```
---
References
<http://java.sun.com/developer/onlineTraining/Media/2DText/style.html#layout>
http://java.sun.com/developer/onlineTraining/Media/2DText/Code/LineBreakSample.java | Handling \n in LineBreakMeasurer | [
"",
"java",
"text",
"drawing",
"awt",
""
] |
Is there any way to avoid the repetition of the type in this kind of declaration of a class member?
```
Dictionary<string, int> myDict = new Dictionary<string, int>();
``` | No, you can only use `var` for local variables. Basically you're stuck with the repetition, I'm afraid.
Eric Lippert has a great [blog post on this](http://blogs.msdn.com/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx).
---
Interesting point to note: Java performs implicit typing and type inference the other way round, based on what you're trying to assign *to*. That means this is legal:
```
// Note: This is Java, not C#!
class CollectionHelpers
{
public static <T> List<T> newList()
{
return new ArrayList<T>();
}
}
// In another class (doesn't have to be static)
static List<String> names = CollectionHelpers.newList();
``` | Sure - use VB.NET. ;)
```
myDict as New Dictionary(Of String, Integer)()
``` | avoid type repetition in class member initializer? | [
"",
"c#",
"refactoring",
""
] |
is there a way to grep(find) the text in a particular file, which is in \*.jar and this \*.jar is in \*.war? | Are you doing this programmatically from Java?
.war files are basically .zip files, just like .jar files. You can open .zip files with java.util.ZipFile.
Open your .war as a ZipFile, find your .jar within it, open your .jar as a ZipFile, find your text file within it. Now you can read the text and process it however you want.
Does this answer your question? | There is a 'common resource grep' command line tool, crgrep, which searches within various resources including archives, images, pdf, pom file dependencies and arbitrary nested combinations of these. So it will grep nestings such as text within a file in a jar which is buried in a war, within an ear. It also greps db table data and web page/url content.
<https://sourceforge.net/projects/crgrep/>
I developed crgrep as an opensource tool. | how to find text in jar file which is in war file? | [
"",
"java",
"jar",
""
] |
I have been interested in programming all my life and for the past 6 years I have worked almost exclusively with Java. I just finished with my University studies and have a job as a Java developer for a company.
All these years programming has been a hobby and a favorite past time, but this had a slightly negative effect in the sense that i grew so accustomed to Java i never ventured beyond it as a programming language. I did try to expand my knowledge of things by learning regular expressions, SQL and studied a bit of XML but i could never get involved enough with a new language to learn how to use it properly party because they all look alike so much at their core, i found the learning curve of every new language irritating. I felt like i had to go through the whole process to end up right were i started as i felt that other imperative languages had nothing more to offer me (i know this statement can start a fight, it is not my intention).
I therefore decided at one point to explore the magical world of functional programming. I begun reading a book on Haskel and found it really interesting from an academic point of view (i majored in Mathematics) but could not find practical applications of it to get me going enough to learn the language.
So now that Java is the main part of my day since i am getting paid to code in it (and i enjoy it as much as i did when it was simply a hobby) i felt the need again to broaden my horizons and again functional programming seems like a good idea.
I thought i would start with Scala since i am Java literate (make the transition easier and be more reusable since they can "talk" to each other) and so my question is : **In your experience does learning a functional language "make sense"? Are there any real life applications where knowing this paradigm may come in handy? Not only for personal entertainment but also would this be a "pro" in the industry?** | Learning a functional language is a big plus, regardless of whether or not you ever use it in your day job. Consider the following:
1. One of the biggest recommendations for successful concurrent programming is to avoid mutable state in your threaded objects whenever possible. Functional programming teaches you how to do this.
2. Most functional programmers, once they get over the not-insubstantial learning curve, claim that their techniques make them far more productive than they can be in standard imperative languages. Their code is more bug-free, and a fraction of the size as that of other languages. Think of the productivity boost you got when you finally understood regular expressions. Now put that on steroids. *That's* what FP can feel like.
3. Functional techniques are rapidly making their way into imperative programming. Think closures in C#, and Javascript, and soon (maybe, if we're lucky) in Java. It's very likely the two worlds will soon come together.
4. Finally, in job interviews, knowing a functional language will help you stand out from your average J2EE/.NET clone. It marks you as a self-starter, a disciplined learner, and a passionate programmer -- whether or not you actually are any of these things. Just don't become yet another slathering Scala fanboy, scolding your soon-to-be boss about how he's missing out on the best programming techniques since... you get the idea. It's never good to insult a prospective employer.
For me, studying Haskell has made programming a lot more fun than it used to be. It may do the same for you as well. Good luck! | In my opinion learning functional programming it is not only a good idea because it makes you a better programmer (think which I agree, of course) but because it seems it will become very popular in a near future.
A lot "gurus" are saying that it will be the only way to keep Moore's law alive. Computer clock speed has reach a top and the only way to improve processors speed will be adding more and more cores. In this scenario functional programing becomes handy because in those languages data is immutable and that makes them very easy to paralelize (it can be done automatically actually).
You might want to have a look to the next references
* [Free lunch is over](http://www.gotw.ca/publications/concurrency-ddj.htm): An excellent and famous article by Herb Sutter explaining the Moore's law issue
* [It's Time to Get Good at Functional Programming](http://www.ddj.com/development-tools/212201710;jsessionid=3MQLTTYJRPL3CQSNDLRSKH0CJUNN2JVN): a Dr Dobbs post regarding this subject
* [InfoQ comparison between Erlang and Scala](http://www.infoq.com/news/2008/06/scala-vs-erlang)
* [A presentation about F# that also mentions this issue](http://www.google.es/url?sa=t&source=web&ct=res&cd=7&url=http%3A%2F%2Fwww.nwcpp.org%2FDownloads%2F2008%2FFunctional_Programming_with_F.pdf&ei=f4pnSp6yJZ-OnQO7zYynDw&usg=AFQjCNGljK0Ax0j8jSWAT3eazA30IDNo4A&sig2=jHDxU-1wx3td8Pln4_77cw)
Buff, I hope it wasn't too bored, ;-) | Functional programming applied | [
"",
"java",
"scala",
"functional-programming",
""
] |
I am trying to use a little inheritance in a Python program I am working on. I have a base class, User, which implements all of the functionality of a user. I am adding the concept of an unapproved user, which is just like a user, with the addition of a single method.
The User class has some methods that return a User object. This will not work when I subclass, since I will end up having an UnapprovedUser return a User, preventing me from calling this method, among other things.
```
class User(object):
base_dn = 'ou=Users,dc=example,dc=org'
@classmethod
def get(cls, uid):
ldap_data = LdapUtil.get(uid + ',' + self.base_dn)
return User._from_ldap(ldap_data)
class UnapprovedUser(User):
base_dn = 'ou=UnapprovedUsers,dc=example,dc=org'
def approve(self):
new_dn = '' # the new DN
LdapUtil.move(self.dn, new_dn)
```
The `get()` and `_from_ldap()` methods are the same for both classes, though the `get()` method in UnapprovedUser needs to return an UnapprovedUser object, not a User.
How can I cast one of the instances of User that I get from `User.get()` into an UnapprovedUser?
I want to do something like:
```
class UnapprovedUser(User):
# continued from before
@classmethod
def get(cls, uid):
user = super(UnapprovedUser, cls).get(uid)
return (UnapprovedUser) user # invalid syntax
```
so that I can wrap the method from the parent and simply cast the returned value to the correct class. Then again, doing it that way could lead to the parent using their value for `self.base_dn`, which would break everything. | Rather than "casting", I think you really want to create an `UnapprovedUser` rather than a `User` when invoking `UnapprovedUser.get()`. To do that:
Change `User.get` to actually use the `cls` argument that's passed-in:
```
@classmethod
def get(cls, uid):
ldap_data = LdapUtil.get(uid + ',' + self.base_dn)
return cls._from_ldap(ldap_data)
```
You'll need to do something similar in `_from_ldap`. You didn't list the code for `_from_ldap`, but I assume that at some point it does something like:
```
result = User(... blah ...)
```
You want to replace this with:
```
result = cls(... blah ...)
```
Remember: in Python a class object is a callable that constructs instances of that class. So you can use the `cls` parameter of a classmethod to construct instances of the class used to call the classmethod. | In a class method, the class is passed in in the cls parameter. So instead of User.something do cls.something. Done!
That said, I'm not sure I would do this with two types of user. I'm not 100% sure what you mean with "Approved" here, I it seems to me to be one of two things.
1. It may mean the user isn't really logged in yet. In that case I'd have a special Anonymous User instance for not logged in users. Since you are moving the DN when approving, this seems more likely to be what you are doing.
2. It may mean that the user hasn't been approved as a full member or something. This is just a special case of permission handling, and you are probably going to end up wanting to have more permissions later. I'd instead add support for giving the user roles, and making "Approved" a role.
If you mean something else with approved, feel free to ignore this. :-) | How do you cast an instance to a derived class? | [
"",
"python",
"oop",
"inheritance",
""
] |
I'm trying to use the context menu in a listview to run some code that requires data from which item it originated from.
I initially just did this:
XAML:
```
<ListView x:Name="lvResources" ScrollViewer.VerticalScrollBarVisibility="Visible">
<ListView.Resources>
<ContextMenu x:Key="resourceContextMenu">
<MenuItem Header="Get Metadata" Name="cmMetadata" Click="cmMetadata_Click" />
</ContextMenu>
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="ContextMenu" Value="{StaticResource resourceContextMenu}" />
</Style>
</ListView.ItemContainerStyle>
...
```
C#:
```
private void cmMetadata_Click(object sender, RoutedEventArgs e)
{
// code that needs item data here
}
```
But I found that the originating listview item was not accessible that way.
I've read some tactics about how to get around this, like intercepting the MouseDown event and setting a private field to the listviewitem that was clicked, but that doesn't sit well with me as it seems a bit hacky to pass data around that way. And WPF is supposed to be easy, right? :) I've read this [SO question](https://stackoverflow.com/questions/747872/wpf-displaying-a-context-menu-for-a-gridviews-items) and this [MSDN forum question](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/03c902a7-6543-4c83-a1b7-0d880bf86c8c), but I'm still not sure how to really do this, as neither of those articles seem to work in my case. Is there a better way to pass the item that was clicked on through to the context menu?
Thanks! | So I decided to try and implement a command solution. I'm pretty pleased with how it's working now.
First, created my command:
```
public static class CustomCommands
{
public static RoutedCommand DisplayMetadata = new RoutedCommand();
}
```
Next in my custom listview control, I added a new command binding to the constructor:
```
public SortableListView()
{
CommandBindings.Add(new CommandBinding(CustomCommands.DisplayMetadata, DisplayMetadataExecuted, DisplayMetadataCanExecute));
}
```
And also there, added the event handlers:
```
public void DisplayMetadataExecuted(object sender, ExecutedRoutedEventArgs e)
{
var nbSelectedItem = (MyItem)e.Parameter;
// do stuff with selected item
}
public void DisplayMetadataCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
e.Handled = true;
}
```
I was already using a style selector to dynamically assign styles to the listview items, so instead of doing this in the xaml, I have to set the binding in the codebehind. You could do it in the xaml as well though:
```
public override Style SelectStyle(object item, DependencyObject container)
{
ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(container);
MyItem selectedItem = (MyItem)item;
Style s = new Style();
var listMenuItems = new List<MenuItem>();
var mi = new MenuItem();
mi.Header= "Get Metadata";
mi.Name= "cmMetadata";
mi.Command = CustomCommands.DisplayMetadata;
mi.CommandParameter = selectedItem;
listMenuItems.Add(mi);
ContextMenu cm = new ContextMenu();
cm.ItemsSource = listMenuItems;
// Global styles
s.Setters.Add(new Setter(Control.ContextMenuProperty, cm));
// other style selection code
return s;
}
```
I like the feel of this solution much better than attempting to set a field on mouse click and try to access what was clicked that way. | Similar to Charlie's answer, but shouldn't require XAML changes.
```
private void cmMetadata_Click(object sender, RoutedEventArgs e)
{
MenuItem menu = sender as MenuItem;
ListViewItem lvi = lvResources.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListViewItem;
}
``` | Determining which ListViewItem was clicked on in a ListView when executing a ContextMenu MenuItem | [
"",
"c#",
"wpf",
"listview",
"contextmenu",
"listviewitem",
""
] |
I authored a Java freeware (closed source) product that I deploy on a web host and distribute via JNLP, inclusive Linux clients.
I plan to suggest this product for inclusion into several Linux distro, if possible "as is" (JNLP-based).
Can I already contact distros, or I need to reconfigure something (deploy on another host, convert JNLP to something, etc.)? What is your experience? | Figure out a way to package it properly on each of the platforms you want to include your software on, and prepare for rigid software management (freezing, multiple versions etc if you want the code included in the standard installation.
Otherwise you may be able to create a simple package just containing the link to the JNLP page which may be included in the non-core parts. It is worth a try.
What applcation are we talking about? | I would say that a freeware JNLP application is pretty much the opposite of what Linux distributions would tend to include.
Firstly, JNLP will not work with the native package management solution. If you wanted to get an application included in a distribution it would need to be package in the native format and updated in the standard way.
Secondly, most distributions will favour open source packages and many will not include non open source packages in their default repositories. Some distributions may have specical non-free repositories. Up until OpenJDK you may not even Java itself would be in these repositories.
In my opinion you would be better trying to build a user base on your own as you then have complete control over releases etc. | Hosting Java Web Start application for inclusion into Linux distros | [
"",
"java",
"linux",
"hosting",
"packaging",
"jnlp",
""
] |
I have 2 procedures. One that builds a temp table and another (or several others) that use a temp table that's created in the first proc. Is this considered bad form? I'm walking into an existing codebase here and it uses this pattern a lot. It certainly bothers me but I can't say that it's explicitly a bad idea. I just find it to be an annoying pattern -- something smells rotten but I can't say what. I'd prefer to build the table locally and then fill it with an exec. But that requires procs that only return one table, which is unusual in the existing codebase.
Do the gurus of SQL shy away from this sort of temp table sharing? If so, why? I'm trying to form a considered opinion about this and would like some input.
Would a view be a viable alternative?
What about performance? Would it be better to build a @table locally or build a #table in the "fill" proc?
There's a good discussion of all methods here: <http://www.sommarskog.se/share_data.html> | As a programming paradigm it is ugly because it involves passing out-of-band parameters ('context parameters') that are not explicitly called out in the procedure signatures. This creates hidden dependencies and leads to spaghetti effect.
But in the specific context of SQL, there is simply **no alternative**. SQL works with data sets and you cannot pass back and forth these data sets as procedure parameters. You have few alternatives:
* Pass through the client. All too obvious not a real option.
* XML or strings with delimiters types to represent results. Not a serious option by any stretch, they may give good 'programming' semantics (ie. [Demeter Law](http://en.wikipedia.org/wiki/Law_of_Demeter) conformance) but they really really suck when performance comes into play.
* shared tables (be it in tempdb or in appdb) like Raj suggest. You're loosing the #temp automated maintenance (cleanup on ref count goes to 0) and you have to be prepared for creation race conditions. Also they can grow large for no reason (they're no longer partitioned by session into separate rowsets, like #temp tables are).
* @tables. They're scoped to the declaration context (ie. the procedure) and cannot be passed back and forth between procedures. I also discovered [some nasty problems under memory pressure](https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=467035). | Sometimes this is the only way to go. If you need to do this, then **DOCUMENT, DOCUMENT, DOCUMENT** the facts. Here is one way to make it clear, put the table definition as a comment in the parameter section...
```
CREATE PROCEDURE xyz
(
@param1 int --REQUIRED, what it does
,@param2 char(1) --OPTIONAL, what it does
,@param3 varchar(25) --OPTIONAL, what it does
--this temp table is required and must be created in the calling procedure
--#TempXyz (RowID int not null primary key
-- ,DataValue varchar(10) not null
-- ,DateValue datetime null
-- )
)
```
Also document in the calling procedure where the temp table is created....
```
--** THIS TEMP TABLE IS PASSED BETWEEN STORED PROCEDURES **
--** ALL CHANGES MUST TAKE THIS INTO CONSIDERATION!!! **
CREATE TABLE #TempXyz
(RowID int not null primary key
,DataValue varchar(10) not null
,DateValue datetime null
)
``` | is sharing temp tables across procedures considered bad form? | [
"",
"sql",
"sql-server",
""
] |
Is .NET better than Win32 or the othe way around?
Which would be the pros \ cons of both, in what situations one would be better than the other.
Has Microsoft released .Net as a replacement for Win32?
I am not asking about the amount of projects needed to be maintained, but about
new projects being developed, and which would be better for what.
Do you think .Net lacks important stuff from win32 (without using dllImport )?
And do you think Win32 will be replaced by .Net
I am asking this, because i am having an argument with a friend of mine,
and as we both agree both must be studied in depth
My friend argues that .Net is incomplete, and i say that it can manage almost any task
non-driver related. Where does .Net fail? | These are all from my POV. Your mileage may vary.
Advantages of .NET:
* Cross platform capability (via Mono and .Net Core)
* Good selection of framework classes typically means less code.
* Easy integration of components, regardless of the language the component was coded in. (You like F#, or IronPython, great! Code your assemblies in whichever language is most appropriate.)
Disadvantages of .NET:
* .NET means different things to different people. (For example where does WPF come into the equation?)
* Sometimes DLLImport and/or PInvoke is the only way to get to the functionality you need, which means you lose the cross-platform capability.
Advantages of WIN32:
* If you know what you are doing, you can construct great applications with minimal dependencies.
* More suitable for "low level" operations than a .NET based solution.
Disadvantages of WIN32:
* If you don't know what you're doing, you can easily shoot yourself in the foot in a more application or system fatal manner.
* You frequently have to write code that you would get "for free" using .NET.
Both have their place, and will probably continue to exist until a true replacement OS ([Midori](http://en.wikipedia.org/wiki/Midori_%28operating_system%29)? Some form of web-based OS?) comes online and gains widespread acceptance. | .Net (or the WinForms parts, anyway) sits *on top of* Win32. Or, put another way, Win32 was used to build .Net forms components. So in that sense you can think of .Net as a set of pre-built win32 widgets. You can also think of .Net as the logical successor to MFC.
.Net also has the ability to call into the Win32 API directly when necessary, gives you garbage collection, a very nice class library in the BCL, and a lot of nice language features over C/C++ in C# and VB.Net.
What you lose to get all these things is a certain amount of independence. .Net is an add-on *framework* that is not shipped with all versions of windows by default, and therefore you have extra dependencies to worry about at deployment. You also have performance considerations to think about when using any high-level garbage collected language, where seemingly simple code might be doing a lot more than you expect behind the scenes. This is especially true for some of the winforms components. | Win32 vs .Net | [
"",
".net",
"c++",
"windows",
"winapi",
""
] |
I just downloaded a fresh copy of Tomcat6 to install on a development server. The server is running Win2k3 SP2 and Java6.
When I go to start Tomcat6 it reports the following:
```
D:\>d:\tomcat\bin\tomcat6.exe //TS/Tomcat6
[2009-07-14 15:26:38] [427 prunsrv.c] [error] The operation completed successfully.
[2009-07-14 15:26:38] [1336 prunsrv.c] [error] Load configuration failed
```
It seems like Tomcat is having config issues, but I'm not sure where to start looking. It's a bit surprising that Tomcat had this problem right out of the box. Is there any compatability problem between Java6 and Tomcat6? Why might the default config be failing? | Ok, Solved this one myself. It turns out that "Load configuration failed" was a red herring. This was caused by Tomcat being unable to load java. I discovered this in $CATALINA\_HOME\logs\jakarta\_service\_YYYMMDD.log.
I solved the problem by following these [instructions](http://vittoriop77.blogspot.com/2007/09/failed-creating-java-prunsrvc.html). Which basically amounts to copying msvcr71.dll to c:\windows\system32 | Just curious if your CATALINA\_HOME and JAVA\_HOME set? Those environment variables are prerequisite to run Tomcat. Go to Start-->My Computer (right click on it) -->Properties-->Advanced-->Environment Variables (button) and then set CATALINA\_HOME to the path of your Tomcat and JAVA\_HOME to the location of your JDK, also add JAVA\_HOME\bin to your PATH variable. | Tomcat6 won't start on Windows and Java6 | [
"",
"java",
"windows",
"tomcat",
""
] |
This might be something I can't do but...
```
parent.document.getElementById('<?php echo $_GET['song']; ?>')
.innerHTML = '<img src="heart.png" onmouseover="heartOver('');" >';
```
The `onmouseover="heartOver('');` portion breaks my JavaScript. Is there a way to escape the quotes so I can do this? | Escape nested quotes with a backslash: `\'`
Also, **never** echo user data without validating or sanitizing it:
```
$song = $_GET['song'];
// Validate HTML id (http://www.w3.org/TR/REC-html40/types.html#type-name)
if(!preg_match('/^[a-z][-a-z0-9_:\.]*$/', $song) {
// Display error because $song is invalid
}
```
OR
```
// Sanitize
$song = preg_replace('/(^[^a-z]*|[^-a-z0-9_:\.])/', '', $song);
``` | It's all just a matter of escaping the quotes properly.
```
parent.document.getElementById('<?php echo $_GET['song']; ?>').innerHTML =
'<a href="heart.php?action=unlove&song=<?php echo $song; ?>" target="hiddenframe">'
+ '<img src="images/heart.png" alt="Love!" onmouseover="heartOver(\'\');" width="16" height="16" border="0"></a>';
```
Also you're missing and end quote for the alt attribute. | How can I properly escape JavaScript in JavaScript? | [
"",
"javascript",
"escaping",
"quotes",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.