Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I need customers to be able to download PDFs of letters that have been sent to them.
I have read the threads about database versus filesystem storage of documents or images, and it does sound like the consensus is that, for anything more than just a few images, filesystem is the way to go.
What I want to know:
* would a reasonable alternative be to just store the letter details in the database, and recreate the PDF 'on the fly' when it is requested?
* Is that approach superior or inferior to fetching the PDF from the filesystem?
|
I'd store it off for two reasons
1) If you ever change how you generate the PDF, you probably don't want historical items to change. If you generate them every time, either they will change or you need to keep compatibility code to generate "old-style" records
2) Disk space is cheap. User's patience isn't. Unless you're really pressed for storage or pulling out of storage is harder than generating the PDF, be kind to your users and store it off.
Obviously if you create thousands of these an hour from a sparse dataset, you may not have the storage. But if you have the space, I'd vote for "use it"
|
If it is for archival purposes, I would definitely store the PDF because in future, your PDF generation script may change and then the letter will not be exactly the same as what was originally sent. The customer will be expecting it to be exactly the same.
It doesn't matter what approach is superior, sometimes it is better to go for what approach is safer.
|
Should I dynamically recreate a PDF, rather than store it in either the database or the filesystem?
|
[
"",
"c#",
"asp.net",
"sql-server-2005",
"itext",
""
] |
I have two tables in my database, called *ratings* and *movies*.
**Ratings:**
> `| id | movie_id | rating |`
**Movies:**
> `| id | title |`
A typical movie record might be like this:
> `| 4 | Cloverfield (2008) |`
and there may be several rating records for Cloverfield, like this:
> `| 21 | 4 | 3 |` (rating number 21, on movie number 4, giving it a rating of 3)
>
> `| 22 | 4 | 2 |` (rating number 22, on movie number 4, giving it a rating of 2)
>
> `| 23 | 4 | 5 |` (rating number 23k on movie number 4, giving it a rating of 5)
**The question:**
How do I create a JOIN query for only selecting the rows in the movie table that have more than `x` number of ratings in the ratings table? For example, in the above example if Cloverfield only had one rating in the ratings table and `x` was 2, it would not be selected.
Thanks for any help or advice!
|
Use the HAVING clause. Something along these lines:
```
SELECT movies.id, movies.title, COUNT(ratings.id) AS num_ratings
FROM movies
LEFT JOIN ratings ON ratings.movie_id=movies.id
GROUP BY movies.id
HAVING num_ratings > 5;
```
|
The JOIN method is somewhat stilted and confusing because that's not exactly what it was intended to do. The most direct (and in my opinion, easily human-parseable) method uses EXISTS:
```
SELECT whatever
FROM movies m
WHERE EXISTS( SELECT COUNT(*)
FROM reviews
WHERE movie_id = m.id
HAVING COUNT(*) > xxxxxxxx )
```
Read it out loud -- SELECT something FROM movies WHERE there EXIST rows in Reviews where the movie\_id matches and there are > xxxxxx rows
|
How can I create a MySQL JOIN query for only selecting the rows in one table where a certain number of references to that row exist in another table?
|
[
"",
"sql",
"mysql",
""
] |
I'm hoping there's something in the same conceptual space as the old VB6 `IsNumeric()` function?
|
**2nd October 2020:** note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point "`.`":
```
function isNumeric(str) {
if (typeof str != "string") return false // we only process strings!
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}
```
---
## To check if a variable (including a string) is a number, check if it is not a number:
This works regardless of whether the variable content is a string or number.
```
isNaN(num) // returns true if the variable does NOT contain a valid number
```
### Examples
```
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
isNaN('') // false
isNaN(' ') // false
isNaN(false) // false
```
Of course, you can negate this if you need to. For example, to implement the `IsNumeric` example you gave:
```
function isNumeric(num){
return !isNaN(num)
}
```
## To convert a string containing a number into a number:
Only works if the string *only* contains numeric characters, else it returns `NaN`.
```
+num // returns the numeric value of the string, or NaN
// if the string isn't purely numeric characters
```
### Examples
```
+'12' // 12
+'12.' // 12
+'12..' // NaN
+'.12' // 0.12
+'..12' // NaN
+'foo' // NaN
+'12px' // NaN
```
## To convert a string loosely to a number
Useful for converting '12px' to 12, for example:
```
parseInt(num) // extracts a numeric value from the
// start of the string, or NaN.
```
### Examples
```
parseInt('12') // 12
parseInt('aaa') // NaN
parseInt('12px') // 12
parseInt('foo2') // NaN These last three may
parseInt('12a5') // 12 be different from what
parseInt('0x10') // 16 you expected to see.
```
## Floats
Bear in mind that, unlike `+num`, `parseInt` (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use `parseInt()` *because of* this behaviour, [you're probably better off using another method instead](https://parsebox.io/dthree/gyeveeygrngl)):
```
+'12.345' // 12.345
parseInt(12.345) // 12
parseInt('12.345') // 12
```
## Empty strings
Empty strings may be a little counter-intuitive. `+num` converts empty strings or strings with spaces to zero, and `isNaN()` assumes the same:
```
+'' // 0
+' ' // 0
isNaN('') // false
isNaN(' ') // false
```
But `parseInt()` does not agree:
```
parseInt('') // NaN
parseInt(' ') // NaN
```
|
If you're just trying to check if a string is a whole number (no decimal places), regex is a good way to go. Other methods such as `isNaN` are too complicated for something so simple.
```
function isNumeric(value) {
return /^-?\d+$/.test(value);
}
console.log(isNumeric('abcd')); // false
console.log(isNumeric('123a')); // false
console.log(isNumeric('1')); // true
console.log(isNumeric('1234567890')); // true
console.log(isNumeric('-23')); // true
console.log(isNumeric(1234)); // true
console.log(isNumeric(1234n)); // true
console.log(isNumeric('123.4')); // false
console.log(isNumeric('')); // false
console.log(isNumeric(undefined)); // false
console.log(isNumeric(null)); // false
```
To only allow *positive* whole numbers use this:
```
function isNumeric(value) {
return /^\d+$/.test(value);
}
console.log(isNumeric('123')); // true
console.log(isNumeric('-23')); // false
```
|
How can I check if a string is a valid number?
|
[
"",
"javascript",
"validation",
"numeric",
""
] |
We have inherited an ant build file but now need to deploy to both 32bit and 64bit systems.
The non-Java bits are done with GNUMakefiles where we just call "uname" to get the info. Is there a similar or even easier way to mimic this with ant?
|
you can get at the java system properties (<http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperties()>) from ant with ${os.arch}. other properties of interest might be os.name, os.version, sun.cpu.endian, and sun.arch.data.model.
|
Late to the party, but what the heck...
${os.arch} only tells you if the JVM is 32/64bit. You may be running the 32bit JVM on a 64bit OS. Try this:
```
<var name ="os.bitness" value ="unknown"/>
<if>
<os family="windows"/>
<then>
<exec dir="." executable="cmd" outputproperty="command.ouput">
<arg line="/c SET ProgramFiles(x86)"/>
</exec>
<if>
<contains string="${command.ouput}" substring="Program Files (x86)"/>
<then>
<var name ="os.bitness" value ="64"/>
</then>
<else>
<var name ="os.bitness" value ="32"/>
</else>
</if>
</then>
<elseif>
<os family="unix"/>
<then>
<exec dir="." executable="/bin/sh" outputproperty="command.ouput">
<arg line="/c uname -m"/>
</exec>
<if>
<contains string="${command.ouput}" substring="_64"/>
<then>
<var name ="os.bitness" value ="64"/>
</then>
<else>
<var name ="os.bitness" value ="32"/>
</else>
</if>
</then>
</elseif>
</if>
<echo>OS bitness: ${os.bitness}</echo>
```
**EDIT:**
As @GreenieMeanie pointed out, this requires the ant-contrib library from ant-contrib.sourceforge.net
|
How to determine build architecture (32bit / 64bit) with ant?
|
[
"",
"java",
"ant",
"build",
"64-bit",
""
] |
I have a site that requires Windows Authentication the application obtains the credential from the Security.Prinicipal once the user is autenticated the problem is that my credentials on my local environment are different that the ones stored in the DB and the user preferences cannot be obtain. i am doing the following workaround in order to deal with this issue.
```
#if DEBUG
var myUser = userBL.GetSingle(@"desiredDomain\otherUserName");
#else
var myUser = userBL.GetSingle(HttpApplication.User.Identity.Name);
#endif
Session.Add("User",myUser);
```
is there any other way rather than impersonating or the above mentioned workaorund to change the the value of HttpApplication.User.Identity.Name this is beacuse I have to change my code everytime I need to commit into repository or deploy the App
|
While you could alter userBL, why wouldn't you instead alter the database records to reflect that they're in a different domain. I'm assuming you're not hitting the production database, so there should be no issues with a 'sanitizing' step that makes the database useable for dev/test.
e.g.
```
UPDATE Users
SET
UserName = REPLACE(UserName, '\\ProductionDomain\', '\\DevDomain\')
```
1. using #if DEBUG is bad for this sort of thing. Someone could/should legitimately load a debug version of code on production, and all of a sudden logins are broken. These things are better controlled in a web.config when they are needed.
2. Developers should be working against a dev copy of the database. It is very typical to sanitize some aspects of the database when the copy is made. Sometimes this is for privacy regulations (e.g. obscuring users real names and logins)
|
Have you looked into using Impersonation in Web.Config to set the id to your test credentials. I would presume that you have a "test" web.config and a "production" web.config. This way you won't have to worry about removing it when you go live.
|
How to change HttpApplication.User.Identity.Name on a local environment?
|
[
"",
"c#",
".net",
"security",
"authentication",
""
] |
I am trying to read an XML-file from another server. However the the company that's hosting me seems to have turned of the file\_get\_contents function from retrieving files for files from other servers (and their support is not very bright and it takes forever for them to answer). So I need a work around in some way.
This is my current code
```
$url = urldecode( $object_list_url );
$xmlstr = file_get_contents ( $url );
$obj = new SimpleXMLElement ( $xmlstr, LIBXML_NOCDATA );
```
|
You could use [cURL](http://www.php.net/curl) (if that's not been disabled).
Something like this:
```
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$xmlstr = curl_exec($c);
```
|
The ini var you're referring to is `allow_url_fopen`. To check, run this script:
```
var_dump(ini_get('allow_url_fopen'));
```
Ask your host to turn that ini value on (if it's disabled - it's on by default).
You should not be able to access any remote url without that ini setting on.
Also an idea if they won't could be to try [`copy`](http://docs.php.net/manual/en/function.copy.php)ing the file to your server. I expect all filesystem functions will be covered by that ini setting but it's always worth a try.
|
The number of ways of reading an xml file from another server in PHP?
|
[
"",
"php",
"xml",
"apache",
""
] |
Another poster asked about [preferred syntax for infinite loops](https://stackoverflow.com/questions/224138/infinite-loops-top-or-bottom).
A follow-up question: *Why* do you use infinite loops in your code? I typically see a construct like this:
```
for (;;) {
int scoped_variable = getSomeValue();
if (scoped_variable == some_value) {
break;
}
}
```
Which lets you get around not being able to see the value of scoped\_variable in the `for` or `while` clause. What are some other uses for "infinite" loops?
|
A loop like:
```
while (true)
{
// do something
if (something else) break;
// do more
}
```
lets you break out of the loop in the middle, rather than at the start (while/for) or end (do-while).
If you've got a complex condition, you might also want to use this style to make the code clearer.
|
I use an infinite loop for the body of my embedded control code, since it is designed to run forever once it is started.
|
Why use infinite loops?
|
[
"",
"c++",
"coding-style",
""
] |
I have a bunch of JSP files and backend in Tomcat. I have 3 different versions of JSP with same logic inside but with different layouts. So if I change some logic I have three JSP file to fix.
What is the proper soution for such a scenario? I thought of some XML and XSLT stack: backend gives only data in XML and than for each layout I have XSLT that does some magic.
Just imagine that you need to provide stackoverflow in various languages in JSP. Logic the same but layout different.
Could you point me into some direction?
|
Learn about MVC (Model View Controller) and the idea that JSP should be the View part of it and should not contain any logic whatsoever. Logic belongs in a Model class.
|
This is usually solved by using some templating engine - you create smaller page fragments, and then you declare to the template engine that certain views should consist of these parts, put together in a certain way.
Struts tiles is the classic example in the Java world, but it is really getting old and crufty compared to more modern framworks in Java and other languages. Tapestry and Wicket are two more modern ones (haven't used them though).
For only 3 pages applying a whole web framework is probably overkill though, but if your site grows...
|
Different layouts and i18n in JSP application
|
[
"",
"java",
"model-view-controller",
"jsp",
"tomcat",
""
] |
I saw a code snippet yesterday in one of the responses here on StackOverflow that intrigued me. It was something like this:
```
List<string> myList = new List<string> {"aBc", "HELLO", "GoodBye"};
myList.ForEach(d=>d.ToLower());
```
I was hoping I could use it to convert all items in myList to lowercase. However, it doesn't happen... after running this, the casing in myList is unchanged.
So my question is whether there IS a way, using LINQ and Lambda expressions to easily iterate through and modify the contents of a list in a manner similar to this.
Thanks,
Max
|
Easiest approach:
```
myList = myList.ConvertAll(d => d.ToLower());
```
Not too much different than your example code. `ForEach` loops the original list whereas `ConvertAll` creates a new one which you need to reassign.
|
That's because ToLower **returns** a lowercase string rather than converting the original string. So you'd want something like this:
```
List<string> lowerCase = myList.Select(x => x.ToLower()).ToList();
```
|
How to Convert all strings in List<string> to lower case using LINQ?
|
[
"",
"c#",
"linq",
"lambda",
"foreach",
""
] |
I have a Stored procedure which schedules a job. This Job takes a lot of time to get completed (approx 30 to 40 min). I need to get to know the status of this Job.
Below details would help me
1) How to see the list of all jobs that have got scheduled for a future time and are yet to start
2) How to see the the list of jobs running and the time span from when they are running
3) How to see if the job has completed successfully or has stoped in between because of any error.
|
You could try using the system stored procedure sp\_help\_job. This returns information on the job, its steps, schedules and servers. For example
```
EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'
```
[SQL Books Online](http://msdn.microsoft.com/en-us/library/ms186722(SQL.90).aspx) should contain lots of information about the records it returns.
For returning information on multiple jobs, you could try querying the following system tables which hold the various bits of information on the job
* msdb.dbo.SysJobActivity (thanks to @kenny-evitt)
* msdb.dbo.SysJobs
* msdb.dbo.SysJobSteps
* msdb.dbo.SysJobSchedules
* msdb.dbo.SysJobServers
* msdb.dbo.SysJobHistory
Their names are fairly self-explanatory (apart from SysJobServers which hold information on when the job last run and the outcome).
Again, information on the fields can be found at MSDN. For example, check out the page for [SysJobs](http://msdn.microsoft.com/en-us/library/ms189817.aspx)
|
I would like to point out that none of the T-SQL on this page will work precisely because none of them join to the **syssessions** table to get only the current session and therefore could include false positives.
See this for reference: [What does it mean to have jobs with a null stop date?](https://stackoverflow.com/questions/13037668/what-does-it-mean-to-have-jobs-with-a-null-stop-date/13038752#13038752)
You can also validate this by analyzing the **sp\_help\_jobactivity** procedure in **msdb**.
I realize that this is an old message on SO, but I found this message only partially helpful because of the problem.
```
SELECT
job.name,
job.job_id,
job.originating_server,
activity.run_requested_date,
DATEDIFF( SECOND, activity.run_requested_date, GETDATE() ) as Elapsed
FROM
msdb.dbo.sysjobs_view job
JOIN
msdb.dbo.sysjobactivity activity
ON
job.job_id = activity.job_id
JOIN
msdb.dbo.syssessions sess
ON
sess.session_id = activity.session_id
JOIN
(
SELECT
MAX( agent_start_date ) AS max_agent_start_date
FROM
msdb.dbo.syssessions
) sess_max
ON
sess.agent_start_date = sess_max.max_agent_start_date
WHERE
run_requested_date IS NOT NULL AND stop_execution_date IS NULL
```
|
How can I determine the status of a job?
|
[
"",
"sql",
"sql-server-2005",
"t-sql",
"stored-procedures",
""
] |
What is the difference between `ref` and `out` parameters in .NET? What are the situations where one can be more useful than the other? What would be a code snippet where one can be used and another can't?
|
They're pretty much the same - the only difference is that a variable you pass as an `out` parameter doesn't need to be initialized but passing it as a `ref` parameter it has to be set to something.
```
int x;
Foo(out x); // OK
int y;
Foo(ref y); // Error: y should be initialized before calling the method
```
`Ref` parameters are for data that might be modified, `out` parameters are for data that's an additional output for the function (eg `int.TryParse`) that are already using the return value for something.
|
[Why does C# have both 'ref' and 'out'?](http://evacion.wordpress.com/2009/08/12/why-does-c-have-both-ref-and-out/)
The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning.
In contrast ref parameters are considered initially assigned by the caller. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.
So, `out` means out, while `ref` is for in and out.
These correspond closely to the `[out]` and `[in,out]` parameters of COM interfaces, the advantages of `out` parameters being that callers need not pass a pre-allocated object in cases where it is not needed by the method being called - this avoids both the cost of allocation, and any cost that might be associated with marshaling (more likely with COM, but not uncommon in .NET).
|
Difference between ref and out parameters in .NET
|
[
"",
"c#",
".net",
""
] |
I have a ListBox that when in focus, and when I have an item selected returns a valid SelectedIndex. If I have a valid SelectedIndex and I click on a TextBox on the same Forum, the SelectedIndex now becomes -1. However I want it to keep its SelectedIndex from changing. How would I go about doing this?
|
ListBox will keep it's SelectedIndex regardless of focus.
I tested it on a blank project with one ListBox, one TextBox and one Label used to display the ListBox's SelectedIndex. Under both the ListBox's SelectedIndexChanged and the TextBox's TextChanged events I updated the Label with the ListBox's SelectedIndex
There must be something else going on to cause the Selected Index to change to -1.
|
I had the same issue as original poster.
I couldn't figure it out totally but it seems like when you have the listbox bound to an observable collection and the collection gets changed that the selected item loses the focus.
I hacked around the issue by saving the selected index in a variable and resetting it if the selected index was -1 (and it was valid to restore it)
|
ListBox keep selection after losing focus
|
[
"",
"c#",
".net",
"listbox",
""
] |
Is it possible to set the cursor to 'wait' on the entire html page in a simple way? The idea is to show the user that something is going on while an ajax call is being completed. The code below shows a simplified version of what I tried and also demonstrate the problems I run into:
1. if an element (#id1) has a cursor style set it will ignore the one set on body (obviously)
2. some elements have a default cursor style (a) and will not show the wait cursor on hover
3. the body element has a certain height depending on the content and if the page is short, the cursor will not show below the footer
The test:
```
<html>
<head>
<style type="text/css">
#id1 {
background-color: #06f;
cursor: pointer;
}
#id2 {
background-color: #f60;
}
</style>
</head>
<body>
<div id="id1">cursor: pointer</div>
<div id="id2">no cursor</div>
<a href="#" onclick="document.body.style.cursor = 'wait'; return false">Do something</a>
</body>
</html>
```
Later edit...
It worked in firefox and IE with:
```
div#mask { display: none; cursor: wait; z-index: 9999;
position: absolute; top: 0; left: 0; height: 100%;
width: 100%; background-color: #fff; opacity: 0; filter: alpha(opacity = 0);}
<a href="#" onclick="document.getElementById('mask').style.display = 'block'; return false">
Do something</a>
```
The problem with (or feature of) this solution is that it will prevent clicks because of the overlapping div (thanks Kibbee)
Later later edit...
A simpler solution from Dorward:
```
.wait, .wait * { cursor: wait !important; }
```
and then
```
<a href="#" onclick="document.body.className = 'wait'; return false">Do something</a>
```
This solution only shows the wait cursor but allows clicks.
|
I understand you may not have control over this, but you might instead go for a "masking" div that covers the entire body with a z-index higher than 1. The center part of the div could contain a loading message if you like.
Then, you can set the cursor to wait on the div and don't have to worry about links as they are "under" your masking div. Here's some example CSS for the "masking div":
```
body { height: 100%; }
div#mask { cursor: wait; z-index: 999; height: 100%; width: 100%; }
```
|
If you use this slightly modified version of the CSS you posted from Dorward,
```
html.wait, html.wait * { cursor: wait !important; }
```
you can then add some really simple [jQuery](http://api.jquery.com/) to work for all ajax calls:
```
$(document).ready(function () {
$(document).ajaxStart(function () { $("html").addClass("wait"); });
$(document).ajaxStop(function () { $("html").removeClass("wait"); });
});
```
or, for older jQuery versions (before 1.9):
```
$(document).ready(function () {
$("html").ajaxStart(function () { $(this).addClass("wait"); });
$("html").ajaxStop(function () { $(this).removeClass("wait"); });
});
```
|
Wait cursor over entire html page
|
[
"",
"javascript",
"html",
"css",
"dynamic-css",
""
] |
I am trying to include a value from a database table within the value element of an input field.
This is what I have, but it is not working:
```
?><input type="text" size="10" value="<?= date("Y-m-d",
strtotime($rowupd['upcoming_event_featured_date'])) ?>" name="upcoming_event_featured_date"
id="keys"/><?php
```
I have done this before, but I usually print it out like this:
```
print '<input type="text" size="10" value="'.date("Y-m-d",
strtotime($rowupd['upcoming_event_featured_date'])).'" name="upcoming_event_featured_date"
id="keys"/>';
```
What is the appropriate way of doing this without using `print ''`?
|
It's a good idea to always use full PHP tags, because that will keep your app from breaking if you move to a different server or your config is changed not to allow short tags.
```
?>
<input type="text" size="10" value="<?php
echo(date("Y-m-d", strtotime($rowupd['upcoming_event_featured_date'])));
?>"name="upcoming_event_featured_date" id="keys"/><?php
```
Also, note that you are missing the `;` from the end of your PHP code.
You may find it better to keep the whole thing in PHP too, and just `echo()` out the HTML, as that will keep you from having to switch back and forth from PHP to HTML parsing.
|
As some other replies have mentioned, make sure `short_open_tag` is enabled in your php.ini. This lets you use the `<?=` syntax. A lot of people recommend not using short tags, since not all servers allow them, but if you're sure you won't be moving this to another server, I think it's fine.
Besides that, I don't know of any technical reason to choose one way over the other. Code readability should be your main focus. For example, you might want to set your value to a variable before outputting it:
```
$featured_date = date("Y-m-d",strtotime($rowupd['featured_date']));
?><input type="text" value="<?=$featured_date?>" name="featured_date" /><?php
```
In fact, I'd try to do as little processing as possible while you're in the middle of a block of HTML. Things will be a lot cleaner if you define all your variables at the beginning of the script, then output all of the HTML, inserting the variables as needed. You're almost getting into templating at that point, but without needing the overhead of a template engine.
|
How do I include a php variable within the value element of an html input tag?
|
[
"",
"php",
"html",
""
] |
Is there any library function for this purpose, so I don't do it by hand and risk ending in TDWTF?
```
echo ceil(31497230840470473074370324734723042.6);
// Expected result
31497230840470473074370324734723043
// Prints
<garbage>
```
|
This will work for you:
```
$x = '31497230840470473074370324734723042.9';
bcscale(100);
var_dump(bcFloor($x));
var_dump(bcCeil($x));
var_dump(bcRound($x));
function bcFloor($x)
{
$result = bcmul($x, '1', 0);
if ((bccomp($result, '0', 0) == -1) && bccomp($x, $result, 1))
$result = bcsub($result, 1, 0);
return $result;
}
function bcCeil($x)
{
$floor = bcFloor($x);
return bcadd($floor, ceil(bcsub($x, $floor)), 0);
}
function bcRound($x)
{
$floor = bcFloor($x);
return bcadd($floor, round(bcsub($x, $floor)), 0);
}
```
Basically it finds the flooy by multiplying by one with zero precision.
Then it can do ceil / round by subtracting that from the total, calling the built in functions, then adding the result back on
Edit: fixed for -ve numbers
|
**UPDATE: See my improved answer here: [How to ceil, floor and round bcmath numbers?](https://stackoverflow.com/questions/1642614/how-to-ceil-floor-and-round-bcmath-numbers/1653826#1653826).**
---
These functions seem to make more sense, at least to me:
```
function bcceil($number)
{
if ($number[0] != '-')
{
return bcadd($number, 1, 0);
}
return bcsub($number, 0, 0);
}
function bcfloor($number)
{
if ($number[0] != '-')
{
return bcadd($number, 0, 0);
}
return bcsub($number, 1, 0);
}
function bcround($number, $precision = 0)
{
if ($number[0] != '-')
{
return bcadd($number, '0.' . str_repeat('0', $precision) . '5', $precision);
}
return bcsub($number, '0.' . str_repeat('0', $precision) . '5', $precision);
}
```
**They support negative numbers and the precision argument for the bcround() function.**
Some tests:
```
assert(bcceil('4.3') == ceil('4.3')); // true
assert(bcceil('9.999') == ceil('9.999')); // true
assert(bcceil('-3.14') == ceil('-3.14')); // true
assert(bcfloor('4.3') == floor('4.3')); // true
assert(bcfloor('9.999') == floor('9.999')); // true
assert(bcfloor('-3.14') == floor('-3.14')); // true
assert(bcround('3.4', 0) == number_format('3.4', 0)); // true
assert(bcround('3.5', 0) == number_format('3.5', 0)); // true
assert(bcround('3.6', 0) == number_format('3.6', 0)); // true
assert(bcround('1.95583', 2) == number_format('1.95583', 2)); // true
assert(bcround('5.045', 2) == number_format('5.045', 2)); // true
assert(bcround('5.055', 2) == number_format('5.055', 2)); // true
assert(bcround('9.999', 2) == number_format('9.999', 2)); // true
```
|
How to round/ceil/floor a bcmath number in PHP?
|
[
"",
"php",
"largenumber",
"bcmath",
""
] |
I need to use an alias in the WHERE clause, but It keeps telling me that its an unknown column. Is there any way to get around this issue? I need to select records that have a rating higher than x. Rating is calculated as the following alias:
```
sum(reviews.rev_rating)/count(reviews.rev_id) as avg_rating
```
|
You could use a HAVING clause, which *can* see the aliases, e.g.
```
HAVING avg_rating>5
```
but in a where clause you'll need to repeat your expression, e.g.
```
WHERE (sum(reviews.rev_rating)/count(reviews.rev_id))>5
```
BUT! Not all expressions will be allowed - using an aggregating function like SUM will not work, in which case you'll need to use a HAVING clause.
From the [MySQL Manual](http://dev.mysql.com/doc/refman/5.0/en/select.html):
> It is not allowable to refer to a
> column alias in a WHERE clause,
> because the column value might not yet
> be determined when the WHERE clause
> is executed. See [Section B.1.5.4,
> “Problems with Column Aliases”](http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html).
|
I don't know if this works in mysql, but using sqlserver you can also just wrap it like:
```
select * from (
-- your original query
select .. sum(reviews.rev_rating)/count(reviews.rev_id) as avg_rating
from ...) Foo
where Foo.avg_rating ...
```
|
Can you use an alias in the WHERE clause in mysql?
|
[
"",
"mysql",
"sql",
"having",
"having-clause",
""
] |
How would you program a C/C++ application that could run without opening a window or console?
|
When you write a WinMain program, you automatically get the /SUBSYSTEM option to be windows in the compiler. (Assuming you use Visual Studio). For any other compiler a similar option might be present but the flag name might be different.
This causes the compiler to create an entry in the executable file format ([PE format](http://webster.cs.ucr.edu/Page_TechDocs/pe.txt)) that marks the executable as a windows executable.
Once this information is present in the executable, the system loader that starts the program will treat your binary as a windows executable and not a console program and therefore it does not cause console windows to automatically open when it runs.
But a windows program need not create any windows if it need not want to, much like all those programs and services that you see running in the taskbar, but do not see any corresponding windows for them. This can also happen if you create a window but opt not to show it.
All you need to do, to achieve all this is,
```
#include <Windows.h>
int WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int cmdShow)
{
/* do your stuff here. If you return from this function the program ends */
}
```
The reason you require a WinMain itself is that once you mark the subsystem as Windows, the linker assumes that your entry point function (which is called after the program loads and the C Run TIme library initializes) will be WinMain and not main. If you do not provide a WinMain in such a program you will get an un-resolved symbol error during the linking process.
|
**In windows:**
```
#include <windows.h>
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
// <-- Program logic here
return 0;
}
```
Be sure to use the /SUBSYSTEM linker switch as mentioned by Adam Mitz.
**On other platforms:**
```
int main(int argc, char**argv)
{
// <-- Program logic here
return 0;
}
```
|
Create an Application without a Window
|
[
"",
"c++",
"c",
"winapi",
""
] |
> **Possible Duplicate:**
> [How costly is .NET reflection?](https://stackoverflow.com/questions/25458/how-costly-is-net-reflection)
I am currently in a programming mentality that reflection is my best friend. I use it a lot for dynamic loading of content that allows "loose implementation" rather than strict interfaces, as well as a lot of custom attributes.
What is the "real" cost to using reflection?
Is it worth the effort for frequently reflected types to have cached reflection, such as our own pre-LINQ DAL object code on all the properties to table definitions?
Would the caching memory footprint outwieght the reflection CPU usage?
|
Reflection requires a large amount of the type metadata to be loaded and then processed. This can result in a larger memory overhead and slower execution. According to [this article](http://www.west-wind.com/WebLog/posts/351.aspx) property modification is about 2.5x-3x slower and method invocation is 3.5x-4x slower.
Here is an excellent [MSDN article](http://web.archive.org/web/20150118044646/http://msdn.microsoft.com/en-us/magazine/cc163759.aspx) outlining how to make reflection faster and where the overhead is. I highly recommend reading if you want to learn more.
There is also an element of complexity that reflection can add to the code that makes it substantially more confusing and hence difficult to work with. Some people, like [Scott Hanselman](http://www.hanselman.com/blog/CategoryView.aspx?category=Back+to+Basics&page=2) believe that by using reflection you often make more problems than you solve. This is especially the case if your teams is mostly junior devs.
You may be better off looking into the DLR (Dynamic Language Runtime) if you need alot of dynamic behaviour. With the new changes coming in .NET 4.0 you may want to see if you can incorporate some of it into your solution. The added support for dynamic from VB and C# make using dynamic code very elegant and creating your own dynamic objects fairly straight forward.
Good luck.
EDIT: I did some more poking around Scott's site and found this [podcast](http://www.hanselman.com/blog/HanselminutesPodcast27Reflection.aspx) on reflection. I have not listened to it but it might be worth while.
|
There are lots of things you can do to speed up reflection. For example, if you are doing lots of property-access, then [HyperDescriptor](http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx) might be useful.
If you are doing a lot of method-invoke, then you can cache methods to typed delegates using `Delegate.CreateDelegate` - this then does the type-checking etc only once (during `CreateDelegate`).
If you are doing a lot of object construction, then `Delegate.CreateDelegate` won't help (you can't use it on a constructor) - but (in 3.5) `Expression` can be used to do this, again compiling to a typed delegate.
So yes: reflection is slow, but you can optimize it without too much pain.
|
What is the "cost" of .NET reflection?
|
[
"",
"c#",
".net",
"optimization",
"reflection",
""
] |
I have a string.
```
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
```
I need to add a newline after every occurence of "@" symbol in the string.
My Output should be like this
```
fkdfdsfdflkdkfk@
dfsdfjk72388389@
kdkfkdfkkl@
jkdjkfjd@
jjjk@
```
|
Use `Environment.NewLine` whenever you want in any string. An example:
```
string text = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
text = text.Replace("@", "@" + System.Environment.NewLine);
```
|
You can add a new line character after the @ symbol like so:
```
string newString = oldString.Replace("@", "@\n");
```
You can also use the `NewLine` property in the `Environment` Class (I think it is Environment).
|
Adding a newline into a string in C#
|
[
"",
"c#",
"string",
""
] |
What is the maximum number of threads you can create in a C# application? And what happens when you reach this limit? Is an exception of some kind thrown?
|
There is no inherent limit. The maximum number of threads is determined by the amount of physical resources available. See this [article by Raymond Chen](https://devblogs.microsoft.com/oldnewthing/20050729-14/?p=34773) for specifics.
If you need to ask what the maximum number of threads is, you are probably doing something wrong.
[**Update**: Just out of interest: .NET Thread Pool default numbers of threads:
* 1023 in Framework 4.0 (32-bit environment)
* 32767 in Framework 4.0 (64-bit environment)
* 250 per core in Framework 3.5
* 25 per core in Framework 2.0
(These numbers may vary depending upon the hardware and OS)]
|
Mitch is right. It depends on resources (memory).
Although Raymond's article is dedicated to Windows threads, not to C# threads, the logic applies the same (C# threads are mapped to Windows threads).
However, as we are in C#, if we want to be completely precise, we need to distinguish between "started" and "non started" threads. Only started threads actually reserve stack space (as we could expect). Non started threads only allocate the information required by a thread object (you can use reflector if interested in the actual members).
You can actually test it for yourself, compare:
```
static void DummyCall()
{
Thread.Sleep(1000000000);
}
static void Main(string[] args)
{
int count = 0;
var threadList = new List<Thread>();
try
{
while (true)
{
Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);
newThread.Start();
threadList.Add(newThread);
count++;
}
}
catch (Exception ex)
{
}
}
```
with:
```
static void DummyCall()
{
Thread.Sleep(1000000000);
}
static void Main(string[] args)
{
int count = 0;
var threadList = new List<Thread>();
try
{
while (true)
{
Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);
threadList.Add(newThread);
count++;
}
}
catch (Exception ex)
{
}
}
```
Put a breakpoint in the exception (out of memory, of course) in VS to see the value of counter. There is a very significant difference, of course.
|
Maximum number of threads in a .NET app?
|
[
"",
"c#",
".net",
"multithreading",
""
] |
I need to resize PNG, JPEG and GIF files. How can I do this using Java?
|
After loading the image you can try:
```
BufferedImage createResizedCopy(Image originalImage,
int scaledWidth, int scaledHeight,
boolean preserveAlpha)
{
System.out.println("resizing...");
int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
Graphics2D g = scaledBI.createGraphics();
if (preserveAlpha) {
g.setComposite(AlphaComposite.Src);
}
g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose();
return scaledBI;
}
```
|
FWIW I just released (Apache 2, hosted on GitHub) a simple image-scaling library for Java called [imgscalr](https://github.com/thebuzzmedia/imgscalr) (available on [Maven central](http://mvnrepository.com/artifact/org.imgscalr/imgscalr-lib)).
The library implements a few different approaches to image-scaling (including Chris Campbell's incremental approach with a few minor enhancements) and will either pick the most optimal approach for you if you ask it to, or give you the fastest or best looking (if you ask for that).
Usage is dead-simple, just a bunch of static methods. The simplest use-case is:
```
BufferedImage scaledImage = Scalr.resize(myImage, 200);
```
All operations maintain the image's original proportions, so in this case you are asking imgscalr to resize your image within a bounds of 200 pixels wide and 200 pixels tall and by default it will automatically select the best-looking and fastest approach for that since it wasn't specified.
I realize on the outset this looks like self-promotion (it is), but I spent my fair share of time googling this exact same subject and kept coming up with different results/approaches/thoughts/suggestions and decided to sit down and write a simple implementation that would address that 80-85% use-cases where you have an image and probably want a thumbnail for it -- either as fast as possible or as good-looking as possible (for those that have tried, you'll notice doing a Graphics.drawImage even with BICUBIC interpolation to a small enough image, it still looks like garbage).
|
How can I resize an image using Java?
|
[
"",
"java",
"image",
"resize",
""
] |
I'd like a loop that uses a UInt16 (ushort) to loop through all of its values. However, this doesn't do it:
```
for( ushort i = 0; i < UInt16.MaxValue; i++ )
{
// do something
}
```
The problem is that the loop will quit when i == 0xFFFF and not "do something".
If I change the 'for' statement to "for(ushort i = 0; i <= UInt16.MaxValue; i++ )", then it becomes an infinite loop because i never gets to 0x10000 because ushorts only go to 0xFFFF.
I could make 'i' an int and cast it or assign it to a ushort variable in the loop.
Any suggestions?
|
Use a `do...while` loop
```
ushort i = 0;
do
{
// do something
} while(i++ < UInt16.MaxValue);
```
There is an interesting discussion of testing loops at the top vs. the bottom [here](https://stackoverflow.com/questions/224059/do-your-loops-test-at-the-top-or-bottom).
|
[`UInt16.MaxValue` evaluates to `0xffff`](http://msdn.microsoft.com/en-us/library/system.uint16.maxvalue.aspx), not `0x10000`. I think you can do this with a `do`/`while` loop, as a variation on burkhard1979's answer.
```
ushort i = 0;
do {
...
} while (++i != 0);
```
|
Loop from 0x0000 to 0xFFFF
|
[
"",
"c#",
"loops",
"for-loop",
""
] |
Haven't done ASP.NET development since VS 2003, so I'd like to save some time and learn from other's mistakes.
Writing a web services app, but not a WSDL/SOAP/etc. -- more like REST + XML.
Which of the many "New Item" options (Web Form, Generic Handler, ASP.NET Handler, etc.) makes the most sense if I want to handle different HTTP verbs, through the same URI, separately. In a perfect world, I'd like the dispatching done declaratively in the code rather than via web.config -- but if I'm making life too hard that way, I'm open to change.
|
If you're not using the built in web services (*.asmx), then you should probably use a generic handler (*.ashx).
|
This is an idea I've been playing with... use at your own risk, the code is in my "Sandbox" folder ;)
I think I want to move away from using reflection to determine which method to run, it might be faster to register a delegate in a dictionary using the HttpVerb as a key. Anyway, this code is provided with no warranty, blah, blah, blah...
Verbs to use with REST Service
```
public enum HttpVerb
{
GET, POST, PUT, DELETE
}
```
Attribute to mark methods on your service
```
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=false)]
public class RestMethodAttribute: Attribute
{
private HttpVerb _verb;
public RestMethodAttribute(HttpVerb verb)
{
_verb = verb;
}
public HttpVerb Verb
{
get { return _verb; }
}
}
```
Base class for a Rest Service
```
public class RestService: IHttpHandler
{
private readonly bool _isReusable = true;
protected HttpContext _context;
private IDictionary<HttpVerb, MethodInfo> _methods;
public void ProcessRequest(HttpContext context)
{
_context = context;
HttpVerb verb = (HttpVerb)Enum.Parse(typeof (HttpVerb), context.Request.HttpMethod);
MethodInfo method = Methods[verb];
method.Invoke(this, null);
}
private IDictionary<HttpVerb, MethodInfo> Methods
{
get
{
if(_methods == null)
{
_methods = new Dictionary<HttpVerb, MethodInfo>();
BuildMethodsMap();
}
return _methods;
}
}
private void BuildMethodsMap()
{
Type serviceType = this.GetType();
MethodInfo[] methods = serviceType.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (MethodInfo info in methods)
{
RestMethodAttribute[] attribs =
info.GetCustomAttributes(typeof(RestMethodAttribute), false) as RestMethodAttribute[];
if(attribs == null || attribs.Length == 0)
continue;
HttpVerb verb = attribs[0].Verb;
Methods.Add(verb, info);
}
}
public bool IsReusable
{
get { return _isReusable; }
}
}
```
Sample REST Service
```
public class MyRestService: RestService
{
[RestMethod(HttpVerb.GET)]
public void HelloWorld()
{
_context.Current.Response.Write("Hello World");
_context.Current.Response.End();
}
}
```
|
What's the best ASP.NET file type for a (non-SOAP, non-WSDL) web services project?
|
[
"",
"c#",
"asp.net",
"web-services",
""
] |
I'm working on a site which contains a whole bunch of mp3s and images, and I'd like to display a loading gif while all the content loads.
I have no idea how to achieve this, but I do have the animated gif I want to use.
Any suggestions?
|
Typically sites that do this by loading content via ajax and listening to the `readystatechanged` event to update the DOM with a loading GIF or the content.
How are you currently loading your content?
The code would be similar to this:
```
function load(url) {
// display loading image here...
document.getElementById('loadingImg').visible = true;
// request your data...
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
// content is loaded...hide the gif and display the content...
if (req.responseText) {
document.getElementById('content').innerHTML = req.responseText;
document.getElementById('loadingImg').visible = false;
}
}
};
request.send(vars);
}
```
There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.
|
You said you didn't want to do this in AJAX. While AJAX is great for this, there is a way to show one DIV while waiting for the entire `<body>` to load. It goes something like this:
```
<html>
<head>
<style media="screen" type="text/css">
.layer1_class { position: absolute; z-index: 1; top: 100px; left: 0px; visibility: visible; }
.layer2_class { position: absolute; z-index: 2; top: 10px; left: 10px; visibility: hidden }
</style>
<script>
function downLoad(){
if (document.all){
document.all["layer1"].style.visibility="hidden";
document.all["layer2"].style.visibility="visible";
} else if (document.getElementById){
node = document.getElementById("layer1").style.visibility='hidden';
node = document.getElementById("layer2").style.visibility='visible';
}
}
</script>
</head>
<body onload="downLoad()">
<div id="layer1" class="layer1_class">
<table width="100%">
<tr>
<td align="center"><strong><em>Please wait while this page is loading...</em></strong></p></td>
</tr>
</table>
</div>
<div id="layer2" class="layer2_class">
<script type="text/javascript">
alert('Just holding things up here. While you are reading this, the body of the page is not loading and the onload event is being delayed');
</script>
Final content.
</div>
</body>
</html>
```
The onload event won't fire until all of the page has loaded. So the layer2 `<DIV>` won't be displayed until the page has finished loading, after which onload will fire.
|
How to display a loading screen while site content loads
|
[
"",
"javascript",
"html",
"css",
"loading",
"pageload",
""
] |
From within a DLL that's being called by a C#.NET web app, how do you find the base url of the web app?
|
Will this work?
```
HttpContext.Current.Request.Url
```
UPDATE:
To get the base URL you can use:
```
HttpContext.Current.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)
```
|
If it's an assembly that might be referenced by non-web projects then you might want to avoid using the System.Web namespace.
I would use DannySmurf's method.
|
How do you find the base url from a DLL in C#?
|
[
"",
"c#",
".net",
"asp.net",
"url",
"web-applications",
""
] |
Python has several ways to parse XML...
I understand the very basics of parsing with **SAX**. It functions as a stream parser, with an event-driven API.
I understand the **DOM** parser also. It reads the XML into memory and converts it to objects that can be accessed with Python.
Generally speaking, it was easy to choose between the two depending on what you needed to do, memory constraints, performance, etc.
(Hopefully I'm correct so far.)
Since Python 2.5, we also have **ElementTree**. How does this compare to DOM and SAX? Which is it more similar to? Why is it better than the previous parsers?
|
ElementTree is much easier to use, because it represents an XML tree (basically) as a structure of lists, and attributes are represented as dictionaries.
ElementTree needs much less memory for XML trees than DOM (and thus is faster), and the parsing overhead via `iterparse` is comparable to SAX. Additionally, `iterparse` returns partial structures, and you can keep memory usage constant during parsing by discarding the structures as soon as you process them.
ElementTree, as in Python 2.5, has only a small feature set compared to full-blown XML libraries, but it's enough for many applications. If you need a validating parser or complete XPath support, lxml is the way to go. For a long time, it used to be quite unstable, but I haven't had any problems with it since 2.1.
ElementTree deviates from DOM, where nodes have access to their parent and siblings. Handling actual documents rather than data stores is also a bit cumbersome, because text nodes aren't treated as actual nodes. In the XML snippet
```
<a>This is <b>a</b> test</a>
```
The string `test` will be the so-called `tail` of element `b`.
In general, I recommend ElementTree as the default for all XML processing with Python, and DOM or SAX as the solutions for specific problems.
|
# Minimal DOM implementation:
[Link](http://docs.python.org/2/library/xml.dom.minidom.html#module-xml.dom.minidom).
Python supplies a full, W3C-standard implementation of XML DOM (*xml.dom*) and a minimal one, *xml.dom.minidom*. This latter one is simpler and smaller than the full implementation. However, from a "parsing perspective", it has all the pros and cons of the standard DOM - i.e. it loads everything in memory.
Considering a basic XML file:
```
<?xml version="1.0"?>
<catalog>
<book isdn="xxx-1">
<author>A1</author>
<title>T1</title>
</book>
<book isdn="xxx-2">
<author>A2</author>
<title>T2</title>
</book>
</catalog>
```
A possible Python parser using *minidom* is:
```
import os
from xml.dom import minidom
from xml.parsers.expat import ExpatError
#-------- Select the XML file: --------#
#Current file name and directory:
curpath = os.path.dirname( os.path.realpath(__file__) )
filename = os.path.join(curpath, "sample.xml")
#print "Filename: %s" % (filename)
#-------- Parse the XML file: --------#
try:
#Parse the given XML file:
xmldoc = minidom.parse(filepath)
except ExpatError as e:
print "[XML] Error (line %d): %d" % (e.lineno, e.code)
print "[XML] Offset: %d" % (e.offset)
raise e
except IOError as e:
print "[IO] I/O Error %d: %s" % (e.errno, e.strerror)
raise e
else:
catalog = xmldoc.documentElement
books = catalog.getElementsByTagName("book")
for book in books:
print book.getAttribute('isdn')
print book.getElementsByTagName('author')[0].firstChild.data
print book.getElementsByTagName('title')[0].firstChild.data
```
Note that *xml.parsers.expat* is a Python interface to the Expat non-validating XML parser (docs.python.org/2/library/pyexpat.html).
The *xml.dom* package supplies also the exception class *DOMException*, but it is not supperted in *minidom*!
# The ElementTree XML API:
[Link](http://docs.python.org/2/library/xml.etree.elementtree.html).
*ElementTree* is much easier to use and it requires less memory than XML DOM. Furthermore, a C implementation is available (*xml.etree.cElementTree*).
A possible Python parser using *ElementTree* is:
```
import os
from xml.etree import cElementTree # C implementation of xml.etree.ElementTree
from xml.parsers.expat import ExpatError # XML formatting errors
#-------- Select the XML file: --------#
#Current file name and directory:
curpath = os.path.dirname( os.path.realpath(__file__) )
filename = os.path.join(curpath, "sample.xml")
#print "Filename: %s" % (filename)
#-------- Parse the XML file: --------#
try:
#Parse the given XML file:
tree = cElementTree.parse(filename)
except ExpatError as e:
print "[XML] Error (line %d): %d" % (e.lineno, e.code)
print "[XML] Offset: %d" % (e.offset)
raise e
except IOError as e:
print "[XML] I/O Error %d: %s" % (e.errno, e.strerror)
raise e
else:
catalogue = tree.getroot()
for book in catalogue:
print book.attrib.get("isdn")
print book.find('author').text
print book.find('title').text
```
|
XML parsing - ElementTree vs SAX and DOM
|
[
"",
"python",
"xml",
"dom",
"sax",
"elementtree",
""
] |
I have an array of shorts (short[]) that I need to write out to a file. What's the quickest way to do this?
|
Use the BinaryWriter
```
static void WriteShorts(short[] values, string path)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
foreach (short value in values)
{
bw.Write(value);
}
}
}
}
```
|
Following up on Jon B's answer, if your file contains any other data, you might want to prefix the data with the count of values.
i.e.:
```
static void WriteShorts(short[] values, string path)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
// Write the number of items
bw.Write(values.Length);
foreach (short value in values)
{
bw.Write(value);
}
}
}
}
```
|
What's the best way to write a short[] array to a file in C#?
|
[
"",
"c#",
".net",
"filestream",
""
] |
I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way of doing this?
---
It would be a lot of code to post but as an example:
```
struct
{
WORD version;
BOOL upgrade;
time_t time1;
time_t time2;
} apparms;
File *fp;
fp = fopen(filePath, "r+b");
fread(&apparms, sizeof(apparms), 1, fp);
return Py_BuildValue("{s:i,s:l,s:l}",
"sysVersion",apparms.version,
"powerFailTime", apparms.time1,
"normKitExpDate", apparms.time2
);
```
Now on a 32 bit system this works great, but on a 64 bit my time\_t sizes are different (32bit vs 64 bit longs).
---
Damn, you people are fast.
Patrick, I originally started using the struct package but found it just way to slow for my needs. Plus I was looking for an excuse to write a Python Extension.
I know this is a stupid question but what types do I need to watch out for?
Thanks.
|
Explicitly specify that your data types (e.g. integers) are 32-bit. Otherwise if you have two integers next to each other when you read them they will be read as one 64-bit integer.
When you are dealing with cross-platform issues, the two main things to watch out for are:
1. Bitness. If your packed data is written with 32-bit ints, then all of your code must explicitly specify 32-bit ints when reading *and* writing.
2. Byte order. If you move your code from Intel chips to PPC or SPARC, your byte order will be wrong. You will have to import your data and then byte-flip it so that it matches up with the current architecture. Otherwise 12 (`0x0000000C`) will be read as 201326592 (`0x0C000000`).
Hopefully this helps.
|
The 'struct' module should be able to do this, although alignment of structs in the middle of the data is always an issue. It's not very hard to get it right, however: find out (once) what boundary the structs-in-structs align to, then pad (manually, with the 'x' specifier) to that boundary. You can doublecheck your padding by comparing struct.calcsize() with your actual data. It's certainly easier than writing a C extension for it.
In order to keep using Py\_BuildValue() like that, you have two options. You can determine the size of time\_t at compiletime (in terms of fundamental types, so 'an int' or 'a long' or 'an ssize\_t') and then use the right format character to Py\_BuildValue -- 'i' for an int, 'l' for a long, 'n' for an ssize\_t. Or you can use PyInt\_FromSsize\_t() manually, in which case the compiler does the upcasting for you, and then use the 'O' format characters to pass the result to Py\_BuildValue.
|
Reading 32bit Packed Binary Data On 64bit System
|
[
"",
"python",
"c",
"64-bit",
""
] |
I have a form with a textarea. Users enter a block of text which is stored in a database.
Occasionally a user will paste text from Word containing smart quotes or emdashes. Those characters appear in the database as: –, ’, “ ,â€
What function should I call on the input string to *convert smart quotes to regular quotes and emdashes to regular dashes*?
I am working in PHP.
Update: Thanks for all of the great responses so far. The page on Joel's site about encodings is very informative: <http://www.joelonsoftware.com/articles/Unicode.html>
Some notes on my environment:
The MySQL database is using UTF-8 encoding. Likewise, the HTML pages that display the content are using UTF-8 (Update:) by explicitly setting the meta content-type.
On those pages the smart quotes and emdashes appear as a diamond with question mark.
Solution:
Thanks again for the responses. The solution was twofold:
1. Make sure the database and HTML
files were explicitly set to use
UTF-8 encoding.
2. Use `htmlspecialchars()` instead of
`htmlentities()`.
|
This sounds like a Unicode issue. Joel Spolsky has a good jumping off point on the topic: <http://www.joelonsoftware.com/articles/Unicode.html>
|
> The mysql database is using UTF-8
> encoding. Likewise, the html pages
> that display the content are using
> UTF-8.
The content of the HTML can be in UTF-8, yes, but are you explicitly setting the content type (encoding) of your HTML pages (generated via PHP?) to UTF-8 as well? Try returning a `Content-Type` header of `"text/html;charset=utf-8"` or add `<meta>` tags to your HTMLs:
```
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
```
That way, the content type of the data submitted to PHP will also be the same.
I had a similar issue and adding the `<meta>` tag worked for me.
|
How do I convert Word smart quotes and em dashes in a string?
|
[
"",
"php",
"unicode",
"smart-quotes",
""
] |
```
List<String> nameList = new List<String>();
DropDownList ddl = new DropDownList();
```
List is populated here, then sorted:
```
nameList.Sort();
```
Now I need to drop it into the dropdownlist, which is where I'm having issues (using foreach):
```
foreach (string name in nameList){
ddl.Items.Add(new ListItem(nameList[name].ToString()));
}
```
No workie - any suggestions? It's giving me compile errors:
```
Error - The best overloaded method match for 'System.Collections.Generic.List<string>.this[int]' has some invalid arguments
Error - Argument '1': cannot convert from 'string' to 'int'
```
|
Replace this:
```
ddl.Items.Add(new ListItem(nameList[name].ToString()));
```
with this:
```
ddl.Items.Add(new ListItem(name));
```
Done like dinner.
|
Why not just bind the DDL directly to the List like
```
DropDownList ddl = new DropDownList();
ddl.DataSource = nameList;
ddl.DataBind();
```
|
C# - Dumping a list to a dropdownlist
|
[
"",
"c#",
"list",
"drop-down-menu",
""
] |
In T-SQL, you can do this:
```
SELECT ProductId, COALESCE(Price, 0)
FROM Products
```
How do you do the same thing in Access SQL? I see examples for doing it with Nz in VBA, but I'm looking for the SQL equivalent.
Thanks.
|
Access supports the `Nz` function and allows you to use it in a query. Note though that `Nz` is the same as the T-SQL `ISNULL` function. It can not take an arbitrary number of parameters like `COALESCE` can.
|
If it's in an Access query, you can try this:
```
"Price = IIf([Price] Is Null,0,[Price])"
```
|
coalesce alternative in Access SQL
|
[
"",
"sql",
"ms-access",
""
] |
Is it possible to chain static methods together using a static class? Say I wanted to do something like this:
```
$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();
```
. . . and obviously I would want $value to be assigned the number 14. Is this possible?
**Update**: It doesn't work (you can't return "self" - it's not an instance!), but this is where my thoughts have taken me:
```
class TestClass {
public static $currentValue;
public static function toValue($value) {
self::$currentValue = $value;
}
public static function add($value) {
self::$currentValue = self::$currentValue + $value;
return self;
}
public static function subtract($value) {
self::$currentValue = self::$currentValue - $value;
return self;
}
public static function result() {
return self::$value;
}
}
```
After working that out, I think it would just make more sense to simply work with a class instance rather than trying to chain static function calls (which doesn't look possible, unless the above example could be tweaked somehow).
|
I like the solution provided by Camilo above, essentially since all you're doing is altering the value of a static member, and since you do want chaining (even though it's only syntatic sugar), then instantiating TestClass is probably the best way to go.
I'd suggest a Singleton pattern if you want to restrict instantiation of the class:
```
class TestClass
{
public static $currentValue;
private static $_instance = null;
private function __construct () { }
public static function getInstance ()
{
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
public function toValue($value) {
self::$currentValue = $value;
return $this;
}
public function add($value) {
self::$currentValue = self::$currentValue + $value;
return $this;
}
public function subtract($value) {
self::$currentValue = self::$currentValue - $value;
return $this;
}
public function result() {
return self::$currentValue;
}
}
// Example Usage:
$result = TestClass::getInstance ()
->toValue(5)
->add(3)
->subtract(2)
->add(8)
->result();
```
|
```
class oop{
public static $val;
public static function add($var){
static::$val+=$var;
return new static;
}
public static function sub($var){
static::$val-=$var;
return new static;
}
public static function out(){
return static::$val;
}
public static function init($var){
static::$val=$var;
return new static;
}
}
echo oop::init(5)->add(2)->out();
```
|
Chaining Static Methods in PHP?
|
[
"",
"php",
"oop",
"method-chaining",
""
] |
Nightly, I need to fill a SQL Server 2005 table from an ODBC source with over 8 million records. Currently I am using an insert statement from linked server with syntax select similar to this:
```
Insert Into SQLStagingTable from Select * from OpenQuery(ODBCSource, 'Select * from SourceTable')
```
This is really inefficient and takes hours to run. I'm in the middle of coding a solution using SqlBulkInsert code similar to the code found in [this question](https://stackoverflow.com/questions/127152/how-to-change-slow-parametrized-inserts-into-fast-bulk-copy-even-from-memory).
The code in that question is first populating a datatable in memory and then passing that datatable to the SqlBulkInserts WriteToServer method.
What should I do if the populated datatable uses more memory than is available on the machine it is running (a server with 16GB of memory in my case)?
I've thought about using the overloaded ODBCDataAdapter [fill](http://msdn.microsoft.com/en-us/library/59wzthcw(VS.80).aspx) method which allows you to fill only the records from x to n (where x is the start index and n is the number of records to fill). However that could turn out to be an even slower solution than what I currently have since it would mean re-running the select statement on the source a number of times.
What should I do? Just populate the whole thing at once and let the OS manage the memory? Should I populate it in chunks? Is there another solution I haven't thought of?
|
The easiest way would be to use ExecuteReader() against your odbc data source and pass the [IDataReader](http://msdn.microsoft.com/en-us/library/system.data.idatareader.aspx) to the [WriteToServer(IDataReader)](http://msdn.microsoft.com/en-us/library/434atets.aspx) overload.
Most data reader implementations will only keep a very small portion of the total results in memory.
|
SSIS performs well and is very tweakable. In my experience 8 million rows is not out of its league. One of my larger ETLs pulls in 24 million rows a day and does major conversions and dimensional data warehouse manipulations.
|
What's the best way to use SqlBulkCopy to fill a really large table?
|
[
"",
"c#",
".net",
"sql-server",
"vb.net",
"sqlbulkcopy",
""
] |
I have a SQL script that creates a package with a comment containing an ampersand (&). When I run the script from SQL Plus, I am prompted to enter a substitute value for the string starting with &. How do I disable this feature so that SQL Plus ignores the ampersand?
|
This may work for you:
```
set define off
```
Otherwise the ampersand needs to be at the end of a string,
```
'StackOverflow &' || ' you'
```
EDIT: I was click-happy when saving... This was referenced from a [blog](http://blog.andrewbeacock.com/2008/09/using-ampersands-without-variable_15.html).
|
If you sometimes use substitution variables you might not want to turn define off. In these cases you could convert the ampersand from its numeric equivalent as in `|| Chr(38) ||` or append it as a single character as in `|| '&' ||`.
|
How do I ignore ampersands in a SQL script running from SQL Plus?
|
[
"",
"sql",
"oracle",
"sqlplus",
""
] |
I have a WinForms TreeView with one main node and several sub-nodes.
How can I hide the + (plus sign) in the main node?
|
Treview Property: **`.ShowRootLines = false`**
When `ShowRootLines` is false, the Plus/Minus sign will not be shown for the root node, but will still show when necessary on child nodes.
With the Plus/Minus sign hidden, you might consider executing the `Expand()` method of the root node once the tree is populated. That will make sure that the root node shows all first-level child nodes.
Note: There is a `ShowPlusMinus` property on the TreeView, but it works on *all* nodes.
|
See the TreeView::ShowExpandCollapse property. Set it to false to disable the expand/collapse node indicators.
|
Hide WinForms TreeView plus sign
|
[
"",
"c#",
"winforms",
"treeview",
""
] |
Can Eclipse make parameters for generated methods (overwriting, implementing interface, etc.) final, and if so, how?
If I'm not mistaken, IntelliJ had an option for it. I could not find something similar in Eclipse.
I have become accustomed to making parameters final manually, but I am hoping for an automatic solution.
|
AFAIK, that is not possible. I've not found any option to customize it under `Window > Preferences > Java > Editor > Templates or under Window > Preferences > Java > Code Style > Code Templates`.
Anyway, Eclipse 3.3+ comes with "save actions", an alternative mechanism for doing that. Under `Preferencens > Java > Editors > Save` actions it is possible to configure "additional save actions". On the code style tab there is an option to automatically add final modifiers to private fields, method parameters and local variables.
|
It is indeed in the "save actions". Check this blog post for a screenshot: [Eclipse and the automagical final](http://enfranchisedmind.com/blog/2007/12/05/eclipse-and-the-automagical-final/)
|
Eclipse - generated method parameters final
|
[
"",
"java",
"eclipse",
"coding-style",
""
] |
**Summary:** I'm developing a persistent Java web application, and I need to make sure that all resources I persist have globally unique identifiers to prevent duplicates.
**The Fine Print:**
1. I'm not using an RDBMS, so I don't have any fancy sequence generators (such as the one provided by Oracle)
2. I'd like it to be fast, preferably all in memory - I'd rather not have to open up a file and increment some value
3. It needs to be thread safe (I'm anticipating that only one JVM at a time will need to generate IDs)
4. There needs to be consistency across instantiations of the JVM. If the server shuts down and starts up, the ID generator shouldn't re-generate the same IDs it generated in previous instantiations (or at least the chance has to be really, really slim - I anticipate many millions of presisted resources)
5. I have seen the examples in the EJB unique ID pattern article. They won't work for me (I'd rather not rely solely on System.currentTimeMillis() because we'll be persisting multiple resources per millisecond).
6. I have looked at the answers proposed in [this question](https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string-in-java). My concern about them is, what is the chance that I will get a duplicate ID over time? I'm intrigued by the suggestion to use [java.util.UUID](http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html) for a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier), but again, the chances of a duplicate need to be infinitesimally small.
7. I'm using JDK6
|
Pretty sure UUIDs are "good enough". There are 340,282,366,920,938,463,463,374,607,431,770,000,000 UUIDs available.
<http://www.wilybeagle.com/guid_store/guid_explain.htm>
"To put these numbers into perspective, one's annual risk of being hit by a meteorite is estimated to be one chance in 17 billion, that means the probability is about 0.00000000006 (6 × 10−11), equivalent to the odds of creating a few tens of trillions of UUIDs in a year and having one duplicate. In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. The probability of one duplicate would be about 50% if every person on earth owns 600 million UUIDs"
<http://en.wikipedia.org/wiki/Universally_Unique_Identifier>
|
```
public class UniqueID {
private static long startTime = System.currentTimeMillis();
private static long id;
public static synchronized String getUniqueID() {
return "id." + startTime + "." + id++;
}
}
```
|
Generating a globally unique identifier in Java
|
[
"",
"java",
"persistence",
"uuid",
"uniqueidentifier",
""
] |
I have a repeater control where in the footer I have a DropDownList. In my code-behind I have:
```
protected void ddMyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item
|| e.Item.ItemType == ListItemType.AlternatingItem)
{
// Item binding code
}
else if (e.Item.ItemType == ListItemType.Footer)
{
DropDownList ddl = e.Item.FindDropDownList("ddMyDropDownList");
// Fill the list control
ddl.SelectedIndexChanged += new
EventHandler(ddMyDropDownList_SelectedIndexChanged);
ddl.AutoPostBack = true;
}
}
```
The page appear to PostBack however my EventHandler does not get called. Any ideas?
|
If you just want to fire the OnSelectedIndexChanged, this is how it should look:
**Page.aspx - Source**
```
<FooterTemplate>
<asp:DropDownList ID="ddlOptions"
runat="server"
AutoPostBack="true"
onselectedindexchanged="ddlOptions_SelectedIndexChanged">
<asp:ListItem>Option1</asp:ListItem>
<asp:ListItem>Option2</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
```
**Page.aspx.cs - Code-behind**
```
protected void ddlOptions_SelectedIndexChanged(object sender, EventArgs e)
{
//Event Code here.
}
```
And that's it. Nothing more is needed.
|
If the DropDownList is within a Repeater then to make the SelectIndexChanged event fire, you need to disable EnableViewState on the GridView / Repeater.
e.g.
```
EnableViewState="false"
```
You also need to databind the GridView / Repeater on each postback so databind it in the Page Load method.
|
DropDownList in Repeater control, can't fire SelectedIndexChanged
|
[
"",
"c#",
"asp.net",
""
] |
I have a PHP client that requests an XML file over HTTP (i.e. loads an XML file via URL). As of now, the XML file is only several KB in size. A problem I can foresee is that the XML becomes several MBs or Gbs in size. I know that this is a huge question and that there are probably a myriad of solutions, but What ideas do you have to transport this data to the client?
Thanks!
|
based on your use case i'd definitely suggest zipping up the data first. in addition, you may want to md5 hash the file and compare it before initiating the download (no need to update if the file has no changes), this will help with point #2.
also, would it be possible to just send a segment of XML that has been instead of the whole file?
|
Ignoring how well a browser may or may-not handle a GB-sized XML file, the only real concern I can think of off the top of my head is if the execution time to generate all the XML is greater than any execution time thresholds that are set in your environment.
* [PHP's max\_execution\_time setting](http://us.php.net/manual/en/info.configuration.php#ini.max-execution-time)
* [PHP's set\_time\_limit() function](http://us.php.net/manual/en/function.set-time-limit.php)
* [Apache's TimeOut Directive](http://httpd.apache.org/docs/1.3/mod/core.html#timeout)
|
Sending large files via HTTP
|
[
"",
"php",
"xml",
"http",
""
] |
I have a database full of small HTML documents and I need to programmatically insert several into, say, a PDF document with *iText* or a Word document with *Aspose.Words*. I need to preserve any formatting within the HTML documents (within reason, honouring <b> tags is a must, CSS like <span style="blah"> is a nice-to-have).
Both iText and Aspose work (roughly) along the lines:
```
Document document = new Document( Size.A4, Aspect.PORTRAIT );
document.setFont( "Helvetica", 20, Font.BOLD );
document.insert( "some string" )
document.setBold( true );
document.insert( "A bold string" );
```
Therefore (I think) I need some kind of HTML parser which will I can inspect for strings and styles to insert into my document.
Can anybody suggest a good library or a sensible approach to this problem? Platform is Java
|
[HTMLparser](http://htmlparser.sourceforge.net/) is a good HTML parser.
I have used this to parse HTML on one of my projects.
You can write your own filters to parse the HTML for what you want, so the
`<br>` tag shouldn't be difficult to parse out
Yo can parse out CSS usin the [CssSelectorNodeFilter](http://htmlparser.sourceforge.net/javadoc/org/htmlparser/filters/CssSelectorNodeFilter.html)
|
If the HTML is "well-formed XML" (XHTML) why not use an XML parser (such as Xerces) and then inspect programatically the DOM tree.
|
How do I programmatically inspect a HTML document
|
[
"",
"java",
"html",
"parsing",
""
] |
I've recently seen the light of EventWaitHandle's powerful behavior in C# and decided to move some functionality in a sister application to do the same. The only problem is that the sister app is written in C.
No big deal, I'm using pthreads, which have a pthread\_cond\_t datatype that allows for signalling. My only question is, is it possible for a cond to be 'signalled' before something is waiting on it?
Right now my testing says no. That is, if ThreadA fires a signal before ThreadB is waiting, ThreadB will wait indefinately. Is there another pthread type that I can use that behaves closer to the functionality of the EventWaitHandle in C#? An object is signalled, meaning that the first thread to wait on it, will pass immediately, and set it to unsignalled.
Wrapping the pthread\_cond into another data structure wouldn't be too hard to achieve this. But again, is this functionality already available in the pthread library?
|
If you're using condition variables correctly, this won't matter.
The basic flow of your code should be (in pseudocode):
```
lock(lockobj);
while (!signalled) {
wait(condvar);
}
signalled = false;
unlock(lockobj);
```
on the waiting side, and:
```
lock(lockobj);
signalled = true;
notify(condvar);
unlock(lockobj);
```
on the signalling side. (Of course, the lock object and condition variable used have to be the same on both sides.) Hope this helps!
|
I ended up just wrapping a condition type in a new structure and created some simple functions to behave much like the EventWaitHandle from C#. I needed two mutexes to acheive proper serialized access.
The the cond\_mutex is used for waiting on the conditional variable, while the data\_mutex is used when setting the state from signaled to not signaled.
The reset mode is the same from C#. AUTO or MANUAL. This allows for the event\_wait\_t to reset itself automatically after waiting. Or letting the programmer manually do it with a call to event\_wait\_reset(event\_wait\_t \*ewh);
|
EventWaitHandle behavior for pthread_cond_t
|
[
"",
"c#",
"c",
"multithreading",
"data-structures",
"pthreads",
""
] |
Lately I've been in the habit of assigning integer values to constants and simply using the constant name as a means of identifying its purpose. However, in some cases this has resulted in the need to write a function like typeToString($const) when a string representation is needed. Obviously this is inefficient and unneccesary, but is only an issue every once and a while.
So my question is, are there any other tradeoffs I should consider? Which case is considered to be cleaner/more standards-compliant? Also, is the performance difference negligable for most cases?
**Case 1: (faster when a string version is not needed?)**
```
class Foo {
const USER_TYPE_ADMIN = 0;
const USER_TYPE_USER = 1;
const USER_TYPE_GUEST = 2;
public $userType = self::USER_TYPE_ADMIN;
public function __construct($type) {
$this->userType = $type;
}
public function typeToString() {
switch($this->userType) {
case self::USER_TYPE_ADMIN:
return 'admin';
break;
case self::USER_TYPE_USER:
return 'user';
break;
case self::USER_TYPE_GUEST:
return 'guest';
break;
default:
return 'unknown';
break;
}
}
}
$foo = new Foo(Foo::USER_TYPE_GUEST);
echo $foo->typeToString();
// Displays "guest"
```
**Case 2:(faster/easier when a string version is needed)**
```
class Foo {
const USER_TYPE_ADMIN = 'admin';
const USER_TYPE_USER = 'user';
const USER_TYPE_GUEST = 'guest';
public $userType = self::USER_TYPE_ADMIN;
public function __construct($type) {
$this->userType = $type;
}
}
$foo = new Foo(Foo::USER_TYPE_GUEST);
echo $foo->userType();
// Displays "guest"
```
|
The performance difference will be negligible unless you're storing a lot of them.
I'd write the `toString()` method more concisely:
```
$strings = array
(
self::USER_TYPE_ADMIN => 'admin',
self::USER_TYPE_USER => 'user',
);
if (!isset($strings[$type]))
return 'unknown';
return $strings[$type];
```
Also, you could make the `$strings` array a `static`.
|
I'll be honest, I don't know if there's a performance "hit" of any kind when you define your constants natively as strings - but if there is one at all I'm willing to bet that it's so small it would be difficult to measure.
Personally, if the constant's value is meaningful as a literal, then just assign it that value. If the constant's value is meaningful only as an option selector (or some other *indication* of value), then use integers or whatever you choose appropriate.
|
PHP Constants: Advantages/Disadvantages
|
[
"",
"php",
"performance",
"standards",
"coding-style",
"constants",
""
] |
For example:
```
public void doSomething() {
final double MIN_INTEREST = 0.0;
// ...
}
```
Personally, I would rather see these substitution constants declared statically at the class level.
I suppose I'm looking for an "industry viewpoint" on the matter.
|
My starting position is that every variable or constant should be declared/initialized as close to its first use as possible/practical (i.e. don't break a logical block of code in half, just to declare a few lines closer), and scoped as tightly as possible. -- Unless you can give me a damn good reason why it should be different.
For example, a method scoped final won't be visible in the public API. Sometimes this bit of information could be quite useful to the users of your class, and should be moved up.
In the example you gave in the question, I would say that `MIN_INTEREST` is probably one of those pieces of information that a user would like to get their hands on, and it should be scoped to the class, not the method. (Although, there is no context to the example code, and my assumption could be completely wrong.)
|
I would think that you should only put them at the class level if they are used by multiple methods. If it is only used in that method then that looks fine to me.
|
What are your thoughts on method scoped constants?
|
[
"",
"java",
"constants",
""
] |
I have a pattern to match with the string:
string pattern = @"asc"
I am checking the SQL SELECT query for right syntax, semantics, ...
I need to say that in the end of the query string I can have "asc" or "desc".
How can it be written in C#?
|
That'd look like
```
new Regex("asc$|desc$").IsMatch(yourQuery)
```
assuming that you're mandating that asc/desc is the end of the query. You could also do `(?:asc|desc)$` which is a little cleaner with the single `$`, but less readable.
|
You want the "alternation" operator, which is the pipe.
For instance, I believe this would be represented as:
```
asc|desc
```
If you want to make it a non-capturing group you can do it in the normal way. I'm not a regex expert, but that's the first thing to try.
EDIT: MSDN has a page about [regular expression language elements](http://msdn.microsoft.com/en-us/library/az24scfc.aspx) which may help you.
|
How can I use "or", "and" in C# Regex?
|
[
"",
"c#",
"regex",
""
] |
I need to do some large integer math. Are there any classes or structs out there that represent a 128-bit integer and implement all of the usual operators?
BTW, I realize that `decimal` can be used to represent a 96-bit int.
|
**It's here in [System.Numerics](https://learn.microsoft.com/en-us/dotnet/api/system.numerics.biginteger?view=net-6.0)**. "The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds."
```
var i = System.Numerics.BigInteger.Parse("10000000000000000000000000000000");
```
|
While `BigInteger` is the best solution for most applications, if you have performance critical numerical computations, you can use the complete `Int128` and `UInt128` implementations in my [**Dirichlet.Numerics**](https://github.com/ricksladkey/dirichlet-numerics) library. These types are useful if `Int64` and `UInt64` are too small but `BigInteger` is too slow.
|
What type should I use for a 128-bit number in in .NET?
|
[
"",
"c#",
".net",
"int128",
""
] |
Can you get the distinct combination of 2 different fields in a database table? if so, can you provide the SQL example.
|
How about simply:
```
select distinct c1, c2 from t
```
or
```
select c1, c2, count(*)
from t
group by c1, c2
```
|
If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.
|
SQL distinct for 2 fields in a database
|
[
"",
"sql",
"distinct",
""
] |
In c# (3.0 or 3.5, so we can use lambdas), is there an elegant way of sorting a list of dates in descending order? I know I can do a straight sort and then reverse the whole thing,
```
docs.Sort((x, y) => x.StoredDate.CompareTo(y.StoredDate));
docs.Reverse();
```
but is there a lambda expression to do it one step?
In the above example, StoredDate is a property typed as a DateTime.
|
Though it's untested...
```
docs.Sort((x, y) => y.StoredDate.CompareTo(x.StoredDate));
```
should be the opposite of what you originally had.
|
What's wrong with:
```
docs.OrderByDescending(d => d.StoredDate);
```
|
Sort List<DateTime> Descending
|
[
"",
"c#",
"sorting",
"lambda",
""
] |
It appears that our implementation of using Quartz - JDBCJobStore along with Spring, Hibernate and Websphere is throwing unmanaged threads.
I have done some reading and found a tech article from IBM stating that the usage of Quartz with Spring will cause that. They make the suggestion of using CommnonJ to address this issue.
I have done some further research and the only examples I have seen so far all deal with the plan old JobStore that is not in a database.
So, I was wondering if anyone has an example of the solution for this issue.
Thanks
|
We have a working solution for this (two actually).
1) Alter the quartz source code to use a WorkManager daemon thread for the main scheduler thread. It works, but requires changing quarts. We didn't use this though since we didn't want maintain a hacked version of quartz. (That reminds me, I was going to submit this to the project but completely forgot)
2) Create a WorkManagerThreadPool to be used as the quartz threadpool. Implement the interface for the quartz ThreadPool, so that each task that is triggered within quartz is wrapped in a commonj Work object that will then be scheduled in the WorkManager. The key is that the WorkManager in the WorkManagerThreadPool has to be initialized before the scheduler is started, from a Java EE thread (such as servlet initialization). The WorkManagerThreadPool must then create a daemon thread which will handle all the scheduled tasks by creating and scheduling the new Work objects. This way, the scheduler (on its own thread) is passing the tasks to a managed thread (the Work daemon).
Not simple, and unfortunately I do not have code readily available to include.
|
Adding another answer to the thread, since i found a solution for this, finally.
**My environment**: WAS 8.5.5, Quartz 1.8.5, no Spring.
**The problem** i had was the (above stated) unmanaged thread causing a NamingException from `ctx.lookup(myJndiUrl)`, that was instead correctly working in other application servers (JBoss, Weblogic); actually, Webpshere was firing an "incident" with the following message:
> *javax.naming.ConfigurationException: A JNDI operation on a "java:" name cannot be completed because the server runtime is not able to associate the operation's thread with any J2EE application component. This condition can occur when the JNDI client using the "java:" name is not executed on the thread of a server application request. Make sure that a J2EE application does not execute JNDI operations on "java:" names within static code blocks or in threads created by that J2EE application. Such code does not necessarily run on the thread of a server application request and therefore is not supported by JNDI operations on "java:" names.*
The following steps solved the problem:
**1)** upgraded to quartz 1.8.6 (no code changes), just maven pom
**2)** added the following dep to classpath (in my case, EAR's /lib folder), to make the new WorkManagerThreadExecutor available
```
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-commonj</artifactId>
<version>1.8.6</version>
</dependency>
```
Note: in [QTZ-113](http://jira.terracotta.org/jira/browse/QTZ-113) or the official Quartz Documentation [1.x](http://quartz-scheduler.org/documentation/quartz-1.x/configuration/) [2.x](http://quartz-scheduler.org/documentation/quartz-2.2.x/configuration/) there's no mention on how to activate this fix.
**3)** added the following to quartz.properties ("wm/default" was the JNDI of the already configured DefaultWorkManager in my WAS 8.5.5, see *Resources -> AsynchronousBeans -> WorkManagers* in WAS console):
```
org.quartz.threadExecutor.class=org.quartz.custom.WorkManagerThreadExecutor
org.quartz.threadExecutor.workManagerName=wm/default
```
Note: right class is *org.quartz.**custom**.WorkManagerThreadExecutor* for quartz-scheduler-1.8.6 (tested), or *org.quartz.**commonj**.WorkManagerThreadExecutor* from **2.1.1** on (not tested, but verified within actual [quartz-commonj's jars](http://mvnrepository.com/artifact/org.quartz-scheduler/quartz-commonj) on maven's repos)
**4)** moved the **JNDI lookup in the empty constructor of the quartz job** (thanks to [m\_klovre's "Thread outside of the J2EE container"](http://forum.springsource.org/showthread.php?61458-Spring-Quartz-JNDI-in-WebSphere-problem&p=233179#post233179)); that is, the constructor was being invoked by reflection (`newInstance()` method) from the very same J2EE context of my application, and had access to `java:global` namespace, while the `execute(JobExecutionContext)` method was still running in a poorer context, which was missing all of my application's EJBs
Hope this helps.
Ps. as a reference, you can find [here](https://gist.github.com/pcompieta/783eeea8341e532ba9f7) an example of the quartz.properties file I was using above
|
Unmanaged Threads Spring Quartz Websphere Hibernate
|
[
"",
"java",
"hibernate",
"spring",
"websphere",
"quartz-scheduler",
""
] |
I found [a posting on the MySQL forums from 2005](http://forums.mysql.com/read.php?100,22967,22967), but nothing more recent than that. Based on that, it's not possible. But a lot can change in 3-4 years.
What I'm looking for is a way to have an index over a view but have the table that is viewed remain unindexed. Indexing hurts the writing process and this table is written to quite frequently (to the point where indexing slows everything to a crawl). However, this lack of an index makes my queries painfully slow.
|
I don't think MySQL supports materialized views which is what you would need, but it wouldn't help you in this situation anyway. Whether the index is on the view or on the underlying table, it would need to be written and updated at some point during an update of the underlying table, so it would still cause the write speed issues.
Your best bet would probably be to create summary tables that get updated periodically.
|
Have you considered abstracting your transaction processing data from your analytical processing data so that they can both be specialized to meet their unique requirements?
The basic idea being that you have one version of the data that is regularly modified, this would be the transaction processing side and requires heavy normalization and light indexes so that write operations are fast. A second version of the data is structured for analytical processing and tends to be less normalized and more heavily indexed for fast reporting operations.
Data structured around analytical processing is generally built around the cube methodology of data warehousing, being composed of fact tables that represent the sides of the cube and dimension tables that represent the edges of the cube.
|
Is it possible to have an indexed view in MySQL?
|
[
"",
"sql",
"mysql",
"view",
"materialized-views",
"indexed-view",
""
] |
i was just about to finish up my project and install it as a windows service. I have the installer, etc. - everything i need. When i went to choose Application Type, Windows service does not appear as an option.
Here is the kicker. When I dev in VB.NET, i have that option. The project mentioned above is in c#.
Also, if i try to add a new project, i cannot select windows service as a project type. From within the project i can add a windows service and an installer class.
Any ideas or am i just forgetting something stupid?
|
You need an installer class in your project, then you need a Setup project which will incorporate the output of the project's build.
See here: <http://msdn.microsoft.com/en-us/library/aa984464(VS.71).aspx> for a great walkthrough.
|
I posted here:
What i ended up doing was creating a sep class file that created an instance of the winservice - compiled it as a windows service then used installutil to install the service - works like a champ and i didnt have to create an installer project :-)
|
VS2005 + cant select windows service as project type
|
[
"",
"c#",
".net",
"visual-studio",
""
] |
I have a Tab Control with multiple Tab Pages. I want to be able to fade the tabs back and forth. I don't see an opacity option on the Tab Controls. Is there a way to cause a fade effect when I switch from one Tab Page to another?
|
There is no magic Fade switch in the standard windows control.
You could dump the content of the tab to a bitmap (using [DrawToBitmap](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.drawtobitmap.aspx) or [CopyFromScreen](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.copyfromscreen.aspx)?), show that bitmap in front of the TabControl, switch tabs, and then fade the bitmap.
|
I decided to post what I did to get my solution working. GvS had the closest answer and sent me on my quest in the right direction so I gave him (might be a her, but come on) the correct answer check mark since I can't give it to myself.
I never did figure out how to "crossfade" from one tab to another (bring opacity down on one and bring opacity up on the other) but I found a wait to paint a grey box over a bitmap with more and more grey giving it the effect of fading into my background which is also grey. Then I start the second tab as a bitmap of grey that I slowly add less grey combined with the tab image each iteration giving it a fade up effect.
This solution leads to a nice fade effect (even if I do say so myself) but it is very linear. I am going to play a little with a Random Number Generator for the alphablend variable and see if that might make it a little less linear, but then again the users might appreciate the predictability. Btw, I fire the switch tab event with a button\_click.
```
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
public int alphablend;
public Bitmap myBitmap;
private void button1_Click(object sender, EventArgs e)
{
alphablend = 0;
pictureBox1.Visible = true;
myBitmap = new Bitmap(tabControl1.Width, tabControl1.Height);
while (alphablend <= 246)
{
tabControl1.DrawToBitmap(myBitmap, new Rectangle(0, 0, tabControl1.Width, tabControl1.Height));
alphablend = alphablend + 10;
pictureBox1.Refresh();//this calls the paint action
}
tabControl1.SelectTab("tabPage2");
while (alphablend >= 0)
{
tabControl1.DrawToBitmap(myBitmap, new Rectangle(0, 0, tabControl1.Width, tabControl1.Height));
alphablend = alphablend - 10;
pictureBox1.Refresh();//this calls the paint action
}
pictureBox1.Visible = false;
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics bitmapGraphics = Graphics.FromImage(myBitmap);
SolidBrush greyBrush = new SolidBrush(Color.FromArgb(alphablend, 240, 240, 240));
bitmapGraphics.CompositingMode = CompositingMode.SourceOver;
bitmapGraphics.FillRectangle(greyBrush, new Rectangle(0, 0, tabControl1.Width, tabControl1.Height));
e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected;
e.Graphics.DrawImage(myBitmap, 0, 0);
}
```
|
Fade between Tab Pages in a Tab Control
|
[
"",
"c#",
".net",
"winforms",
"animation",
"tabcontrol",
""
] |
> ```
> List<tinyClass> ids = new List<tinyClass();
> ids.Add(new tinyClass(1, 2));
>
> bool b = ids.IndexOf(new tinyClass(1, 2)) >= 0; //true or false?
> ```
If it compares by value, it should return true; if by reference, it will return false.
If it compares by reference, and I make tinyClass a struct - will that make a difference?
|
From MSDN:
> This method determines equality using the default equality comparer EqualityComparer<T>.Default for T, the type of values in the list.
>
> The Default property checks whether type T implements the System.IEquatable<T> generic interface and if so returns an EqualityComparer<T> that uses that implementation. Otherwise it returns an EqualityComparer<T> that uses the overrides of Object.Equals and Object.GetHashCode provided by T.
It seems like it uses the Equals method, unless the stored class implements the IEquatable<T> interface.
|
It depends on the object's implementation of .Equals(..). By default for an object, the references are compared. If you did change it to a struct, then I believe it would evaluate to true based on the equality of the private members, but it would still be more programmically sound to implement IEquatable.
|
Does List<>.IndexOf compare by reference or value?
|
[
"",
"c#",
".net",
""
] |
How can I have a dynamic variable setting the amount of rows to return in SQL Server? Below is not valid syntax in SQL Server 2005+:
```
DECLARE @count int
SET @count = 20
SELECT TOP @count * FROM SomeTable
```
|
```
SELECT TOP (@count) * FROM SomeTable
```
This will only work with SQL 2005+
|
The syntax "select top (@var) ..." only works in SQL SERVER 2005+. For SQL 2000, you can do:
```
set rowcount @top
select * from sometable
set rowcount 0
```
Hope this helps
Oisin.
(edited to replace @@rowcount with rowcount - thanks augustlights)
|
Dynamic SELECT TOP @var In SQL Server
|
[
"",
"sql",
"sql-server-2005",
""
] |
I ran into the problem that my primary key sequence is not in sync with my table rows.
That is, when I insert a new row I get a duplicate key error because the sequence implied in the serial datatype returns a number that already exists.
It seems to be caused by import/restores not maintaining the sequence properly.
|
```
-- Login to psql and run the following
-- What is the result?
SELECT MAX(id) FROM your_table;
-- Then run...
-- This should be higher than the last result.
SELECT nextval('your_table_id_seq');
-- If it's not higher... run this set the sequence last to your highest id.
-- (wise to run a quick pg_dump first...)
BEGIN;
-- protect against concurrent inserts while you update the counter
LOCK TABLE your_table IN EXCLUSIVE MODE;
-- Update the sequence
SELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false);
COMMIT;
```
[Source - Ruby Forum](http://www.ruby-forum.com/topic/64428#72333)
|
[`pg_get_serial_sequence`](http://www.postgresql.org/docs/9.4/static/functions-info.html) can be used to avoid any incorrect assumptions about the sequence name. This resets the sequence in one shot:
```
SELECT pg_catalog.setval(pg_get_serial_sequence('table_name', 'id'), (SELECT MAX(id) FROM table_name)+1);
```
Or more concisely:
```
SELECT pg_catalog.setval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name;
```
However this form can't handle empty tables correctly, since max(id) is null, and neither can you setval 0 because it would be out of range of the sequence. One workaround for this is to resort to the `ALTER SEQUENCE` syntax i.e.
```
ALTER SEQUENCE table_name_id_seq RESTART WITH 1;
ALTER SEQUENCE table_name_id_seq RESTART; -- 8.4 or higher
```
But `ALTER SEQUENCE` is of limited use because the sequence name and restart value cannot be expressions.
It seems the best all-purpose solution is to call `setval` with false as the 3rd parameter, allowing us to specify the "next value to use":
```
SELECT setval(pg_get_serial_sequence('t1', 'id'), coalesce(max(id),0) + 1, false) FROM t1;
```
This ticks all my boxes:
1. avoids hard-coding the actual sequence name
2. handles empty tables correctly
3. handles tables with existing data, and does not leave a
hole in the sequence
Finally, note that `pg_get_serial_sequence` only works if the sequence is owned by the column. This will be the case if the incrementing column was defined as a `serial` type, however if the sequence was added manually it is necessary to ensure `ALTER SEQUENCE .. OWNED BY` is also performed.
i.e. if `serial` type was used for table creation, this should all work:
```
CREATE TABLE t1 (
id serial,
name varchar(20)
);
SELECT pg_get_serial_sequence('t1', 'id'); -- returns 't1_id_seq'
-- reset the sequence, regardless whether table has rows or not:
SELECT setval(pg_get_serial_sequence('t1', 'id'), coalesce(max(id),0) + 1, false) FROM t1;
```
But if sequences were added manually:
```
CREATE TABLE t2 (
id integer NOT NULL,
name varchar(20)
);
CREATE SEQUENCE t2_custom_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE t2 ALTER COLUMN id SET DEFAULT nextval('t2_custom_id_seq'::regclass);
ALTER SEQUENCE t2_custom_id_seq OWNED BY t2.id; -- required for pg_get_serial_sequence
SELECT pg_get_serial_sequence('t2', 'id'); -- returns 't2_custom_id_seq'
-- reset the sequence, regardless whether table has rows or not:
SELECT setval(pg_get_serial_sequence('t2', 'id'), coalesce(max(id),0) + 1, false) FROM t1;
```
|
How to reset Postgres' primary key sequence when it falls out of sync?
|
[
"",
"sql",
"postgresql",
"primary-key",
"ddl",
"database-sequence",
""
] |
I want to create an alias for a class name. The following syntax would be perfect:
```
public class LongClassNameOrOneThatContainsVersionsOrDomainSpecificName
{
...
}
public class MyName = LongClassNameOrOneThatContainsVersionOrDomainSpecificName;
```
but it won't compile.
---
## Example
**Note** This example is provided for convenience only. Don't try to solve this particular problem by suggesting changing the design of the entire system. The presence, or lack, of this example doesn't change the original question.
Some existing code depends on the presence of a static class:
```
public static class ColorScheme
{
...
}
```
This color scheme is the Outlook 2003 color scheme. i want to introduce an Outlook 2007 color scheme, while retaining the Outlook 2003 color scheme:
```
public static class Outlook2003ColorScheme
{
...
}
public static class Outlook2007ColorScheme
{
...
}
```
But i'm still faced with the fact that the code depends on the presence of a static class called `ColorScheme`. My first thought was to create a `ColorScheme` class that I will inherit from either `Outlook2003` or `Outlook2007`:
```
public static class ColorScheme : Outlook2007ColorScheme
{
}
```
but you cannot inherit from a static class.
My next thought was to create the static `ColorScheme` class, but make `Outlook2003ColorScheme` and `Outlook2007ColorScheme` classes non-static. Then a static variable in the static `ColorScheme` class can point to either "true" color scheme:
```
public static class ColorScheme
{
private static CustomColorScheme = new Outlook2007ColorScheme();
...
}
private class CustomColorScheme
{
...
}
private class Outlook2008ColorScheme : CustomColorScheme
{
...
}
private class Outlook2003ColorScheme : CustomColorScheme
{
...
}
```
but that would require me to convert a class composed entirly of readonly static Colors into overridable properties, and then my `ColorScheme` class would need to have the 30 different property getters thunk down into the contained object.
That's just too much typing.
So my next thought was to alias the class:
```
public static ColorScheme = Outlook2007ColorScheme;
```
But that doesn't compile.
How can I alias a static class into another name?
---
**Update:** Can someone please add the answer *"You cannot do this in C#"*, so I can mark that as the accepted answer. Anyone else wanting the answer to the same question will find this question, the accepted answer, and a number of workarounds that might, or might not, be useful.
I just want to close this question out.
|
You cannot alias a class name in C#.
There are things you can do that are not aliasing a class name in C#.
But to answer the original question: you cannot alias a class name in C#.
---
**Update:** People are confused why `using` doesn't work. Example:
**Form1.cs**
```
private void button1_Click(object sender, EventArgs e)
{
this.BackColor = ColorScheme.ApplyColorScheme(this.BackColor);
}
```
**ColorScheme.cs**
```
class ColorScheme
{
public static Color ApplyColorScheme(Color c) { ... }
}
```
And everything works. Now i want to create a *new* class, and *alias* `ColorScheme` to it (so that **no code needs to be modified**):
**ColorScheme.cs**
```
using ColorScheme = Outlook2007ColorScheme;
class Outlook2007ColorScheme
{
public static Color ApplyColorScheme(Color c) { ... }
}
```
Ohh, i'm sorry. This code doesn't compile:

My question was how to *alias* a class in C#. It cannot be done. There are things i can do that are *not* aliasing a class name in C#:
* change everyone who depends on `ColorScheme` to `using` `ColorScheme` instead (code change workaround because i cannot alias)
* change everyone who depends on `ColorScheme` to use a factory pattern them a polymorphic class or interface (code change workaround because i cannot alias)
But these workarounds involve breaking existing code: not an option.
If people depend on the presence of a `ColorScheme` class, i have to actually copy/paste a `ColorScheme` class.
In other words: i cannot alias a class name in C#.
This contrasts with other object oriented languages, where i could define the alias:
```
ColorScheme = Outlook2007ColorScheme
```
and i'd be done.
|
**You can’t**. The next best thing you *can* do is have `using` declarations in the files that use the class.
For example, you could rewrite the dependent code using an import alias (as a quasi-`typedef` substitute):
```
using ColorScheme = The.Fully.Qualified.Namespace.Outlook2007ColorScheme;
```
Unfortunately this needs to go into every scope/file that uses the name.
I therefore don't know if this is practical in your case.
|
How do I alias a class name in C#, without having to add a line of code to every file that uses the class?
|
[
"",
"c#",
"class-design",
""
] |
I am currently trying to learn all new features of C#3.0. I have found a very nice collection of [sample to practice LINQ](http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx) but I can't find something similar for Lambda.
Do you have a place that I could practice Lambda function?
## Update
LINQpad is great to learn Linq (thx for the one who suggest) and use a little bit Lambda in some expression. But I would be interesting in more specific exercise for Lambda.
|
[LINQPad](http://linqpad.net/) is a good tool for learning LINQ
|
Lambdas are just something that, once you get your head around, you "get" it. If you're using a delegate currently, you can replace it with a lambda. Also the `System.Action<...>`, `System.Func<...>`, and `System.Predicate<...>` additions are nice shortcuts. Some examples showing syntax would be helpful though (warning: they are inane but I wanted to illustrate how you can swap functions):
```
public static void Main()
{
// ToString is shown below for clarification
Func<int,string,string> intAndString = (x, y) => x.ToString() + y.ToString();
Func<bool, float, string> boolAndFloat = (x, y) => x.ToString() + y.ToString();
// with declared
Combine(13, "dog", intAndString);
Combine(true, 37.893f, boolAndFloat);
// inline
Combine("a string", " with another", (s1, s2) => s1 + s2);
// and multiline - note inclusion of return
Combine(new[] { 1, 2, 3 }, new[] { 6, 7, 8 },
(arr1, arr2) =>
{
var ret = "";
foreach (var i in arr1)
{
ret += i.ToString();
}
foreach (var n in arr2)
{
ret += n.ToString();
}
return ret;
}
);
// addition
PerformOperation(2, 2, (x, y) => 2 + 2);
// sum, multi-line
PerformOperation(new[] { 1, 2, 3 }, new[] { 12, 13, 14 },
(arr1, arr2) =>
{
var ret = 0;
foreach (var i in arr1)
ret += i;
foreach (var i in arr2)
ret += i;
return ret;
}
);
Console.ReadLine();
}
public static void Combine<TOne, TTwo>(TOne one, TTwo two, Func<TOne, TTwo, string> vd)
{
Console.WriteLine("Appended: " + vd(one, two));
}
public static void PerformOperation<T,TResult>(T one, T two, Func<T, T, TResult> func)
{
Console.WriteLine("{0} operation {1} is {2}.", one, two, func(one,two));
}
```
Mostly what confused me was the shortcut syntax, for example when using System.Action to just execute a delegate with no parameters you could use:
```
var a = new Action(() => Console.WriteLine("Yay!"));
```
Or you could do:
```
Action a = () => Console.WriteLine("Yay");
```
When you've got an `Action`, `Func`, or `Predicate` that takes one argument you can omit the parenthesis:
```
var f = new Func<int, bool>(anInt => anInt > 0);
```
or:
```
// note: no var here, explicit declaration
Func<int,bool> f = anInt => anInt > 0;
```
instead of:
```
Func<int,bool> f = (anInt) => anInt > 0;
```
or to go to the extreme:
```
Func<int,bool> f = (anInt) =>
{
return anInt > 0;
}
```
As shown above, single line lambdas do not require the return statement, though multiline `Func` lambdas do.
I think you will find the best way to learn how to use lambdas is to work a lot with collections and include System.Linq in your using namespaces - you will see a ton of extension methods for your collections and most of these methods allow you to exercise your knowledge of lambdas.
|
Where to practice Lambda function?
|
[
"",
"c#",
".net-3.5",
"lambda",
"c#-3.0",
""
] |
If you are creating a 1d array, you can implement it as a list, or else use the 'array' module in the standard library. I have always used lists for 1d arrays.
What is the reason or circumstance where I would want to use the array module instead?
Is it for performance and memory optimization, or am I missing something obvious?
|
Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in [amortized constant time](http://en.wikipedia.org/wiki/Dynamic_array#Geometric_expansion_and_amortized_cost). If you need to shrink and grow your list time-efficiently and without hassle, they are the way to go. But they use **a lot more space than C arrays**, in part because each item in the list requires the construction of an individual Python object, even for data that could be represented with simple C types (e.g. `float` or `uint64_t`).
The `array.array` type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data (that is to say, all of the same type) and so it uses only `sizeof(one object) * length` bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, `ioctl` or `fctnl`).
`array.array` is also a reasonable way to represent a **mutable** string in Python 2.x (`array('B', bytes)`). However, Python 2.6+ and 3.x offer a mutable *byte* string as [`bytearray`](https://docs.python.org/3/library/stdtypes.html#bytearray).
However, if you want to do **math** on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays.
**To make a long story short**: `array.array` is useful when you need a homogeneous C array of data for reasons *other than doing math*.
|
For almost all cases the normal list is the right choice. The arrays module is more like a thin wrapper over C arrays, which give you kind of strongly typed containers (see [docs](http://docs.python.org/library/array.html#module-array)), with access to more C-like types such as signed/unsigned short or double, which are not part of the built-in types. I'd say use the arrays module only if you really need it, in all other cases stick with lists.
|
Python list vs. array – when to use?
|
[
"",
"python",
"arrays",
"list",
""
] |
What do you recommend for setting up a shared server with php from a security/performance point of view?
* Apache mod\_php (how do you secure that? other than safe\_mode as it won't be in PHP6)
* Apache CGI + suexec
* Lighttpd and spawn a FastCGI per user
LE: I'm not interested in using an already made control panel as i'm trying to write my own so i want to know what's the best way to setup this myself.
I was thinking in using Lighttpd and spawn a fastcgi for every hosted user making the fcgi process run under his credentials (there is a tutorial for this on lighttpd wiki).
This would be somewhat secure but would this affect performance (lots of users / memory needed for every fcgi) so much that it's not a viable solution?
|
Personally, while Lighttpd is OK, I would go with Nginx + FastCGI if you end up going with a lightweight webserver + FastCGI solution. I've run benchmarks and read all the code, and Nginx is an order of magnitude faster/more stable under load -- it's very good.
But, that's not what you asked. Essentially, I would say there's a spectrum of security/scaleability vs. speed tradeoffs in the three options you list, and you just need to decide where you want to be. If you're a shared hosting provider with untrusted users installing god-knows-what PHP apps you'll lean more toward security, if this is shared amongst more trusted users you might lean toward performance. Here are my thoughts:
**CGI + suexec:** This is by far the most secure, and most efficient/scaleable for you in terms of numbers of users/sites in a shared hosting environment. Processes are spawned and memory used only as requests come in. Of course, the CGI-spawning makes this the slowest for execution time of individual scripts. How much slower? Well you would have to benchmark, but generally if people are running long-running apps (i.e. something like WordPress which takes 0.25-0.5 seconds just to load its libs and initialize on each request), then the CGI-spawning penalty starts to look pretty negligible in context.
**FastCGI:** The issue here (and it doesn't matter if your webserver is Apache, Lighttpd or Nginx) is figuring out how many FCGI child processes you let each user leave running, because each process eats memory equal to the size of the PHP interpreter (in Linux not all of it is wired of course, but I digress). And, unlike mod\_php, these processes aren't shared among users so you have to limit per user. For instance, Dreamhost caps this at 3 for their customers -- now, for a customer running a website that gets bursts of more than 2-5 page views a second, that's actually pretty bad because those requests just stack up and the site hangs. Now, I like FastCGI with a lightweight webserver when I'm running apps on a *dedicated* server/cluster, when I can give the app hundreds of FCGI children (all with webserver privs of course, à la Apache/prefork + mod\_php). But, I don't think it makes sense for shared hosting where you have to allocate/cap the FCGI children per user.
**Apache + mod\_php:** Least secure since everything running with webserver privs, but your pool of live PHP processes is shared so it's best on the performance end. From a developer perspective, I can't tolerate php\_safe mode, and from a sysadmin perspective it's really only an illusion of security (it mitigates against stupid users but doesn't protect from an actual attack) so I would actually rather have CGI if my other option has to include safe\_mode.
Dreamhost does sort of a hybrid, they do Apache CGI + suexec by default, but let the (small) percentage of their more users who are sophisticated elect to do FCGI if they want to, subject to a cap and their own monitoring of memory usage. That saves a ton of memory resources versus enabling FCGI for everyone by default.
Another issue if you're talking about standard commercial shared hosting is, Apache is full-featured, has modules for just about anything (including stuff like mod\_security you might want), and your users will like it because all their .htaccess configs will work etc. -- you will run into support headaches with anything else when they go to install Drupal or WordPress or whatever (a lot less of an issue if we're talking internal users).
Personally I would recommend just keeping it simple to start and going with CGI + suexec for best security and scaleability. If your users want FCGI or mod\_php and you have a good channel open for suggestions/communication with them, they'll ask for it, but either of these are a much bigger headache for you with only marginal performance improvements for them, so my suggestion would be to not do either of them initially but be responsive if they clamor for it.
I do sympathize with the desire to do something "interesting" like Lighttpd + FCGI instead of the standard Apache + CGI + suexec, but I deep down I really can't recommend it.
If you're running multiple servers, you could end up putting CGI on some and something else for the power users on the others. And be sure to have cron grep all the www dirs for things like old-ass versions of phpBB!
|
I recommend [Suhosin](http://www.hardened-php.net/suhosin/index.html)
|
What do you recommend for setting up a shared server with php
|
[
"",
"php",
"apache",
"lighttpd",
"shared-hosting",
""
] |
I'm trying to implement a unit test for a function in a project that doesn't have unit tests and this function requires a System.Web.Caching.Cache object as a parameter. I've been trying to create this object by using code such as...
```
System.Web.Caching.Cache cache = new System.Web.Caching.Cache();
cache.Add(...);
```
...and then passing the 'cache' in as a parameter but the Add() function is causing a NullReferenceException. My best guess so far is that I can't create this cache object in a unit test and need to retrieve it from the HttpContext.Current.Cache which I obviously don't have access to in a unit test.
How do you unit test a function that requires a System.Web.Caching.Cache object as a parameter?
|
When I've been faced with this sort of problem (where the class in question doesn't implement an interface), I often end up writing a wrapper with associated interface around the class in question. Then I use my wrapper in my code. For unit tests, I hand mock the wrapper and insert my own mock object into it.
Of course, if a mocking framework works, then use it instead. My experience is that all mocking frameworks have some issues with various .NET classes.
```
public interface ICacheWrapper
{
...methods to support
}
public class CacheWrapper : ICacheWrapper
{
private System.Web.Caching.Cache cache;
public CacheWrapper( System.Web.Caching.Cache cache )
{
this.cache = cache;
}
... implement methods using cache ...
}
public class MockCacheWrapper : ICacheWrapper
{
private MockCache cache;
public MockCacheWrapper( MockCache cache )
{
this.cache = cache;
}
... implement methods using mock cache...
}
public class MockCache
{
... implement ways to set mock values and retrieve them...
}
[Test]
public void CachingTest()
{
... set up omitted...
ICacheWrapper wrapper = new MockCacheWrapper( new MockCache() );
CacheManager manager = new CacheManager( wrapper );
manager.Insert(item,value);
Assert.AreEqual( value, manager[item] );
}
```
Real code
```
...
CacheManager manager = new CacheManager( new CacheWrapper( HttpContext.Current.Cache ));
manager.Add(item,value);
...
```
|
I think your best bet would be to use a mock object (look into Rhino Mocks).
|
Creating a System.Web.Caching.Cache object in a unit test
|
[
"",
"c#",
"asp.net",
""
] |
I have a standalone Java app that has some licensing code that I want to secure, i.e., prevent users from changing my software to circumvent the licensing. What is the best way to do this?
I've looked at obfuscation, but that entails all sorts of problems: reflection, serialization, messed-up stack traces, etc. Perhaps jar signing could be a solution? But how do I verify the jar at runtime? And how do I ensure that the user doesn't change the jar verification code?
|
Sorry, if your users are savy enough to tamper with your class files, they will remove the signature checking features first thing.
I agree with obfuscation, but shouldn't a good obfuscator keep some dictionary to convert an obfuscated stack-trace for you?
This discussion is really old, and really really complicated. Just look at the game industry. Maybe you should consider shipping a guitar with your application?
Combine the two, and you should have good synergies.
|
We currently use an obfuscator, which provides reasonable protection against attack. The one we are using right now provides a stack trace tool which will de-obfuscate them when they come out the other end (based upon the log file generated at obfuscation time).
Even with this, there is no real protection against the determined hacker.
|
Jar security
|
[
"",
"java",
"security",
""
] |
I want to save and store simple mail objects via serializing, but I get always an error and I can't find where it is.
```
package sotring;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.sun.org.apache.bcel.internal.generic.INEG;
public class storeing {
public static void storeMail(Message[] mail){
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("mail.ser"));
out.writeObject(mail);
out.flush();
out.close();
} catch (IOException e) {
}
}
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
for (int i=0; i< array.length;i++)
System.out.println("EMail von:"+ array[i].getSender() + " an " + array[i].getReceiver()+ " Emailbetreff: "+ array[i].getBetreff() + " Inhalt: " + array[i].getContent());
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
return null;
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User user1 = new User("User1", "geheim");
User user2 = new User("User2", "geheim");
Message email1 = new Message(user1.getName(), user2.getName(), "Test", "Fooobaaaar");
Message email2 = new Message(user1.getName(), user2.getName(), "Test2", "Woohoo");
Message email3 = new Message(user1.getName(), user2.getName(), "Test3", "Okay =) ");
Message [] mails = {email1, email2, email3};
storeMail(mails);
Message[] restored = getStoredMails();;
}
}
```
Here are the user and message class
```
public class Message implements Serializable{
static final long serialVersionUID = -1L;
private String receiver; //Empfänger
private String sender; //Absender
private String Betreff;
private String content;
private String timestamp;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
Message (String receiver, String sender, String Betreff, String content) {
this.Betreff= Betreff;
this.receiver = receiver;
this.sender = sender;
this.content = content;
this.timestamp = getDateTime();
}
Message() { // Just for loaded msg
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getBetreff() {
return Betreff;
}
public void setBetreff(String betreff) {
Betreff = betreff;
}
public String getContent() {
return content;
}
public String getTime() {
return timestamp;
}
public void setContent(String content) {
this.content = content;
}
}
public class User implements Serializable{
static final long serialVersionUID = -1L;
private String username; //unique Username
private String ipadress; //changes everytime
private String password; //Password
private int unreadMsg; //Unread Messages
private static int usercount;
private boolean online;
public String getName(){
return username;
}
public boolean Status() {
return online;
}
public void setOnline() {
this.online = true;
}
public void setOffline() {
this.online = false;
}
User(String username,String password){
if (true){
this.username = username;
this.password = password;
usercount++;
} else System.out.print("Username not availiable");
}
public void changePassword(String newpassword){
password = newpassword;
}
public void setIP(String newip){
ipadress = newip;
}
public String getIP(){
if (ipadress.length() >= 7){
return ipadress;
} else return "ip address not set.";
}
public int getUnreadMsg() {
return unreadMsg;
}
}
```
Here is the exception:
`exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type Message[]
at sotring.storeing.getStoredMails(storeing.java:22)
at sotring.storeing.main(storeing.java:57)`
THANK YOU FOR YOUR HELP!!!!!!!!!!!
|
If an exception occurs, you never get to the return statement in getStoredMails. You need to either throw the exception you catch (possibly wrapping it in another more descriptive exception) or just return null at the end of the method. It really depends on what you want to do if there's an error.
Oh, and your in.close() should be in a finally block. Otherwise, it is possible that you could read the data fine but then throw it away if you can't close the stream.
|
The catch clauses need to return something.
```
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null; //fix
}
```
|
Java: Serializing beginner problem :-(
|
[
"",
"java",
"arrays",
"serialization",
""
] |
I've got to get a quick and dirty configuration editor up and running. The flow goes something like this:
configuration (POCOs on server) are serialized to XML.
The XML is well formed at this point. The configuration is sent to the web server in XElements.
On the web server, the XML (Yes, ALL OF IT) is dumped into a textarea for editing.
The user edits the XML directly in the webpage and clicks Submit.
In the response, I retrieve the altered text of the XML configuration. At this point, ALL escapes have been reverted by the process of displaying them in a webpage.
I attempt to load the string into an XML object (XmlElement, XElement, whatever). KABOOM.
The problem is that serialization escapes attribute strings, but this is lost in translation along the way.
For example, let's say I have an object that has a regex. Here's the configuration as it comes to the web server:
```
<Configuration>
<Validator Expression="[^<]" />
</Configuration>
```
So, I put this into a textarea, where it looks like this to the user:
```
<Configuration>
<Validator Expression="[^<]" />
</Configuration>
```
So the user makes a slight modification and submits the changes back. On the web server, the response string looks like:
```
<Configuration>
<Validator Expression="[^<]" />
<Validator Expression="[^&]" />
</Configuration>
```
So, the user added another validator thingie, and now BOTH have attributes with illegal characters. If I try to load this into any XML object, it throws an exception because < and & are not valid within a text string. I CANNOT CANNOT CANNOT CANNOT use any kind of encoding function, as it encodes the entire bloody thing:
var result = Server.HttpEncode(editedConfig);
results in
```
<Configuration>
<Validator Expression="[^<]" />
<Validator Expression="[^&]" />
</Configuration>
```
This is NOT valid XML. If I try to load this into an XML element of any kind I will be hit by a falling anvil. I don't like falling anvils.
SO, the question remains... Is the ONLY way I can get this string XML ready for parsing into an XML object is by using regex replaces? Is there any way to "turn off constraints" when I load? How do you get around this???
---
One last response and then wiki-izing this, as I don't think there is a valid answer.
The XML I place in the textarea IS valid, escaped XML. The process of 1) putting it in the text area 2) sending it to the client 3) displaying it to the client 4) submitting the form it's in 5) sending it back to the server and 6) retrieving the value from the form REMOVES ANY AND ALL ESCAPES.
Let me say this again: I'M not un-escaping ANYTHING. Just displaying it in the browser does this!
Things to mull over: Is there a way to prevent this un-escaping from happening in the first place? Is there a way to take almost-valid XML and "clean" it in a safe manner?
---
This question now has a bounty on it. To collect the bounty, you demonstrate how to edit VALID XML in a browser window WITHOUT a 3rd party/open source tool that doesn't require me to use regex to escape attribute values manually, that doesn't require users to escape their attributes, and that doesn't fail when roundtripping (&amp;amp;amp;etc;)
|
Erm … *How* do you serialize? Usually, the XML serializer should never produce invalid XML.
/EDIT in response to your update: Do **not** display invalid XML to your user to edit! Instead, display the properly escaped XML in the TextBox. Repairing broken XML isn't fun and I actually see no reason not to display/edit the XML in a valid, escaped form.
Again I could ask: *how* do you display the XML in the TextBox? You seem to intentionally unescape the XML at some point.
/EDIT in response to your latest comment: Well yes, obviously, since the it can contain HTML. You need to escape your XML properly before writing it out into an HTML page. With that, I mean the *whole* XML. So this:
```
<foo mean-attribute="<">
```
becomes this:
```
<foo mean-attribute="&<">
```
|
Of course when you put entity references inside a textarea they come out unescaped. Textareas aren't magic, you have to &escape everything you put in them just like every other element. Browsers might *display* a raw '<' in a textarea, but only because they're trying to clean up your mistakes.
So if you're putting editable XML in a textarea, you need to escape the attribute value once to make it valid XML, and then you have to escape the whole XML again to make it valid HTML. The final source you want to appear in the page would be:
```
<textarea name="somexml">
<Configuration>
<Validator Expression="[^&lt;]" />
<Validator Expression="[^&amp;]" />
</Configuration>
</textarea>
```
Question is based on a misunderstanding of the content model of the textarea element - a validator would have picked up the problem right away.
ETA re comment: Well, what problem remains? That's the issue on the serialisation side. All that remains is parsing it back in, and for that you have to assume the user can create well-formed XML.
Trying to parse non-well-formed XML, in order to allow errors like having '<' or '&' unescaped in an attribute value is a loss, totally against how XML is supposed to work. If you can't trust your users to write well-formed XML, give them an easier non-XML interface, such as a simple newline-separated list of regexp strings.
|
How the heck can you edit valid XML in a webpage?
|
[
"",
"c#",
"xml",
"serialization",
"character-encoding",
""
] |
I'm building an application that is used by several different customers. Each customer has a fair amount of custom business logic, which I have cleverly refactored out into an assembly that gets loaded at runtime. The name of that assembly, along with a number of other customer-specific settings, are stored in the application's configuration file.
Right now, here's what I have to do in order to debug the application for customer foo:
1. Go to the filesystem in my project directory and delete `app.config`
2. Copy `app.config.foo` to `app.config.foo - Copy`.
3. Rename `app.config.foo - Copy` as `app.config`.
4. Tell Windows that yes, I want to change the file's extension.
5. Switch back to Visual Studio.
6. Open the `Settings.settings` item in my project.
7. Click "Yes" 13 or 14 times as VS asks me if I want to use the new settings that have been changed in `app.config`.
8. Close `Settings.settings`.
Okay! Now I'm ready to debug!
It seems to me that the rigamarole of opening `Settings.settings` is, or ought to be, unnecessary: I don't need the default values in `Settings.cs` to be regenerated, because I don't use them. But it's the only way I know of to make VS aware of the fact that the `app.config` file has changed, so that the build will copy it to the output directory.
There's got to be an easier way of doing this. What is it?
|
A couple of people suggested using multiple VS configurations, which I think would have worked, except that it would require me to rebuild the solution every time I switched between configurations.
What I did instead seemed a little stupid while I was doing it, but I've been using it for nearly a year now and it works extremely smoothly. In my project directly, I create a separate `app.config.XXX` file for each customer. The actual `app.config` file is used solely to generate `Settings.cs` - it has all of the correct setting names and their default values. It doesn't get copied to the build directories, ever.
Then I wrote a little program that lets me select a customer, and that simply goes through the directories for each project and, if I selected customer XXX, copies `app.config.XXX` to `bin\debug\myprogram.exe.config` and `bin\release\myprogram.exe.config`. As long as this program knows where the root of the solution is (I have to be a little careful whenever I branch the code), it works like a charm.
|
You can also let Visual Studio automate Robert`s approach by:
1. Define a Build Configuration for each client
2. In the post build event, simply xcopy app.config.xxx to your bin folder. Where XXX is the name of a Build Config accessible in VS. Something like: xcopy app.config.$(ConfigurationName) $(OutDir)/app.config
VS will drop a distinct build for your clients in separate folders, aolong with the proper config file.
bin/Client1/
bin/Client2/
|
Manage multiple app config files during development
|
[
"",
"c#",
".net",
"visual-studio",
"app-config",
""
] |
I have the following unmanaged C++ code:
```
MessageBox( NULL, strMessage, "Cool Product", MB_RETRYCANCEL | MB_ICONEXCLAMATION);
```
I want to disable the RETRY button for 10 seconds (for example), then enable it.
How can I do this?
|
Like [@ffpf](https://stackoverflow.com/questions/176062/how-do-i-disable-and-then-enable-the-retry-button-in-a-messagebox-c#176082) says, you need to make your own dialog to do this, using MFC, ATL, raw Win32, etc.
Then create a timer that would enable and disable the button.
|
You cannot directly manipulate the MessageBox controls, but you can use a hack. Install a WH`_`CBT hook just before displaying the dialog and handle the HCBT`_`ACTIVATE event. This will give you the HWND of the message box, so that you can do whatever you want with it (subclass it, manage its buttons and set a timer).
You can find a [Custom MessageBox](http://www.catch22.net/tuts/msgbox) tutorial with demo code in James Brown's site.
|
How do I disable and then enable the Retry button in a MessageBox?
|
[
"",
"c++",
"winapi",
"unmanaged",
""
] |
I'm possibly just stupid, but I'm trying to find a user in Active Directory from C#, using the Login name ("domain\user").
My "Skeleton" AD Search Functionality looks like this usually:
```
de = new DirectoryEntry(string.Format("LDAP://{0}", ADSearchBase), null, null, AuthenticationTypes.Secure);
ds = new DirectorySearcher(de);
ds.SearchScope = SearchScope.Subtree;
ds.PropertiesToLoad.Add("directReports");
ds.PageSize = 10;
ds.ServerPageTimeLimit = TimeSpan.FromSeconds(2);
SearchResult sr = ds.FindOne();
```
Now, that works if I have the full DN of the user (ADSearchBase usually points to the "Our Users" OU in Active Directory), but I simply have no idea how to look for a user based on the "domain\user" syntax.
Any Pointers?
|
You need to set a filter (DirectorySearcher.Filter) something like:
"(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))"
Note that you only specify the username (without the domain) for the property sAMAccountName. To search for domain\user, first locate the naming context for the required domain, then search there for sAMAccountName.
By the way, when building LDAP query strings using String.Format, you should generally be careful to escape any special characters. It probably isn't necessary for an account name, but could be if you're searching by other properties such as the user's first (givenName property) or last (sn property) name. I have a utility method EscapeFilterLiteral to do this: you build your string like this:
```
String.Format("(&(objectCategory=person)(objectClass=user)(sn={0}))",
EscapeFilterLiteral(lastName, false));
```
where EscapeFilterLiteral is implemented as follows:
```
public static string EscapeFilterLiteral(string literal, bool escapeWildcards)
{
if (literal == null) throw new ArgumentNullException("literal");
literal = literal.Replace("\\", "\\5c");
literal = literal.Replace("(", "\\28");
literal = literal.Replace(")", "\\29");
literal = literal.Replace("\0", "\\00");
literal = literal.Replace("/", "\\2f");
if (escapeWildcards) literal = literal.Replace("*", "\\2a");
return literal;
}
```
This implementation allows you treat the \* character as part of the literal (escapeWildcard = true) or as a wildcard character (escapeWildcard = false).
UPDATE: This is nothing to do with your question, but the example you posted does not call Dispose on the disposable objects it uses. Like all disposable objects these objects (DirectoryEntry, DirectorySearcher, SearchResultCollection) should always be disposed, normally with the using statement. See [this post](https://stackoverflow.com/questions/90652/can-i-get-more-than-1000-records-from-a-directorysearcher-in-aspnet#90668) for more info.
|
Thanks. I figured that i can get the Domain (at least in my AD) through specifying "LDAP://{0}.somedomain.com/DC={0},DC=somedomain,DC=com", replacing {0} with the domain, which works in our my environment at least.
One question though: sAMAccountName seems depreciated: [The logon name used to support clients and servers running older versions of the operating system, such as Windows NT 4.0, Windows 95, Windows 98, and LAN Manager. This attribute must be less than 20 characters to support older clients.](http://msdn.microsoft.com/en-us/library/ms679635%28VS.85%29.aspx)
Is this still the best approach to it? Or is there a more "modern" field to query? (Windows 2003 Active Directory, Windows XP or 2003 Clients, .net 3.0)
**Edit:** Thanks again. Our structure is a bit complicated: we have a big "domain.com" forest, with several domains for regional offices. Essentially: The Login is "something\username", the full domain us something.domain.com and the mail is user@domain.com (without the something), but the principal name is user@something.domain.com. I will manually "translate" something\username to username@something.domain.com, as this seems to be the most robust way. Especially since I want to keep the Auto-Discovery feature in.
|
Finding a User in Active Directory with the Login Name
|
[
"",
"c#",
"active-directory",
""
] |
Is it possible to produce an alert similar to JavaScript's alert("message") in python, with an application running as a daemon.
This will be run in Windows, Most likely XP but 2000 and Vista are also very real possibilities.
Update:
This is intended to run in the background and alert the user when certain conditions are met, I figure that the easiest way to alert the user would be to produce a pop-up, as it needs to be handled immediately, and other options such as just logging, or sending an email are not efficient enough.
|
what about this:
```
import win32api
win32api.MessageBox(0, 'hello', 'title')
```
Additionally:
```
win32api.MessageBox(0, 'hello', 'title', 0x00001000)
```
will make the box appear on top of other windows, for urgent messages. See [MessageBox function](http://msdn.microsoft.com/en-us/library/windows/desktop/ms645505(v=vs.85).aspx) for other options.
|
For those of us looking for a purely Python option that doesn't interface with Windows and is platform independent, I went for the option listed on the following website:
<https://pythonspot.com/tk-message-box/> (archived link: <https://archive.ph/JNuvx>)
```
# Python 3.x code
# Imports
import tkinter
from tkinter import messagebox
# This code is to hide the main tkinter window
root = tkinter.Tk()
root.withdraw()
# Message Box
messagebox.showinfo("Title", "Message")
```
You can choose to show various types of messagebox options for different scenarios:
* showinfo()
* showwarning()
* showerror ()
* askquestion()
* askokcancel()
* askyesno ()
* askretrycancel ()
*edited code per my comment below*
|
Alert boxes in Python?
|
[
"",
"python",
"alerts",
""
] |
When writing the string "¿" out using
```
System.out.println(new String("¿".getBytes("UTF-8")));
```
¿ is written instead of just ¿.
WHY? And how do we fix it?
|
You don't have to use UTF-16 to solve this:
```
new String("¿".getBytes("UTF-8"), "UTF-8");
```
works just fine. As long as the encoding given to the `getBytes()` method is the same as the encoding you pass to the String constructor, you should be fine!
|
You need to specify the Charset in the String constructor (see the [API docs](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#String%28byte[],%20java.nio.charset.Charset%29)).
|
Why does the string "¿" get translated to "¿" when calling .getBytes()
|
[
"",
"java",
"utf-8",
"character-encoding",
""
] |
Exception: Failed to compare two elements in the array.
```
private void assignNames(DropDownList ddl, Hashtable names)
{
List<ListItem> nameList = new List<ListItem>();
if (ddl != null)
{
ddl.ClearSelection();
ddl.Items.Add(new ListItem("Select Author"));
foreach (string key in names.Keys)
{
nameList.Add(new ListItem(names[key].ToString(), key));
}
nameList.Sort();
}
```
So how can I use Sort() to compare on the "names" and not get stuck on the key?
|
Provide a [`Comparison<T>`](http://msdn.microsoft.com/en-us/library/tfakywbh.aspx) to instruct the [`List`](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) on how to sort the items.
```
nameList.Sort(delegate(ListItem thisItem, ListItem otherItem) {
return thisItem.Text.CompareTo(otherItem.Text);
});
```
You might also want to check for `null` to be complete, unless you already know there won't be any, as in this case.
|
nameList=nameList.OrderBy(li => li.Text).ToList();
|
C# - Sorting a list when it has more than one value per 'row'?
|
[
"",
"c#",
".net",
"list",
"sorting",
""
] |
I'm looking for a good reader/writer lock in C++. We have a use case of a single infrequent writer and many frequent readers and would like to optimize for this. Preferable I would like a cross-platform solution, however a Windows only one would be acceptable.
|
Newer versions of [boost::thread](http://www.boost.org/doc/libs/1_50_0/doc/html/thread.html) have read/write locks (1.35.0 and later, apparently the previous versions did not work correctly).
They have the names [`shared_lock`](http://www.boost.org/doc/libs/1_50_0/doc/html/thread/synchronization.html#thread.synchronization.locks.unique_lock), [`unique_lock`](http://www.boost.org/doc/libs/1_50_0/doc/html/thread/synchronization.html#thread.synchronization.locks.shared_lock), and [`upgrade_lock`](http://www.boost.org/doc/libs/1_50_0/doc/html/thread/synchronization.html#thread.synchronization.locks.upgrade_lock) and operate on a [`shared_mutex`](http://www.boost.org/doc/libs/1_50_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex).
|
Since C++ 14 (VS2015) you can use the standard:
```
#include <shared_mutex>
typedef std::shared_mutex Lock;
typedef std::unique_lock< Lock > WriteLock; // C++ 11
typedef std::shared_lock< Lock > ReadLock; // C++ 14
Lock myLock;
void ReadFunction()
{
ReadLock r_lock(myLock);
//Do reader stuff
}
void WriteFunction()
{
WriteLock w_lock(myLock);
//Do writer stuff
}
```
For older compiler versions and standards you can use **boost** to create a read-write lock:
```
#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>
typedef boost::shared_mutex Lock;
typedef boost::unique_lock< Lock > WriteLock;
typedef boost::shared_lock< Lock > ReadLock;
```
|
Reader/Writer Locks in C++
|
[
"",
"c++",
"multithreading",
"locking",
""
] |
I need to be able to validate a string against a list of the possible United States Postal Service state abbreviations, and Google is not offering me any direction.
I know of the obvious solution: and that is to code a horridly huge if (or switch) statement to check and compare against all 50 states, but I am asking StackOverflow, since there has to be an easier way of doing this. Is there any RegEx or an enumerator object out there that I could use to quickly do this the most efficient way possible?
[C# and .net 3.5 by the way]
[List of USPS State Abbreviations](https://www.usps.com/send/official-abbreviations.htm)
|
I like something like this:
```
private static String states = "|AA|AE|AK|AL|AP|AR|AS|AZ|CA|CO|CT|DE|DC|FL|FM|GA|GU|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MH|MI|MN|MO|MP|MS|MT|NC|ND|NE|NH|NJ|NM|NV|NY|OH|OK|OR|PA|PR|PW|RI|SC|SD|TN|TX|UM|UT|VA|VI|VT|WA|WI|WV|WY|";
public static bool isStateAbbreviation (String state)
{
return state.Length == 2 && states.IndexOf( state ) > 0;
}
```
This method has the advantage of using an optimized system routine that is probably using a single machine instruction to do the search. If I was dealing with non-fixed length words, then I'd check for "|" + state + "|" to ensure that I hadn't hit a substring instead of full match. That would take a wee bit longer, due to the string concatenation, but it would still match in a fixed amount of time. If you want to validate lowercase abbreviations as well as uppercase, then either check for state.UpperCase(), or double the 'states' string to include the lowercase variants.
I'll guarantee that this will beat the Regex or Hashtable lookups every time, no matter how many runs you make, and it will have the least memory usage.
|
I'd populate a hashtable with valid abbreviations and then check it with the input for validation. It's much cleaner and probably faster if you have more than one check per dictionary build.
|
Validate String against USPS State Abbreviations
|
[
"",
"c#",
".net",
""
] |
I'm trying to get the following code working:
```
string url = String.Format(@"SOMEURL");
string user = "SOMEUSER";
string password = "SOMEPASSWORD";
FtpWebRequest ftpclientRequest = (FtpWebRequest)WebRequest.Create(new Uri(url));
ftpclientRequest.Method = WebRequestMethods.Ftp.ListDirectory;
ftpclientRequest.UsePassive = true;
ftpclientRequest.Proxy = null;
ftpclientRequest.Credentials = new NetworkCredential(user, password);
FtpWebResponse response = ftpclientRequest.GetResponse() as FtpWebResponse;
```
This normally works, but for 1 particular server this gives an Error 500: Syntax not recognized. The Change Directory command is disabled on the problem server, and the site administrator told me that .NET issues a Change Directory command by default with all FTP connections. Is that true? Is there a way to disable that?
EDIT: When I login from a command line I am in the correct directory:
ftp> pwd
257 "/" is current directory
|
I just tested this on one of our dev servers and indeed there is a CWD issued by the .NET FtpWebRequest:
```
new connection from 172.16.3.210 on 172.16.3.210:21 (Explicit SSL)
hostname resolved : devpc
sending welcome message.
220 Gene6 FTP Server v3.10.0 (Build 2) ready...
USER testuser
testuser, 331 Password required for testuser.
testuser, PASS ****
testuser, logged in as "testuser".
testuser, 230 User testuser logged in.
testuser, OPTS utf8 on
testuser, 501 Please CLNT first.
testuser, PWD
testuser, 257 "/" is current directory.
testuser, CWD /
testuser, change directory '/' -> 'D:\testfolder' --> Access allowed.
testuser, 250 CWD command successful. "/" is current directory.
testuser, TYPE I
testuser, 200 Type set to I.
testuser, PORT 172,16,3,210,4,127
testuser, 200 Port command successful.
testuser, NLST
testuser, 150 Opening data connection for directory list.
testuser, 226 Transfer ok.
testuser, 421 Connection closed, timed out.
testuser, disconnected. (00d00:05:01)
```
This was without even specifying '/' in the uri when creating the FtpWebRequest object.
If you debug or browse the source code, a class called 'FtpControlStream' comes into play. See call stack:
```
System.dll!System.Net.FtpControlStream.BuildCommandsList(System.Net.WebRequest req) Line 555 C#
System.dll!System.Net.CommandStream.SubmitRequest(System.Net.WebRequest request =
{System.Net.FtpWebRequest}, bool async = false, bool readInitalResponseOnConnect = true) Line 143 C#
System.dll!System.Net.FtpWebRequest.TimedSubmitRequestHelper(bool async) Line 1122 + 0x13 bytes C#
System.dll!System.Net.FtpWebRequest.SubmitRequest(bool async = false) Line 1042 + 0xc bytes C#
System.dll!System.Net.FtpWebRequest.GetResponse() Line 649 C#
```
There's a method named BuildCommandsList() which is invoked. BuildCommandsList() builds a list of commands to send to the FTP server. This method has the following snippet of code:
```
if (m_PreviousServerPath != newServerPath) {
if (!m_IsRootPath
&& m_LoginState == FtpLoginState.LoggedIn
&& m_LoginDirectory != null)
{
newServerPath = m_LoginDirectory+newServerPath;
}
m_NewServerPath = newServerPath;
commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", newServerPath), PipelineEntryFlags.UserCommand));
}
```
Upon the first connection to the server m\_PreviousServerPath is always null, the value of newServerPath is "/" and is computed by a function named GetPathAndFileName() (invoked a few lines prior to this block of code). GetPathAndFileName() computes newServerPath as "/" if no path is supplied or if "/" is explicitly tacked on the end of the 'ftp://....' uri.
So this of course ultimately causes the CWD command to be added to the command pipeline because null != "/".
In a nutshell unfortunately you can't override this behaviour because it's burned in the source.
|
Though the post is like long time ago... never mind, I'll provide the answer here.
Instead of using `ftp://server/path` as the uri, try `ftp://server/%2fpath/`.
The added `%2f`" is just an escaped `/`, adding this will make C# treat the whole path as absolute.
Or else C# will login to `ftp://server/` with the username, go to the user's home folder, then cd to your specified path, so your path become `user_home_path/path`, which may not be desirable.
More info could be found at msdn
<http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx>
Hope this helps.
|
C# FTP with CD Disabled
|
[
"",
"c#",
"ftp",
""
] |
I have an application where 2 threads are running... Is there any certanty that when I change a global variable from one thread, the other will notice this change?
I don't have any syncronization or Mutual exclusion system in place... but should this code work all the time (imagine a global **bool** named **dataUpdated**):
Thread 1:
```
while(1) {
if (dataUpdated)
updateScreen();
doSomethingElse();
}
```
Thread 2:
```
while(1) {
if (doSomething())
dataUpdated = TRUE;
}
```
Does a compiler like gcc optimize this code in a way that it doesn't check for the global value, only considering it value at compile time (because it nevers get changed at the same thred)?
PS: Being this for a game-like application, it really doen't matter if there will be a read while the value is being written... all that matters is that the change gets noticed by the other thread.
|
Yes. No. Maybe.
First, as others have mentioned you need to make dataUpdated volatile; otherwise the compiler may be free to lift reading it out of the loop (depending on whether or not it can see that doSomethingElse doesn't touch it).
Secondly, depending on your processor and ordering needs, you may need memory barriers. volatile is enough to guarentee that the other processor will see the change eventually, but not enough to guarentee that the changes will be seen in the order they were performed. Your example only has one flag, so it doesn't really show this phenomena. If you need and use memory barriers, you should no longer need volatile
[Volatile considered harmful](http://www.kernel.org/doc/Documentation/volatile-considered-harmful.txt) and [Linux Kernel Memory Barriers](http://www.kernel.org/doc/Documentation/memory-barriers.txt) are good background on the underlying issues; I don't really know of anything similar written specifically for threading. Thankfully threads don't raise these concerns nearly as often as hardware peripherals do, though the sort of case you describe (a flag indicating completion, with other data presumed to be valid if the flag is set) is exactly the sort of thing where ordering matterns...
|
Here is an example that uses boost condition variables:
```
bool _updated=false;
boost::mutex _access;
boost::condition _condition;
bool updated()
{
return _updated;
}
void thread1()
{
boost::mutex::scoped_lock lock(_access);
while (true)
{
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
// note that the second parameter to timed_wait is a predicate function that is called - not the address of a variable to check
if (_condition.timed_wait(lock, &updated, xt))
updateScreen();
doSomethingElse();
}
}
void thread2()
{
while(true)
{
if (doSomething())
_updated=true;
}
}
```
|
C++ Thread, shared data
|
[
"",
"c++",
"multithreading",
"synchronization",
"mutex",
""
] |
I have three tables, A, B, C, where A is many to one B, and B is many to one C. I'd like a list of all C's in A.
My tables are something like this: A[id, valueA, lookupB], B[id, valueB, lookupC], C[id, valueC]. I've written a query with two nested SELECTs, but I'm wondering if it's possible to do INNER JOIN with DISTINCT somehow.
```
SELECT valueC
FROM C
INNER JOIN
(
SELECT DISTINCT lookupC
FROM B INNER JOIN
(
SELECT DISTINCT lookupB
FROM A
)
A2 ON B.id = A2.lookupB
)
B2 ON C.id = B2.lookupC
```
EDIT:
The tables are fairly large, A is 500k rows, B is 10k rows and C is 100 rows, so there are a lot of uneccesary info if I do a basic inner join and use DISTINCT in the end, like this:
```
SELECT DISTINCT valueC
FROM
C INNER JOIN B on C.id = B.lookupB
INNER JOIN A on B.id = A.lookupB
```
This is very, very slow (magnitudes times slower than the nested SELECT I do above.
|
I did a test on MS SQL 2005 using the following tables: A 400K rows, B 26K rows and C 450 rows.
The estimated query plan indicated that the basic inner join would be 3 times slower than the nested sub-queries, however when actually running the query, the basic inner join was twice as fast as the nested queries, The basic inner join took 297ms on very minimal server hardware.
What database are you using, and what times are you seeing? I'm thinking if you are seeing poor performance then it is probably an index problem.
|
I believe your **1:m** relationships should already implicitly create DISTINCT JOINs.
But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.
```
SELECT DISTINCT a.valueA, c.valueC
FROM C
INNER JOIN B ON B.lookupC = C.id
INNER JOIN A ON A.lookupB = B.id
ORDER BY a.valueA, c.valueC
```
|
Using DISTINCT inner join in SQL
|
[
"",
"sql",
"distinct",
"inner-join",
""
] |
Someone told me that it's faster to concatenate strings with StringBuilder. I have changed my code but I do not see any Properties or Methods to get the final build string.
How can I get the string?
|
You can use `.ToString()` to get the `String` from the `StringBuilder`.
|
When you say "it's faster to concatenate strings with a `StringBuilder`", this is only true if you are **repeatedly** (I repeat - **repeatedly**) concatenating to the same object.
If you're just concatenating 2 strings and doing something with the result immediately as a `string`, there's no point to using `StringBuilder`.
I just stumbled on Jon Skeet's nice write up of this:
<https://jonskeet.uk/csharp/stringbuilder.html>
If you are using `StringBuilder`, then to get the resulting `string`, it's just a matter of calling `ToString()` (unsurprisingly).
|
StringBuilder: how to get the final String?
|
[
"",
"c#",
"string",
"stringbuilder",
""
] |
I would like to learn more about C++0x. What are some good references and resources? Has anyone written a good book on the subject yet?
|
## Articles on
[Lambda Expressions](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=254),
[The Type Traits Library](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=276),
[The rvalue Reference](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=310),
[Concepts](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=313),
[Variadic Templates](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=396),
[shared\_ptr](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=239)
[Regular Expressions](http://www.ddj.com/cpp/185300414)
[Tuples](http://www.ddj.com/cpp/184401974)
[Multi Threading](http://www.informit.com/guides/printerfriendly.aspx?g=cplusplus&seqNum=414)
## General Discussion
[The C/C++ Users Journal](http://www.petebecker.com/newlib1.html),
[The New C++](http://www.petebecker.com/newlib.html),
[Article](http://www.artima.com/cppsource/cpp0x.html)
## Videos
[Google tech talk](http://video.google.com/videoplay?docid=2768126766555555011)
## overview of various features
[overview at wikipedia](http://en.wikipedia.org/wiki/C%2B%2B0x)
## Library
[Boost](http://www.boost.org/)
|
* [ISO C++ committee](http://www.open-std.org/jtc1/sc22/wg21/)
* [Bjarne Stroustrup](http://www.research.att.com/~bs)
+ Especially his [C++0x FAQ](http://www.research.att.com/~bs/C++0xFAQ.html)
+ [*The Design of C++0x* (pdf)](http://www.research.att.com/~bs/rules.pdf) from C/C++ Users Journal, May 2005
* Wikipedia's [C++0x article](http://en.wikipedia.org/wiki/C%2B%2B0x)
* G++'s [experimental support for C++0x](http://gcc.gnu.org/projects/cxx0x.html) with the -std=c++0x switch
* SO's [c++0x](/questions/tagged/c%2b%2b0x "show questions tagged 'c++0x'") tag
|
Where can I learn more about C++0x?
|
[
"",
"c++",
"c++11",
"reference-manual",
""
] |
I'm using the MIDP 2.0 (JSR 118) and I just noticed that there is no reader for strings in J2ME.
Does anyone know how you are supposed to read Strings from an `InputStream` or `InputStreamReader` in a platform independent way (i.e. between two java enabled cell phones of different models)?
|
Alternatively have a look at [`DataInputStream.readUTF()`](http://java.sun.com/javame/reference/apis/jsr118/java/io/DataInputStream.html#readUTF()).
It does required that the string being read off the InputStream be encoded appropriately (as in by a corresponding [`DataOutputStream.writeUTF(String)`](http://java.sun.com/javame/reference/apis/jsr118/java/io/DataOutputStream.html#writeUTF(java.lang.String))) so it might not be what you're looking for - but it does work across different phones/models etc.
|
Which profile are you using? The MID profile in JSR 118 specifies [InputStreamReader](http://java.sun.com/javame/reference/apis/jsr118/java/io/InputStreamReader.html) (not StringReader, but that wouldn't help you read from an InputStream anyway).
EDIT: To reflect the change to the question :)
You use InputStreamReader.read(char[], int, int) and when you've read all you want to, create a new string from a char array. If you want to read a line at a time as you would from BufferedReader, you basically need to implement the functionality of BufferedReader yourself (keeping a buffer of "read but not consumed" chars) and keep reading until you hit a line break.
|
How do I read strings in J2ME?
|
[
"",
"java",
"java-me",
"network-programming",
"midp",
""
] |
I want to override OnMouseClick and OnMouseDoubleClick and perform different actions depending on which click style was used.
The problem is that OnMouseClick is happening for both single and double clicks, and is getting called before OnMouseDoubleClick.
I'm certain this must be a common requirement, so I guess I'm missing something pretty obvious. Can someone fill me in?
Edit to add: the MouseEventArgs.Clicks count doesn't help. In the case of a double-click, the first click is handled as a single click in OnMouseClick with MouseEventArgs.Clicks == 1.
Edit to add: the objects are image thumbnails. Single click should toggle selection on and off for export. Double click should make the thumbnail full screen. The selection and "activation" actions are orthogonal. This may indicate an underlying problem with the two actions...
Cheers,
Rob
|
That happens throughout Windows. I don't think they added anything special to handle it in .Net.
The normal means of handling this is
* a) just make single click something
you'd want to happen before a double
click, like select.
* b) if that's not an option, then on the click event, start a timer. On the timer tick, do the single click action. If the double-click event occurs first, kill the timer, and do the double click action.
The amount of time you set the time for should be equal to the system's Double-Click time (which the user can specify in the control panel). It's available from System.Windows.Forms.SystemInformation.DoubleClickTime. The full details are in the MSDN, [here](http://msdn.microsoft.com/en-us/library/ms172533.aspx)
|
The issue is that most objects don't implement both. The few objects that can reasonably have different actions for single and double clicks generally are OK to run the single click action before the double click action (highlight then open a folder, enter focus on an address bar before selecting it, etc.) The only way to determine would probably be to wait on the single click for an amount of time and cancel the action for the single click if a double click is detected.
|
How can I differentiate between single and double clicks in .Net?
|
[
"",
"c#",
".net",
"user-interface",
"click",
""
] |
I've been given a requirement for an internal web application to send documents to a printer transparently. The idea would be that the user can select their nearest printer, and the web application would send their print jobs to the printer they selected.
The first printer we have to roll out against are Canons, so my questions is: How would I go about sending a document to print aross the network to a specific Canon? The type of Cannon is question is an iR5570 and the documents that will be said will mainly be Word and PDFs
I'm currently working my way through the terrible, IE only Canon Developer site, but I'm kinda hoping someone can point me in the right direction or point me at a 3rd party assembly :)
|
The key phrase in that question is 'web application'.
In a normal web app using only HTML+Javascript over HTTP, you *can't* just send a document directly to a printer. That's one of the reasons web browsers exist, and without that functionality everyone's printer would collect the same kind of junk that a public fax machine does.
So you need some kind of work-around. One option is to build on a common plug-in, like flash, silverlight, java applet, or even something like greasemonkey. Another is a custom plug-in, like a hosted winforms control or custom browser extension.
You are very fortunate, in that it looks like you have complete control (or knowlege of) the deployment environment, and that this environment if fairly homogenous. This means you have an additional option that others have started to explore. If you can install all of the printers in your environment to the web server, then it's fairly easy using the built-in .Net printer classes (in the `System.Drawing.Printing` namespace) to list out those printer, either show them to the user so they can pick or keep some kind of IP to Printer mapping table, and then print directly to that printer from your web app. Note that this scheme may require your app to run at a higher level of trust than would otherwise be required.
Now it comes to actually printing your PDF's and word documents. For acrobat, check this link:
[http://support.adobe.com/devsup/devsup.nsf/docs/52080.htm](http://web.archive.org/web/20090206162133/http://support.adobe.com/devsup/devsup.nsf/docs/52080.htm) (Wayback machine)
Note that it's a little dated, but I believe the concept is still valid. You'll have to experiment some to make sure it works as expected.
For Word, I'm not normally a fan of Office interop/automation in a web app. But in this case you're not editing any documents: just loading it up long enough to print. And the fact that you're relying on another scarce resource (the printers) should keep this from scaling beyond what your web server could cope with. So you may have a rare case where Office automation in a web project makes sense.
|
Many printers and multifunction devices today support the printing of PDFs directly, this may solve one of your problems. Simply have the PDF sent to the printer. In fact, some even support the sending of a URL and the printer will then go get the document and print it. Lexmark for sure does this and I think a few other vendors do as well. This still mean you have to deal with the Word document. Word 2007 supports PDF (with the [add-in installed from Microsoft](http://www.microsoft.com/downloads/details.aspx?FamilyId=4D951911-3E7E-4AE6-B059-A2E79ED87041&displaylang=en)) and I've used this function programatically with great success in C#.
Here's the code for that:
```
Microsoft.Office.Interop.Word.ApplicationClass msWord = new Microsoft.Office.Interop.Word.ApplicationClass();
object paramUnknown = Type.Missing;
object missing = Type.Missing;
object paramSaveChangesNo = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
//object paramFonts = Microsoft.Office.Interop.Word.wde
object paramFormatPDF = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
object paramTrue = true;
object paramReadOnly = true;
object sourceDoc = @"c:\input.doc"
object target = @"c:\output.pdf";
msWord.Visible = false;
//open .doc
msWord.Documents.Open(ref sourceDoc, ref paramUnknown, ref paramReadOnly, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown);
//so it won't show on the taskbar
msWord.Application.Visible = false;
msWord.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateMinimize;
//save .doc to new target name and format
msWord.ActiveDocument.SaveAs(ref targetDoc, ref paramFormatPDF, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramTrue, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown);
msWord.ActiveDocument.Close(ref missing, ref missing, ref missing);
msWord.Quit(ref paramSaveChangesNo, ref paramUnknown, ref paramUnknown);
```
Lastly, if your device doesn't support PDF printing then you could use Ghostscript or other tools to convert your PDF to PS or even PCL. Not the greatest as this mean running a little unmanaged code or worst case, shelling out and executing the GS command line, that being said, we currently do this in one of our web apps and it works well. As an aside, we don't do it for print but rather the joining of a number of PDFs togheter, but in the end it will work the same.
|
Send document to printer with C#
|
[
"",
"c#",
"printing",
""
] |
Is there a better way to negate a boolean in Java than a simple if-else?
```
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
```
|
```
theBoolean = !theBoolean;
```
|
```
theBoolean ^= true;
```
Fewer keystrokes if your variable is longer than four letters
**Edit**: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's ***bitwise XOR*** as [described here](https://www.tutorialspoint.com/Java-Bitwise-Operators).
|
Cleanest way to toggle a boolean variable in Java?
|
[
"",
"java",
"boolean",
""
] |
I've got a web system where users log in, and it stores a cookie of their session. When they log in as someone else or log out I want to remove that original cookie that I stored. What's the best way to do that?
I'm using Python and Apache, though I suppose the answer will remain the same for most languages.
|
Set the cookie again, as if you hadn't set it the first time, but specify an expiration date that is in the past.
|
I guess the best way is to set the expiration to a date of the cookie to some date in the past.
|
How do I remove a cookie that I've set on someone's computer?
|
[
"",
"python",
"apache",
"http",
"cookies",
""
] |
Does anyone know of a way, in Java, to convert an earth surface position from lat, lon to UTM (say in WGS84)? I'm currently looking at Geotools but unfortunately the solution is not obvious.
|
I was able to use Geotools 2.4 to get something that works, based on some [example code](http://svn.geotools.org/trunk/demo/referencing/src/main/java/org/geotools/demo/referencing/CTSTutorial.java).
```
double utmZoneCenterLongitude = ... // Center lon of zone, example: zone 10 = -123
int zoneNumber = ... // zone number, example: 10
double latitude, longitude = ... // lat, lon in degrees
MathTransformFactory mtFactory = ReferencingFactoryFinder.getMathTransformFactory(null);
ReferencingFactoryContainer factories = new ReferencingFactoryContainer(null);
GeographicCRS geoCRS = org.geotools.referencing.crs.DefaultGeographicCRS.WGS84;
CartesianCS cartCS = org.geotools.referencing.cs.DefaultCartesianCS.GENERIC_2D;
ParameterValueGroup parameters = mtFactory.getDefaultParameters("Transverse_Mercator");
parameters.parameter("central_meridian").setValue(utmZoneCenterLongitude);
parameters.parameter("latitude_of_origin").setValue(0.0);
parameters.parameter("scale_factor").setValue(0.9996);
parameters.parameter("false_easting").setValue(500000.0);
parameters.parameter("false_northing").setValue(0.0);
Map properties = Collections.singletonMap("name", "WGS 84 / UTM Zone " + zoneNumber);
ProjectedCRS projCRS = factories.createProjectedCRS(properties, geoCRS, null, parameters, cartCS);
MathTransform transform = CRS.findMathTransform(geoCRS, projCRS);
double[] dest = new double[2];
transform.transform(new double[] {longitude, latitude}, 0, dest, 0, 1);
int easting = (int)Math.round(dest[0]);
int northing = (int)Math.round(dest[1]);
```
|
No Library, No Nothing. Copy This!
Using These Two Classes , You can Convert Degree(latitude/longitude) to UTM and Vice Versa!
```
private class Deg2UTM
{
double Easting;
double Northing;
int Zone;
char Letter;
private Deg2UTM(double Lat,double Lon)
{
Zone= (int) Math.floor(Lon/6+31);
if (Lat<-72)
Letter='C';
else if (Lat<-64)
Letter='D';
else if (Lat<-56)
Letter='E';
else if (Lat<-48)
Letter='F';
else if (Lat<-40)
Letter='G';
else if (Lat<-32)
Letter='H';
else if (Lat<-24)
Letter='J';
else if (Lat<-16)
Letter='K';
else if (Lat<-8)
Letter='L';
else if (Lat<0)
Letter='M';
else if (Lat<8)
Letter='N';
else if (Lat<16)
Letter='P';
else if (Lat<24)
Letter='Q';
else if (Lat<32)
Letter='R';
else if (Lat<40)
Letter='S';
else if (Lat<48)
Letter='T';
else if (Lat<56)
Letter='U';
else if (Lat<64)
Letter='V';
else if (Lat<72)
Letter='W';
else
Letter='X';
Easting=0.5*Math.log((1+Math.cos(Lat*Math.PI/180)*Math.sin(Lon*Math.PI/180-(6*Zone-183)*Math.PI/180))/(1-Math.cos(Lat*Math.PI/180)*Math.sin(Lon*Math.PI/180-(6*Zone-183)*Math.PI/180)))*0.9996*6399593.62/Math.pow((1+Math.pow(0.0820944379, 2)*Math.pow(Math.cos(Lat*Math.PI/180), 2)), 0.5)*(1+ Math.pow(0.0820944379,2)/2*Math.pow((0.5*Math.log((1+Math.cos(Lat*Math.PI/180)*Math.sin(Lon*Math.PI/180-(6*Zone-183)*Math.PI/180))/(1-Math.cos(Lat*Math.PI/180)*Math.sin(Lon*Math.PI/180-(6*Zone-183)*Math.PI/180)))),2)*Math.pow(Math.cos(Lat*Math.PI/180),2)/3)+500000;
Easting=Math.round(Easting*100)*0.01;
Northing = (Math.atan(Math.tan(Lat*Math.PI/180)/Math.cos((Lon*Math.PI/180-(6*Zone -183)*Math.PI/180)))-Lat*Math.PI/180)*0.9996*6399593.625/Math.sqrt(1+0.006739496742*Math.pow(Math.cos(Lat*Math.PI/180),2))*(1+0.006739496742/2*Math.pow(0.5*Math.log((1+Math.cos(Lat*Math.PI/180)*Math.sin((Lon*Math.PI/180-(6*Zone -183)*Math.PI/180)))/(1-Math.cos(Lat*Math.PI/180)*Math.sin((Lon*Math.PI/180-(6*Zone -183)*Math.PI/180)))),2)*Math.pow(Math.cos(Lat*Math.PI/180),2))+0.9996*6399593.625*(Lat*Math.PI/180-0.005054622556*(Lat*Math.PI/180+Math.sin(2*Lat*Math.PI/180)/2)+4.258201531e-05*(3*(Lat*Math.PI/180+Math.sin(2*Lat*Math.PI/180)/2)+Math.sin(2*Lat*Math.PI/180)*Math.pow(Math.cos(Lat*Math.PI/180),2))/4-1.674057895e-07*(5*(3*(Lat*Math.PI/180+Math.sin(2*Lat*Math.PI/180)/2)+Math.sin(2*Lat*Math.PI/180)*Math.pow(Math.cos(Lat*Math.PI/180),2))/4+Math.sin(2*Lat*Math.PI/180)*Math.pow(Math.cos(Lat*Math.PI/180),2)*Math.pow(Math.cos(Lat*Math.PI/180),2))/3);
if (Letter<'M')
Northing = Northing + 10000000;
Northing=Math.round(Northing*100)*0.01;
}
}
private class UTM2Deg
{
double latitude;
double longitude;
private UTM2Deg(String UTM)
{
String[] parts=UTM.split(" ");
int Zone=Integer.parseInt(parts[0]);
char Letter=parts[1].toUpperCase(Locale.ENGLISH).charAt(0);
double Easting=Double.parseDouble(parts[2]);
double Northing=Double.parseDouble(parts[3]);
double Hem;
if (Letter>'M')
Hem='N';
else
Hem='S';
double north;
if (Hem == 'S')
north = Northing - 10000000;
else
north = Northing;
latitude = (north/6366197.724/0.9996+(1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)-0.006739496742*Math.sin(north/6366197.724/0.9996)*Math.cos(north/6366197.724/0.9996)*(Math.atan(Math.cos(Math.atan(( Math.exp((Easting - 500000) / (0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting - 500000) / (0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3))-Math.exp(-(Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*( 1 - 0.006739496742*Math.pow((Easting - 500000) / (0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3)))/2/Math.cos((north-0.9996*6399593.625*(north/6366197.724/0.9996-0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996 )/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3))/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996)))*Math.tan((north-0.9996*6399593.625*(north/6366197.724/0.9996 - 0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996 )*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3))/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996))-north/6366197.724/0.9996)*3/2)*(Math.atan(Math.cos(Math.atan((Math.exp((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3))-Math.exp(-(Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3)))/2/Math.cos((north-0.9996*6399593.625*(north/6366197.724/0.9996-0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3))/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996)))*Math.tan((north-0.9996*6399593.625*(north/6366197.724/0.9996-0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3))/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996))-north/6366197.724/0.9996))*180/Math.PI;
latitude=Math.round(latitude*10000000);
latitude=latitude/10000000;
longitude =Math.atan((Math.exp((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3))-Math.exp(-(Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2)/3)))/2/Math.cos((north-0.9996*6399593.625*( north/6366197.724/0.9996-0.006739496742*3/4*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.pow(0.006739496742*3/4,2)*5/3*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2* north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4-Math.pow(0.006739496742*3/4,3)*35/27*(5*(3*(north/6366197.724/0.9996+Math.sin(2*north/6366197.724/0.9996)/2)+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/4+Math.sin(2*north/6366197.724/0.9996)*Math.pow(Math.cos(north/6366197.724/0.9996),2)*Math.pow(Math.cos(north/6366197.724/0.9996),2))/3)) / (0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2))))*(1-0.006739496742*Math.pow((Easting-500000)/(0.9996*6399593.625/Math.sqrt((1+0.006739496742*Math.pow(Math.cos(north/6366197.724/0.9996),2)))),2)/2*Math.pow(Math.cos(north/6366197.724/0.9996),2))+north/6366197.724/0.9996))*180/Math.PI+Zone*6-183;
longitude=Math.round(longitude*10000000);
longitude=longitude/10000000;
}
}
```
|
Java, convert lat/lon to UTM
|
[
"",
"java",
"geolocation",
"latitude-longitude",
"geography",
"geotools",
""
] |
I would like to display a Drupal view without the page template that normally surrounds it - I want just the plain HTML content of the view's nodes.
This view would be included in another, non-Drupal site.
I expect to have to do this with a number of views, so a solution that lets me set these up rapidly and easily would be the best - I'd prefer not to have to create a .tpl.php file every time I need to include a view somewhere.
|
I was looking for a way to pull node data via ajax and came up with the following solution for Drupal 6. After implementing the changes below, if you add ajax=1 in the URL (e.g. mysite.com/node/1?ajax=1), you'll get just the content and no page layout.
in the template.php file for your theme:
```
function phptemplate_preprocess_page(&$vars) {
if ( isset($_GET['ajax']) && $_GET['ajax'] == 1 ) {
$vars['template_file'] = 'page-ajax';
}
}
```
then create page-ajax.tpl.php in your theme directory with this content:
```
<?php print $content; ?>
```
|
Based on the answer of Ufonion Labs I was able to completely remove all the HTML output around the page content in Drupal 7 by implementing both `hook_preprocess_page` and `hook_preprocess_html` in my themes template.php, like this:
```
function MY_THEME_preprocess_page(&$variables) {
if (isset($_GET['response_type']) && $_GET['response_type'] == 'embed') {
$variables['theme_hook_suggestions'][] = 'page__embed';
}
}
function MY_THEME_preprocess_html(&$variables) {
if (isset($_GET['response_type']) && $_GET['response_type'] == 'embed') {
$variables['theme_hook_suggestions'][] = 'html__embed';
}
}
```
Then I added two templates to my theme: `html--embed.tpl.php`:
```
<?php print $page; ?>
```
and `page--embed.tpl.php`:
```
<?php print render($page['content']); ?>
```
Now when I open a node page, such as <http://example.com/node/3>, I see the complete page as usual, but when I add the response\_type parameter, such as <http://example.com/node/3?response_type=embed>, I *only* get the `<div>` with the page contents so it can be embedded in another page.
|
displaying a Drupal view without a page template around it
|
[
"",
"php",
"drupal",
"drupal-views",
""
] |
I'm working with a combobox in a Swing-based application, and I'm having a hard time figuring out what to do to differentiate between an ItemEvent that is generated from a user event vs one caused by the application.
For instance, Lets say I have a combobox, '`combo`' and I'm listening for itemStateChanged events with my ItemListener, '`listener`'. When either a user changes the selection to item 2 or I execute the line (pseudocode):
`combo.setSelection(2)`
.. it seems like I'm not able to tell these events apart.
That said, I'm no Swing expert by any means, so I thought I would ask.
Thanks!
|
The Action and Reaction law is quite clear :). If you try to react on change there is no need to distinguish between user and application. I can imagine only one use case where you need to "distinguish". The case where application is displaying some data. In this case you have, probably, data model for your application. And also there are some change listener in this model and application GUI will react by setting values to components. And also. If user selects anything into GUI component. The data model will react by changing value. In this case it is easy to set up some sort of read-only state on data model which will notify model to ignore ANY event coming from observed objects. This notification set should run in EDT and there is no problem with flagging. Small example:
```
class ApplicationDataModel {
private Flag current = Flag.RW;
public void setData(ApplicationData data) {
current = Flag.RO;
setDataImpl(data);
notifyObservers();
current = Flag.RW;
}
public void reaction(Event e) {
if (flag = Flag.RO) return;
...
}
}
```
Be careful with flagging and don't forget about threading. If you are calling setData from another thread then EDT you are going into trouble. Of course. The extraction of `ApplicationData` object has to be run in different thread ;). In general, rethink design of your application.
|
Whether the user selects Item 2, or the API calls setSelection(2), **the event will appear the same**.
The solution to your problem might be in re-thinking what you want the itemStateChanged code to do when the selection changes. Why would your app work differently under each condition? Maybe there are similarities that you can use to your advantage.
**Be careful when using flags**. The itemStateChanged event will occur on the Event Dispatch Thread, which is a different thread than the one on which you'd set the state of the flag. This would mean that using a flag may not be 100% reliable.
|
Swing: Is there a way to differentiate between a user-caused ItemEvent and an application-caused one?
|
[
"",
"java",
"swing",
"events",
"combobox",
"listeners",
""
] |
Is it possible to create an STL-like container, or even just an STL-style iterator, for an existing array of POD-type elements?
For example, suppose I have an array of ints. It would be convenient to be able to call some of the STL functions, such as find\_if, count\_if, or sort directly on this array.
Non-solution: copying the entire array, or even just references to the elements. The goal is to be very memory- and time-saving while hopefully allowing use of other STL algorithms.
|
You can call many of the STL algorithms directly on a regular C style array - they were designed for this to work. e.g.,:
```
int ary[100] = ...;
// init ...
// note: technically, std::begin(ary) can just be ary in this context
std::sort(std::begin(ary), std::end(ary)); // sort the array
std::find(std::begin(ary), std::end(ary), pred); // find some element
// or since C++20:
std::rangs::sort(ary);
std::ranges::find(ary, pred);
```
I think you'll find that most stuff works just as you would expect.
|
You can use an inline function template so that you don't have to duplicate the array index
```
template <typename T, int I>
inline T * array_begin(T (&t)[I])
{
return t;
}
template <typename T, int I>
inline T * array_end(T (&t)[I])
{
return t + I;
}
void foo ()
{
int array[100];
// any standard
std::find(array_begin(array), array_end(array), 10);
// or, since C+11
std::find(std::begin(array), std::end(array), 10);
// or, since C++20
std::ranges::find(array, 10);
}
```
|
STL non-copying wrapper around an existing array?
|
[
"",
"c++",
"arrays",
"stl",
"iterator",
""
] |
I have to write a reliable, totally-ordered multicast system from scratch in Python. I can't use any external libraries. I'm allowed to use a central sequencer.
There seems to be two immediate approaches:
1. write an efficient system, attaching a unique id to each multicasted message,
having the sequencer multicast sequence numbers for the message id's it receives,
and sending back and forth ACK's and NACK's.
2. write an inefficient flooding system, where each multicaster simply re-sends each
message it receives once (unless it was sent by that particular multicaster.)
I'm allowed to use the second option, and am inclined to do so.
I'm currently multicasting UDP messages (which seems to be the only option,) but that means that some messages might get lost. That means I have to be able to uniquely identify each sent UDP message, so that it can be re-sent according to #2. Should I really generate unique numbers (e.g. using the sender address and a counter) and pack them into each and every UDP message sent? How would I go about doing that? And how do I receive a single UDP message in Python, and not a stream of data (i.e. `socket.recv`)?
|
The flooding approach can cause a bad situation to get worse. If messages are dropped due to high network load, having every node resend every message will only make the situation worse.
The best approach to take depends on the nature of the data you are sending. For example:
1. Multimedia data: no retries, a dropped packet is a dropped frame, which won't matter when the next frame gets there anyway.
2. Fixed period data: Recipient node keeps a timer that is reset each time an update is received. If the time expires, it requests the missing update from the master node. Retries can be unicast to the requesting node.
If neither of these situations applies (every packet has to be received by every node, and the packet timing is unpredictable, so recipients can't detect missed packets on their own), then your options include:
1. Explicit ACK from every node for each packet. Sender retries (unicast) any packet that is not ACKed.
2. TCP-based grid approach, where each node is manually repeats received packets to neighbor nodes, relying on TCP mechanisms to ensure delivery.
You could possibly rely on recipients noticing a missed packet upon reception of one with a later sequence number, but this requires the sender to keep the packet around until at least one additional packet has been sent. Requiring positive ACKs is more reliable (and provable).
|
The approach you take is going to depend very much on the nature of the data that you're sending, the scale of your network and the quantity of data you're sending. In particular it is going to depend on the number of targets each of your nodes is connected to.
If you're expecting this to scale to a large number of targets for each node and a large quantity of data then you may well find that the overhead of adding an ACK/NAK to every packet is sufficient to adversely limit your throughput, particularly when you add retransmissions into the mix.
As Frank Szczerba has said multimedia data has the benefit of being able to recover from lost packets. If you have any control over the data that you're sending you should try to design the payloads so that you minimise the susceptibility to dropped packets.
If the data that you're sending cannot tolerate dropped packets *and* you're trying to scale to high utilisation of your network then perhaps udp is not the best protocol to use. Implementing a series of tcp proxies (where each node retransmits, unicast, to all other connected nodes - similar to your flooding idea) would be a more reliable mechanism.
With all of that said, have you considered using true multicast for this application?
---
Just saw the "homework" tag... these suggestions might not be appropriate for a homework problem.
|
Writing a reliable, totally-ordered multicast system in Python
|
[
"",
"python",
"sockets",
"networking",
"ip",
"multicast",
""
] |
XAMPP makes configuring a local LAMP stack for windows a breeze. So it's quite disappointing that enabling `.htaccess` files is such a nightmare.
My problem:
I've got a PHP application that requires apache/php to search for an `/includes/` directory contained within the application. To do this, `.htaccess` files must be allowed in Apache and the `.htaccess` file must specify exactly where the includes directory is.
Problem is, I can't get my Apache config to view these `.htaccess` files. I had major hassles installing this app at uni and getting the admins there to help with the setup. This shouldn't be so hard but for some reason I just can't get Apache to play nice.
This is my setup:
`c:\xampp`
`c:\xampp\htdocs`
`c:\xampp\apache\conf\httpd.conf` - where I've made the changes listed below
`c:\xampp\apache\bin\php.ini` - where changes to this file affect the PHP installation
It is interesting to note that `c:\xampp\php\php.ini` changes mean nothing - this is NOT the ini that affects the PHP installation.
The following lines are additions I've made to the `httpd.conf` file
```
#AccessFileName .htaccess
AccessFileName htaccess.txt
#
# The following lines prevent .htaccess and .htpasswd
# files from being viewed by Web clients.
#
#<Files ~ "^\.ht">
<Files ~ "^htaccess\.">
Order allow,deny
Deny from all
</Files>
<Directory "c:/xampp/htdocs">
#
# AllowOverride controls what directives may be placed in
# .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
```
The following is the entire `.htaccess` file contained in:
`c:\xampp\htdocs\application\htaccess.txt`
```
<Files ~ "\.inc$">
Order deny,allow
Deny from all
</Files>
php_value default_charset "UTF-8"
php_value include_path ".;c:\xampp\htdocs\application\includes"
php_value register_globals 0
php_value magic_quotes_gpc 0
php_value magic_quotes_runtime 0
php_value magic_quotes_sybase 0
php_value session.use_cookies 1
php_value session.use_only_cookies 0
php_value session.use_trans_sid 1
php_value session.gc_maxlifetime 3600
php_value arg_separator.output "&"
php_value url_rewriter.tags "a=href,area=href,frame=src,input=src,fieldset="
```
The includes directory exists at the location specified.
When I try to access the application I receive the following error:
```
Warning: require(include.general.inc) [function.require]: failed to open stream: No such file or directory in C:\xampp\htdocs\application\menu\logon.php on line 21
```
Fatal error: require() [function.require]: Failed opening required `include.general.inc` (include\_path='.;C:\xampp\php\pear\random') in `C:\xampp\htdocs\application\menu\logon.php` on line 21
The include path `c..\random\` is specified in the `php.ini` file listed above. The XAMPP install fails to allow another include path as specified in the `htaccess.txt` file.
I'm guessing there's probably an error with the `httpd.conf` OR the `htaccess.txt` file.. but it doesn't seem to be reading the `.htaccess` file. I've tried to be as thorough as possible so forgive the verbosity of the post.
Now I know a workaround could be to simply add the include\_path to the PHP file, but I'm not going to have access to the `php.ini` file on the location I plan to deploy my app. I will, however, be able to request the server admin allows `.htaccess` files.
renamed `htacces.txt` to `.htaccess` and ammended the appropriate directives in the `httpd.conf` file and all seems to work. The application suggested the naming of `htaccess.txt` and the ammended directives in the httpd. These are obviously wrong (at least for a XAMPP stack).
By the way, using ini\_set() is a much friendlier way if the app needs to be deployed to multiple locations so thanks especially for that pointer.
|
1. Why do you need to rename .htaccess to htaccess.txt
2. Try setting the include\_path using [set\_include\_path()](http://php.net/set_include_path()) and see if that helps (as an intermediate fix)
3. Verify which php.ini to use through a [phpinfo()](http://php.net/phpinfo)
|
You can alter the include\_path on each request using ini\_set(). This would avoid having to use htaccess at all.
|
.htaccess files, PHP, includes directories, and windows XAMPP configuration nightmare
|
[
"",
"php",
"apache",
".htaccess",
"xampp",
"config",
""
] |
Why is the following displayed different in Linux vs Windows?
```
System.out.println(new String("¿".getBytes("UTF-8"), "UTF-8"));
```
in Windows:
¿
in Linux:
¿
|
System.out.println() outputs the text in the system default encoding, but the console interprets that output according to its own encoding (or "codepage") setting. On your Windows machine the two encodings seem to match, but on the Linux box the output is apparently in UTF-8 while the console is decoding it as a single-byte encoding like ISO-8859-1. Or maybe, as Jon suggested, the source file is being saved as UTF-8 and `javac` is reading it as something else, a problem that can be avoided by using Unicode escapes.
When you need to output anything other than ASCII text, your best bet is to write it to a file using an appropriate encoding, then read the file with a text editor--consoles are too limited and too system-dependent. By the way, this bit of code:
```
new String("¿".getBytes("UTF-8"), "UTF-8")
```
...has no effect on the output. All that does is encode the contents of the string to a byte array and decode it again, reproducing the original string--an expensive no-op. If you want to output text in a particular encoding, you need to use an OutputStreamWriter, like so:
```
FileOutputStream fos = new FileOutputStream("out.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
```
|
Not sure where the problem is exactly, but it's worth noting that
¿ ( 0xc2,0xbf)
is the result of encoding with UTF-8
0xbf,
which is the Unicode codepoint for ¿
So, it looks like in the linux case, the output is not being displayed as utf-8, but as a single-byte string
|
Why is ¿ displayed different in Windows vs Linux even when using UTF-8?
|
[
"",
"java",
"utf-8",
"character-encoding",
""
] |
What is the correct way to setup a named pipe in C# across a network?
Currently I have two machines, 'client' and 'server'.
Server sets up its pipe in the following manner:
```
NamedPipeServerStream pipeServer = new NamedPipeServerStream(
"pipe",
PipeDirection.InOut,
10,
PipeTransmissionMode.Byte,
PipeOptions.None)
pipeServer.WaitForConnection();
//... Read some data from the pipe
```
The client sets up its connection in the following manner:
```
NamedPipeClientStream pipeClient = new NamedPipeClientStream(
"server",
"pipe",
PipeDirection.InOut);
pipeClient.Connect(); //This line throws an exception
//... Write some data to the pipe
```
The 'server' machine can be accessed on the network by going to "\\server".
Whenever I run the program, I get a System.UnauthorizedAccessException that says "Access to the path is denied." The code works fine when I run the server and client on my local machine and attempt to connect to "." with the client.
|
It is not possible to used named pipes between machines.
"The WCF-NetNamedPipe adapter provides cross-process communication on the **same computer**"
<http://msdn.microsoft.com/en-us/library/bb226493.aspx>
|
You need to set permissions on the NamedPipeServerStream so that the client will have permissions to access the pipe.
I would look at the SetAccessControl method of your NamedPipeServerStream.
|
C# 3.5 - Connecting named pipe across network
|
[
"",
"c#",
".net-3.5",
"networking",
"named-pipes",
""
] |
For the computer game I'm making, I obviously want to play sound. So far, I've been using AudioClip to play WAV files. While this approach works fine, the WAV files tend to be gigantic. A few seconds of sound end up being hundreds of kB. I'm faced with having a game download that's 95% audio!
The obvious option here would be to use MP3 or Ogg Vorbis. But I've had limited success with this - I can play MP3 using JLayer (but it plays in the same thread). As for Ogg, I've had no luck at all. Worse, JLayer's legal status is a bit on the dubious side.
So my question is to both Java developers and generally people who actually know something about sound: What do I do? Can I somehow "trim the fat" off my WAVs? Is there some way of playing Ogg in Java? Is there some other sound format I should use instead?
|
You could use [JOrbis](http://www.jcraft.com/jorbis/) library to play back OGG music. For working sample usage you can look at these files [here](http://code.google.com/p/open-ig/source/browse/#svn/trunk/open-ig/src/hu/openig/music).
I also experimented with some lossless audio compression, for example I had a 16 bit mono sound. I separated the upper and lower bytes of each sample and put them after each other. Then I applied a differential replacement where each byte is replaced by its difference from the last byte. And finally used GZIP to compress the data. I was able to reduce the data size to 50-60% of the original size. Unfortunately this was not enough so I turned to the OGG format.
One thing I noticed with 8 bit music is that if I change the audio volume, the playback becomes very noisy. I solved this problem by upsampling the audio data to 16 bit right before the SourceDataLine.write().
|
These may be outdated, but they are officially recognized by the Xiph.org team (who maintain Ogg and Vorbis, among others).
<http://www.vorbis.com/software/#java>
|
Playing small sounds in Java game
|
[
"",
"java",
"audio",
"mp3",
"ogg",
""
] |
I want to write a web application using [Google App Engine](http://code.google.com/appengine/) (so the reference language would be **Python**). My application needs a simple search engine, so the users would be able to find data specifying keywords.
For example, if I have one table with those rows:
> 1 Office space
> 2 2001: A space
> odyssey
> 3 Brazil
and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).
What are the technical guidelines/algorithms to do this in a simple way?
Can you give me good pointers to the theory behind this?
Thanks.
*Edit*: I'm not looking for anything complex here (say, indexing tons of data).
|
I would not build it yourself, if possible.
App Engine includes the basics of a Full Text searching engine, and there is a [great blog post here](http://appengineguy.com/2008/06/how-to-full-text-search-in-google-app.html) that describes how to use it.
There is also a [feature request in the bug tracker](http://code.google.com/p/googleappengine/issues/detail?id=217) that seems to be getting some attention lately, so you may want to hold out, if you can, until that is implemented.
|
Read Tim Bray's [series of posts on the subject](http://www.tbray.org/ongoing/When/200x/2003/07/30/OnSearchTOC).
> * Background
> * Usage of search engines
> * Basics
> * Precision and recall
> * Search engne intelligence
> * Tricky search terms
> * Stopwords
> * Metadata
> * Internationalization
> * Ranking results
> * XML
> * Robots
> * Requirements list
|
Building a full text search engine: where to start
|
[
"",
"python",
"full-text-search",
""
] |
Hi I'm trying to get some practice with Linked Lists.
I Defined an Object class called `Student`:
```
public class Student
{
protected string Student_Name;
protected int Student_ID;
protected int Student_Mark;
protected char Student_Grade;
public Student() // default Constructor
{
Student_Name = " ";
Student_ID = 0;
Student_Mark = 0;
Student_Grade = ' ';
}
public Student(string Sname, int Sid, int Smark, char Sgrade) // Constructor
{
int len = sname.Length;
Student_Name = sname.Substring(0, len);
//Student_Name = sname.Substring(0, sname.Length);
Student_ID = Sid;
Student_Mark = Smark;
Student_Grade = Sgrade;
}
}
```
and then a `Node` class:
```
public class S_Node
{
public Student Element;
public S_Node Link;
public S_Node()
{
Element = new Student();
Link = null;
}
public Node(Student theElement)
{
Element = theElement;
Link = null;
}
}
```
and the `LinkedList`:
```
public class S_LinkedList
{
protected S_Node header;
protected S_Node tail;
public S_LinkedList()
{
header = new S_Node();
Tail = new S_Node();
header.Link = Tail;
}
// METHODS which i don't know how to do it (never use linkedlist before)
}
```
I need to organize this data using a “linkedlist data structure type”.
Contain all methods of linkedlist as Adding nodes to the list as I've learned -->(Insert),Deleting nodes from the list,as I've learned -->((Remove),Traversing the lists I've learned -->((PrintList),Finding a node in the list as I've learned -->((Find , FindPrevious) the problem I'm selflearning and I've tried to search the net and read more from the stupid C# that was a disaster.
I've done too much that I'm so sad that i don't know how to complete it .
I'm trying hard to Use this classes to write an executable program and to Test it .
If you don't want to help in completing this program (hope not) at least show me some real examples or ideas , after all I'm a selflearner geek :-)
|
```
the head of the list.
( item1
Element: student1
Next ------------> ( item2
) Element: student2
Next ------------> ( item3
) Element: student3
Next: null
)
the tail of the list.
```
First of all, for you to be able to write the StudentList class, you need to write the client code first. Client code is the code that uses your student list. Also, don't just write one thing at a time and throw it away. Instead write a whole bunch of [test] cases that exercise the different ways you *need* to interact with the StudentList. Write exceptional cases too. But don't be tempted to write a swiss-army knife of a class that does everything just because it can. Write the minimal amount of code that gets the job done.
How you need to use the class will heavily dictate how the class is constructed. This is the essence of TDD or Test Driven Design.
Your biggest problem that I can see is you have no idea how you want to use the class. So lets do that first.
```
// create a list of students and print them back out.
StudentList list = new StudentList();
list.Add( new Student("Bob", 1234, 2, 'A') );
list.Add( new Student("Mary", 2345, 4, 'C') );
foreach( Student student in list)
{
Console.WriteLine(student.Name);
}
```
I add the students to the list, and then I print them out.
I have no need for my client code to see inside the StudentList. Therefore StudentList hides how it implements the linked list. Let's write the basics of the StudentList.
```
public class StudentList
{
private ListNode _firstElement; // always need to keep track of the head.
private class ListNode
{
public Student Element { get; set; }
public ListNode Next { get; set; }
}
public void Add(Student student) { /* TODO */ }
}
```
StudentList is pretty basic. Internally it keeps track of the first or head nodes. Keeping track of the first node is obviously always required.
You also might wonder why ListNode is declared inside of StudentList. What happens is the ListNode class is only accessible to the StudentList class. This is done because StudentList doesn't want to give out the details to it's internal implementation because it is controlling all access to the list. StudentList never reveals how the list is implemented. Implementation hiding is an important OO concept.
If we did allow client code to directly manipulate the list, there'd be no point having StudentList is the first place.
Let's go ahead and implement the Add() operation.
```
public void Add(Student student)
{
if (student == null)
throw new ArgumentNullException("student");
// create the new element
ListNode insert = new ListNode() { Element = student };
if( _firstElement == null )
{
_firstElement = insert;
return;
}
ListNode current = _firstElement;
while (current.Next != null)
{
current = current.Next;
}
current.Next = insert;
}
```
The Add operation has to find the last item in the list and then puts the new ListNode at the end. Not terribly efficient though. It's currently O(N) and Adding will get slower as the list gets longer.
Lets optimize this a little for inserts and rewrite the Add method. To make Add faster all we need to do is have StudentList keep track of the last element in the list.
```
private ListNode _lastElement; // keep track of the last element: Adding is O(1) instead of O(n)
public void Add(Student student)
{
if( student == null )
throw new ArgumentNullException("student");
// create the new element
ListNode insert = new ListNode() { Element = student };
if (_firstElement == null)
{
_firstElement = insert;
_lastElement = insert;
return;
}
// fix up Next reference
ListNode last = _lastElement;
last.Next = insert;
_lastElement = insert;
}
```
Now, when we add, we don't iterate. We just need to keep track of the head and tail references.
Next up: the foreach loop. StudentList is a collection, and being a collection we want to enumerate over it and use C#'s `foreach`. The C# compiler can't iterate magically. In order to use the foreach loop We need to provide the compiler with an enumerator to use even if the code we write doesn't explicitly appear to use the enumerator.
First though, lets re-visit how we iterate over a linked list.
```
// don't add this to StudentList
void IterateOverList( ListNode current )
{
while (current != null)
{
current = current.Next;
}
}
```
Okay. so let's hook into C#'s foreach loop and return an enumerator. To do that we alter StudentList to implement IEnumerable. This is getting a little bit advanced, but you should be able to figure out what's going on.
```
// StudentList now implements IEnumerable<Student>
public class StudentList : IEnumerable<Student>
{
// previous code omitted
#region IEnumerable<Student> Members
public IEnumerator<Student> GetEnumerator()
{
ListNode current = _firstElement;
while (current != null)
{
yield return current.Element;
current = current.Next;
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
```
You should be able to spot the linked list iteration in there. Don't get thrown by the `yield` keyword. All yield is doing is returning the current student back to the foreach loop. The enumarator stops returning students when it gets to the end of the linked list.
And that's it! The code works the way we want it to.
---
\* This is by no means the only way to implement the list. I've opted to put the list logic in the StudentList and keep ListNode very basic. But the code does only what my very first unit test needs and nothing more. There are more optimizations you could make, and there are other ways of constructing the list.
Going forward: What you need to do is first create [unit] tests for what your code needs to do, then add the implementation you require.
---
\* fyi I also rewrote the Student class. Bad naming and strange casing from a C# persepctive, not to mention the code you provided doesn't compile. I prefer the `_` as a leader to private member variables. Some people don't like that, however you're new to this so I'll leave them in because they're easy to spot.
```
public class Student
{
private string _name;
private int _id;
private int _mark;
private char _letterGrade;
private Student() // hide default Constructor
{ }
public Student(string name, int id, int mark, char letterGrade) // Constructor
{
if( string.IsNullOrEmpty(name) )
throw new ArgumentNullException("name");
if( id <= 0 )
throw new ArgumentOutOfRangeException("id");
_name = name;
_id = id;
_mark = mark;
_letterGrade = letterGrade;
}
// read-only properties - compressed to 1 line for SO answer.
public string Name { get { return _name; } }
public int Id { get { return _id; } }
public int Mark { get { return _mark; } }
public char LetterGrade { get { return _letterGrade; } }
}
```
* check parameters
* pay attention to the different casing of properties, classes, and variables.
* hide the default constructor. Why do I want to create students without real data?
* provide some read-only properties.
+ This class is immutable as written (i.e. once you create a student, you can't change it).
|
I'll do one for you! You need to draw diagrams with each node as a box, and work out what code you need to use to change the list for each operation. See this for some inspiration:
<http://en.wikipedia.org/wiki/Linked_list>
The diagrams there don't show the main list class as a box, which you should have, with two arrows coming out of it for the header and tail.
Draw yourself some diagrams for the two cases in the Insert method to work out what's going on. One diagram for when there's nothing in the list and header is null, and another diagram for when there's something already in the list. Then from there work out the other operations.
```
public class S_LinkedList {
protected S_Node header = null;
protected S_Node tail = null;
public S_LinkedList()
{
}
// METHODS which i don't know how to do it (never use linkedlist before)
void Insert(Student s)
{
if( header == null )
{
header = new S_Node(s);
tail = header;
}
else
{
tail.Link = new S_Node(s);
tail = tail.Link;
}
}
}
```
|
Am I done with this Linked List code?
|
[
"",
"c#",
"linked-list",
""
] |
I've seen some developers put instance variable declarations at the end of classes though I mostly see them placed at the top. The only reasons I can think of for doing this are stylistic preference or maybe it somehow makes them easier to work with in an IDE. Is there a more legitimate reason for choosing this style?
|
Because of "Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18) (<http://en.wikipedia.org/wiki/Design_Patterns#Introduction.2C_Chapter_1>), some people prefer to declare instance variables at the bottom of the class. the theory being that the user of a class is more interested in what they can do with the class(methods) as opposed to how something is done(variables). Placing the methods at the top of the class exposes them first to the user when they look at the code.
|
There is no particularly "good" reason for doing it one way or another. The only thing that really matters is that everyone on the same project does it the same way.
However, placing them at the top is far more common in my experience, and is the practice recommended by the [Java style guidelines](http://java.sun.com/docs/codeconv/html/CodeConventions.doc2.html#1852), so that's what I'd go with.
You can enforce your chosen convention with an automatic source code formatter such as [Jalopy](http://jalopy.sourceforge.net/), or that which comes with Eclipse.
|
Placement of instance variable declarations
|
[
"",
"java",
"variables",
"coding-style",
""
] |
What is everyone's favorite way to sanitize user data?
I've been using Javascript, but have recently required something more secure (people can turn it off, after all), so I was looking at Flex, but thought I'd ask the community what they thought.
|
NEVER NEVER NEVER use javascript **or any other client-side technology** for the *only* validation. You can use client-side validation to save some load on your server or make your app seem more responsive by showing the error sooner when validation fails, but you should **always** validate using server-side code.
Personally, I like the ASP.Net validation controls because it gives you the benefit of client-side validation with security of server-side, without having to write your logic twice. Of course, the stock controls are pretty bare, but you can extend them.
|
Validation should ALWAYS be done server-side. Doing it client-side, in addition, is fine.
How you do it depends on what your app is written in. Any language should be able to handle validation; the logic used is what matters, not the language.
It also depends on what you're doing with the data you're given. Putting it in a URL or storing it in a SQL database requires two very different kinds of sanitization. If at all possible, white-list valid values--don't black-list invalid values. Someone will always be able to come up with a new mal-input you hadn't considered.
|
Favorite Web Form Validation Technique
|
[
"",
"javascript",
"apache-flex",
"validation",
"sanitization",
""
] |
In Kohana/CodeIgniter, I can have a URL in this form:
```
http://www.name.tld/controller_name/method_name/parameter_1/parameter_2/parameter_3 ...
```
And then read the parameters in my controller as follows:
```
class MyController
{
public function method_name($param_A, $param_B, $param_C ...)
{
// ... code
}
}
```
How do you achieve this in the Zend Framework?
|
**Update (04/13/2016):**
The link in my answer below moved and has been fixed. However, just in case it disappears again -- here are a few alternatives that provide some in depth information on this technique, as well as use the original article as reference material:
* [Zend Framework Controller Actions with Function Parameters](http://codeutopia.net/blog/2009/03/16/zend_controller-actions-that-accept-parameters/)
* [Zend\_Controller actions that accept parameters?](http://codeutopia.net/blog/2009/03/16/zend_controller-actions-that-accept-parameters/)
---
@[Andrew Taylor](https://stackoverflow.com/questions/161443/url-segment-to-action-method-parameter-in-zend-framework#161636)'s response is the proper Zend Framework way of handling URL parameters. However, if you would like to have the URL parameters in your controller's action (as in your example) - check out [this tutorial on Zend DevZone](http://devzone.zend.com/1138/actions-now-with-parameters/).
|
Take a look at the Zend\_Controller\_Router classes:
<http://framework.zend.com/manual/en/zend.controller.router.html>
These will allow you to define a Zend\_Controller\_Router\_Route which maps to your URL in the way that you need.
An example of having 4 static params for the Index action of the Index controller is:
```
$router = new Zend_Controller_Router_Rewrite();
$router->addRoute(
'index',
new Zend_Controller_Router_Route('index/index/:param1/:param2/:param3/:param4', array('controller' => 'index', 'action' => 'index'))
);
$frontController->setRouter($router);
```
This is added to your bootstrap after you've defined your front controller.
Once in your action, you can then use:
```
$this->_request->getParam('param1');
```
Inside your action method to access the values.
Andrew
|
Use URL segments as action method parameters in Zend Framework
|
[
"",
"php",
"zend-framework",
""
] |
My current position is this: if I thoroughly test my ASP.NET applications using web tests (in my case via the VS.NET'08 test tools and WatiN, maybe) with code coverage and a broad spectrum of data, I should have no need to write individual unit tests, because my code will be tested in conjunction with the UI through all layers. Code coverage will ensure I'm hitting every functional piece of code (or reveal unused code) and I can provide data that will cover all reasonably expected conditions.
However, if you have a different opinion, I'd like to know:
1. What *additional* benefit does unit testing give that justifies the effort to include it in a project (keep in mind, I'm doing the web tests anyway, so in many cases, the unit tests would be covering code that web tests already cover).
2. Can you explain your reasons in detail with concete examples? Too often I see responses like "that's not what it's meant for" or "it promotes higher quality" - which really doesn't address the practical question I have to face, which is, how can I justify - with tangible results - spending more time testing?
|
> Code coverage will ensure I'm *hitting* every functional piece of code
### "Hit" *does not* mean "Testing"
The problem with only doing web-testing is that it only ensures that you *hit* the code, and that it *appears* to be correct at a high-level.
Just because you loaded the page, and it didn't crash, doesn't mean that it actually works correctly. Here are some things I've encountered where 'web tests' covered 100% of the code, yet completely missed some very serious bugs which unit testing would not have.
1. The page loaded correctly from a cache, but the actual database was broken
2. The page loaded every item from the database, but only displayed the first one - it appeared to be fine even though it failed completely in production because it took too long
3. The page displayed a valid-looking number, which was actually wrong, but it wasn't picked up because 1000000 is easy to mistake for 100000
4. The page displayed a valid number by coincidence - 10x50 is the same as 25x20, but one is WRONG
5. The page was supposed to add a log entry to the database, but that's not visible to the user so it wasn't seen.
6. Authentication was bypassed to make the web-tests actually work, so we missed a glaring bug in the authentication code.
It is easy to come up with hundreds more examples of things like this.
You need both unit tests to make sure that your code actually does what it is supposed to do at a low level, and then functional/integration (which you're calling web) tests on top of those, to prove that it actually works when all those small unit-tested-pieces are chained together.
|
Unit testing is likely to be significantly quicker in turn-around than web testing. This is true not only in terms of development time (where you can test a method in isolation much more easily if you can get at it directly than if you have to construct a particular query which will eventually hit it, several layers later) but also in execution time (executing thousands of requests in sequence will take longer than executing short methods thousands of times).
Unit testing will test small units of functionality, so when they fail you should be able to isolate where the issue is very easily.
In addition, it's a lot easier to mock out dependencies with unit tests than when you hit the full front end - unless I've missed something really cool. (A few years ago I looked at how mocking and web testing could integrate, and at the time there was nothing appropriate.)
|
Why should I both Unit test AND Web test (instead of just web test)?
|
[
"",
"c#",
"asp.net",
"visual-studio",
"unit-testing",
""
] |
Right now, I have
```
SELECT gp_id FROM gp.keywords
WHERE keyword_id = 15
AND (SELECT practice_link FROM gp.practices
WHERE practice_link IS NOT NULL
AND id = gp_id)
```
This does not provide a syntax error, however for values where it should return row(s), it just returns 0 rows.
What I'm trying to do is get the gp\_id from gp.keywords where the the keywords table keyword\_id column is a specific value and the practice\_link is the practices table corresponds to the gp\_id that I have, which is stored in the id column of that table.
|
I'm not even sure that is valid SQL, so I'm surprised it is working at all:
```
SELECT gp_id
FROM gp.keywords
WHERE keyword_id = 15
AND (SELECT practice_link FROM gp.practices WHERE practice_link IS NOT NULL AND id = gp_id)
```
How about this instead:
```
SELECT kw.gp_id, p.practice_link
FROM gp.keywords AS kw
INNER JOIN gp.practices AS p
ON p.id = kw.gp_id
WHERE kw.keyword_id = 15
```
I would steer clear of implicit joins as in the other examples. It only leads to tears later.
|
```
select k.gp_id
from gp.keywords as k,
gp.practices as p
where
keyword_id=15
and practice_link is not null
and p.id=k.gp_id
```
|
What is the proper syntax for a cross-table SQL query?
|
[
"",
"mysql",
"sql",
""
] |
1. What is the most efficient way to check if an array is **a flat array
of primitive values** or if it is a **multidimensional array**?
2. Is there any way to do this without actually looping through an
array and running `is_array()` on each of its elements?
|
The short answer is no you can't do it without at least looping implicitly if the 'second dimension' could be anywhere. If it has to be in the first item, you'd just do
```
is_array($arr[0]);
```
But, the most efficient general way I could find is to use a foreach loop on the array, shortcircuiting whenever a hit is found (at least the implicit loop is better than the straight for()):
```
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
$c = array(1 => 'a',2 => 'b','foo' => array(1,array(2)));
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
function is_multi2($a) {
foreach ($a as $v) {
if (is_array($v)) return true;
}
return false;
}
function is_multi3($a) {
$c = count($a);
for ($i=0;$i<$c;$i++) {
if (is_array($a[$i])) return true;
}
return false;
}
$iters = 500000;
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi($a);
is_multi($b);
is_multi($c);
}
$end = microtime(true);
echo "is_multi took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi2($a);
is_multi2($b);
is_multi2($c);
}
$end = microtime(true);
echo "is_multi2 took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi3($a);
is_multi3($b);
is_multi3($c);
}
$end = microtime(true);
echo "is_multi3 took ".($end-$time)." seconds in $iters times\n";
?>
$ php multi.php
is_multi took 7.53565130424 seconds in 500000 times
is_multi2 took 4.56964588165 seconds in 500000 times
is_multi3 took 9.01706600189 seconds in 500000 times
```
Implicit looping, but we can't shortcircuit as soon as a match is found...
```
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
var_dump(is_multi($a));
var_dump(is_multi($b));
?>
$ php multi.php
bool(true)
bool(false)
```
|
Use count() twice; one time in default mode and one time in recursive mode. If the values match, the array is *not* multidimensional, as a multidimensional array would have a higher recursive count.
```
if (count($array) == count($array, COUNT_RECURSIVE))
{
echo 'array is not multidimensional';
}
else
{
echo 'array is multidimensional';
}
```
This option second value `mode` was added in PHP 4.2.0. From the [PHP Docs](http://us.php.net/count):
> If the optional mode parameter is set to COUNT\_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. count() does not detect infinite recursion.
However this method does not detect `array(array())`.
|
Checking if array is multidimensional or not?
|
[
"",
"php",
"arrays",
"loops",
"multidimensional-array",
"element",
""
] |
I'm looking for a method (or function) to strip out the `example.ext` part of any URL that's fed into the function. The domain extension can be anything (.com, .co.uk, .nl, .whatever), and the URL that's fed into it can be anything from `http://www.example.com` to `www.example.com/path/script.php?=whatever`
What's the best way to go about doing this?
I'd like `example.com`.
|
[parse\_url](http://www.php.net/manual/en/function.parse-url.php) turns a URL into an associative array:
```
php > $foo = "http://www.example.com/foo/bar?hat=bowler&accessory=cane";
php > $blah = parse_url($foo);
php > print_r($blah);
Array
(
[scheme] => http
[host] => www.example.com
[path] => /foo/bar
[query] => hat=bowler&accessory=cane
)
```
|
You can also write a regular expression to get exactly what you want.
Here is my attempt at it:
```
$pattern = '/\w+\..{2,3}(?:\..{2,3})?(?:$|(?=\/))/i';
$url = 'http://www.example.com/foo/bar?hat=bowler&accessory=cane';
if (preg_match($pattern, $url, $matches) === 1) {
echo $matches[0];
}
```
The output is:
```
example.com
```
This pattern also takes into consideration domains such as 'example.com.au'.
Note: I have not consulted the relevant RFC.
|
How to isolate the domain name from a URL?
|
[
"",
"php",
"urlparse",
""
] |
I'm checking for existing of a row in in\_fmd, and the ISBN I look up can be the ISBN parameter, or another ISBN in a cross-number table that may or may not have a row.
```
select count(*)
from in_fmd i
where (description='GN')
and ( i.isbn in
(
select bwi_isbn from bw_isbn where orig_isbn = ?
union all
select cast(? as varchar) as isbn
)
)
```
I don't actually care about the count of the rows, but rather mere existence of at least one row.
This used to be three separate queries, and I squashed it into one, but I think there's room for more improvement. It's PostgreSQL 8.1, if it matters.
|
Why bother with the `UNION ALL`
```
select count(*)
from in_fmd i
where (description='GN')
and (
i.isbn in (
select bwi_isbn from bw_isbn where orig_isbn = ?
)
or i.isbn = cast(? as varchar)
)
```
I would probably use a `LEFT JOIN`-style query instead of the `IN`, but that's more personal preference:
```
select count(*)
from in_fmd i
left join bw_isbn
on bw_isbn.bwi_isbn = i.isbn
and bw_isbn.orig_isbn = ?
where (i.description='GN')
and (
bw_isbn.bwi_isbn is not null
or i.isbn = cast(? as varchar)
)
```
The inversion discussed over IM:
```
SELECT SUM(ct)
FROM (
select count(*) as ct
from in_fmd i
inner join bw_isbn
on bw_isbn.bwi_isbn = i.isbn
and bw_isbn.orig_isbn = ?
and i.isbn <> cast(? as varchar)
and i.description = 'GN'
UNION
select count(*) as ct
from in_fmd i
where i.isbn = cast(? as varchar)
and i.description = 'GN'
) AS x
```
|
> I don't actually care about the count of the rows, but rather mere existence of at least one row.
Then how about querying `SELECT ... LIMIT 1` and checking in the calling program whether you get one result row or not?
|
How can I improve this SQL query?
|
[
"",
"sql",
"postgresql",
""
] |
i've never created a shopping cart, or forum in php. aside from viewing and analyzing another persons project or viewing tutorials that display how to make such a project or how to being such a project. how would a person know how to design the database structure to create such a thing? im guessing its probbably through trial and error...
|
The main technique you can learn about database design is called [Database Normalization](http://en.wikipedia.org/wiki/Database_normalization).
Database normalization has it's limits, especially if you have many transactions. At some point you may be forced to [Denormalize](http://en.wikipedia.org/wiki/Denormalization).
But imho it's always better to start with a normalized database design.
|
you should read up and understand the basics of [normalization](http://en.wikipedia.org/wiki/Database_normalization). for most projects, normalizing to 3rd normal form will be just fine. there are always certain scenarios when you want more or less normalization, but understanding the concepts behind it will allow you to think about how your database is structured in a normalized format.
here's a very basic example of normalizing a table:
```
students
student_id
student_name
student_class
student_grade
```
a pretty standard table containing various data, but we can see some issues right away. we can see that a student's name is dependant on his ID, however, a student may be involved in more than one class, and each class would conceivably have a different grade. we can then think about the tables as such:
```
students
student_id
student_name
class
class_id
class_name
```
this is not bad, now we can see we have various students, and various classes, but we haven't captured the student's grades.
```
grades
student_id
class_id
grade
```
now we have a 3rd table, which allows us to understand the relation between a particular student, a particular class, and a grade associated with that class. from our first initial table, we now have 3 tables in a normalized database (let's assume we don't need to normalize grades any further for sake of example :) )
a few things we can glean from this very basic example:
* our data is all tied to a key of some sort (student\_id, class\_id, and student\_id + class\_id). these are unique identifiers within each table.
* with our keyed relations, we're able to relate information to each other (how many classes is student #4096 enrolled in?)
* we can see our tables will not contain duplicated data now (think about our first table, where student\_class could be the same value for many students. if we had to change the class name, we'd have to update all the records. in our normalized format, we can just update class\_name of class\_id)
|
how do you know how to design a mysql database when creating an advanced php application?
|
[
"",
"php",
"mysql",
"database",
"structure",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.