Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
```
python -c "for x in range(1,10) print x"
```
I enjoy python one liners with -c, but it is limited when indentation is needed.
Any ideas? | ```
python -c "for x in range(1,10): print x"
```
Just add the colon.
To address the question in the comments:
> How can I make this work though? python -c "import calendar;print calendar.prcal(2009);for x in range(1,10): print x"
```
python -c "for x in range(1,10): x==1 and __import__('calendar').prcal(2009); print x;"
```
As you can see it's pretty gross. We can't import before the loop. To get around this we check if x is at the first iteration in the loop, if so we do the import.
More examples [here](https://web.archive.org/web/20071223101511/http://mail.python.org/pipermail/python-list/2003-April/199822.html). | Not a python script, but might help:
```
for /L %i in (1, 1, 10) do echo %i
``` | How can I make this one-liner work in DOS? | [
"",
"python",
"command-line",
""
] |
I'm struggling with the automated data collection of a PHP script from a webserver. [The files in question](http://www.iac.ethz.ch/php/chn_meteo_roof/) contain meteo data and are updated every 10 minutes. Weirdly enough, the 'file modified' date on the webserver doesn't change.
A simple [fopen](http://de.php.net/fopen)('http://...')-command tries to get the freshest version of the last file in this directory every hour. But regularly I end up with a version up to 4 hours old. This happens on a Linux server which (As my system administrator has assured me) doesn't use a proxy server of any kind.
Does PHP implement its own caching mechanism? Or what else could be interfering here?
(My current workaround is to grab the file via exec('wget --nocache...') which works.) | Since you're getting the file via HTTP, I'm assuming that PHP will be honouring any cache headers the server is responding with.
A very simple and dirty way to avoid that is to append some random get parameter to each request. | The Q related to observed caching of content accessed by a fopen('http://...') and the poster wondered whether PHP implement its own caching mechanism? The other answers included some speculation, but surely the easiest way to find out is to check by looking at the source code or perhaps easier instrumenting the system calls to see what is going on? This is trivial to do on Debian systems as follows:
```
$ echo "Hello World" > /var/www/xx.txt
$ strace -tt -o /tmp/strace \
> php -r 'echo file_get_contents("http://localhost/xx.txt");'
Hello World
```
I've included the relevant extract of the strace log below but what this shows is the the PHP RTS simply connects to **localhost:80**, sends a "GET /xx.txt", gets a response comprising headers and file content which it then echoes to STDOUT.
Absolutely no client-side caching occurs within the PHP RTS, and since this is doing direct HTTP socket dialogue, it is hard to envision where caching could occur on the client. We are left with the possibility of server-side or intermediate proxy caching. (Note I default to an expires of Access + 7 days on txt files).
## Logfile Extract
```
00:15:41.887904 socket(PF_INET6, SOCK_STREAM, IPPROTO_IP) = 3
00:15:41.888029 fcntl(3, F_GETFL) = 0x2 (flags O_RDWR)
00:15:41.888148 fcntl(3, F_SETFL, O_RDWR|O_NONBLOCK) = 0
00:15:41.888265 connect(3, {sa_family=AF_INET6, sin6_port=htons(80), inet_pton(AF_INET6, "::1", &sin6_addr), sin6_flowinfo=0, sin6_scope_id=0}, 28) = -1 EINPROGRESS (Operation now in progress)
00:15:41.888487 poll([{fd=3, events=POLLIN|POLLOUT|POLLERR|POLLHUP}], 1, 60000) = 1 ([{fd=3, revents=POLLOUT}])
00:15:41.888651 getsockopt(3, SOL_SOCKET, SO_ERROR, [0], [4]) = 0
00:15:41.888838 fcntl(3, F_SETFL, O_RDWR) = 0
00:15:41.888975 sendto(3, "GET /xx.txt HTTP/1.0\r\n", 22, MSG_DONTWAIT, NULL, 0) = 22
00:15:41.889172 sendto(3, "Host: localhost\r\n", 17, MSG_DONTWAIT, NULL, 0) = 17
00:15:41.889307 sendto(3, "\r\n", 2, MSG_DONTWAIT, NULL, 0) = 2
00:15:41.889437 poll([{fd=3, events=POLLIN|POLLPRI|POLLERR|POLLHUP}], 1, 0) = 0 (Timeout)
00:15:41.889544 poll([{fd=3, events=POLLIN|POLLERR|POLLHUP}], 1, 60000) = 1 ([{fd=3, revents=POLLIN}])
00:15:41.891066 recvfrom(3, "HTTP/1.1 200 OK\r\nDate: Wed, 15 F"..., 8192, MSG_DONTWAIT, NULL, NULL) = 285
00:15:41.891235 poll([{fd=3, events=POLLIN|POLLERR|POLLHUP}], 1, 60000) = 1 ([{fd=3, revents=POLLIN}])
00:15:41.908909 recvfrom(3, "", 8192, MSG_DONTWAIT, NULL, NULL) = 0
00:15:41.909016 poll([{fd=3, events=POLLIN|POLLERR|POLLHUP}], 1, 60000) = 1 ([{fd=3, revents=POLLIN}])
00:15:41.909108 recvfrom(3, "", 8192, MSG_DONTWAIT, NULL, NULL) = 0
00:15:41.909198 close(3) = 0
00:15:41.909323 write(1, "Hello World\n", 12) = 12
00:15:41.909532 munmap(0x7ff3866c9000, 528384) = 0
00:15:41.909600 close(2) = 0
00:15:41.909648 close(1) = 0
``` | Does PHPs fopen function implement some kind of cache? | [
"",
"php",
"http",
"caching",
"fopen",
""
] |
What does this do, and why should one include the `if` statement?
```
if __name__ == "__main__":
print("Hello, World!")
```
---
If you are trying to close a question where someone should be using this idiom and isn't, consider closing as a duplicate of [Why is Python running my module when I import it, and how do I stop it?](https://stackoverflow.com/questions/6523791) instead. For questions where someone simply hasn't called any functions, or incorrectly expects a function named `main` to be used as an entry point automatically, use [Why doesn't the main() function run when I start a Python script? Where does the script start running?](https://stackoverflow.com/questions/17257631). | # Short Answer
It's boilerplate code that protects users from accidentally invoking the script when they didn't intend to. Here are some common problems when the guard is omitted from a script:
* If you import the guardless script in another script (e.g. `import my_script_without_a_name_eq_main_guard`), then the latter script will trigger the former to run *at import time* and *using the second script's command line arguments*. This is almost always a mistake.
* If you have a custom class in the guardless script and save it to a pickle file, then unpickling it in another script will trigger an import of the guardless script, with the same problems outlined in the previous bullet.
# Long Answer
To better understand why and how this matters, we need to take a step back to understand how Python initializes scripts and how this interacts with its module import mechanism.
Whenever the Python interpreter reads a source file, it does two things:
* it sets a few special variables like `__name__`, and then
* it executes all of the code found in the file.
Let's see how this works and how it relates to your question about the `__name__` checks we always see in Python scripts.
## Code Sample
Let's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called `foo.py`.
```
# Suppose this is foo.py.
print("before import")
import math
print("before function_a")
def function_a():
print("Function A")
print("before function_b")
def function_b():
print("Function B {}".format(math.sqrt(100)))
print("before __name__ guard")
if __name__ == '__main__':
function_a()
function_b()
print("after __name__ guard")
```
## Special Variables
When the Python interpreter reads a source file, it first defines a few special variables. In this case, we care about the `__name__` variable.
**When Your Module Is the Main Program**
If you are running your module (the source file) as the main program, e.g.
```
python foo.py
```
the interpreter will assign the hard-coded string `"__main__"` to the `__name__` variable, i.e.
```
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__"
```
**When Your Module Is Imported By Another**
On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:
```
# Suppose this is in some other main program.
import foo
```
The interpreter will search for your `foo.py` file (along with searching for a few other variants), and prior to executing that module, it will assign the name `"foo"` from the import statement to the `__name__` variable, i.e.
```
# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
```
## Executing the Module's Code
After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.
**Always**
1. It prints the string `"before import"` (without quotes).
2. It loads the `math` module and assigns it to a variable called `math`. This is equivalent to replacing `import math` with the following (note that `__import__` is a low-level function in Python that takes a string and triggers the actual import):
```
# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
```
3. It prints the string `"before function_a"`.
4. It executes the `def` block, creating a function object, then assigning that function object to a variable called `function_a`.
5. It prints the string `"before function_b"`.
6. It executes the second `def` block, creating another function object, then assigning it to a variable called `function_b`.
7. It prints the string `"before __name__ guard"`.
**Only When Your Module Is the Main Program**
8. If your module is the main program, then it will see that `__name__` was indeed set to `"__main__"` and it calls the two functions, printing the strings `"Function A"` and `"Function B 10.0"`.
**Only When Your Module Is Imported by Another**
8. (**instead**) If your module is not the main program but was imported by another one, then `__name__` will be `"foo"`, not `"__main__"`, and it'll skip the body of the `if` statement.
**Always**
9. It will print the string `"after __name__ guard"` in both situations.
***Summary***
In summary, here's what'd be printed in the two cases:
```
# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
```
```
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
```
## Why Does It Work This Way?
You might naturally wonder why anybody would want this. Well, sometimes you want to write a `.py` file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself. Examples:
* Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.
* Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing `.py` files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.
* Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.
Beyond those examples, it's elegant that running a script in Python is just setting up a few magic variables and importing the script. "Running" the script is a side effect of importing the script's module.
## Food for Thought
* Question: Can I have multiple `__name__` checking blocks? Answer: it's strange to do so, but the language won't stop you.
* Suppose the following is in `foo2.py`. What happens if you say `python foo2.py` on the command-line? Why?
```
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
def function_a():
print("a1")
from foo2 import function_b
print("a2")
function_b()
print("a3")
def function_b():
print("b")
print("t1")
if __name__ == "__main__":
print("m1")
function_a()
print("m2")
print("t2")
```
* Now, figure out what will happen in `foo3.py` (having removed the `__name__` check):
```
# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
def function_a():
print("a1")
from foo3 import function_b
print("a2")
function_b()
print("a3")
def function_b():
print("b")
print("t1")
print("m1")
function_a()
print("m2")
print("t2")
```
* What will this do when used as a script? When imported as a module?
```
# Suppose this is in foo4.py
__name__ = "__main__"
def bar():
print("bar")
print("before __name__ guard")
if __name__ == "__main__":
bar()
print("after __name__ guard")
``` | When your script is run by passing it as a command to the Python interpreter,
```
python myscript.py
```
all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets run. Unlike other languages, there's no `main()` function that gets run automatically - the `main()` function is implicitly all the code at the top level.
In this case, the top-level code is an `if` block. `__name__` is a built-in variable which evaluates to the name of the current module. However, if a module is being run directly (as in `myscript.py` above), then `__name__` instead is set to the string `"__main__"`. Thus, you can test whether your script is being run directly or being imported by something else by testing
```
if __name__ == "__main__":
...
```
If your script is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed, but the code in the then-body of the `if` clause above won't get run as the condition is not met. As a basic example, consider the following two scripts:
```
# file one.py
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
```
```
# file two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
```
Now, if you invoke the interpreter as
```
python one.py
```
The output will be
```
top-level in one.py
one.py is being run directly
```
If you run `two.py` instead:
```
python two.py
```
You get
```
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
```
Thus, when module `one` gets loaded, its `__name__` equals `"one"` instead of `"__main__"`. | What does if __name__ == "__main__": do? | [
"",
"python",
"namespaces",
"program-entry-point",
"python-module",
"idioms",
""
] |
Is there a way to measure the the amount of a string that will fit into a printed area without using the graphics object?
This is the only way I could find to do it:
```
Graphics instance = this.CreateGraphics();
instance.MeasureString(text, f, printArea1, StringFormat.GenericDefault,
out end, out lines);
```
I am using .net 2.0 and c# but I don't mind VB code. | Yes, there is, in .NET 2.0
`Size size = TextRenderer.MeasureString(this.Text, this.Font);` | The amount of space the string will take directly depends on the graphics object you want to render the string on.
Are you printing the string on the screen, a printer, a memory surface or a bitmap? What's the DPI of the surface you are trying to measure the text on? What unit? What space transformations need to be applied?
This all depends on System.Drawing.Graphics since it is the graphics object that keeps track of this information.
What are the reasons you don't want to use a Graphics object? If for some reason you are rendering to a non graphic object, you can always create one that fits as much as possible your *other* target and keep it for measuring. | Is there a way to measure the amount of a string that will fit into a printed area without using the graphics object? | [
"",
"c#",
".net",
"vb.net",
""
] |
I have a php / mysql / jquery web app that makes 13 ajax queries to various APIs and stores the result in a database table. To each result I assign a score and when all the results have completed I want to display a 'total score'.
My problem is knowing when all the ajax queries have completed and all the results are in and ready to be tallied.
Here's the existing workflow:
1. User enters data in the query box and hits submit.
2. Page reloads and inserts a 'scan id' into a 'scan\_index' table.
3. Page then executes a jquery $.get function for each of 13 queries ( all queries use the same javascript function to perform their work ).
4. As each result is returned, the result is inserted into a 'scans' table using the previously inserted 'scan id' to allow association with the proper scan. The result is also displayed to the user along with that result's score.
At this point what I would do is retrieve all results in the scans table using the scan\_id value, and total up the score and display that to the user.
But my problem is knowing when to kick off the query to retrieve all the totals. Any given query could take up to 10 seconds ( my predefined timeout value ) before completing ( or failing ), but they usually take only about 3 seconds max to complete.
So, without knowing when a query will complete, how can I tell when all queries have completed? | It sounds like the key piece of information you're missing is the callback functionality of $.get. You can specify a function as the second or third argument which will fire when the request has completed
```
$.get('http://example.com/data', {'foo':'bar'}, function(resonseData){
//code here will be called when the ajax call has completed
})
```
So you'll want to setup a counter variable somewhere that gets incremented by one once for each request that's made, and then in the callback will decrement this value by one.
Then, after you've made the final get request, setup a watcher using setInterval that will check periodically (once a second, say) to see if the counter is zero. If it is, you're done with all your requests. You could probably add this check to the $.get callback itself, but that seems like it might be susceptible to timing issues.
That's the basic solution, but this could easily be abstracted out into a more robust/elegant queuing solution. | Here is another option. Code may need to be tweaked, I didn't actually test it, but it's a start.
```
var complete = 0;
function submitRequests () {
$.get("http://server/query1", {"data": "for Query"}, processResult(1));
$.get("http://server/query2", {"data": "for Query"}, processResult(2));
//...
$.get("http://server/query13", {"data": "for Query"}, processResult(13));
}
function processResults (query) {
complete += Math.pow(2,(query-1));
if (complete == 8191) {
$.get("http://server/results", scanid, function() {
//Show results
})
}
}
``` | How to know when jquery $.get ajax calls have completed? | [
"",
"php",
"jquery",
"mysql",
"ajax",
"get",
""
] |
In what kind of scenarios would we declare a member function as a 'friend function' ?..What exact purpose does 'friend function' which defies one of central concept of 'Encapsulation' of OOP serve? | You would use a friend function for the same sort of reasons that you would use a friend class, but on a member function (rather than entire class) basis. Some good explanations are in [this thread](https://stackoverflow.com/questions/521754/when-to-use-friend-class-in-c).
While friend functions and classes do violate encapsulation, they can be useful in some scenarios. For example, you may want to allow a test harness to access class internals to allow you to do whitebox testing. Rather than opening up the entire class to the test harness, you could open up a particular function which accesses the internals required by the test harness. While this still violates encapsulation, it's less risky than opening up the entire class.
Also see [this article](http://www.cprogramming.com/tutorial/friends.html) for some more information about friend classes and functions. | Friend functions and classes do not violate encapsulation when you are trying to build an abstraction or interface that must physically span multiple C++ classes or functions! That is why friend was invented.
Those types of cases don't come up often, but sometimes you are forced to implement an abstraction or interface with disparate classes and functions. The classic example is implementing some type of complex number class. The non-member operator functions are given friendship to the main complex number class.
I also recall doing this when programming with CORBA in C++. CORBA forced me to have separate classes to implement CORBA servants. But for a particular part of our software, I needed to marry these together as one interface. Friendship allowed these two classes to work together to provide a seamless service to one part of our software.
Having the ability to mark a particular member function on another class as a friend to your class may seem even stranger, but it is just a way of tightly controlling the friendship. Instead of allowing the entire other class "in" as your friend, you only allow one of its member functions access. Again, this isn't common, but *very* useful when you need it. | In what scenarios should one declare a member function a friend? | [
"",
"c++",
"function",
"friend",
""
] |
> **Possible Duplicate:**
> [Why does Microsoft Visual C# 2008 Express Edition debugger randomly exit?](https://stackoverflow.com/questions/310788/why-does-microsoft-visual-c-sharp-2008-express-edition-debugger-randomly-exit)
I've faced the strangest problem with Visual Studio C# debugger in my career. In short, after a break point in my code was hit I cannot step through the code. `F11` (step into) and `F10` (step over) work for several times, but eventually Visual Studio performs `F5` (continue) action. I am still able to debug using break point on every line.
This behavior reproduces on each project developer's machine. It's Visual Studio SP1 everywhere.
I've checked every (as far as I understand) option. I've disabled "Just My Code". I've disabled "step through properties". I've disabled automatic property evaluation. In despair, I've recreated all project and solution files from scratch.
Is there any solution to my problem?
**Update** This behavior could be reproduced only on this project.
**Update 2** This does not seems like threading problem: it reproduces under Visual Studio's developer web server... | OK then. It's [NHProf](http://nhprof.com/)'s fault. I've just disabled it and debugger went right.
[NHProf](http://nhprof.com/) generates *SocketException*s if there no mother application running aside. It provokes context switching.
Thank you, Jon Tackabury | This [KB article](http://support.microsoft.com/default.aspx/kb/957912) might be interesting for those that find this thread back. | Why does Visual Studio debugging mode not work properly (performing F5 when F11 was pressed)? | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"debugging",
""
] |
I have a tutorial from a website [Net Tuts](http://net.tutsplus.com/videos/screencasts/how-to-open-zip-files-with-php/) which is used to upload a zip file and extract the data from within the file into the server.
Copying and pasting the code straight from the web page did not work, an error occured half way through the script being processed.
```
Fatal error: Cannot instantiate non-existent class: ziparchive in /www/website_here.co.uk/httpdocs/test/functions.php on line 6
```
Is it possible that this is to do with the version of PHP I am using? Here is the code it gets stuck on:
```
<?php
function openZip($file_to_open) {
global $target;
global $unique_folder;
$zip = new ZipArchive();
$x = $zip->open($file_to_open);
if ($x === true) {
$zip->extractTo($target . $unique_folder);
$zip->close();
unlink($file_to_open); #deletes the zip file. We no longer need it.
} else {
die("There was a problem. Please try again!");
}
}
?>
```
line 6: $zip = new ZipArchive();
I am using PHP version 4.3.9. | On PHP 4 you absolutely need to install [PECL zip 1.1.0](http://pecl.php.net/package/zip) (or newer) in order to have access to the `ZipArchive` class. Follow [these instructions](http://us.php.net/manual/en/install.pecl.php).
If that is not possible, you will have to use the non-OO `zip_open`, `zip_read` etc. API. | You could use PclZip too:
```
include('pclzip.lib.php');
$zip = new PclZip($file_to_open);
if ($zip->extract(PCLZIP_OPT_PATH, $target . $unique_folder) == 0) {
die("There was a problem. Please try again!");
} else {
unlink($file_to_open);
}
```
<http://www.phpconcept.net/pclzip> | Extracting data from a zip file (PHP) | [
"",
"php",
"zip",
"zlib",
""
] |
I've been asked to create a website in [SharePoint](http://en.wikipedia.org/wiki/Microsoft_SharePoint) within the next couple of weeks or so and I'm entirely new to SharePoint.
Does anyone have any good examples/tutorials on how to do some basic operations such as creating custom forms, using basic [CRUD](http://en.wikipedia.org/wiki/Create,_read,_update_and_delete) operations, with a custom [SQL Server](http://en.wikipedia.org/wiki/Microsoft_SQL_Server) database?
Also is there any way to code in ASP.NET (with [code-behind](http://en.wikipedia.org/wiki/ASP.NET#Code-behind_model) pages), but use the SharePoint look and feel and authentication stuff? | SharePoint is not *quite* like what you're used to. My two main gripes are:
**Deployment:**
If your requirements are for a single production site (no staging/test/development sites) your best bet is probably to go with the [SharePoint Designer](http://en.wikipedia.org/wiki/Microsoft_Office_SharePoint_Designer) and hack stuff together directly on the production site (yes I know it's dirty).
If you need those other environments you should produce deployment packages for everything (no xcopy deployment). Deployment packages are a [PITA](http://en.wiktionary.org/wiki/PITA) IMHO and are *very* easy to get wrong.
**IIS**
SharePoint basically takes over your [IIS](http://en.wikipedia.org/wiki/Internet_Information_Services) installation and introduces a new set of rules for where things are located etc. One gotcha is "ghosted" files. i.e. whenever a file is changed using the SharePoint Designer the file is backed up to a database and from now on IIS will only use the file in the database, so there is no use changing the one in the file system.
**To sum up:**
In my humble opinion if you are making a site where uptime isn't that important and you can afford to make mistakes in production, SharePoint can be good enough with the designer. If you are making a [CMS](http://en.wikipedia.org/wiki/Content_management_system) site where you need the code to go through multiple environments before it reaches production, (with [continuous integration](http://en.wikipedia.org/wiki/Continuous_integration)), I can think of no other .NET based CMS that does a worse job. You will spend a LOT of time grokking how to get the deployment routines to work for you, and you will spend a LOT of time with issues relating to "ghosted" files
Good luck. | Technet has a bunch of [virtual labs](http://technet.microsoft.com/en-us/virtuallabs/bb512933.aspx) for SharePoint products. | SharePoint for a C# ASP.NET Developer | [
"",
"c#",
"asp.net",
"sharepoint",
""
] |
```
$befal = mysql_query("SELECT * FROM users WHERE username = $_GET[username]");
$rad = mysql_fetch_assoc($befal);
```
Equals
```
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in C:\profile.php on line 4
```
I have a user called Admin in the field username and it still dont work. profile.php?user=Admin...
This works if I use the ID though:
```
$befal = mysql_query("SELECT * FROM users WHERE user_id = $_GET[id]");
$rad = mysql_fetch_assoc($befal);
```
What can be the problem?
Thanks | Try it like this:
```
$befal = mysql_query("SELECT * FROM users WHERE username = '$_GET[username]'");
```
You have to encapsulate a string parameter in apostrophes.
**[UPDATE]**
Just like [cletus](https://stackoverflow.com/questions/572731/php-problem-in-a-sql-statement-when-using-a-string-parameter/572744#572744) and [Olaf](https://stackoverflow.com/questions/572731/php-problem-in-a-sql-statement-when-using-a-string-parameter/572742#572742) pointed out, with the above sql statement you are **very prone to SQL Injection**. Check out their posted answers to see what I mean. | Errr... that's a recipe for getting hacked. I would like to introduce you to [SQL injection](http://en.wikipedia.org/wiki/SQL_injection) as characterized by this [very funny yet poignant cartoon](https://stackoverflow.com/questions/84556/whats-your-favorite-programmer-cartoon/84629#84629).
Try this instead.
```
$username = mysql_escape_string($_GET['username']);
$query = mysql_query("SELECT * FROM users WHERE username = '$username'");
``` | PHP: Problem in a SQL statement when using a String Parameter | [
"",
"php",
"mysql",
""
] |
I have a string (`$string` for this example) and I want to do the following:
Parse the string and convert all urls within it to "actual links" (adding the open/close anchor tag).
What is the best way to do this? I tried using `preg_split()` to create an array of the links contained in the string, with the idea of using `str_replace()` after the fact to make the changes. This approach isn't working however because I am having a hard time isolating the links in the string of text with `preg_split()`.
`$string` could contain several links within it so that's why I was going with this approach. If I knew precisely what the links were ahead of time or if `str_replace()` worked with pattern matching I would be set.
In short, I don't think the approach described above is the best way to go. What is a better method? | This is precisely the kind of thing `preg_replace` was intended for...
```
preg_replace('/your URL regex/', '<a href="$0">$0</a>', $string);
```
*EDIT*: whaddya know, top Google hit for "URL regex PHP": <http://snipplr.com/view/2371/regex-regular-expression-to-match-a-url/>
```
# PHP Example: Automatically link URL's inside text.
$text = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $text);
```
Note that if you want to match URLs in full generality, you'll need a devilishly complicated regular expression, but to match most common HTTP/HTTPS URLs, the above regex should work. | I think you're misunderstanding the purpose of `preg_split()`. It's used to split a string apart based on a regex. For example if you have a data string "one1two2three3four" you could use `preg_split` with a regex of "\d" and you'd get a 4-element array returned, consisting of "one", "two", "three", "four".
So unless the links are always separated by specific characters, `preg_split()` isn't the right tool for the job. You'll probably want to use `preg_match()` and then loop over the different matches that are returned.
Edit: or as David stated, `preg_replace()` is even better than `preg_match()`. | Convert all urls in a string to anchors | [
"",
"php",
"regex",
"string",
"parsing",
"hyperlink",
""
] |
As a follow on from [this question.](https://stackoverflow.com/questions/492115/c-enums-as-function-parameters)
How can I call a function and pass in an Enum?
For example I have the following code:
```
enum e1
{
//...
}
public void test()
{
myFunc( e1 );
}
public void myFunc( Enum e )
{
var names = Enum.GetNames(e.GetType());
foreach (var name in names)
{
// do something!
}
}
```
Although when I do this I am getting the 'e1' is a 'type' but is used like a 'variable' Error message. Any ideas to help?
I am trying to keep the function generic to work on any Enum not just a specific type? Is this even possible?... How about using a generic function? would this work? | You can use a generic function:
```
public void myFunc<T>()
{
var names = Enum.GetNames(typeof(T));
foreach (var name in names)
{
// do something!
}
}
```
and call like:
```
myFunc<e1>();
```
**(EDIT)**
The compiler complains if you try to constraint `T` to `Enum` or `enum`.
So, to ensure type safety, you can change your function to:
```
public static void myFunc<T>()
{
Type t = typeof(T);
if (!t.IsEnum)
throw new InvalidOperationException("Type is not Enum");
var names = Enum.GetNames(t);
foreach (var name in names)
{
// do something!
}
}
``` | Why not passing the type?
like:
```
myfunc(typeof(e1));
public void myFunc( Type t )
{
}
``` | c# Enum Function Parameters | [
"",
"c#",
"enums",
"function-parameter",
""
] |
Does C++ have access to infile data through a filehandle? For example the typical idiom in Perl is:
```
while (<DATA>) {
chomp;
# do sth with $_
}
__DATA__
Foo
Bar
```
What's the way to do that in C++ ? | I wouldn't say it's idiomatic as I've never seen it in any C++ code, but you can use C++ string stream and C pre-processor string pasting to treat a multi-line string as an input stream:
```
#include <sstream>
#include <iostream>
using namespace std;
const string data =
"once upon a time, " \
"a young lass called Goldilocks\n" \
"went for a walk in the forest.\n";
int main ()
{
istringstream in (data);
for (string line; getline(in, line); )
cout << line << endl;
return 0;
}
``` | You mean including the file inside the program?
No, C++ can't do that. Not in the same way as Perl. There are many tools that will take binary or text files and package them as C/C++ source code. They just end up as a global array.
One thing I always found useful is the ability to open random memory as a file handle, which is similar to what you appear to be asking. In standard C++ this might be accomplished with the istringstream class, which has the same interface as ifstream.
But the context of your question may imply that there's a better way to accomplish what you're thinking in C/C++. More information is needed. | Infile Handle in C++ (ala __DATA__ in Perl) | [
"",
"c++",
"filehandle",
""
] |
I often find myself implementing a class maintaining some kind of own status property as an enum: I have a Status enum and ONE Status property of Status type. How should I solve this name conflict?
```
public class Car
{
public enum Status
{
Off,
Starting,
Moving
};
Status status = Status.Off;
public Status Status // <===== Won't compile =====
{
get { return status; }
set { status = value; DoSomething(); }
}
}
```
If the Status enum were common to different types, I'd put it outside the class and the problem would be solved. But Status applies to Car only hence it doesn't make sense to declare the enum outside the class.
What naming convention do you use in this case?
NB: This question was partially debated in comments of an answer of [this question](https://stackoverflow.com/questions/211567/enum-and-property-naming-conflicts). Since it wasn't the *main* question, it didn't get much visibility.
EDIT: Filip Ekberg suggests an IMO excellent workaround for the specific case of 'Status'. Yet I'd be interesting to read about solutions where the name of the enum/property is different, as in Michael Prewecki's *answer*.
EDIT2 (May 2010): My favorite solution is to pluralize the enum type name, as suggested by Chris S. According to MS guidelines, this should be used for flag enums only. But I've come to like it more and more. I now use it for regular enums as well. | I'll add my 1 euro to the discussion but it's probably not adding anything new.
The obvious solution is to move Status out of being a nested Enum. Most .NET enums (except possibly some in Windows.Forms namespace) aren't nested and it makes it annoying to use for the developer consuming your API, having to prefix the classname.
*One thing that hasn't been mentioned* is that flag enums according to MSDN guidelines should [be pluralized nouns](http://msdn.microsoft.com/en-us/library/ms229058.aspx) which you probably already know (Status is a simple enum so singular nouns should be used).
State (enum called States) is the vocative, "Status" is the nominative of a noun that the English like most of our language absorbed from Latin. Vocative is what you name a noun for its condition and nominative is the subject of the verb.
So in other words when the car *is moving*, that's the verb - moving is its status. But the car doesn't go off, its engine does. Nor does it start, the engine does (you probably picked an example here so this might be irrelevant).
```
public class Car
{
VehicleState _vehicleState= VehicleState.Stationary;
public VehicleState VehicleState
{
get { return _vehicleState; }
set { _vehicleState = value; DoSomething(); }
}
}
public enum VehicleState
{
Stationary, Idle, Moving
}
```
State is such a generalised noun wouldn't it be better to describe what state it is referring to? Like I did above
The type example also in my view doesn't refer to the reader type, but its database. I would prefer it if you were describing the reader's database product which isn't necessarily relevant to the type of reader (e.g. the type of reader might be forward only, cached and so on). So
```
reader.Database = Databases.Oracle;
```
In reality this never happens as they're implemented as drivers and an inheritance chain instead of using enums which is why the line above doesn't look natural. | The definition of "Off", "Starting" and "Moving" is what i would call a "State". And when you are implying that you are using a "State", it is your "Status". So!
```
public class Car
{
public enum State
{
Off,
Starting,
Moving
};
State state = State.Off;
public State Status
{
get { return state ; }
set { state= value; DoSomething(); }
}
}
```
If we take another example from the one stated where you'd like to use the word "Type" such in this case:
```
public class DataReader
{
public enum Type
{
Sql,
Oracle,
OleDb
}
public Type Type { get; set; } // <===== Won't compile =====
}
```
You really need to see that there is a difference between enums and enums, right? But when creating a framework or talking about architecture you need to focus on the simillarities, ok lets find them:
**When something is set to a State, it's defined as the "things" Status**
Example: The Car's Status is in Running State, Stopped State, and so on.
What you want to acheive in the second example is somewhat this:
```
myDataReader.Type = DataReader.Database.OleDb
```
You might think that this says against what i've been preaching about to others, that you need to follow a standard. But, you are following a standard! The Sql-case is a specific case aswell and therefore need a somewhat specific solution.
However, the enum would be re-usable within your `System.Data` space, and that's what the patterns is all about.
Another case to look at with the "Type" is "Animal" where Type defines the Species.
```
public class Animal
{
public enum Type
{
Mammal,
Reptile,
JonSkeet
}
public Type Species{ get; set; }
}
```
This is following a pattern, you don't specificly need to "know" the Object for this and you are not specifing "AnimalType" or "DataReaderType", you can re-use the enums in your namespace of choice. | C# naming convention for enum and matching property | [
"",
"c#",
".net",
"enums",
"naming-conventions",
""
] |
If string is a value type, which I assume it is, why would the following declaration be legal:
```
struct Refsample<T> where T : class
RefSameple<string>; //why is it legal?
```
Taken from the C# in depth, page 75 | string is immutable reference type.
Are you trying to say?
```
struct Refsample<T> where T : class
```
struct itself is value type but it can contain reference type.
Value type variable stored in the memory stack, but reference type variable has a memory address that pointing to the heap.
e.g.
```
struct Refsample<T> where T : class
{
// stored in the stack as well.
public int Age;
// memory address pointing to the heap stored in the stack,
// but the actual object is stored in the heap.
public string Name;
// same as string above if T was reference type;
// otherwise, if value type, same as Age above.
public T SomeThing;
}
``` | System.String is a reference type, although it has some characteristics of a value type. | String a value type part of generics constraint | [
"",
"c#",
""
] |
Consider following schema:
```
Customers:
Col | Type |
-------------------|
id | INTEGER |
name | VARCHAR |
Orders:
Col | Type |
----------------------|
id | INTEGER |
customer_id | INTEGER |
date | DATE |
Items
Col | Type |
----------------------|
id | INTEGER |
order_id | INTEGER |
name | VARCHAR |
quantity | INTEGER |
```
And here's the breif run down of the schema:
Customer can have many orders, and an order can have many items
Note: You may argue that the items should refer to some products table with a product\_id, but let it be simple as is now.
From my database, I want to ask following question:
For a given customer, list all the items that start with La.
My version of the query goes like this:
SELECT \* FROM items WHERE name LIKE 'La%'
This would return ALL the items that Begin with La for ALL the customers. What I want is that I get all the items for a SPECIFIC customer with say id 1. How do I write such a query? My second version that would do is like this:
SELECT \* FROM items WHERE name LIKE 'La%' AND order\_id in (SELECT id FROM orders WHERE customer\_id=1);
But is their any other efficient/elegant or a more better way to do the same thing? | The elegant way to do this is called a join.
```
SELECT
c.id customer_id,
c.name customer_name,
i.id item_id,
i.name item_name,
COUNT(i.id) order_count,
SUM(i.quantity) items_ordered
FROM
customers c
INNER JOIN orders o ON c.id = o.customer_id
INNER JOIN items i ON i.id = o.order_id
WHERE
i.name LIKE 'La%'
AND c.id = 1
GROUP BY
c.id,
c.name,
i.id,
i.name
``` | > select i.name from customers c
> join oders o
> on c.id = o.customer\_id
> join Items i
> on o.id = i.order\_id where c.id = WHATEVER\_CUSTOMER\_ID\_YOU\_WANT
> and i.name LIKE 'La%' | SQL: Searching grand child table for specifc items | [
"",
"sql",
""
] |
I have the following code.
```
from xml.dom.minidom import Document
doc = Document()
root = doc.createElement('root')
doc.appendChild(root)
main = doc.createElement('Text')
root.appendChild(main)
text = doc.createTextNode('Some text here')
main.appendChild(text)
print doc.toprettyxml(indent='\t')
```
The result is:
```
<?xml version="1.0" ?>
<root>
<Text>
Some text here
</Text>
</root>
```
This is all fine and dandy, but what if I want the output to look like this?
```
<?xml version="1.0" ?>
<root>
<Text>Some text here</Text>
</root>
```
Can this easily be done?
Orjanp... | > Can this easily be done?
It depends what exact rule you want, but generally no, you get little control over pretty-printing. If you want a specific format you'll usually have to write your own walker.
The DOM Level 3 LS parameter format-pretty-print in [pxdom](http://www.doxdesk.com/software/py/pxdom.html) comes pretty close to your example. Its rule is that if an element contains only a single TextNode, no extra whitespace will be added. However it (currently) uses two spaces for an indent rather than four.
```
>>> doc= pxdom.parseString('<a><b>c</b></a>')
>>> doc.domConfig.setParameter('format-pretty-print', True)
>>> print doc.pxdomContent
<?xml version="1.0" encoding="utf-16"?>
<a>
<b>c</b>
</a>
```
(Adjust encoding and output format for whatever type of serialisation you're doing.)
If that's the rule you want, and you can get away with it, you might also be able to monkey-patch minidom's Element.writexml, eg.:
```
>>> from xml.dom import minidom
>>> def newwritexml(self, writer, indent= '', addindent= '', newl= ''):
... if len(self.childNodes)==1 and self.firstChild.nodeType==3:
... writer.write(indent)
... self.oldwritexml(writer) # cancel extra whitespace
... writer.write(newl)
... else:
... self.oldwritexml(writer, indent, addindent, newl)
...
>>> minidom.Element.oldwritexml= minidom.Element.writexml
>>> minidom.Element.writexml= newwritexml
```
All the usual caveats about the badness of monkey-patching apply. | I was looking for exactly the same thing, and I came across this post. (the indenting provided in xml.dom.minidom broke another tool that I was using to manipulate the XML, and I needed it to be indented) I tried the accepted solution with a slightly more complex example and this was the result:
```
In [1]: import pxdom
In [2]: xml = '<a><b>fda</b><c><b>fdsa</b></c></a>'
In [3]: doc = pxdom.parseString(xml)
In [4]: doc.domConfig.setParameter('format-pretty-print', True)
In [5]: print doc.pxdomContent
<?xml version="1.0" encoding="utf-16"?>
<a>
<b>fda</b><c>
<b>fdsa</b>
</c>
</a>
```
The pretty printed XML isn't formatted correctly, and I'm not too happy about monkey patching (i.e. I barely know what it means, and understand it's bad), so I looked for another solution.
I'm writing the output to file, so I can use the xmlindent program for Ubuntu ($sudo aptitude install xmlindent). So I just write the unformatted to the file, then call the xmlindent from within the python program:
```
from subprocess import Popen, PIPE
Popen(["xmlindent", "-i", "2", "-w", "-f", "-nbe", file_name],
stderr=PIPE,
stdout=PIPE).communicate()
```
The -w switch causes the file to be overwritten, but annoyingly leaves a named e.g. "myfile.xml~" which you'll probably want to remove. The other switches are there to get the formatting right (for me).
P.S. xmlindent is a stream formatter, i.e. you can use it as follows:
```
cat myfile.xml | xmlindent > myfile_indented.xml
```
So you might be able to use it in a python script without writing to a file if you needed to. | Python xml minidom. generate <text>Some text</text> element | [
"",
"python",
"xml",
"minidom",
""
] |
I am using `TreeBidiMap` from the [Apache Collections](https://commons.apache.org/proper/commons-collections/) library. I want to sort this on the values which are `doubles`.
My method is to retrieve a `Collection` of the values using:
```
Collection coll = themap.values();
```
Which naturally works fine.
**Main Question:** I now want to know how I can convert/cast (not sure which is correct) `coll` into a `List` so it can be sorted?
I then intend to iterate over the sorted `List` object, which should be in order and get the appropriate keys from the `TreeBidiMap` (`themap`) using `themap.getKey(iterator.next())` where the iterator will be over the list of `doubles`. | ```
List list = new ArrayList(coll);
Collections.sort(list);
```
As Erel Segal Halevi says below, if coll is already a list, you can skip step one. But that would depend on the internals of TreeBidiMap.
```
List list;
if (coll instanceof List)
list = (List)coll;
else
list = new ArrayList(coll);
``` | Something like this should work, calling the [ArrayList constructor](http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-java.util.Collection-) that takes a Collection:
```
List theList = new ArrayList(coll);
``` | How to convert a Collection to List? | [
"",
"java",
"list",
"sorting",
"collections",
"apache-commons-collection",
""
] |
I've been struggling with this for far too long, and I don't see any error.
I've got a table that holds a bunch of locations. When I'm adding a location via my php script, I get an error of 'Wrong parameter count for mysql\_query()'.
When I echo the mysql query, everything looks fine,and I can copy and and paste it into phpmyAdmin , everything runs perfectly.
The query looks like this
```
INSERT IGNORE INTO locations (name, address, city, state, zip) VALUES ('Soboba Casino','23333 Soboba Road', 'San Jacinto', 'CA', '92581')
```
Am I missing something? Why would this not run in my script, but run in phpmyAdmin?
Sorry, Missed putting in the php, the offensive php seems pretty straight forward
```
// insert the venue
$insertLoc="INSERT IGNORE INTO locastions (loc, address, city, state, zip) VALUES ('$venueName','$streetAddress', '$city', '$state', '$zip')";
echo $insertLoc;
mysql_query($insertLoc)or die(mysql_query());
``` | Try replacing the third line with
```
mysql_query($insertLoc)or die(mysql_error());
```
(Note that I've replaced the second `mysql_query()` with `mysql_error()`.) | `or die(mysql_query());` should be `or die(mysql_error());`
Also, in your SQL I guess `locastions` should be `locations` | wrong parameter count error in mysql via php | [
"",
"php",
"mysql",
""
] |
How does your team handle Builds?
We use Cruise Control, but (due to lack of knowledge) we are facing some problems - [Code freeze in SVN - Build management](https://stackoverflow.com/questions/419133/code-freeze-in-svn)
Specifically, how do you make available a particular release when code is constantly being checked in?
Generally, can you discuss what best practices you use in release management? | I'm positively astonished that this isn't a duplicate, but I can't find another one.
Okay, here's the deal. They are two separate, but related questions.
For build management, the essential point is that you should have an automatic, repeatable build that rebuilds the entire collection of software from scratch, and goes all the way to your deliverable configuration. in other words, you should build effectively a release candidate every time. Many projects don't really do this, but I've seen it burn people (read "been burned by it") too many times.
Continuous integration says that this build process should be repeated every time there is a significant change event to the code (like a check in) if at all possible. I've done several projects in which this turned into a build every night because the code was large enough that it took several hours to build, but the ideal is to set up your build process so that some automatic mechanism --- like an ant script or make file --- only rebuilds the pieces affected by a change.
You handle the issue of providing a specific release by in some fashion preserving the exact configuration of all affected artifacts for each build, so you can apply your repeatable build process to the exact configuration you had. (That's why it's called "configuration management.") The usual version control tools, like git or subversion, provide ways to identify and name configurations so they can be recovered; in svn, for example, you might construct a tag for a particular build. You simply need to keep a little bit of metadata around so you know which configuration you used.
You might want to read one of the "Pragmatic Version Control" books, and of course the stuff on CI and Cruise Control on Martin Fowler's site is essential. | Look at [continuous integration: best pratices](http://www.martinfowler.com/articles/continuousIntegration.html), from Martin Fowler.
Well, I have managed to find a [related thread](http://www.coderanch.com/t/130861/Agile-Other-Processes/Continuous-Integration-builds-version-tags), I participated in, a year ago. You might find it useful, as well.
And here is how we do it.
**[Edited]**
We are using Cruise Control as integration tool. We just deal with the trunk, which is the main Subversion repository in our case. We seldom pull out a new branch for doing new story cards, when there is a chance of complex conflicts. Normally, we pull out a branch for a version release and create the build from that and deliver that to our test team. Meanwhile we continue the work in trunk and wait for the feedback from test team. Once all tested we create a tag from the branch, which is immutable logically in our case. So, we can release any version any time to any client in case. In case of bugs in the release we don't create tag, we fix the things there in the branch. After getting everything fixed and approved by test team, we merge the changes back to trunk and create a new tag from the branch specific to that release.
So, the idea is our branches and tags are not really participating in continuous integration, directly. Merging branch code back to the trunk automatically make that code becomes the part CI (Continuous Integration). We normally do just bugfixes, for the specific release, in branches, so it doesn't really participate into CI process, I believe. To the contrary, if we start doing new story cards, for some reasons, in a branch, then we don't keep that branch apart too long. We try to merge it back to trunk as soon as possible.
Precisely,
* We create branches manually, when we plan a next release
* We create a branch for the release and fix bugs in that branch in case
* After getting everything good, we make a tag from that branch, which is logically immutable
* At last we merge the branch back to trunk if has some fixes/modifications | Build management/ Continuous Integration best practices | [
"",
"java",
"build-process",
"release",
""
] |
I creating a small addin to help with my source control.
Does anybody know how I could retrieve the Branch Name and Version Number of a source file in Rational ClearCase. I want to do this using C#. Where is all the information actually stored? | You need, from C#, to execute a `cleartool` command
More specifically, a `descr` with a [format option](http://publib.boulder.ibm.com/infocenter/cchelp/v7r0m1/index.jsp?topic=/com.ibm.rational.clearcase.cc_ref.doc/topics/fmt_ccase.htm) only displaying *exactly* what you are after.
```
cleartool descr -fmt "%Sn" youFileFullPath
```
That will return a string like `/main/34`, meaning `/branch/version`
```
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo(@"cleartool");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.Arguments = "descr -fmt \"%Sn\" \"" + yourFilePath + "\"";
psi.UseShellExecute = false;
System.Diagnostics.Process monProcess;
monProcess= System.Diagnostics.Process.Start(psi);
System.IO.StreamReader myOutput = monProcess.StandardOutput;
monProcess.WaitForExit();
if (monProcess.HasExited)
{
//la sortie du process est recuperee dans un string
string output = myOutput.ReadToEnd();
MessageBox.Show(output);
}
```
Note: it is recommended to always use double quotes around your file full path, in case that path or that file name includes spaces
---
As I have explained in this other [ClearCase SO question](https://stackoverflow.com/questions/268595), you could also use the [CAL interface](http://www.ibm.com/developerworks/rational/library/06/0207_joshi/index.html) (COM object), but I have always found `cleartool` (the basic CLI -- Command Line Interface --) more reliable especially when things go wrong: the error message is much more precise. | Your best bet is probably to use the cleartool.exe command line and parse the result. Ideally this is usually done from a perl or python script but it'll work from C# as well. I doubt you'll find any more direct way of interrogating clearcase which is as simple. | Retrieving the version number of a source file in ClearCase | [
"",
"c#",
"clearcase",
"visual-studio-addins",
""
] |
I'm new to Linq to Xml. I have a very simple xml file like this:
```
<Items>
<Item>
<Stuff>Strings</Stuff>
</Item>
<Item>
<Stuff>Strings</Stuff>
</Item>
</Items>
```
And I'm trying to query it like this:
```
XDocument doc = XDocument.Load(myStream)
from node in doc.Descendants(XName.Get("Item"))
select new { Stuff = node.Element(XName.Get("Stuff")).Value }
```
But doc.Descendents(XName.Get("Item")) returns null. Something is wrong with my understanding here. | Your code actually works:
```
static void Main(string[] args)
{
string xml = @"
<Items>
<Item>
<Stuff>Strings</Stuff>
</Item>
<Item>
<Stuff>Strings</Stuff>
</Item>
</Items>";
using (StringReader myStream = new StringReader(xml))
{
XDocument doc = XDocument.Load(myStream);
var query = from node in doc.Descendants(XName.Get("Item"))
select new { Stuff =
node.Element(XName.Get("Stuff")).Value };
foreach (var item in query)
{
Console.WriteLine("Stuff: {0}", item.Stuff);
}
}
```
It should be noted that if the elements are not qualified with namespaces, then you don't really need XName:
```
static void Main(string[] args)
{
string xml = @"
<Items>
<Item>
<Stuff>Strings</Stuff>
</Item>
<Item>
<Stuff>Strings</Stuff>
</Item>
</Items>";
using (StringReader myStream = new StringReader(xml))
{
XDocument doc = XDocument.Load(myStream);
var query = from node in doc.Descendants("Item")
select new { Stuff = node.Element("Stuff").Value };
foreach (var item in query)
{
Console.WriteLine("Stuff: {0}", item.Stuff);
}
}
}
``` | Try using doc.Root.Decendants("Item") | What is wrong with my simple query? | [
"",
"c#",
"linq-to-xml",
""
] |
Consider the following code:
```
for (var i = 0; i < 3; i++) {
var num = i + 0.50;
var output = num + " " + Math.round(num) + " " + num.toFixed(0);
alert(output);
}
```
In Opera 9.63 I get:
> 0.5 1 **0**
>
> 1.5 2 2
>
> 2.5 3 **2**
In FF 3.03 I get:
> 0.5 1 **1**
>
> 1.5 2 2
>
> 2.5 3 **3**
In IE 7 I get:
> 0.5 1 **0**
>
> 1.5 2 2
>
> 2.5 3 **3**
Note the bolded results. Why are this inconsistencies present? Does this mean that `toFixed(0)` should be avoided? What's the correct way to round a number to the nearest integer? | Edit: To answer your edit, use `Math.round`. You could also prototype the `Number` object to have it do your bidding if you prefer that syntax.
```
Number.prototype.round = function() {
return Math.round(this);
}
var num = 3.5;
alert(num.round())
```
I've never used `Number.toFixed()` before (mostly because most JS libraries provide a [`toInt()`](http://mootools.net/docs/Native/Number#Number:toInt) method), but judging by your results I would say it would be more consistent to use the `Math` methods (`round`, `floor`, `ceil`) then `toFixed` if cross-browser consistency is what you are looking for. | To address your two *original* issues/questions:
## Math.round(num) vs num.toFixed(0)
The issue here lies in the misconception that these should always give the same result. They are, in fact, governed by different rules. Look at negative numbers, for example. Because [`Math.round`](http://www.ecma-international.org/ecma-262/5.1/#sec-15.8.2.15) uses ["round half up"](http://en.wikipedia.org/wiki/Rounding#Round_half_up) as the rule, you will see that `Math.round(-1.5)` evaluates to `-1` even though `Math.round(1.5)` evaluates to `2`.
`Number.prototype.toFixed`, on the other hand, uses what is basically equivalent to ["round half away from zero"](http://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero) as the rule, according to [step 6 of the spec](http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4.5), which essentially says to treat negatives as positive numbers, and then add back the negative sign at the end. Thus, `(-1.5).toFixed(0) === "-2"` and `(1.5).toFixed(0) === "2"` are true statements in all spec-compliant browsers. Note that these values are strings, not numbers. Note further that both `-1.5.toFixed(0)` and `-(1.5).toFixed(0)` are `=== -2` (the number) due to operator precedence.
## Browser inconsistencies
Most modern browsers—or at least the ones you might be expected to support at the time of this writing **[except for IE](https://stackoverflow.com/a/19169968/357774)**—should all implement the specs correctly. (According to [Renee's comment](https://stackoverflow.com/questions/566564/javascript-functions-math-roundnum-vs-num-tofixed0-and-browser-inconsistenci#comment2034745_566564), the `toFixed` issue you pointed out in Opera has been fixed, presumably since they started using the same JS engine as Chrome.) It's still worth reiterating that, even if the specs were implemented consistently across all browsers, the behavior defined in the spec, particularly for `toFixed` rounding, can still be a bit unintuitive for "mere mortal" JS developers who expect true mathematical accuracy—see [Javascript toFixed Not Rounding](https://stackoverflow.com/q/10015027) and [this "works as intended" bug](https://bugs.chromium.org/p/v8/issues/detail?id=522) that was filed on the V8 JS engine for examples.
## Conclusion
In short, these are two different functions with two different return types and two different sets of rules for rounding.
As others have suggested, I would also like to say "use whichever function fits your particular use case" (taking special care to note the peculiarities of `toFixed`, especially IE's errant implementation). I would personally lean more towards recommending some explicit combination of `Math.round/ceil/floor`, again, as others have mentioned. *Edit:* ...though, after going back and reading your clarification, your use case (rounding to a whole number) definitely calls for the aptly-named `Math.round` function. | Math.round(num) vs num.toFixed(0) and browser inconsistencies | [
"",
"javascript",
"cross-browser",
""
] |
I used previously StyleCop + FxCop on my Visual Studio's projects. But now I am testing Visual Studio Code Analysis tool, which is easier to integrate into MSBuild, and I have found that this tools analyses some of the rules of both FxCop and StyleCop.
Is this tool a full replacement for both FxCop and StyleCop or does it just implement some of their rules? | Visual Studio includes FxCop + more.
From the [developer blog of FxCop](http://davesbox.com/archive/2008/08/17/fxcop-1-36-released.aspx):
> Sorry about my ignorance, but I assume
> FxCop is completely separate from the
> Code Analysis in VSTS? More
> specifically, I assume that if I
> install the new version of FxCop, VSTS
> will not take advantage (no shared
> code?)? If this is the case, any idea
> when these changes will make it into
> VSTS code analysis? Thanks!
>
> That's correct, they are different
> products, however they do have a
> common engine. Visual Studio 2008 SP1
> already comes with the same fixes and
> analysis (plus a little bit more), so
> there is no need to 'update' Visual
> Studio with the latest FxCop.
A [developer blog](http://blogs.msdn.com/fxcop/archive/2008/01/07/faq-which-rules-shipped-in-which-version.aspx) also gave the exact rules which are in each.
As for StyleCop, it's independent of VS Code Analysis as described in [this blog post](http://blogs.msdn.com/sourceanalysis/archive/2008/07/20/clearing-up-confusion.aspx), which links to [Jader Dias' post](https://stackoverflow.com/questions/580168/visual-studio-code-analysis-vs-stylecop-fxcop/580182#580182). | My understanding is that Visual Studio Code Analysis is basically a slightly modified version of FxCop. From my experience they are almost the same thing (in fact I believe Code Analysis uses the FxCop executable behind the scenes).
Although there is overlap between FxCop/CodeAnalysis and StyleCop; FxCop tends to focus more on design rules and StyleCop is focusing on coding style (casing, white space, indents, etc).
Also FxCop analyzes the IL while StyleCop analyzes the source code directly. This imposes a different set of restrictions on what rules they can each enforce. | Visual Studio Code Analysis vs StyleCop + FxCop | [
"",
"c#",
"visual-studio-2008",
"code-analysis",
"fxcop",
"stylecop",
""
] |
I'm using an if statement to declare whether a user is an admin, mod or neither with this code below, but its messing up by always making $status = "admin" even if that person is neither, this has really baffled me.
```
if($info['rights'] == "m") {
$status = '<font color="#FFFFFF">(mod)</font>';
}elseif ($info['rights'] == "a"); {
$status = '<font color="#FFFFFF">(admin)</font>';
}
``` | You seem to have accidentaly added a semicolon (;) after the elseif, so the second code block is always getting executed. | Is there supposed to be a semi-colon after "a")? | What is wrong with my `if` statement? | [
"",
"php",
"syntax",
"if-statement",
""
] |
I have several functions in my program that look like this:
```
void foo(int x, int y)
```
Now I want my program to take a string that looks like:
```
foo(3, 5)
```
And execute the corresponding function. What's the most straightforward way to implement this?
When I say straightforward, I mean reasonably extensible and elegant, but it shouldn't take too long to code up.
**Edit:**
While using a real scripting language would of course solve my problem, I'd still like to know if there is a quick way to implement this in pure C++. | I'd also go for the scripting language answer.
Using pure C++, I would probably use a parser generator, which will will get the token and grammar rules, and will give me C code that exactly can parse the given function call language, and provides me with an syntax tree of that call. [`flex`](https://github.com/westes/flex) can be used to tokenize an input, and [`bison`](http://www.gnu.org/software/bison/) can be used to parse the tokens and transform them into an syntax tree. Alternatively to that approach, [Boost Spirit](http://www.boost.org/doc/libs/1_37_0/libs/spirit/classic/index.html) can be used to parse the function call language too. I have never used any of these tools, but have worked on programs that use them, thus I somewhat know what I would use in case I had to solve that problem.
For very simple cases, you could change your syntax to this:
```
func_name arg1, arg2
```
Then you can use:
```
std::istringstream str(line);
std::string fun_name; str >> fun_name;
map[fun_name](tokenize_args(str));
```
The map would be a
```
std::map<std::string, boost::function<void(std::vector<std::string>)> > map;
```
Which would be populated with the functions at the start of your program. `tokenize_args` would just separate the arguments, and return a vector of them as strings. Of course, this is very primitive, but i think it's reasonable if all you want is some way to call a function (of course, if you want really script support, this approach won't suffice). | You can embed Python fairly simply, and that would give you a really powerful, extensible way to script your program. You can use the following to easily (more or less) expose your C++ code to Python:
* [Boost Python](http://www.boost.org/doc/libs/release/libs/python/doc/)
* [SWIG](http://www.swig.org/)
I personally use Boost Python and I'm happy with it, but it is slow to compile and can be difficult to debug. | Making a C++ app scriptable | [
"",
"c++",
"string",
"scripting",
""
] |
I'm looking to refactor the below query to something more readable and modifiable. The first half is identical to the second, with the exception of the database queried from (table names are the same though.)
```
SELECT
Column 1 AS c1,
...
Column N AS cN
FROM
database1.dbo.Table1
UNION
SELECT
'Some String' as c1,
...
NULL as cN
FROM
database1.dbo.Table2
UNION
SELECT
Column 1 AS c1,
...
Column N AS cN
FROM
database2.dbo.Table1
UNION
SELECT
'Some String' as c1,
...
NULL as cN
FROM
database2.dbo.Table2
```
This query is the definition of [DRY](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself) and is calling to me to be re-written, but I have no idea how!
**EDIT**: We can't use linq and we desire distinct results; I'm looking to make the query smaller in physical file size, not in results returned.
**EDIT**: The database I'm querying off is a proprietary ERP database. Restructuring it is not an option. | This is a pretty standard SQL pattern. Sometimes it's easy to inadvisedly transfer OOP/Procedural code principles like DRY to SQL, but they aren't necessarily transferable concepts.
Note how easily you can grok the entire logical design of the query, vs. hunting through submodules. If one of the subexpressions had an extra column, or columns reversed, it would stick out. This is basically a pretty simple SQL statement to grok as an execution unit, where disaggregating it would muddle it.
And when you're debugging, it's handy to be able to use the editor's text highlighting option to selectively exercise parts of the statement - a technique that doesn't exist in procedural code. OTOH, it can get messy trying to trace down all the pieces if they are scattered into views etc. Even CTEs can make this inconvenient. | I'm going to go out on a limb here, and say, based on the information you've given us;
**That's as good as it's going to get** | How would you write this query? | [
"",
"sql",
"refactoring",
"url-rewriting",
""
] |
I am wondering how to do this in a functional programming language. Maybe F# or Haskell.
Can someone show me an example without using any function calls except for `find` and `rfind`?
This function finds the next slash using `i` as the num of `slash` (<0 for backwards).
```
size_t findSlash(const char *sz, size_t i)
{
std::string s = sz;
size_t a, b, c, n, ai = abs(i), pos=0;
for (n=0; n<ai; n++)
{
if (i<0)
{
a = s.rfind("\\", pos);
b = s.rfind("/", pos);
}
else
{
a = s.find("\\", pos);
b = s.find("/", pos);
}
if (a==-1u)
{
if (b==-1u)
return pos;
c = b;
}
else if (b==-1u)
c = a;
else
c = min(a, b);
pos = c+1;
}
return c;
}
``` | In first, your code is broken. `size_t` is unsigned type and never can be `i<0`.
In second, your code is ugly std library misuse and ineffective. There should be used regular expression library or such or use handcrafted scanner. Resulting code is far cleaner and faster. For example (I have not been using C for many years but below code crafted in 10 minutes works.):
```
size_t findSlash(const char *sz, int i)
{
const char *s = sz;
if (i<0) {
for(;*s;s++);
for(;;s--){
if(s<sz) return -1;
if((*s == '/') || (*s == '\\'))
if(! ++i) break;
}
}
else {
for(;;s++){
if(! *s) return -1;
if((*s == '/') || (*s == '\\'))
if(! i--) break;
}
}
return s-sz;
}
```
I haven't used to write Haskell or F# but for example below code in Erlang should state as example how to do it in functional language:
```
findslash(L, I) when is_list(L), is_integer(I) ->
if I<0 ->
case findslash(lists:reverse(L), -1*I - 1, 0) of
none -> none;
X -> length(L) - X - 1
end;
I>=0 -> findslash(L, I, 0)
end.
findslash([H|_], 0, X) when H=:=$/; H=:=$\\ -> X;
findslash([H|T], I, X) when H=:=$/; H=:=$\\ ->
findslash(T, I-1, X+1);
findslash([_|T], I, X) -> findslash(T, I, X+1);
findslash([], _, _) -> none.
```
My attempt in Haskell with error checking and keeps laziness for i>=0:
```
findSlash :: String -> Int -> Maybe Int
findSlash str i
| i < 0 = reversed (_findSlash (reverse str) (-1*i-1) 0)
| i >= 0 = _findSlash str i 0
where
reversed Nothing = Nothing
reversed (Just a) = Just ((length str) - a - 1)
_findSlash (x:xs) i n
| x == '/' || x == '\\' = if i==0 then Just n else _findSlash xs (i-1) (n+1)
| True = _findSlash xs i (n+1)
_findSlash [] _ _ = Nothing
``` | Haskell:
```
import Data.List
findSlash :: String -> Int -> Int
findSlash str i = findIndices (\c -> c == '\\' || c == '/') str !! i
```
Handling the negative index (which is ugly 'cause you don't really want to do it):
```
findSlash :: String -> Int -> Int
findSlash str i =
index (findIndices (\c -> c == '\\' || c == '/') str) i
where index xs i | i < 0 = (reverse xs) !! ((-i) - 1)
| i >= 0 = xs !! i
```
Handling errors:
```
findSlash :: String -> Int -> Maybe Int
findSlash str i = index i
where xs = findIndices (\c -> c == '\\' || c == '/') str
l = length xs
index i
| i < 0 && i < (-l) = Nothing
| i >= 0 && i >= l = Nothing
| i < 0 = Just $ (reverse xs) !! ((-i) - 1)
| i >= 0 = Just $ xs !! i
```
Now you can say:
```
map (findSlash "/foo/bar/baz") [-4..4]
```
and get:
```
-- -4 -3 -2 -1 0 1 2 3 4
[Nothing,Just 0,Just 4,Just 8,Just 0,Just 4,Just 8,Nothing,Nothing]
```
Anyway, handling the offset from the end makes the code pretty ugly, and ruins the possibility for lazy evaluation. So I think most people would use the first one, perhaps with a bit of error-checking thrown in. (Which also kills laziness, since length would force evaluation of the whole list. You can use "drop" instead of "!!" to avoid errors AND to prevent evaluation of the entire result list, however. TMTOWTDI.) | C++ to functional | [
"",
"c++",
"haskell",
"f#",
"port",
""
] |
All I want to do is serialize and unserialize tuples of strings or ints.
I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects.
marshal is a little better in terms of space but the result is full of nasty \x00 bytes. Ideally I would like the result to be human readable.
I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?
This is getting stored in a db, not a file. Byte overhead matters because it could make the difference between requiring a TEXT column versus a varchar, and generally data compactness affects all areas of db performance. | Take a look at [json](http://docs.python.org/library/json.html), at least the generated `dumps` are readable with many other languages.
> JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. | personally i would use [yaml](http://pyyaml.org/wiki/PyYAML). it's on par with json for encoding size, but it can represent some more complex things (e.g. classes, recursive structures) when necessary.
```
In [1]: import yaml
In [2]: x = [1, 2, 3, 'pants']
In [3]: print(yaml.dump(x))
[1, 2, 3, pants]
In [4]: y = yaml.load('[1, 2, 3, pants]')
In [5]: y
Out[5]: [1, 2, 3, 'pants']
``` | Lightweight pickle for basic types in python? | [
"",
"python",
"serialization",
"pickle",
""
] |
I am currently looking to make my own collection, which would be just like a regular list, except that it would only hold 10 items. If an item was added when there were already 10 items in the list, then the first item would be removed before the new item was appended.
What I want to do is create a class that extends `System.Collections.Generic.List<T>`, and then modifies the `Add(T item)` method to include the functionality which removes the first item if necessary. | First, you can't override Add and still have polymorphism against [List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx), meaning that if you use the new keyword and your class is cast as a List, your new Add method won't be called.
Second, I suggest you look into the [Queue](http://msdn.microsoft.com/en-us/library/7977ey2c.aspx) class, as what you are trying to do is more of a queue than it is a list. The class is optimized for exactly what you want to do, but does not have any sort of a size limiter.
If you really want something to act like a List but work like a Queue with a maximum size, I suggest you implement [IList](http://msdn.microsoft.com/en-us/library/5y536ey6.aspx) and keep an instance of a Queue to store your elements.
For example:
```
public class LimitedQueue<T> : IList<T>
{
public int MaxSize {get; set;}
private Queue<T> Items = new Queue<T>();
public void Add(T item)
{
Items.Enqueue(item);
if(Items.Count == MaxSize)
{
Items.Dequeue();
}
}
// I'll let you do the rest
}
``` | You can also implement the add method via
```
public new void Add(...)
```
in your derived class to hide the existing add and introduce your functionality.
Edit: Rough Outline...
```
class MyHappyList<T> : List<T>
{
public new void Add(T item)
{
if (Count > 9)
{
Remove(this[0]);
}
base.Add(item);
}
}
```
Just a note, figured it was implied but you must always reference your custom list by the actual type and never by the base type/interface as the hiding method is only available to your type and further derived types. | How do I override List<T>'s Add method in C#? | [
"",
"c#",
"generics",
"inheritance",
"collections",
""
] |
GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contiguous memory block for element pointers. Having huge list()s can be considered bad programming practice, but even if no huge structure is created in program itself, CPython maintains some behind the scenes.
It appears that CPython is maintaining single global list of objects or something. I.e. application that has many small objects tend to allocate bigger and bigger single blocks of memory.
First idea was gc, and disabling it changes application behavior a bit but still some structures are maintained.
A simplest short application that experience the issue is:
```
a = b = []
number_of_lists = 8000000
for i in xrange(number_of_lists):
b.append([])
b = b[0]
```
Can anyone enlighten me how to prevent CPython from allocating huge internal structures when having many objects in application? | On a 32-bit system, each of the 8000000 lists you create will allocate 20 bytes for the list object itself, plus 16 bytes for a vector of list elements. So you are trying to allocate at least (20+16) \* 8000000 = 20168000000 bytes, about 20 GB. And that's in the best case, if the system malloc only allocates exactly as much memory as requested.
I calculated the size of the list object as follows:
* 2 Pointers in the `PyListObject` structure itself (see [listobject.h](http://svn.python.org/view/python/branches/release26-maint/Include/listobject.h?view=markup))
* 1 Pointer and one `Py_ssize_t` for the `PyObject_HEAD` part of the list object (see [object.h](http://svn.python.org/view/python/branches/release26-maint/Include/object.h?view=markup))
* one `Py_ssize_t` for the `PyObject_VAR_HEAD` (also in object.h)
The vector of list elements is slightly overallocated to avoid having to resize it at each append - see list\_resize in [listobject.c](http://svn.python.org/view/python/branches/release26-maint/Objects/listobject.c?view=markup). The sizes are 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... Thus, your one-element lists will allocate room for 4 elements.
Your data structure is a somewhat pathological example, paying the price of a variable-sized list object without utilizing it - all your lists have only a single element. You could avoid the 12 bytes overallocation by using tuples instead of lists, but to further reduce the memory consumption, you will have to use a different data structure that uses fewer objects. It's hard to be more specific, as I don't know what you are trying to accomplish. | I'm a bit confused as to what you're asking. In that code example, nothing should be garbage collected, as you're never actually killing off any references. You're holding a reference to the top level list in a and you're adding nested lists (held in b at each iteration) inside of that. If you remove the 'a =', *then* you've got unreferenced objects.
Edit: In response to the first part, yes, Python holds a list of objects so it can know what to cull. Is that the whole question? If not, comment/edit your question and I'll do my best to help fill in the gaps. | CPython internal structures | [
"",
"python",
"google-app-engine",
"data-structures",
"internals",
"cpython",
""
] |
I want to add small images-arrows for moving up and down on table row in Javascript (maybe jQuery) and save the reordered table (only the order) in cookie for further use. An example would be - Joomla, inside the admin area in the Articles area (but that is done with php). Thanks. | Probably can be refactored a bit more, but I leave the saving to you:
```
function swap(a, b, direction){
var html = a.wrapInner('<tr></tr>').html()
a.replaceWith(b.wrapInner('<tr></tr>').html())
b.replaceWith(html)
}
function getParent(cell){ return $(cell).parent('tr') }
$(document).ready(function(){
$('.upArrow').live('click', function(){
var parent = getParent(this)
var prev = parent.prev('tr')
if(prev.length == 1){ swap(prev, parent); }
})
$('.downArrow').live('click', function(){
var parent = getParent(this)
var next = parent.next('tr')
if(next.length == 1){ swap(next, parent) }
})
})
```
Assuming this table:
```
<table>
<tbody>
<tr><td>1</td><td class="upArrow">up</td><td class="downArrow">down</td></tr>
<tr><td>2</td><td class="upArrow">up</td><td class="downArrow">down</td></tr>
<tr><td>3</td><td class="upArrow">up</td><td class="downArrow">down</td></tr>
</tbody>
</table>
``` | For the jQuery part of things, you could look into modifying [this plugin](http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/) to use clicking on icons instead of drag-and-drop. | Reordering of table rows with arrow images for up and down? | [
"",
"javascript",
"jquery",
"web-applications",
""
] |
Today again, I have a MAJOR issue with what appears to be parameter sniffing in SQL Server 2005.
I have a query comparing some results with known good results. I added a column to the results and the known good results, so that each month, I can load a new months results in both sides and compare only the current month. The new column is first in the clustered index, so new months will add to the end.
I add a criteria to my `WHERE` clause - this is code-generated, so it's a literal constant:
`WHERE DATA_DT_ID = 20081231` -- Which is redundant because all DATA\_DT\_ID are 20081231 right now.
Performance goes to pot. From 7 seconds to compare about 1.5m rows to 2 hours and nothing completing. Running the generated SQL right in SSMS - no SPs.
I've been using SQL Server for going on 12 years now and I have never had so many problems with parameter sniffing as I have had on this production server since October (build build 9.00.3068.00). And in every case, it's not because it was run the first time with a different parameter or the table changed. This is a new table and it's only run with this parameter or no `WHERE` clause at all.
And, no, I don't have DBA access, and they haven't given me enough rights to see the execution plans.
It's to the point where I'm not sure I'm going to be able to handle this system off to SQL Server users with only a couple years experience.
**UPDATE** Turns out that although statistics claim to be up to date, running UPDATE STATISTICS WITH FULLSCAN clears up the problem.
**FINAL UPDATE** Even with recreating the SP, using WITH RECOMPILE and UPDATE STATISTICS, it turned out the query had to be rewritten in a different way to use a NOT IN instead of a LEFT JOIN with NULL check. | Not quite an answer, but I'll share my experience.
Parameter sniffing took a few years of SQL Server to come and bite me, when I went back to Developer DBA after moving away to mostly prod DBA work. I understood more about the engine, how SQL works, what was best left to the client etc and I was a better SQL coder.
For example, dynamic SQL or CURSORs or just plain bad SQL code probably won't ever suffer parameter sniffing. But better set programming or how to avoid dynamic SQL or more elegant SQL more likely will.
I noticed it for complex search code (plenty of conditionals) and complex reports where parameter defaults affected the plan. When I see how less experienced developers would write this code, then it won't suffer parameter sniffing.
In any event, I prefer parameter masking to WITH RECOMPILE. Updating stats or indexes forces a recompile anyway. But why recompile all the time? I've answered elsewhere to one of your questions with a link that mentions parameters are sniffed during compilation, so I don't have faith in it either.
Parameter masking is an overhead, yes, but it allows the optimiser to evaluate the query case by case, rather than blanket recompiling. Especially with statement level recompilation of SQL Server 2005
OPTIMISE FOR UNKNOWN in SQL Server 2008 also appears to do exactly the same thing as masking. My SQL Server MVP colleague and I spent some time investigating and came to this conclusion. | I suspect your problem is caused by out of data statistics. Since you do not have DBA access to the server, I would encourage you to ask the DBA when the last time statistics were updated. This can have a huge impact on performance. It also sounds like your tables are not indexed very well.
Basically, this does not "feel" like a parameter sniffing issue, but more of a "healthy" database issue.
This article describes how you can determine the last time statistics were updated:
[Statistics Update Time](http://weblogs.sqlteam.com/joew/archive/2007/09/06/60322.aspx) | At some point in your career with SQL Server does parameter sniffing just jump out and attack? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"parameter-sniffing",
""
] |
I have a DataTable which is populated from a CSV file then, using a DataGridView the data is edited in memory. As far as I understand the programmatic editing of the data should be done on the DataTable where the user editing is done via. the DataGridView.
However when I add columns programmatically to the DataTable, it is not reflected automatically in the DataGridView and I suspect the converse is also true.
How do you keep the two concurrent? I thought the idea of data binding was that this was automatic...
Also adding rows works fine.
---
**SOLVED:**
The `AutoGeneratedColumns` was set to `false` in the designer code despite being `true` in the properties dialog (and set explicitly in the code). The initial columns were generated programmatically and so should not have appeared however this was not picked up on since the designer code also continued to generate 'designed in' columns that were originally used for debugging.
Moral: Check the autogenerated code!
In addition to this, see [this post](https://stackoverflow.com/questions/499321/) and [this post](https://stackoverflow.com/questions/530176/) | This doesn't sound right. To test it out, I wrote a simple app, that creates a DataTable and adds some data to it.
On the `button1.Click` it binds the table to the DataGridView.
Then, I added a second button, which when clicked, adds another column to the underlying DataTable.
When I tested it, and I clicked the second button, the grid immedialtey reflected the update.
To test the reverse, I added a third button which pops up a dialog with a DataGridView that gets bound to the same DataTable. At runtime, I then added some values to the first DataGridView, and when I clicked the button to bring up the dialog, the changes were reflected.
My point is, they are supposed to stay concurrent. Mark may be right when he suggested you check if `AutoGenerateColumns` is set to `true`. You don't need to call DataBind though, that's only for a DataGridView on the web. Maybe you can post of what you're doing, because this SHOULD work.
How I tested it:
```
DataTable table = new DataTable();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
table.Columns.Add("Name");
table.Columns.Add("Age", typeof(int));
table.Rows.Add("Alex", 26);
table.Rows.Add("Jim", 36);
table.Rows.Add("Bob", 34);
table.Rows.Add("Mike", 47);
table.Rows.Add("Joe", 61);
this.dataGridView1.DataSource = table;
}
private void button2_Click(object sender, EventArgs e)
{
table.Columns.Add("Height", typeof(int));
foreach (DataRow row in table.Rows)
{
row["Height"] = 100;
}
}
private void button3_Click(object sender, EventArgs e)
{
GridViewer g = new GridViewer { DataSource = table };
g.ShowDialog();
}
public partial class GridViewer : Form //just has a DataGridView on it
{
public GridViewer()
{
InitializeComponent();
}
public object DataSource
{
get { return this.dataGridView1.DataSource; }
set { this.dataGridView1.DataSource = value; }
}
}
``` | Is AutoGenerateColumns set to true? If you are making changes after the initial Binding you'll also have to call DataBind() to rebind the changed datasource. I know this is true for an AJAX callback, I *think* it is true for a WinForms control PostBack. | Adding columns to a DataTable bound to a DataGridView does not update the view | [
"",
"c#",
"winforms",
"visual-studio-2008",
"datagridview",
"datatable",
""
] |
Suppose I have this:
```
class external {
JFrame myFrame;
...
class internal implements ActionListener {
public void actionPerformed(ActionEvent e) {
...
myFrame.setContentPane(this.createContentPane());
}
}
...
}
```
`createContentPane` returns a Container. Now, if I was doing this code outside of the `ActionListener` it would work, because I'd have access to this. But, inside it, I don't. I have access to `myFrame`, which is what is going to be updated with the contents of the method, but that isn't enough to do what I want, unless I can get a this out of it.
I also need information from other instance variables to use `createContentPane()`, so I'm not sure I can make it `static`. | You can either :
```
myFrame.setContentPane(createContentPane());
```
or
```
myFrame.setContentPane(external.this.createContentPane());
```
By the way, in Java classes first letter is usually uppercase. Your code will still compile and run if you don't name it like that, but by following coding conventions you'll be able to read others code, and much more important other will be able to read your code.
So this would be a better style:
```
class External {
JFrame myFrame;
...
class Internal implements ActionListener {
public void actionPerformed(ActionEvent e) {
...
myFrame.setContentPane(createContentPane());
//Or myFrame.setContentPane(External.this.createContentPane());
}
}
...
}
```
[Java Code conventions](http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html) | `external.this` will give you access to the instance of the enclosing class, if that's what you want... | Calling this from inside a nested Java ActionListener | [
"",
"java",
"user-interface",
"swing",
"actionlistener",
""
] |
I'm going to be writing a Windows application using the .NET framework and C#. The application will need to store relational data which will be queried, joined and processed.
Previously I've done this using SQL Server, but that is a total overkill for the application I am now making.
What's the simplest, easiest way to store relational data in my application? If I was on a Mac, I'd be using SQLite. What's the .NET equivalent? | If you are using VS 2008 and .NET 3.5, you can use [SQL Server Compact Edition](http://en.wikipedia.org/wiki/SQL_Server_Compact). It's not really a server at all, it runs in-proc with your app and provides a basic SQL database. The databases themselves are a single .sdf file and are deployed with your app. Since it's part of the framework, it also means there's no additional installation. Actually, It's not actually part of the framework, but it's easily redistributable. I'm using SQL Server CE for a personal project I'm currently working on, and it's turned out great so far. | SQL Server Express is what you want. It's free IIRC and easily scales into full-blown SQL Server when required. | Single-user database options | [
"",
"c#",
".net",
"database",
"data-structures",
""
] |
I am toying around with a pretty intensive ajax based jquery web application. It is getting to a point where I almost loose track of what events that should trigger what actions etc.
I am sort of left with a feeling that my javascript structure is wrong, on a more basic level. How do you guys structure your javascript/jquery code, the event handling etc., any advise for a newbie javascript developer. | AMDS!
It's been awhile since first answers got posted to this question and many things have changed.
First and foremost, the JS browser world seems to be moving towards AMDs (asynchronous module definition) for code organization.
The way that works is you write ALL your code as AMD modules, e.g.:
```
define('moduleName', ['dependency1', 'dependency2'], function (dependency1, dependency2) {
/*This function will get triggered only after all dependency modules loaded*/
var module = {/*whatever module object, can be any JS variable here really*/};
return module;
});
```
And then modules get loaded using AMD loaders like **curl.js** or **require.js** etc, for example:
```
curl(
[
'myApp/moduleA',
'myApp/moduleB'
],
).then(
function success (A, B) {
// load myApp here!
},
function failure (ex) {
alert('myApp didn't load. reason: ' + ex.message);
}
);
```
Advantages are:
1. You only have to include single `<script>` element on your page that loads AMD loader itself (some of them are quite tiny).
2. After that all JS files will be fetched automatically in asynchronous NON BLOCKING! fashion, thus way faster!
3. Necessary modules will get executed only after its dependencies got loaded.
4. Modular (which means code that is easier to maintain and re-use).
5. Global variables pollution can be completely curbed if used correctly.
Honestly, once concept has **clicked** in your head, you'll never go back to your old ways.
P.S: jQuery does register itself as AMD module starting from version 1.7.
More information on AMDS:
* <https://github.com/cujojs/curl>
* <http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition>
* <http://requirejs.org/>
* <http://www.bennadel.com/blog/2275-Using-RequireJS-For-Asynchronous-Script-Loading-And-JavaScript-Dependency-Management.htm>
* <https://github.com/Integralist/Blog-Posts/blob/master/2012-01-04-Beginners-guide-to-AMD-and-RequireJS.md> | For javascript code I found the following links from Christian Heilmann indispensable
* [The module pattern](http://www.wait-till-i.com/2007/07/24/show-love-to-the-module-pattern/)
* [Configuring scripts](http://www.wait-till-i.com/2008/05/23/script-configuration/)
I also really like the method described by Peter Michaux [here](http://peter.michaux.ca/articles/how-i-write-javascript-widgets)
For jQuery, I heartily recommend reading the guides on [Authoring](http://docs.jquery.com/Plugins/Authoring) and I found this tutorial on jQuery [plugin patterns](http://www.learningjquery.com/2007/10/a-plugin-development-pattern) very good | How to structure my javascript/jquery code? | [
"",
"javascript",
"jquery",
""
] |
I am mulling over the idea of writing a program to check for
"leaky abstractions" in Java. The one area that popped into mind right away is with exceptions:
```
public class X
{
// this one is fine, Readers throw IOExceptions so it is
// reasonable for the caller to handle it
public void parse(final Reader r)
throws IOException
{
}
// This one is bad. Nothing in the API indicate that JDBC
// is being used at all.
public void process()
throws SQLException
{
}
}
```
Note, I do not want an argument on relative merits of checked/unchecked exceptions. What I am looking for is other examples (doesn't have to be exception handling) that people have that could also be reasonably caught via examining the source code or class files.
I am aware of checkstyle, findbugs, and PMD, and AFAIK none of them deal with this (and I am not opposed to putting the checks into one of those tools rather than write my own).
Are there any other examples of leaky abstractions that you come to mind that could be statically check for?
EDIT:
The reason why the second one is bad is that the method throws an exception where the client has no way of knowing that JDBC (for example, it could be anything) is being used. So the "leaky abstraction" is that JDBC is being used. If the underlying mechanism changed to soemthing else (say JPA which is a different database abstraction library) then the exceptions would all need to change as well. So the underlying database library is being leaked out. | So.
How to detect if an API leaks implementation details or does not keep the same level of abstraction.
You may probably watch the [this talk](http://www.youtube.com/watch?v=aAb7hSCtvGw). It explains how good APIs look like and are designed ( you can deduct from the good practices what are the bad practices )
For instance
> *Functionality should be easy to explain.
> If its a hard name it's generally a bad design.*
From that you could discover, if the methods or return parameters give detail instructions they are not along with the level of abstraction.
For instance a high level method
```
-initProcess(): SGN_MTL
```
May be leaking implemntation details on the return value.
The hard part here is to detect when the level of abstraction changes.
For instance in your method it would be ok to throw SQLExceptions all around if the code it self is the implementation of the JDCB layer.
Other source where you can see more of these topics is this list.
<http://www.jetbrains.com/idea/documentation/inspections.jsp>
See the items under "Abstraction" ie.
* Instance variable of concrete class: Report when the type of an instance variable is declared as a concrete class rather than an interface.
The classic example is:
```
private ArrayList list;
```
when it will be better
```
private List list;
``` | Since I didn't detect a question in the original post, I will ramble.
Any such tool would have to have the user tell it what exceptions qualify as non-leaks for a given class, and anything not on such a list would be a leak.
That's just exceptions. As I understand it, leaky abstractions apply to much more. Consider this:
```
class Client
{
private Integer ID;
public Integer ID() { return this.ID; }
}
```
Does this qualify as a leak? If later I needed to represent ID as Long, then it does. You might fix such a scenario like this:
```
class Client
{
private ClientID ID;
public ClientID ID() { return this.ID; }
}
class ClientID
{
private Integer value;
public ClientID(String id) { this.value = Integer.parseInt(id); }
public String asString() { return value.toString(); }
... other methods that don't reveal value's type here ...
}
```
This would solve the leak out of Client, but now you'd run your tool on ClientID. Is it leaky?
This could get even more complicated if you have to examine methods that aren't simple getters. What if ClientID had a method that did some mathematical operation on its ID (indulge me) and returned an Integer. Is that a leak? Does this qualify as leaking that value is an Integer?
So I'm not sure if this is a code smell that a machine could easily catch. | Java Leaky Abstraction Checker | [
"",
"java",
"devtools",
"lint",
""
] |
Okay I'm trying to rotate a Java Polygon based on it's original position of angle 0. x, and y end up being converted to an int at the end of me using them, so I could understand not seeing some change, but when the difference in angles is big like 0 to 180 I think I should see **something**.
I've been at this for a little while and can't think of what it is. Here's the method. (Sorry if it messes up in the code tags, my firefox messes them up.)
```
public void rotate(double x, double y, obj o1)
{
double dist = Math.sqrt(Math.pow(x - (o1.x + (o1.w/2)), 2) + Math.pow(y - (o1.y + (o1.h/2)),2));
x += (Math.sin(Math.toRadians(o1.a)) * dist);
y -= (Math.cos(Math.toRadians(o1.a)) * dist);
}
``` | The values of `x` and `y` that are being manipulated in the `rotate` method will not be seen in the method that is calling it because [Java passes method arguments by value](http://javadude.com/articles/passbyvalue.htm).
Therefore, the `x` and `y` values that are being changed in the `rotate` method is a local copy, so once it goes out of scope (i.e. returning from the `rotate` method to its calling method), the values of `x` and `y` will disappear.
So currently, what is happening is:
```
x = 10;
y = 10;
o1 = new obj();
o1.a = 100;
rotate(x, y, obj);
System.out.println(x); // Still prints 10
System.out.println(y); // Still prints 10
```
The only way to get multiple values back from a method in Java is to pass an object, and manipulate the object that is passed in. (Actually, a copy of the reference to the object is passed in when an method call is made.)
For example, redefining `rotate` to return a `Point`:
```
public Point rotate(int x, int y, double angle)
{
// Do rotation.
return new Point(newX, newY);
}
public void callingMethod()
{
int x = 10;
int y = 10;
p = rotate(x, y, 45);
System.out.println(x); // Should print something other than 10.
System.out.println(y); // Should print something other than 10.
}
```
That said, as [Pierre suggests](https://stackoverflow.com/questions/576162/math-help-cant-rotate-something-knowing-java-would-be-a-plus/576168#576168), using the [AffineTransform](http://java.sun.com/javase/6/docs/api/java/awt/geom/AffineTransform.html) would be much easier in my opinion.
For example, creating a [`Rectangle`](http://java.sun.com/javase/6/docs/api/java/awt/Rectangle.html) object and rotating it using `AffineTransform` can be performed by the following:
```
Rectangle rect = new Rectangle(0, 0, 10, 10);
AffineTransform at = new AffineTransform();
at.rotate(Math.toRadians(45));
Shape rotatedRect = at.createTransformedShape(rect);
```
`AffineTransform` can be applied to classes which implement the [`Shape`](http://java.sun.com/javase/6/docs/api/java/awt/Shape.html) interface. A list of classes implementing `Shape` can be found in the linked Java API specifications for the `Shape` interface.
For more information on how to use `AffineTransform` and Java 2D:
* [Trail: 2D Graphics](http://java.sun.com/docs/books/tutorial/2d/index.html)
* [Lesson: Advanced Topics in Java2D](http://java.sun.com/docs/books/tutorial/2d/advanced/index.html)
+ [Transforming Shapes, Text, and Images](http://java.sun.com/docs/books/tutorial/2d/advanced/transforming.html) | FYI: Rotating shapes and points has been implemented in [java.awt.geom.AffineTransform](http://java.sun.com/j2se/1.4.2/docs/api/java/awt/geom/AffineTransform.html) | Math help - Can't rotate something (knowing Java would be a plus) | [
"",
"java",
"math",
"polygon",
"angle",
""
] |
I have a certificate generated via MakeCert. I want to use this certificate for WCF message security using PeerTrust. How can I programmatically install the certificate into the "trusted people" local machine certificate store using c# or .NET?
I have a CER file, but can also create a PFX. | I believe that this is correct:
```
using (X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert); //where cert is an X509Certificate object
}
``` | The following works good for me:
```
private static void InstallCertificate(string cerFileName)
{
X509Certificate2 certificate = new X509Certificate2(cerFileName);
X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
store.Add(certificate);
store.Close();
}
``` | How can I install a certificate into the local machine store programmatically using c#? | [
"",
"c#",
".net",
"wcf",
"certificate",
"makecert",
""
] |
I saw the following line of code:
```
class Sample<T,U> where T:class where U: struct, T
```
In the case above, parameter `U` is *value type*, and it derives from *reference type* `T`.
How can that line be legal?
Also, if a value type inherits from a reference type, where is memory allocated: heap or stack? | Contrary to another answer, there are types beyond T=System.Object where this compiles:
```
class Samplewhere T:class where U:struct, T
```
The "T : class" constraint doesn't actually mean that T has to be a class. It means T has to be a reference type. That includes interfaces, and structs can implement interfaces. So, for example, T=IConvertible, U=System.Int32 works perfectly well.
I can't imagine this is a particularly common or useful constraint, but it's not *quite* as counterintuitive as it seems at first sight.
As to the more general point: as Obiwan Kenobi says, it all depends on your point of view. The CLI spec has quite a complicated explanation of this, where "derives from" and "inherits from" don't mean quite the same thing, IIRC. But no, you can't specify the base type of a value type - it's always either `System.ValueType` or `System.Enum` (which derives from `System.ValueType`) and that's picked on the basis of whether you're declaring a `struct` or an `enum`. It's somewhat confusing that both of these are, themselves, reference types... | All structs derive from the ValueType type implicitly. You cannot specify an explicit base type.
Refer to [this MSDN tutorial on structs](http://msdn.microsoft.com/en-us/library/aa288471(VS.71).aspx) as posted by `codemelt`.
* When you instantiate a struct e.g. as a local variable, they are allocated on the stack (better performance)
* Classes may contain structs as members - in which case they are allocated on the heap. | How can a struct inherit from a class in type parameters constrains? | [
"",
"c#",
".net",
"memory-management",
"type-parameter",
""
] |
This question pertains to Ruby on Rails and PHP. When looking for a VPS host for a web application (haven't decided which of the 2 languages to write it in yet), what should I take into consideration more? Memory or CPU? I know that you need a fair balance of both, but which wall will I run into first?
I'm sure it depends on the type of work the application is doing, and in my case its the normal CRUD. My guess would be memory, but I'd just like to make sure. | I think the DBMS and the nature/number of the queries you will be making will be the most important consideration here, rather than anything pertaining to the language used. (Assuming the database is going on the same server)
Unless you've got a very small dataset, memory is likely to be limiting before CPU.
Also, you've not really specified what the combinations on offer are - so its hard to give an answer. | I ran into memory problems long before CPU issues, but I was running the SQL server on the same VPS as the web front-end. There were some serious memory issues until I paid for an upgrade. | Bottleneck of web applications? | [
"",
"php",
"ruby-on-rails",
""
] |
I have two threads. The producer is producing pieces of data (String objects), where the consumer processes these strings. The catch is that my application only needs the most recent data object to be processed. In other words, if the producer managed to produce two strings "s1" and then "s2" then I want the consumer to process only "s2". "s1" can be safely discarded.
Of course there's no problem implementing a class that realizes this behavior, but I want to use a standard mechanism from java.util.concurrent (if such a mechanism exists). Note that SynchronousQueue is not a good solution: the consumer will block when enqueueing "s1" and will not get the chance to produce "s2".
(In short, I am looking for a single-element collection with a blocking remove operation and a non-blocking set operation)
Any ideas? | I think your best answer is probably to use ArrayBlockingQueue, where the producer (you only have one producer, right?) removes any existing element before adding the new element.
Sure, there are race conditions in this implementation: the consumer could start processing an element just before the producer removes it. But those race conditions will always exist, no matter what data structure you use. | What about the [Exchanger](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Exchanger.html) class? This is the standard way of exchanging objects between threads. Specialize it with your class, may be a list of strings. Make the consumer only use the first/last one. | Passing a work item between threads (Java) | [
"",
"java",
"multithreading",
""
] |
I'm trying to install MySQLdb for python on Cygwin. Unfortunately, when I run `python setup.py build`, I get the following error:
```
$ python setup.py build
/bin/sh: /usr/local/bin/mysql_config: No such file or directory
Traceback (most recent call last):
File "setup.py", line 16, in <module>
metadata, options = get_config()
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "/home/Ben/python/MySQL-python-1.2.2/setup_posix.py", line 24, in mysql_config
raise EnvironmentError, "%s not found" % mysql_config.path
EnvironmentError: /usr/local/bin/mysql_config not found
```
Clearly I don't have `mysql_config` installed, which I guess is the problem. This is mentioned in the README for MySQLdb, but it doesn't explain how to either get around it or how to install mysql\_config.
So maybe this is as easy as: How can I install `mysql_config` for Cygwin?
Or maybe it's harder than that.
FYI: I have python 2.5.2 and MySQL 5.1.30, running under Cygwin. | You'll need mysql-devel, if it's available for cygwin, or you'll need to build mysql from source.
Your best bet is probably to just compile the MySQL client yourself in order to get the necessary headers to compile MySQLdb. See [this note](http://cpansearch.perl.org/src/CAPTTOFU/DBD-mysql-3.0000/INSTALL.html#windows_cygwin) on the similar Perl DB driver. | How I did it:
First I installed [`apt-cyg`](https://github.com/transcode-open/apt-cyg). With that:
```
# apt-cyg install gcc # older name
apt-cyg install gcc-core # as of 2015
apt-cyg install python-setuptools
easy_install pip
pip install -U mysql-python
``` | Has anyone installed MySQLdb for Python on Cygwin? | [
"",
"python",
"mysql",
"cygwin",
""
] |
I have the following string:
```
"Look on http://www.google.com".
```
I need to convert it to:
> "Look on <http://www.google.com>"
The original string can have more than 1 URL string.
How do I do this in php?
Thanks | You can use the following:
```
$string = "Look on http://www.google.com";
$string = preg_replace(
"~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~",
"<a href=\"\\0\">\\0</a>",
$string);
```
**PHP versions < 5.3 (ereg\_replace) otherwise (preg\_replace)** | `lib_autolink` does a pretty good job, avoiding pitfalls like extra punctuation after the link and links inside HTML tags:
<https://github.com/iamcal/lib_autolink> | How do I linkify urls in a string with php? | [
"",
"php",
"url",
"string",
""
] |
I have some code that has a dynamic-class system in C++ that has a member called GetClassName(), a rather harmless name one would imagine. However when included in a large project with Windows headers all hell broke loose. Apparently Windows uses a #define GetClassName (GetClassNameA or GetClassNameW) which screws up everything, and my virtual call tree became all messed up making me lose a day in stupid compiler debugging in the dark, trying to figure out what was wrong.
So besides the point that I'm cursing Microsoft for using such a horribly easy to clash name for a #define (I mean someone should honestly be shot for this!) I'm asking for 3 purposes.
1. What's another good name for
GetClassName() ?
2. Is there anyway to
fix this, so in the future, other
developers of my code base won't
suffer similar fate
3. And for
posterity when someone else
encounters this similarly
inexplicable error | I would rename the method.
Of course one can say
```
#include <windows.h>
#undef GetClassName
```
but it is not clean, users of one's code should remember to write ::GetClassNameW when they call win32 function.
One can provide GetClassNameA and GetClassNameW methods in his class, but it's plain ugly.
I see two approaches : either lengthen or shorten the name:)
1) add a prefix for all functions in the subsystem, f.e TI\_ (for type info):
```
TI_GetClassName()
TI_GetBaseClass()
TI_IsDerivedFromClass()
etc
```
2) or put them into some IClass interface
```
interface IClass {
GetName();
GetBase();
IsDerivedFrom();
etc
```
and return that interface from single method,
so that GetClassName() becomes
```
GetClass()->GetName()
``` | 1. `ClassGetName()`
2. `#undef GetClassName`
3. WinAPI is a C API. No namespaces. Some other platforms try to mitigate this by prefixing all symbol names, but eventually that falls apart as well. Best bet: if you're writing code that doesn't depend on the Windows Platform SDK headers, *then don't `#include` them*. | Windows API and GetClassName()? Another name? | [
"",
"c++",
"windows",
"api-design",
""
] |
When I reverse iterate over an ArrayList I am getting a IndexOutOfBoundsException. I tried doing forward iteration and there is no problem. I expect and know that there are five elements in the list. The code is below:
```
Collection rtns = absRtnMap.values();
List list = new ArrayList(rtns);
Collections.sort(list);
for(int j=list.size();j>0;j=j-1){
System.out.println(list.get(j));
}
```
---
Forward iteration - which is working fine, but not useful for me:
```
for(int j=0;j<list.size();j++){
System.out.println(list.isEmpty());
System.out.println(list.get(j));
} // this worked fine
```
---
The error:
```
Exception in thread "Timer-0" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at model.Return.getReturnMap(Return.java:61)
at controller.Poller$1.run(Poller.java:29)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
```
Also if anyone knows of a better idiom for reverse iteration I would be happy to try that out. | Start the iteration at `list.size() - 1` because array (or `ArrayList`) elements are numbered from 0 up through 1 less than the size of the list. This is a fairly standard idiom:
```
for (int j = list.size() - 1; j >= 0; j--) {
// whatever
}
```
Note that your forward iteration works because it stops *before* reaching `list.size()`. | Avoid indexes altogether? How about:
```
for (ListIterator iterator = list.listIterator(list.size()); iterator.hasPrevious();) {
final Object listElement = iterator.previous();
}
``` | Reverse iteration through ArrayList gives IndexOutOfBoundsException | [
"",
"java",
"arraylist",
"iteration",
"reverse",
""
] |
I was recently working on a piece of C++ code for a side project (the [`cpp-markdown` library](https://sourceforge.net/projects/cpp-markdown/), for the curious), and ran into a coding question that I'd like some opinions on.
`cpp-markdown` has a base class called `Token`, which has a number of subclasses. Two of the main subclasses are `Container` (which holds collections of other `Token`s) and `TextHolder` (used as a base class for `Token`s that contain text, of course).
Most of the processing is handled via virtual functions, but some of it was better handled in a single function. For that, I ended up using `dynamic_cast` to down-cast the pointer from a `Token*` to one of its subclasses, so I could call functions that are specific to the subclass and its child classes. There's no chance the casting would fail, because the code is able to tell when such a thing is needed via virtual functions (such as `isUnmatchedOpenMarker`).
There are two other ways I could see to handle this:
1. Create *all* of the functions that I want to call as virtual functions of `Token`, and just leave them with an empty body for every subclass except the one(s) that need to handle them, or...
2. Create a virtual function in `Token` that would return the properly-typed pointer to `this` when it's called on certain subtypes, and a null pointer if called on anything else. Basically an extension of the virtual function system I'm already using there.
The second method seems better than both the existing one and the first one, to me. But I'd like to know other experienced C++ developers' views on it. Or whether I'm worrying too much about trivialities. :-) | #1 pollutes the class namespace and vtable for objects that don't need it. Ok when you have a handful of methods that will generally be implemented, but plain ugly when only needed for a single derived class.
#2 is just `dynamic_cast<>` in a polka-dot dress and lipstick. Doesn't make client code any simpler, and tangles up the entire hierarchy, requiring the base and each derived class to be semi-aware of *every other* derived class.
Just use `dynamic_cast<>`. That's what it's there for. | If you want to get clever, you could also build a [double dispatch](http://en.wikipedia.org/wiki/Double_dispatch) pattern, which is two-thirds of the [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern).
* Create a base `TokenVisitor` class containing empty virtual `visit(SpecificToken*)` methods.
* Add a single virtual `accept(TokenVisitor*)` method to Token that calls the properly-typed method on the passed TokenVisitor.
* Derive from TokenVisitor for the various things you will need to do in varying ways over all tokens.
For the full visitor pattern, useful for tree structures, have the default `accept` methods iterate over children calling `token->accept(this);` on each. | Avoiding dynamic_cast/RTTI | [
"",
"c++",
"casting",
""
] |
I'm trying to get a concensus of what people do with regard to unit tests and sub (or external) projects.
I'll, hopefully, clarify with an example. I have a project P1 that relies on another project P2. P2 has its own unit tests and release cycle. P1 has its own unit tests as well. The question is should the unit tests for P2 be included/ran as part of P1's unit testing or should P2 unit tests be ran only when P2 is being release?
Clear as mud.
Keith. | There's no need to run P2's tests when P1's are run. If P2's code hasn't changed, running the tests again during would provide no benefit.
If P2 breaks because of P1's tests, then more unit tests for P2 are required to ensure you have sufficient coverage (or perhaps you have an interface problem, which is a different issue entirely). | Theoretically, if the unit tests for P2 are good, then you shouldn't need to run them.
However, if you do run them, there is a (maybe slight) chance that you will make them fail, through a difference in environment. If the cost of running them is low, why not? If however, the setup for the tests is complex, you need an extra database or something, then it's maybe not worth the pain.
What you may need are integration tests for the code that uses P2 that tests for the behaviour of specific functionality that you use. If you're using P2, and P2 changes in some subtle way, then how do you know. If P2 has different release cycles, then this is especially important: you don't know what they've broken :-) | Unit Tests for external projects | [
"",
"c#",
"unit-testing",
"nunit",
""
] |
Is there a library that I can use with Java to listen for user logout and possibly other Windows events? (Even better if it supports multiple platforms!)
I remember reading about a library of this sort a number of years ago, but can't seem to find it now. I've seen other threads to do essentially the same thing using Python with win32ts.
Also better if it's free and/or open source.
Thanks.
**Note**: The candidate solution of using `Runtime.getRuntime().addShutdownHook(Thread)` does not work correctly with `javaw`. I am still looking for a solution that will work with javaw. See java bug ids [4486580](https://bugs.java.com/bugdatabase/view_bug?bug_id=4486580) and [4302814](https://bugs.java.com/bugdatabase/view_bug?bug_id=4302814). Thanks --cam | I think you want to look at [Runtime.addShutdownHook()](http://java.sun.com/javase/6/docs/api/index.html?java/lang/Runtime.html). This gives you the last-ditch opportunity to do things before the JVM shuts down. This lets you detect an actual logout where all of the applications are shutdown, but not they just temporarily switch users, leaving their state ready to come back to. However, as a warning, whatever you plan on doing during the shutdown process needs to be brief since the OS may SIGKILL (or the equivalent) on you at any time, which halts the JVM immediately.
If this isn't what you need, you're probably going to need to use JNI to register a native listener. As for the other windows events, the AWT library provides a number of classes for implementing the listeners that most normal apps would be interested in. In this case, you might be interested in a [FocusEvent](http://java.sun.com/javase/6/docs/api/java/awt/event/FocusEvent.html). | My best guess would be to use a [ShutdownHook](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)). You can register a thread which is invoked as soon as the JVM is beeing shut down.
**Edit:**
If you want to realize this under windows, you could create an invisible window and react on the [WM\_QUERYENDSESSION](http://msdn.microsoft.com/en-us/library/aa376890(VS.85).aspx) message which is sent by the OS upon user log off or system shutdown. | Detect windows logout event in Java application | [
"",
"java",
"windows",
"events",
"shutdown-hook",
""
] |
This page does it the way I want it to: <http://www.web-source.net/javascript_redirect_box.htm>
But I want to find a better way using jQuery, can anyone point me to a good script that uses jQuery to accomplish this? | You don't need a pre-packaged script for this, just a couple lines of code.
```
// get your select element and listen for a change event on it
$('#selectEl').change(function() {
// set the window's location property to the value of the option the user has selected
window.location = $(this).val();
});
``` | Others have given good answers on how to do this, but...
Just a warning, IE handles select list onChange very differently from other browsers when someone is navigating via a keyboard. It counts every key up/key down press as an onChange event, meaning that you can't navigate a redirect select list via keyboard, killing accessibility for users who can't use the mouse. (Other browsers wait for an "enter" event, or a tab out of the select list, before firing onChange.) I've spent a long, long time trying to hack a workaround for this, and never fully solved the problem.
I don't know if jQuery accounts for this; hopefully it does, for your site's accessibility's sake.
It may be worth making the select list choose where to go, then have a button next to it actually activate the redirect. (Unless you don't care about IE users' accessibility.) | Redirect automatically when selecting an item from a select drop-down list | [
"",
"javascript",
"jquery",
"html",
""
] |
I am in charge of a database.
It has around 126 sprocs, some 20 views, some UDFs. There are some tables that saves fixed configuration data for our various applications.
I have been using a one-big text file that contained IF EXIST ...DELETE GO CREATE PROCEDURE... for all the sprocs, udfs, views and all the insert/updates for the configuration scripts.
In the course of time, new sprocs were added, or existing sprocs were changed.
The biggest mistake (as far as I am aware of) I have made in creating this BIG single text file is to use the code for new/changed sprocs at the beginning of the text file. I, however, I forgot to exclude the previous code for the new/changed sprocs. Lets illustrate this:
Say my BIG script (version 1) contains script to create sprocs
```
sp 1
sp 2
sp 3
view 1
view 2
```
The databse's version table gets updated with the version 1.
Now there is some change in sp 2. So the version 2 of the BIG script is now:
```
sp2 --> (newly added)
sp1
sp2
sp3
view 1
view 2
```
So, obviously running the BIG script version 2 will not going to update my sp 2.
I am kind of late of realise this with 100+ numbers of sprocs.
Remedial Action:
1. I have created a folder structure. One subfolder for each sproc/view.
2. I have gone through the latest version of the BIG script from the bgeinning and placed the code for all scripts into respective folders. Some scripts are repeated more than once in the BIG script. If there are more than on block of code for creating a specific sproc I am putting the earlier version into another subfolder called "old" within the folder for that sproc. Luckily I have always documented all the changes I made to all sprocs/view etc - I write down the date, a version number and description of changes made as comment in the sproc's code. This has helped me a lot to figure out the the latest version of code for a sprocs when there are more than one block of code for the sproc.
3. I have created a DOS batch process to concatenate all the individual scripts to create my BIG script. I have tried using .net streamreader/writer which messes up with the encoding and the "£" sign. So I am sticking to DOS batch for the time being.
Is there any way I can improve the whole process?
At the moment I am after some way to document the versioning of the BIG script along with its individual sproc versions. For example, I like to have some way to document
```
Big Script (version 1) contains
sp 1 version 1
sp 2 version 1
sp 3 version 3
view 1 version 1
view version 1
Big script (version 2) has
sp 1 version 1
sp 2 version 2
sp 3 version 3
view 1 version 1
view 2 version 1
```
Any feedback is welcomed. | Have you looked at [Visual Studio Team System Database Edition](http://www.microsoft.com/visualstudio/en-us/products/teamsystem/default.mspx#development-edition) (now folded into Developer Edition)?
One of things it will do is allow to maintain the SQL to build the whole database, and then apply only the changes to update the target to the new state. I believe that it will also, given a reference database, create a script to bring a database matching the reference schema up to the current model (e.g. to deploy to production without developers having access to production). | The way we do it is to have separate files for tables, stored procedures, views etc and store them in their own directories as well. For execution we just have a script which executes all the files. Its definitely a lot easier to read than having one huge file.
To update each table for example, we use this template:
```
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MyTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
CREATE TABLE [dbo].[MyTable](
[ID] [int] NOT NULL ,
[Name] [varchar](255) NULL
) ON [PRIMARY]
end else begin
-- MyTable.Name
IF (SELECT COL_LENGTH('MyTable','Name')) IS NULL BEGIN
ALTER TABLE MyTable ADD [Name] [varchar](255) NULL
PRINT 'MyTable.Name CREATED.'
END
--etc
end
``` | How to Manage SQL Source Code? | [
"",
"sql",
"version-control",
"stored-procedures",
"project-management",
""
] |
My friend has allowed me to have access to his server, he has been coding PHP a lot longer than me and still uses php version 4.3.9 and doesn't want to upgrade this current version. Is there anyway for me to install php version 5.2 and use that while he still runs 4.3.9? I require some functions which are only available in 5.2. The server runs on redhat. | Yes you can, one php is run as CGI and other as MODULE.
OR
You could run 2 apache's.
I have apache 1.3.x with php4 on port 82 and apache 2.2.x with php5 on port 80.
In both cases php is run as module.
In both cases I do not recommend this for production server, only for development. | Yes, you can compile with concurrent dso to support this. I really do not recommend mixing 4 and 5, expect those results to be undefined. Its not just PHP that you worry about, its Apache2 and php4.
But, concurrent dso will allow both versions to co-exist peacefully, as far as the loader is concerned. | Can I have different versions of php installed and running on my server? | [
"",
"php",
"linux",
""
] |
One of the products we develop is a phone app for nokia phones done in C++ and Symbian, we started getting "random" crashes a while a ago with a USER 44 panic.
I am pretty new to the symbian environment so I am looking for tools and recommendations to help finding the root of this bug.
Is there a equivalent of a "stack trace" that I can get?
Is there generic panic catching code that could give me some insight into it? | From <http://www.symbian.com/developer/techlib/v9.1docs/doc_source/reference/N10352/UserPanics.html>:
```
This panic is raised by the Free() and FreeZ() member functions of an RHeap.
It is caused when the cell being freed overlaps the next cell on the free
list (i.e. the first cell on the free list with an address higher than the
one being freed).
```
It means, your calling delete/delete[] (which in turn will call Free()/FreeZ()) with an invalid pointer. When debuging under Carbide the debuger should break on the line that causes the panic and you should be able to see the invalid deletion. | As [Kasprzol pointed out](https://stackoverflow.com/questions/566587/how-to-find-the-cause-for-a-user-44-panic/567479#567479), stepping through the debugger should let you narrow down to the set of lines or routine causing the panic. You may also want to ensure that you are not trying to delete a heap object whose ownership was transferred to another heap object (probably through a method call which does not clearly document this fact) which has already deleted that object before you are deleting it explicitly. I have been bitten by the latter before. | How to find the cause for a USER 44 PANIC? | [
"",
"c++",
"debugging",
"symbian",
"panic",
""
] |
if I have:
```
function init(t,y,u)
{
alert(t + " " + y + " " + u);
}
// String.prototype.add = init(5, 6, 7); // 1)
// window.onload = init(5,6,7); // 2)
```
in the 1) `init` will be executed and then it pointer assegned to `String.prototype.add`
but in the 2) the function is only executed one time... but why not two times also
when the `onload` event is raised?
Thanks | This is what happens with your code:
* Defining a function called init with three parameters that will be alerted when the function is called.
* Calling the function init with parameters 5,6,7 (an alert will popup) and assign the result (undefined) to String.prototype.add
* Calling the function init with parameters 5,6,7 (an alert will popup) and assign the result (undefined) to window.onload
If the code above was executed before the window.onload event was fired, nothing will happen when it is fired, because it is set to undefined. | > in the 1) init will be executed and then it pointer assegned to String.prototype.add
No it won't. The function will simply be executed and its return value (`undefined`) will be assigned to `String.prototype.add`. No function pointer will be assigned. To do this, you need to *return* a function!
```
function init(t,y,u) {
alert(t + " " + y + " " + u);
return function () { alert('function call!'); };
}
``` | javascript pointer function | [
"",
"javascript",
"function",
"pointers",
""
] |
I'm currently trying to use a certain SDK that has me loading functions off a DLL that a vendor provides.. I have to pass arguments to these functions and the DLL does all the work..
Now, the DLL is supposed to be communicating with another device, while I just wait for the results. However, I don't have this device, so how do I set up a mock interface to emulate the device?
To be clear, here's an example:
```
myfuncpointer.Open(someparam,anotherparam,...);
```
Now, because I don't have the device, the DLL can't actually perform the above function; it fails. How do I set up testing so that the DLL talks to a class that I designed rather than the device? Is there any way to redirect the DLL's call?
How do I make a DummyDevice class to do this?
Thanks..
P.S. If anything is not clear, please don't be too quick to downvote.. Comment as to what I need to explain and I'll try to clear it up.. Thanks.
---
EDIT: What I DO have, however, is a spec sheet with all of the data structures used and the expected/legal values that it has to contain. So for example, if I call a function:
```
myfuncpointer.getinfo(param,otherparam);
```
where one of the params is a data structure that the DLL fills up with info (say, if an option is enabled) after querying the device.. I can do this
```
param.option = true;
```
after it has finished the getinfo call.
Is this a good way to test the code? It seems very very dangerous to trick this DLL into thinking all the wrong things and seems to be really really hard to scale even just a bit.. | Is emulated device access a stopgap solution for until you get hardware? If so, I recommend finding some other way to be productive: work on something else, write unit tests, etc.
Is emulated device access a permanent requirement? If so, here are a few approaches you could take:
1. **If the other vendor's SDK has a "simulation" or "emulation" mode, use it.** You might be surprised. You're probably not the only client that needs to be able to test/run their application without the other vendor's hardware installed.
2. **Take the other vendor's code out of the picture.** Emulate only the functionality that your application needs, and base it on your program's requirements. Everything is under your control.
a. **Add an indirection layer.** Use polymorphism to switch between two implementations: one that calls into the other vendor's DLL, and one that emulates its behavior. Having your code call into an abstract base class instead of directly calling into the other vendor's DLL also will make it easier to write unit tests for your code.
b. **Write a mock DLL (as Adam Rosenfield suggested).** You need to match the function names and calling conventions exactly. As you upgrade to new versions of the other vendor's DLL, you will need to extend the mock DLL to support any new entrypoints that your application uses.
If you need to choose which DLL to use at runtime, this may require converting your code to load the DLL dynamically (but it sounds like you might already be doing this, given that you said something about function pointers). You may be able to decide at install time whether to install the other vendor's DLL or the mock DLL. And if this is purely for testing purposes, you may be able to choose which DLL to use at compile time, and just build two versions of your application.
3. **Write a mock device driver (as others have suggested).**
If you have the spec for the interface between the other vendor's user mode DLL and their device driver, this may be doable. It will probably take longer than any of the other approaches, even if you're an experienced device driver developer, and especially if you don't have the source to the other vendor's DLL. UMDF (User Mode Driver Framework) might make this slightly easier or less time consuming.
If the spec you mentioned does not describe the user/kernel interface, you will need to reverse engineer that interface. This is probably not going to be an effective use of your time compared with the other options, particularly if the driver interface is complex (e.g. it passes a lot of complex data structures to `DeviceIoControl()`).
In both cases, you will need to revisit this every time you upgrade to a new version of the other vendor's SDK. The same exported DLL functions may require using new `DeviceIoControl()` codes and structures. | It depends on how the DLL accesses the device. If it does so by calling functions in another DLL, you can supply a mock DLL where you've replaced the appropriate functions. However, if the DLL is doing something low-level, such as calling directly into the kernel, you're going to have a much tougher time. In that case, you'll probably have to write a new device driver or kernel extension or something. | Setting up a mock interface in C++ | [
"",
"c++",
"windows",
"oop",
"testing",
""
] |
Edit: I have looked at the answers code: **NONE** of them do what I want (I've checked). It would seem that there is no way to do what I want in native c#. I guess that's not a disaster just a shame given that .NET does support it (see accepted answer).
Thanks all.
---
I have c# code (part of a test framework that will never be run except under a debugger) like this who's point it to avoid actually catching the exception as that makes debugging the code in the unwound part of the stack a royal pain.
```
Bool bad = true;
try
{
MightThrow();
bad = false;
}
finally
{
if(bad) DoSomeLoggingOnFailure();
//// Does not catch!!!!
//// exception continues to unwind stack.
//// Note that re throwing the exception is NOT
//// the same as not catching it in the first place
}
```
is their a better way to do this?
> A solution would have to behave exactly like that under the debugger with regards to un-caught exceptions. It would have to result in the only one first chance exception and the debugger breaking at the point that the exception was *originally* thrown, not in a catch block.
>
> Specifically I need the debugger on un-caught exceptions to stop a in side MightThrow.
The following doesn't work because it fails to have the debugger break in the correct place
```
try { ... } catch { throw; }
```
And this doesn't work because it loses stack info (and also breaks in the wrong place).
```
try { ... } catch(Exception e) { throw e; }
```
I known that in [D](http://www.digitalmars.com/d/1.0/) I could use a [`scope(failure)`](http://www.digitalmars.com/d/1.0/statement.html#ScopeGuardStatement) block | So, in .NET what you're asking for is theoretically possible, but it's not going to be easy.
CIL actually defines *five* types of exception handling block! The `try`, `catch` and `finally` ones you're used to in C#, and two others:
* `filter` - similar to a `catch` block but can run arbitrary code to determine whether it wants to handle the error, rather than just matching on type. This block has access to the exception object, and has the same effect on the exception stack trace as a `catch` block.
* `fault` - similar to a `finally` block, however it is only run when an exception occurs. This block does not have access to the exception object, and has no effect on the exception stack trace (just like a `finally` block).
`filter` is available in some .NET languages (e.g. VB.NET, C++/CLI) but is not available in C#, unfortunately. However I don't know of any language, other than CIL, that allows the `fault` block to be expressed.
Because it *can* be done in IL means not all is lost, though. In theory you could use Reflection.Emit to dynamically emit a function that has a `fault` block and then pass the code you want to run in as lambda expressions (i.e. one for the try part, one for the fault part, and so on), however (a) this isn't easy, and (b) I'm unconvinced that this will actually give you a more useful stack trace than you're currently getting.
Sorry the answer isn't a "here's how to do it" type thing, but at least now you know! What you're doing now is probably the best approach IMHO.
---
Note to those saying that the approach used in the question is 'bad practice', it really isn't. When you implement a `catch` block you're saying "I need to do something with the exception object when an exception occurs" and when you implement a `finally` you're saying "I don't need the exception object, but I need to do something before the end of the function".
If what you're actually trying to say is "I don't need the exception object, but I need to do something when an exception occurs" then you're half way between the two, i.e. you want a `fault` block. As this isn't available in C#, you don't have an ideal option, so you may as well choose the option that is less likely to cause bugs by forgetting to re-throw, and which doesn't corrupt the stack trace. | How about this:
```
try
{
MightThrow();
}
catch
{
DoSomethingOnFailure();
throw; // added based on new information in the original question
}
```
Really, that's all you did. Finally is for things that must run regardless of whether an exception occurred.
[**Edit:** Clarification]
Based on the comments you've been mentioning, you want the exception to continue being thrown without modifying its original stack trace. In that case, you want to use the unadorned throw that I've added. This will allow the exception to continue up the stack and still allow you to handle part of the exception. Typical cases might be to close network connections or files.
[**Second edit:** Regarding your clarification]
> Specifically I need the debugger on
> un-caught exceptions to stop at the
> original point of the throw (in
> MightThrow) not in the catch block.
I would argue against ever breaking a best-practice (and yes, this is a best-practice for partially handling exceptions) to add some minor value to your debugging. You can easily inspect the exception to determine the location of the exception throw.
[**Final edit:** You have your answer]
[kronoz](https://stackoverflow.com/questions/533968/c-finally-block-that-only-runs-on-exceptions/534086#534086) has thoughtfully provided you with the answer you sought. Don't break best practices -- use Visual Studio properly! You can set Visual Studio to break exactly when an exception is thrown. Here's [official info on the subject](http://msdn.microsoft.com/en-us/library/d14azbfh.aspx).
I was actually unaware of the feature, so go give him the accepted answer. But please, don't go trying to handle exceptions in some funky way just to give yourself a hand debugging. All you do is open yourself up to more bugs. | c# "finally" block that only runs on exceptions | [
"",
"c#",
"exception",
"finally",
""
] |
> **Possible Duplicate:**
> [IIS7 Failed to grant minimum permission requests](https://stackoverflow.com/questions/1846816/iis7-failed-to-grant-minimum-permission-requests)
I'm developing an ASP.NET WebSite and I get an exception:
`Required permissions cannot be acquired.`
Is there a way to find out which permission(s) are missing?
I know the assembly that causes the exception, but I don't know which permission it requires. | permcalc -sandbox
stores the information to an xml file that can be used in the web.config file. | [IIS7 Failed to grant minimum permission requests](https://stackoverflow.com/questions/1846816/iis7-failed-to-grant-minimum-permission-requests) | Required permissions cannot be acquired | [
"",
"c#",
"asp.net",
".net-3.5",
"permissions",
""
] |
I have a bunch of keys that each have an unlikeliness variable. I want to randomly choose one of these keys, yet I want it to be more unlikely for unlikely (key, values) to be chosen than a less unlikely (a more likely) object. I am wondering if you would have any suggestions, preferably an existing python module that I could use, else I will need to make it myself.
I have checked out the random module; it does not seem to provide this.
I have to make such choices many millions of times for 1000 different sets of objects each containing 2,455 objects. Each set will exchange objects among each other so the random chooser needs to be dynamic. With 1000 sets of 2,433 objects, that is 2,433 million objects; low memory consumption is crucial. And since these choices are not the bulk of the algorithm, I need this process to be quite fast; CPU-time is limited.
Thx
Update:
Ok, I tried to consider your suggestions wisely, but time is so limited...
I looked at the binary search tree approach and it seems too risky (complex and complicated). The other suggestions all resemble the ActiveState recipe. I took it and modified it a little in the hope of making more efficient:
```
def windex(dict, sum, max):
'''an attempt to make a random.choose() function that makes
weighted choices accepts a dictionary with the item_key and
certainty_value as a pair like:
>>> x = [('one', 20), ('two', 2), ('three', 50)], the
maximum certainty value (max) and the sum of all certainties.'''
n = random.uniform(0, 1)
sum = max*len(list)-sum
for key, certainty in dict.iteritems():
weight = float(max-certainty)/sum
if n < weight:
break
n = n - weight
return key
```
I am hoping to get an efficiency gain from dynamically maintaining the sum of certainties and the maximum certainty. Any further suggestions are welcome. You guys saves me so much time and effort, while increasing my effectiveness, it is crazy. Thx! Thx! Thx!
Update2:
I decided to make it more efficient by letting it choose more choices at once. This will result in an acceptable loss in precision in my algo for it is dynamic in nature. Anyway, here is what I have now:
```
def weightedChoices(dict, sum, max, choices=10):
'''an attempt to make a random.choose() function that makes
weighted choices accepts a dictionary with the item_key and
certainty_value as a pair like:
>>> x = [('one', 20), ('two', 2), ('three', 50)], the
maximum certainty value (max) and the sum of all certainties.'''
list = [random.uniform(0, 1) for i in range(choices)]
(n, list) = relavate(list.sort())
keys = []
sum = max*len(list)-sum
for key, certainty in dict.iteritems():
weight = float(max-certainty)/sum
if n < weight:
keys.append(key)
if list: (n, list) = relavate(list)
else: break
n = n - weight
return keys
def relavate(list):
min = list[0]
new = [l - min for l in list[1:]]
return (min, new)
```
I haven't tried it out yet. If you have any comments/suggestions, please do not hesitate. Thx!
Update3:
I have been working all day on a task-tailored version of Rex Logan's answer. Instead of a 2 arrays of objects and weights, it is actually a special dictionary class; which makes things quite complex since Rex's code generates a random index... I also coded a test case that kind of resembles what will happen in my algo (but I can't really know until I try!). The basic principle is: the more a key is randomly generated often, the more unlikely it will be generated again:
```
import random, time
import psyco
psyco.full()
class ProbDict():
"""
Modified version of Rex Logans RandomObject class. The more a key is randomly
chosen, the more unlikely it will further be randomly chosen.
"""
def __init__(self,keys_weights_values={}):
self._kw=keys_weights_values
self._keys=self._kw.keys()
self._len=len(self._keys)
self._findSeniors()
self._effort = 0.15
self._fails = 0
def __iter__(self):
return self.next()
def __getitem__(self, key):
return self._kw[key]
def __setitem__(self, key, value):
self.append(key, value)
def __len__(self):
return self._len
def next(self):
key=self._key()
while key:
yield key
key = self._key()
def __contains__(self, key):
return key in self._kw
def items(self):
return self._kw.items()
def pop(self, key):
try:
(w, value) = self._kw.pop(key)
self._len -=1
if w == self._seniorW:
self._seniors -= 1
if not self._seniors:
#costly but unlikely:
self._findSeniors()
return [w, value]
except KeyError:
return None
def popitem(self):
return self.pop(self._key())
def values(self):
values = []
for key in self._keys:
try:
values.append(self._kw[key][1])
except KeyError:
pass
return values
def weights(self):
weights = []
for key in self._keys:
try:
weights.append(self._kw[key][0])
except KeyError:
pass
return weights
def keys(self, imperfect=False):
if imperfect: return self._keys
return self._kw.keys()
def append(self, key, value=None):
if key not in self._kw:
self._len +=1
self._kw[key] = [0, value]
self._keys.append(key)
else:
self._kw[key][1]=value
def _key(self):
for i in range(int(self._effort*self._len)):
ri=random.randint(0,self._len-1) #choose a random object
rx=random.uniform(0,self._seniorW)
rkey = self._keys[ri]
try:
w = self._kw[rkey][0]
if rx >= w: # test to see if that is the value we want
w += 1
self._warnSeniors(w)
self._kw[rkey][0] = w
return rkey
except KeyError:
self._keys.pop(ri)
# if you do not find one after 100 tries then just get a random one
self._fails += 1 #for confirming effectiveness only
for key in self._keys:
if key in self._kw:
w = self._kw[key][0] + 1
self._warnSeniors(w)
self._kw[key][0] = w
return key
return None
def _findSeniors(self):
'''this function finds the seniors, counts them and assess their age. It
is costly but unlikely.'''
seniorW = 0
seniors = 0
for w in self._kw.itervalues():
if w >= seniorW:
if w == seniorW:
seniors += 1
else:
seniorsW = w
seniors = 1
self._seniors = seniors
self._seniorW = seniorW
def _warnSeniors(self, w):
#a weight can only be incremented...good
if w >= self._seniorW:
if w == self._seniorW:
self._seniors+=1
else:
self._seniors = 1
self._seniorW = w
def test():
#test code
iterations = 200000
size = 2500
nextkey = size
pd = ProbDict(dict([(i,[0,i]) for i in xrange(size)]))
start = time.clock()
for i in xrange(iterations):
key=pd._key()
w=pd[key][0]
if random.randint(0,1+pd._seniorW-w):
#the heavier the object, the more unlikely it will be removed
pd.pop(key)
probAppend = float(500+(size-len(pd)))/1000
if random.uniform(0,1) < probAppend:
nextkey+=1
pd.append(nextkey)
print (time.clock()-start)*1000/iterations, "msecs / iteration with", pd._fails, "failures /", iterations, "iterations"
weights = pd.weights()
weights.sort()
print "avg weight:", float(sum(weights))/pd._len, max(weights), pd._seniorW, pd._seniors, len(pd), len(weights)
print weights
test()
```
Any comments are still welcome. @Darius: your binary trees are too complex and complicated for me; and I do not think its leafs can be removed efficiently... Thx all | [This activestate recipe](http://code.activestate.com/recipes/117241/) gives an easy-to-follow approach, specifically the version in the comments that doesn't require you to pre-normalize your weights:
```
import random
def weighted_choice(items):
"""items is a list of tuples in the form (item, weight)"""
weight_total = sum((item[1] for item in items))
n = random.uniform(0, weight_total)
for item, weight in items:
if n < weight:
return item
n = n - weight
return item
```
This will be slow if you have a large list of items. A binary search would probably be better in that case... but would also be more complicated to write, for little gain if you have a small sample size. [Here's an example of the binary search approach in python](http://code.activestate.com/recipes/498229/) if you want to follow that route.
(I'd recommend doing some quick performance testing of both methods on your dataset. The performance of different approaches to this sort of algorithm is often a bit unintuitive.)
---
**Edit:** I took my own advice, since I was curious, and did a few tests.
I compared four approaches:
*The weighted\_choice function above.*
*A binary-search choice function like so:*
```
def weighted_choice_bisect(items):
added_weights = []
last_sum = 0
for item, weight in items:
last_sum += weight
added_weights.append(last_sum)
return items[bisect.bisect(added_weights, random.random() * last_sum)][0]
```
*A compiling version of 1:*
```
def weighted_choice_compile(items):
"""returns a function that fetches a random item from items
items is a list of tuples in the form (item, weight)"""
weight_total = sum((item[1] for item in items))
def choice(uniform = random.uniform):
n = uniform(0, weight_total)
for item, weight in items:
if n < weight:
return item
n = n - weight
return item
return choice
```
*A compiling version of 2:*
```
def weighted_choice_bisect_compile(items):
"""Returns a function that makes a weighted random choice from items."""
added_weights = []
last_sum = 0
for item, weight in items:
last_sum += weight
added_weights.append(last_sum)
def choice(rnd=random.random, bis=bisect.bisect):
return items[bis(added_weights, rnd() * last_sum)][0]
return choice
```
I then built a big list of choices like so:
```
choices = [(random.choice("abcdefg"), random.uniform(0,50)) for i in xrange(2500)]
```
And an excessively simple profiling function:
```
def profiler(f, n, *args, **kwargs):
start = time.time()
for i in xrange(n):
f(*args, **kwargs)
return time.time() - start
```
**The results:**
(Seconds taken for 1,000 calls to the function.)
* Simple uncompiled: 0.918624162674
* Binary uncompiled: 1.01497793198
* Simple compiled: 0.287325024605
* Binary compiled: 0.00327413797379
The "compiled" results include the average time taken to compile the choice function once. (I timed 1,000 compiles, then divided that time by 1,000, and added the result to the choice function time.)
So: if you have a list of items+weights which change very rarely, the binary compiled method is *by far* the fastest. | In comments on the original post, Nicholas Leonard suggests that both the exchanging and the sampling need to be fast. Here's an idea for that case; I haven't tried it.
If only sampling had to be fast, we could use an array of the values together with the running sum of their probabilities, and do a binary search on the running sum (with key being a uniform random number) -- an O(log(n)) operation. But an exchange would require updating all of the running-sum values appearing after the entries exchanged -- an O(n) operation. (Could you choose to exchange only items near the end of their lists? I'll assume not.)
So let's aim for O(log(n)) in both operations. Instead of an array, keep a binary tree for each set to sample from. A leaf holds the sample value and its (unnormalized) probability. A branch node holds the total probability of its children.
To sample, generate a uniform random number `x` between 0 and the total probability of the root, and descend the tree. At each branch, choose the left child if the left child has total probability `<= x`. Else subtract the left child's probability from `x` and go right. Return the leaf value you reach.
To exchange, remove the leaf from its tree and adjust the branches that lead down to it (decreasing their total probability, and cutting out any single-child branch nodes). Insert the leaf into the destination tree: you have a choice of where to put it, so keep it balanced. Picking a random child at each level is probably good enough -- that's where I'd start. Increase each parent node's probability, back up to the root.
Now both sampling and exchange are O(log(n)) on average. (If you need guaranteed balance, a simple way is to add another field to the branch nodes holding the count of leaves in the whole subtree. When adding a leaf, at each level pick the child with fewer leaves. This leaves the possibility of a tree getting unbalanced solely by deletions; this can't be a problem if there's reasonably even traffic between the sets, but if it is, then choose rotations during deletion using the leaf-count information on each node in your traversal.)
**Update:** On request, here's a basic implementation. Haven't tuned it at all. Usage:
```
>>> t1 = build_tree([('one', 20), ('two', 2), ('three', 50)])
>>> t1
Branch(Leaf(20, 'one'), Branch(Leaf(2, 'two'), Leaf(50, 'three')))
>>> t1.sample()
Leaf(50, 'three')
>>> t1.sample()
Leaf(20, 'one')
>>> t2 = build_tree([('four', 10), ('five', 30)])
>>> t1a, t2a = transfer(t1, t2)
>>> t1a
Branch(Leaf(20, 'one'), Leaf(2, 'two'))
>>> t2a
Branch(Leaf(10, 'four'), Branch(Leaf(30, 'five'), Leaf(50, 'three')))
```
Code:
```
import random
def build_tree(pairs):
tree = Empty()
for value, weight in pairs:
tree = tree.add(Leaf(weight, value))
return tree
def transfer(from_tree, to_tree):
"""Given a nonempty tree and a target, move a leaf from the former to
the latter. Return the two updated trees."""
leaf, from_tree1 = from_tree.extract()
return from_tree1, to_tree.add(leaf)
class Tree:
def add(self, leaf):
"Return a new tree holding my leaves plus the given leaf."
abstract
def sample(self):
"Pick one of my leaves at random in proportion to its weight."
return self.sampling(random.uniform(0, self.weight))
def extract(self):
"""Pick one of my leaves and return it along with a new tree
holding my leaves minus that one leaf."""
return self.extracting(random.uniform(0, self.weight))
class Empty(Tree):
weight = 0
def __repr__(self):
return 'Empty()'
def add(self, leaf):
return leaf
def sampling(self, weight):
raise Exception("You can't sample an empty tree")
def extracting(self, weight):
raise Exception("You can't extract from an empty tree")
class Leaf(Tree):
def __init__(self, weight, value):
self.weight = weight
self.value = value
def __repr__(self):
return 'Leaf(%r, %r)' % (self.weight, self.value)
def add(self, leaf):
return Branch(self, leaf)
def sampling(self, weight):
return self
def extracting(self, weight):
return self, Empty()
def combine(left, right):
if isinstance(left, Empty): return right
if isinstance(right, Empty): return left
return Branch(left, right)
class Branch(Tree):
def __init__(self, left, right):
self.weight = left.weight + right.weight
self.left = left
self.right = right
def __repr__(self):
return 'Branch(%r, %r)' % (self.left, self.right)
def add(self, leaf):
# Adding to a random branch as a clumsy way to keep an
# approximately balanced tree.
if random.random() < 0.5:
return combine(self.left.add(leaf), self.right)
return combine(self.left, self.right.add(leaf))
def sampling(self, weight):
if weight < self.left.weight:
return self.left.sampling(weight)
return self.right.sampling(weight - self.left.weight)
def extracting(self, weight):
if weight < self.left.weight:
leaf, left1 = self.left.extracting(weight)
return leaf, combine(left1, self.right)
leaf, right1 = self.right.extracting(weight - self.left.weight)
return leaf, combine(self.left, right1)
```
**Update 2:** In [answering another problem](https://stackoverflow.com/questions/2140787/select-random-k-elements-from-a-list-whose-elements-have-weights/2149533#2149533), Jason Orendorff points out that the binary trees can be kept perfectly balanced by representing them in an array just like the classical heap structure. (This saves the space spent on pointers, too.) See my comments to that answer for how to adapt his code to this problem. | Probability distribution in Python | [
"",
"python",
"algorithm",
"random",
"distribution",
"probability",
""
] |
Lets say you had some resource clean up like: This is C#.
```
try{/*stuff*/}
catch(Exception e) {/*rollback logs etc.*/}
finally{
if( context.Transaction != null )
context.Transaction.Dispose();
context.Connection.Close();
context.Connection.Dispose();
}
```
Would it be more robust to do this instead?
```
try{/*stuff*/}
catch(Exception e) {/*rollback logs etc.*/}
finally{
try{
if( context.Transaction != null )
context.Transaction.Dispose();
}catch(Exception e){/*logs*/}
finally{
context.Connection.Close();
context.Connection.Dispose();
}
}
```
This way if the transaction.dispose manages to fail at leat the connection will be given the chance to close. | > Would it be more robust to do this instead?
You would be better with multiple using blocks.
First, your catch blocks will eat all exceptions and are not needed (can have try ... finally without any catches). Only use catch if you can handle (or add value to) the exception.
But better:
```
using (var resA = GetMeAResourceNeedingCleanUp())
using (var resB = new AnotherResourceNeedingCleanUpn(...)) {
// Code that might throw goes in here.
}
```
NB. Once an exception is winding back, and finally blocks are clearing up, throwing an other exception is likely to lead to (at best) confusion about which is being handled. This second guideline:
**DO NOT** throw exceptions from Dispose methods or finalizers. If you need to allow users to handle cleanup failures provide a separate Close method which can report its failure.
Note, the "Framework Design Guidelines" (2nd ed) has this as (§9.4.1):
> **AVOID** throwing an exception from within Dispose(bool) except under critical
> situations where the containing process has been corrupted (leaks, inconsistent
> shared state, etc.). | Three points:
* You don't need to call Close as well as dispose
* Disposing of the transaction in a separate finally block is a better idea, as it guards against exceptions being thrown during disposal. (It shouldn't happen often, but it might do.)
* The `using` statement is almost always the cleanest way to dispose of resources. I use this even if I *also* want a try/catch block, simply because it's the idiomatic way of saying, "This uses a resource which I want to be disposed at the end of the block"
Combining these would lead to two using statements:
```
using (SqlConnection conn = ...)
{
using (Transaction trans = ...)
{
}
}
```
If you want to avoid excessive indentation, you can write this as:
```
using (SqlConnection conn = ...)
using (Transaction trans = ...)
{
}
``` | Multipule Operations in a finally block | [
"",
"c#",
"exception",
""
] |
I am having problems downloading a binary file (video) in my app from the internet. In Quicktime, If I download it directly it works fine but through my app somehow it get's messed up (even though they look exactly the same in a text editor). Here is a example:
```
URL u = new URL("http://www.path.to/a.mp4?video");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(root,"Video.mp4"));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer);
}
f.close();
``` | I don't know if it's the only problem, but you've got a classic Java glitch in there: You're not counting on the fact that read() is *always* allowed to return fewer bytes than you ask for. Thus, your read could get less than 1024 bytes but your write always writes out exactly 1024 bytes possibly including bytes from the previous loop iteration.
Correct with:
```
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
```
Perhaps the higher latency networking or smaller packet sizes of 3G on Android are exacerbating the effect? | ```
new DefaultHttpClient().execute(new HttpGet("http://www.path.to/a.mp4?video"))
.getEntity().writeTo(
new FileOutputStream(new File(root,"Video.mp4")));
``` | Android download binary file problems | [
"",
"java",
"android",
"download",
"httpurlconnection",
"fileoutputstream",
""
] |
Why is `super()` used?
Is there a difference between using `Base.__init__` and `super().__init__`?
```
class Base(object):
def __init__(self):
print "Base created"
class ChildA(Base):
def __init__(self):
Base.__init__(self)
class ChildB(Base):
def __init__(self):
super(ChildB, self).__init__()
ChildA()
ChildB()
``` | `super()` lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of [fun stuff](http://www.artima.com/weblogs/viewpost.jsp?thread=236275) can happen. See the [standard docs on super](https://docs.python.org/2/library/functions.html#super) if you haven't already.
Note that [the syntax changed in Python 3.0](https://docs.python.org/3/library/functions.html#super): you can just say `super().__init__()` instead of `super(ChildB, self).__init__()` which IMO is quite a bit nicer. The standard docs also refer to a [guide to using `super()`](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/) which is quite explanatory. | > ## I'm trying to understand `super()`
The reason we use `super` is so that child classes that may be using cooperative multiple inheritance will call the correct next parent class function in the Method Resolution Order (MRO).
In Python 3, we can call it like this:
```
class ChildB(Base):
def __init__(self):
super().__init__()
```
In Python 2, we were required to call `super` like this with the defining class's name and `self`, but we'll avoid this from now on because it's redundant, slower (due to the name lookups), and more verbose (so update your Python if you haven't already!):
```
super(ChildB, self).__init__()
```
Without super, you are limited in your ability to use multiple inheritance because you hard-wire the next parent's call:
```
Base.__init__(self) # Avoid this.
```
I further explain below.
> ## "What difference is there actually in this code?:"
```
class ChildA(Base):
def __init__(self):
Base.__init__(self)
class ChildB(Base):
def __init__(self):
super().__init__()
```
The primary difference in this code is that in `ChildB` you get a layer of indirection in the `__init__` with `super`, which uses the class in which it is defined to determine the next class's `__init__` to look up in the MRO.
I illustrate this difference in an answer at the [canonical question, How to use 'super' in Python?](https://stackoverflow.com/a/33469090/541136), which demonstrates **dependency injection** and **cooperative multiple inheritance**.
## If Python didn't have `super`
Here's code that's actually closely equivalent to `super` (how it's implemented in C, minus some checking and fallback behavior, and translated to Python):
```
class ChildB(Base):
def __init__(self):
mro = type(self).mro()
check_next = mro.index(ChildB) + 1 # next after *this* class.
while check_next < len(mro):
next_class = mro[check_next]
if '__init__' in next_class.__dict__:
next_class.__init__(self)
break
check_next += 1
```
Written a little more like native Python:
```
class ChildB(Base):
def __init__(self):
mro = type(self).mro()
for next_class in mro[mro.index(ChildB) + 1:]: # slice to end
if hasattr(next_class, '__init__'):
next_class.__init__(self)
break
```
If we didn't have the `super` object, we'd have to write this manual code everywhere (or recreate it!) to ensure that we call the proper next method in the Method Resolution Order!
How does super do this in Python 3 without being told explicitly which class and instance from the method it was called from?
It gets the calling stack frame, and finds the class (implicitly stored as a local free variable, `__class__`, making the calling function a closure over the class) and the first argument to that function, which should be the instance or class that informs it which Method Resolution Order (MRO) to use.
Since it requires that first argument for the MRO, [using `super` with static methods is impossible as they do not have access to the MRO of the class from which they are called](https://bugs.python.org/issue31118).
## Criticisms of other answers:
> `super()` lets you avoid referring to the base class explicitly, which can be nice. . But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.
It's rather hand-wavey and doesn't tell us much, but the point of `super` is not to avoid writing the parent class. The point is to ensure that the next method in line in the method resolution order (MRO) is called. This becomes important in multiple inheritance.
I'll explain here.
```
class Base(object):
def __init__(self):
print("Base init'ed")
class ChildA(Base):
def __init__(self):
print("ChildA init'ed")
Base.__init__(self)
class ChildB(Base):
def __init__(self):
print("ChildB init'ed")
super().__init__()
```
And let's create a dependency that we want to be called after the Child:
```
class UserDependency(Base):
def __init__(self):
print("UserDependency init'ed")
super().__init__()
```
Now remember, `ChildB` uses super, `ChildA` does not:
```
class UserA(ChildA, UserDependency):
def __init__(self):
print("UserA init'ed")
super().__init__()
class UserB(ChildB, UserDependency):
def __init__(self):
print("UserB init'ed")
super().__init__()
```
And `UserA` does not call the UserDependency method:
```
>>> UserA()
UserA init'ed
ChildA init'ed
Base init'ed
<__main__.UserA object at 0x0000000003403BA8>
```
But `UserB` does in-fact call UserDependency because `ChildB` invokes `super`:
```
>>> UserB()
UserB init'ed
ChildB init'ed
UserDependency init'ed
Base init'ed
<__main__.UserB object at 0x0000000003403438>
```
### Criticism for another answer
In no circumstance should you do the following, which another answer suggests, as you'll definitely get errors when you subclass ChildB:
```
super(self.__class__, self).__init__() # DON'T DO THIS! EVER.
```
(That answer is not clever or particularly interesting, but in spite of direct criticism in the comments and over 17 downvotes, the answerer persisted in suggesting it until a kind editor fixed his problem.)
Explanation: Using `self.__class__` as a substitute for explicitly passing the class by name in `super()` will lead to recursion. `super` lets us look up the next parent in the MRO (see the first section of this answer) for child classes. If we tell `super` we're in the child's method, it will then lookup the next method in line (probably this same one we are calling it from) resulting in recursion, causing either a logical failure (as in the answerer's example) or a `RuntimeError` when the maximum recursion depth is exceeded.
```
class Polygon(object):
def __init__(self, id):
self.id = id
class Rectangle(Polygon):
def __init__(self, id, width, height):
super(self.__class__, self).__init__(id)
self.shape = (width, height)
class Square(Rectangle):
pass
>>> Square('a', 10, 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
TypeError: __init__() missing 2 required positional arguments: 'width' and 'height'
```
Python 3's new `super()` calling method with no arguments fortunately allows us to sidestep this issue. | Understanding Python super() with __init__() methods | [
"",
"python",
"class",
"oop",
"inheritance",
"super",
""
] |
How to implement posix threads in linux c++.The smme program when saved as ".c and run using c compiler is ok. but in c++ it is giving error ..
I think i made mistake when compiling
is there any tag to be included like "-lpthread" for c++
Can someone pls send a valid code...?
Actually this is my code
```
int cooperbussman :: startlistenthread()
{
if(pthread_create(&m_thread,0,&packetreadertask,0)<0)
{
cout<<"Unable to create the thread Startlistenthread\n";
return -1;
}
return 1;
```
and the error i am getting is
```
cooperbussman.cpp: In member function âint cooperbussman::startlistenthread()â:
cooperbussman.cpp:76: error: invalid conversion from âvoid* (*)()â to âvoid* (*)(void*)â
cooperbussman.cpp:76: error: initializing argument 3 of âint pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)â
``` | Your `packetreadertask` function must be a function that takes a single `void *` as a parameter. This is the important error message:
```
cooperbussman.cpp:76: error: invalid conversion from âvoid* (*)()â to âvoid* (*)(void*)â
```
Your function is declared something like this:
```
void *packetreadertask();
```
where it must be:
```
void *packetreadertask(void *);
``` | You might look into using Boost.Threads. It gives you some simple semantics in C++ over pthreads on platforms that support it.
But....there's no reason why you can't use pthreads in a C++ program. Your errors may be due to symbol mangling, but there's no way for us to help you more precisely without seeing your code or at least your compiler output. | Posix Threads in c++ | [
"",
"c++",
"multithreading",
"posix",
""
] |
I have the following:
```
set @SomeVariable = @AnotherVariable/isnull(@VariableEqualToZero,1) - 1
```
If @VariableEqualToZero is null it substitutes the 1. I need it to substitute 1 if @VariableEqualToZero = 0 as well. How do I do this? | ```
SET @SomeVariable = @AnotherVariable / COALESCE(
CASE
WHEN @VariableEqualToZero = 0 THEN 1
ELSE @VariableEqualToZero
END, 1) - 1
``` | If you're using SQL Server, you can probably use a `NULLIF` statement?
i.e. set the value to `NULL` if it's `0` then set it to `1` if it's `NULL` - should catch for both 0's and NULLs:
```
SET @SomeVariable = @AnotherVariable/ISNULL(NULLIF(@VariableEqualToZero,0),1) - 1
``` | SQL Server Check for IsNull and for Zero | [
"",
"sql",
"sql-server",
"isnull",
"divide-by-zero",
""
] |
I want to know if it is possible to let compiler issue a warning/error for code as following:
**Note:**
*1. Yea, it is bad programming style and we should avoid such cases - but we are dealing with legacy code and hope compiler can help identify such cases for us.)*
*2. I prefer a compiler option (VC++) to disable or enable object slicing, if there is any.*
```
class Base{};
class Derived: public Base{};
void Func(Base)
{
}
//void Func(Derived)
//{
//
//}
//main
Func(Derived());
```
Here if I comment out the second function, the first function would be called - and the compiler (both VC++ and Gcc) feels comfortable with that.
Is it C++ standard? and can I ask compiler (VC++) to give me a warning when met such code?
Thanks so much!!!
**Edit:**
Thanks all so much for your help!
I can't find a compiler option to give a error/warning - I even posted this in MSDN forum for VC++ compiler consultant with no answer. So I am afraid neither gcc nor vc++ implemented this feature.
So add constructor which take derived classes as paramter would be the best solution for now.
**Edit**
I have submit a feedbak to MS and hope they will fix it soon:
<https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=421579>
-Baiyan | If you can modify the base class you could do something like:
```
class Base
{
public:
// not implemented will cause a link error
Base(const Derived &d);
const Base &operator=(const Derived &rhs);
};
```
Depending on your compiler that should get you the translation unit, and maybe the function where the slicing is happening. | As a variation of [Andrew Khosravian's answer](https://stackoverflow.com/questions/580375/how-to-generate-a-compiler-warning-error-when-object-sliced/580533#580533), I'll suggest using templated copy constructors and assignment operators. This way you don't need to know all the derived classes of a given base class in order to safeguard that base class against slicing:
```
class Base
{
private: // To force a compile error for non-friends (thanks bk1e)
// Not implemented, so will cause a link error for friends
template<typename T> Base(T const& d);
template<typename T> Base const& operator=(T const& rhs);
public:
// You now need to provide a copy ctor and assignment operator for Base
Base(Base const& d) { /* Initialise *this from d */ }
Base const& operator=(Base const& rhs) { /* Copy d to *this */ }
};
```
Although this reduces the amount of work needed, with this approach you still need to mess with each base class in order to safeguard it. Also, it will cause problems if there are legitimate conversions from `Base` to `SomeOtherClass` that employ an `operator Base()` member of `SomeOtherClass`. (In that case, a more elaborate solution involving `boost::disable_if<is_same<T, SomeOtherClass> >` can be used.) In any case, you should remove this code once you've identified all instances of object slicing.
**To the compiler implementors of the world:** Testing for object slicing is definitely something that would be worthwhile creating (optional) warnings for! I can't think of one instance where it would be desired behaviour, and it's very commonly seen in newbie C++ code.
**[EDIT 27/3/2015:]** As pointed out by Matt McNab, you actually don't need to declare the copy constructor and assignment operator explicitly as I've done above, as they will still be implicitly declared by the compiler. In the 2003 C++ standard, this is explicitly mentioned in footnote 106 under 12.8/2:
> Because a template constructor is never a copy constructor, the presence of such a template does not suppress the implicit declaration of a copy constructor. Template constructors participate in overload resolution with other constructors, including copy constructors, and a template constructor may be used to copy an object if it provides a better match than other constructors. | How to generate a compiler warning/error when object sliced | [
"",
"c++",
"compiler-construction",
"truncate",
"slice",
""
] |
What are the Advantages/Drawbacks of these two ways of iterating through a container / which one do you prefer and why:
```
for (MyClass::iterator i = m.begin(), e = m.end() ; i != e ; i++)
{
// ...
}
```
or
```
for (MyClass::iterator i = m.begin() ; i != m.end() ; i++)
{
// ...
}
```
Subsidiary question: i++ or ++i? Why? | If the iterator is non-trivial (ie. not a pointer), ++i is definitely faster as it doesn't involves a copy to a temporary, which may or may not be optimized out.
The first form is a little faster but could be wrong if you erase or insert things in the loop.
For simple iteration over a container I use
```
#define foreach BOOST_FOREACH // in some header
foreach(MyType &element, any_container) {
// deal with element
}
```
most of the time for succinctness and clarity. | Unless you have optimizations turned off, both are equivalent. As for i++ or ++i, ++i is more efficient because it does not involve a temporary value. | Best way to iterate through a container | [
"",
"c++",
"iterator",
"containers",
""
] |
The short version is: How do I learn the size (in bits) of an individual field of a c++ field?
To clarify, an example of the field I am talking about:
```
struct Test {
unsigned field1 : 4; // takes up 4 bits
unsigned field2 : 8; // 8 bits
unsigned field3 : 1; // 1 bit
unsigned field4 : 3; // 3 bits
unsigned field5 : 16; // 16 more to make it a 32 bit struct
int normal_member; // normal struct variable member, 4 bytes on my system
};
Test t;
t.field1 = 1;
t.field2 = 5;
// etc.
```
To get the size of the entire Test object is easy, we just say
```
sizeof(Test); // returns 8, for 8 bytes total size
```
We can get a normal struct member through
```
sizeof(((Test*)0)->normal_member); // returns 4 (on my system)
```
I would like to know how to get the size of an individual field, say Test::field4. The above example for a normal struct member does not work. Any ideas? Or does someone know a reason why it cannot work? I am fairly convinced that sizeof will not be of help since it only returns size in bytes, but if anyone knows otherwise I'm all ears.
Thanks! | You can calculate the size at run time, fwiw, e.g.:
```
//instantiate
Test t;
//fill all bits in the field
t.field1 = ~0;
//extract to unsigned integer
unsigned int i = t.field1;
... TODO use contents of i to calculate the bit-width of the field ...
``` | You cannot take the `sizeof` a bitfield and get the number of bits.
Your best bet would be use `#define`s or `enum`s:
```
struct Test {
enum Sizes {
sizeof_field1 = 4,
sizeof_field2 = 8,
sizeof_field3 = 1,
sizeof_field4 = 3,
sizeof_field5 = 16,
};
unsigned field1 : sizeof_field1; // takes up 4 bits
unsigned field2 : sizeof_field2; // 8 bits
unsigned field3 : sizeof_field3; // 1 bit
unsigned field4 : sizeof_field4; // 3 bits
unsigned field5 : sizeof_field5; // 16 more to make it a 32 bit struct
int normal_member; // normal struct variable member, 4 bytes on my system
};
printf("%d\n", Test::sizeof_field1); // prints 4
```
For the sake of consistency, I believe you can move `normal_member` up to the top and add an entry in `Sizes` using `sizeof(normal_member)`. This messes with the order of your data, though. | Getting the size of an indiviual field from a c++ struct field | [
"",
"c++",
"struct",
"field",
"sizeof",
""
] |
Which code-Analyzer or Code-Review tool do you suggest ,
For Analyzing **DotNet 2.0 & 3.5** code and getting
*All classes , Methods , Properties , Instances , Definition ,
Databases & and their relation to code ,*
I want to **get print-ready Information** about codes & projects ,
( *here I dont mean a tool for testing the code & structures* )
Is there anyone with similar specifications ? | Maybe [NDepend](http://www.ndepend.com/)? | [Reflector](http://www.red-gate.com/products/reflector/) is very good and free. The [Code Metrics](http://www.codeplex.com/reflectoraddins/Wiki/View.aspx?title=CodeMetrics&referringTitle=Home) add-in will give you good quality metrics. This may not give you the print-readiness you need.
[doxygen](http://www.doxygen.org/) can analyze your source code and output documentation listing all classes, namespaces, call trees, dependencies, etc. This should give you printability. | Best tool for Code-Analyzement or Code-Review | [
"",
"c#",
"asp.net",
""
] |
Okay, I tested this on an empty program, and just having a while(true){} running gave me >50% on my CPU. I have a game I'm working on that uses a while loop as it's main loop, and it's CPU is at 100 all the time.
How can I get Java to repeat something over and over without eating up >50% of my CPU just to do the repeating? | Add a sleep to put the thread into idle for some interval:
[`Thread.sleep`](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#sleep(long))
Without having a sleep, the while loop will consume all the computing resources that is available. (For example, theoretically, 100% in a single core system, or 50% in a dual core, and so on.)
For example, the following will cycle once through a `while` loop approximately every 50 milliseconds:
```
while (true)
{
try
{
Thread.sleep(50);
}
catch (Exception e)
{
e.printStackTrace();
}
}
```
This should bring down the CPU utilization quite a bit.
With a sleep in the loop, the operating system will also give enough system time for other threads and processes to do their things, so the system will be responsive as well. Back in the days of single core systems and operating systems with not-so-good schedulers, loops like this could have made the system very unresponsive.
---
Since the topic of use of `while` loops for a game came up, if the game is going to involve a GUI, the game loop must be in a separate thread or else the GUI itself will become unresponsive.
If the program is going to be a console-based game, then threading is not going to be an issue, but with graphical user interfaces which are event-driven, having a long-living loop in the code will make the GUI unresponsive.
Threading and such are pretty tricky areas of programming, especially when getting started, so I suggest that another question be raised when it becomes necessary.
The following is an example of a Swing application based in a `JFrame` which updates a `JLabel` that will contain the returned value from `System.currentTimeMillis`. The updating process takes place in a separate thread, and a "Stop" button will stop the update thread.
Few concepts the example will illustrate:
* A Swing-based GUI application with a separate thread to update time -- This will prevent lock up of the GUI thread. (Called the EDT, or event dispatch thread in Swing.)
* Having the `while` loop with a loop condition that is not `true`, but substituted with a `boolean` which will determine whether to keep the loop alive.
* How `Thread.sleep` factors into an actual application.
Please excuse me for the long example:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TimeUpdate
{
public void makeGUI()
{
final JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JLabel l = new JLabel();
class UpdateThread implements Runnable
{
// Boolean used to keep the update loop alive.
boolean running = true;
public void run()
{
// Typically want to have a way to get out of
// a loop. Setting running to false will
// stop the loop.
while (running)
{
try
{
l.setText("Time: " +
System.currentTimeMillis());
Thread.sleep(50);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
// Once the run method exits, this thread
// will terminate.
}
}
// Start a new time update thread.
final UpdateThread t = new UpdateThread();
new Thread(t).start();
final JButton b = new JButton("Stop");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
t.running = false;
}
});
// Prepare the frame.
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(l, BorderLayout.CENTER);
f.getContentPane().add(b, BorderLayout.SOUTH);
f.setLocation(100, 100);
f.pack();
f.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TimeUpdate().makeGUI();
}
});
}
}
```
Some resources about threading and using Swing:
* [Threads and Swing](http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html)
* [Lesson: Concurrency](http://java.sun.com/docs/books/tutorial/essential/concurrency/) | Thread.Sleep may not be the whole answer. For most games, there's way too much CPU for the amount of work needed. Simply sleeping for a set amount of time isn't all that efficient, since you will likely either still burn too many resources, or not enough. You typically want to time your work in some way.
If you think about it, the screen only updates at a certain rate, typically less than 100 times per second. I'm not familiar with the Java api's for this sort of thing, but what you want is to find out the refresh speed of the monitor and then update only a single time between each refresh.
Further, you don't need a loop like that for your main loop, you can use timers to call your update code at a regular interval. This is even more efficient. | How can I stop a Java while loop from eating >50% of my CPU? | [
"",
"java",
"loops",
"cpu-usage",
""
] |
I'm not that into dynamic programming languages but I've written my fair share of JavaScript code. I never really got my head around this prototype-based programming, does any one know how this works?
```
var obj = new Object();
obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();
```
I remember a lot discussion I had with people a while back (I'm not exactly sure what I'm doing) but as I understand it, there's no concept of a class. It's just an object, and instances of those objects are clones of the original, right?
But what is the exact purpose of this ".prototype" property in JavaScript? How does it relate to instantiating objects?
### Update: correct way
```
var obj = new Object(); // not a functional object
obj.prototype.test = function() { alert('Hello?'); }; // this is wrong!
function MyObject() {} // a first class functional object
MyObject.prototype.test = function() { alert('OK'); } // OK
```
Also these [slides](http://ejohn.org/apps/learn/#64) really helped a lot. | Every JavaScript object [has an internal "slot"](https://www.ecma-international.org/ecma-262/10.0/index.html#sec-ordinary-object-internal-methods-and-internal-slots) called `[[Prototype]]` whose value is either `null` or an `object`. You can think of a slot as a property on an object, internal to the JavaScript engine, hidden from the code you write. The square brackets around `[[Prototype]]` are deliberate, and are an ECMAScript specification convention to denote internal slots.
The value pointed at by the `[[Prototype]]` of an object, is colloquially known as "the prototype of that object."
If you access a property via the dot (`obj.propName`) or bracket (`obj['propName']`) notation, and the object does not directly have such a property (ie. an *own property*, checkable via `obj.hasOwnProperty('propName')`), the runtime looks for a property with that name on the object referenced by the `[[Prototype]]` instead. If the `[[Prototype]]` *also* does not have such a property, its `[[Prototype]]` is checked in turn, and so on. In this way, the original object's *prototype chain* is walked until a match is found, or its end is reached. At the top of the prototype chain is the `null` value.
Modern JavaScript implementations allow read and/or write access to the `[[Prototype]]` in the following ways:
1. The `new` operator (configures the prototype chain on the default object returned from a constructor function),
2. The `extends` keyword (configures the prototype chain when using the class syntax),
3. `Object.create` will set the supplied argument as the `[[Prototype]]` of the resulting object,
4. `Object.getPrototypeOf` and `Object.setPrototypeOf` (get/set the `[[Prototype]]` *after* object creation), and
5. The standardized accessor (ie. getter/setter) property named `__proto__` (similar to 4.)
`Object.getPrototypeOf` and `Object.setPrototypeOf` are preferred over `__proto__`, in part because the behavior of `o.__proto__` [is unusual](https://stackoverflow.com/a/35458348/38522) when an object has a prototype of `null`.
An object's `[[Prototype]]` is initially set during object creation.
If you create a new object via `new Func()`, the object's `[[Prototype]]` will, by default, be set to the object referenced by `Func.prototype`.
Note that, therefore, **all classes, and all functions that can be used with the `new` operator, have a property named `.prototype` in addition to their own `[[Prototype]]` internal slot.** This dual use of the word "prototype" is the source of endless confusion amongst newcomers to the language.
Using `new` with constructor functions allows us to simulate classical inheritance in JavaScript; although JavaScript's inheritance system is - as we have seen - prototypical, and not class-based.
Prior to the introduction of class syntax to JavaScript, constructor functions were the only way to simulate classes. We can think of properties of the object referenced by the constructor function's `.prototype` property as shared members; ie. members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are conceptually added to the `.prototype` property; an object's fields, however, are instance-specific and are therefore added to the object itself during construction.
Without the class syntax, developers had to manually configure the prototype chain to achieve similar functionality to classical inheritance. This led to a preponderance of different ways to achieve this.
Here's one way:
```
function Child() {}
function Parent() {}
Parent.prototype.inheritedMethod = function () { return 'this is inherited' }
function inherit(child, parent) {
child.prototype = Object.create(parent.prototype)
child.prototype.constructor = child
return child;
}
Child = inherit(Child, Parent)
const o = new Child
console.log(o.inheritedMethod()) // 'this is inherited'
```
...and here's another way:
```
function Child() {}
function Parent() {}
Parent.prototype.inheritedMethod = function () { return 'this is inherited' }
function inherit(child, parent) {
function tmp() {}
tmp.prototype = parent.prototype
const proto = new tmp()
proto.constructor = child
child.prototype = proto
return child
}
Child = inherit(Child, Parent)
const o = new Child
console.log(o.inheritedMethod()) // 'this is inherited'
```
The class syntax introduced in ES2015 simplifies things, by providing `extends` as the "one true way" to configure the prototype chain in order to simulate classical inheritance in JavaScript.
So, similar to the code above, if you use the class syntax to create a new object like so:
```
class Parent { inheritedMethod() { return 'this is inherited' } }
class Child extends Parent {}
const o = new Child
console.log(o.inheritedMethod()) // 'this is inherited'
```
...the resulting object's `[[Prototype]]` will be set to an instance of `Parent`, whose `[[Prototype]]`, in turn, is `Parent.prototype`.
Finally, if you create a new object via `Object.create(foo)`, the resulting object's `[[Prototype]]` will be set to `foo`. | In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects--and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class.
In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. It's not difficult, but a little foreign and hard to metabolize for somebody used to the classical way.
Example:
```
//Define a functional object to hold persons in JavaScript
var Person = function(name) {
this.name = name;
};
//Add dynamically to the already defined object a new getter
Person.prototype.getName = function() {
return this.name;
};
//Create a new object of type Person
var john = new Person("John");
//Try the getter
alert(john.getName());
//If now I modify person, also John gets the updates
Person.prototype.sayMyName = function() {
alert('Hello, my name is ' + this.getName());
};
//Call the new method on john
john.sayMyName();
```
Until now I've been extending the base object, now I create another object and then inheriting from Person.
```
//Create a new object of type Customer by defining its constructor. It's not
//related to Person for now.
var Customer = function(name) {
this.name = name;
};
//Now I link the objects and to do so, we link the prototype of Customer to
//a new instance of Person. The prototype is the base that will be used to
//construct all new instances and also, will modify dynamically all already
//constructed objects because in JavaScript objects retain a pointer to the
//prototype
Customer.prototype = new Person();
//Now I can call the methods of Person on the Customer, let's try, first
//I need to create a Customer.
var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();
//If I add new methods to Person, they will be added to Customer, but if I
//add new methods to Customer they won't be added to Person. Example:
Customer.prototype.setAmountDue = function(amountDue) {
this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function() {
return this.amountDue;
};
//Let's try:
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());
```
```
var Person = function (name) {
this.name = name;
};
Person.prototype.getName = function () {
return this.name;
};
var john = new Person("John");
alert(john.getName());
Person.prototype.sayMyName = function () {
alert('Hello, my name is ' + this.getName());
};
john.sayMyName();
var Customer = function (name) {
this.name = name;
};
Customer.prototype = new Person();
var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();
Customer.prototype.setAmountDue = function (amountDue) {
this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function () {
return this.amountDue;
};
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());
```
While as said I can't call setAmountDue(), getAmountDue() on a Person.
```
//The following statement generates an error.
john.setAmountDue(1000);
``` | How does JavaScript .prototype work? | [
"",
"javascript",
"dynamic-languages",
"prototype-oriented",
""
] |
I'm working on a Web app where users need to input a date and time. I've used this calendar widget before and it works fine:
<http://www.dynarch.com/projects/calendar/>
However, it hasn't been updated since 2005. I'm wondering if anyone knows of a better one.
The calendar in jQuery UI doesn't handle times. Only dates. I need something that will let the user input both date and time using one control. | I am not aware of any single widget which does both date and time well. Any combined widget I've seen is overly complex and confusing.
There are however independent date and time widgets which I use frequently: [ClockPick](http://www.jnathanson.com/index.cfm?page=jquery/clockpick/ClockPick) and [datePicker](http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/). Both are [jQuery](http://jquery.com) plugins, work great across browsers, and are very easy to customize. | I don't think anything exists that does both date **and** time (at least nothing really good).
The general practice seems to be to use a drop-down list or some variation of one. If you're looking for something more flexible, there is a jQuery plugin for a time picker that imitates the Google Calendar time picker interface which I find very usable.
<http://labs.perifer.se/timedatepicker/> | Recommend a JS calendar widget that handles both date and time? | [
"",
"javascript",
"datetime",
"datepicker",
"date",
"widget",
""
] |
Does anybody have a known reliable way to create a video from a series of image files? Before you mod me down for not searching for the answer before posting the question, and before you fire off a simple message like "use FFMPEG," read the rest of this message.
I'm trying to create a video, it doesn't matter too much what format as long as it's widely supported, from a series of images (.jpg, .bmp, etc.). My platform is Windows Server 2008, 64-bit. If I can make the video from within my C# program, that's great, but I'm not averse to writing a series of image files to a directory and then firing off an external program to make a video from those images.
The only constraints are: it must work on my Windows Server 2008 system, and be scriptable. That is, no GUI programs that require operator intervention.
I found a number of similar questions on StackOverflow, and have tried several of the solutions, all with varying degrees of frustration and none with anything like success.
FFMPEG looks like a great program. Maybe it is, on Linux. The two Windows builds I downloaded are broken. Given this command line:
```
ffmpeg -r 1 -f image2 -i jpeg\*.jpg video.avi
```
One of the builds reads the images and then crashes due to data execution prevention. The other reads the first file and then spits out an error message that says "cannot find suitable codec for file jpeg/image2.jpg". Helpful, that. In any case, FFMPEG looks like a non-starter under Windows.
One answer to a previous posting recommended [Splicer](http://www.codeplex.com/splicer) . It looks like pretty good code. I compiled the samples and tried to run, but got some cryptic error message about a file not found. It looks like a COM class isn't registered. I suppose I need to install something (DirectShow, maybe, although I thought that was already installed?). Depending on what's required, I might have a difficult time justifying its installation on a server. ("What? Why do you need that on a server?")
Another answer suggested the [AviFile](http://www.codeproject.com/KB/audio-video/avifilewrapper.aspx) library from Code Project. That looks simple enough: a wrapper around the Windows AviFile subsystem. Except that the AVI files the package creates appear to have all of the frames, but only the first frame shows when I play the AVI in Windows Media Player. Well, that and if you try to create a compressed video, the program throws an exception.
So, I'm left wondering if there is a good, reliable way to do what I want: on a Windows system, create an AVI or other common video file format from a series of images, either through a .NET API or using an external program. Any help? | After working with it a while and taking a look at x264 and VideoLan, I went back to Splicer. It turns out that the cryptic error message was due to an error in my code.
It looks like Splicer will do what I want: programmatically create videos from a series of images.
Thanks to all who responded. | You can use VideoLan and I'd recommend it.
I've had direct experience in a C# application with VideoLan doing these two things:
1. Embedding a VLC viewer in my C# application (there are 3-4 C# "wrappers" for the VLC veiwer).
2. Using vlc.exe in a separate Process by sending it command-line arguments.
The fact that VideoLan has a command-line interface is a great thing. And VLC supports a command-line option that disables any visual element; so the VLC GUI doesn't pop up and neither does a command-line window. Thus, in a C# application you can farm out the video-related work to the VLC client. C# has the Process class which can manage your vlc.exe instances for you. It ends up being a pretty neat solution. | Working way to make video from images in C# | [
"",
"c#",
"video",
"ffmpeg",
""
] |
I'm using Visual Studio C++ 2008 Express to learn a native API for a new project. What I'm wondering is: what productivity features present in the full version that you take for granted are missing from Visual Studio Express? I'm not referring to large "paid" features like MFC support - I'm thinking of small features (sometimes provided by Add Ins) like ["Copy File to Output Dir"](http://jelle.druyts.net/2005/10/20/CopyToOutputDirectory.aspx)
Also, it doesn't have to be specific to C++ edition - that's just the exact release I happen to be using.
Note: I'm an experienced Java programmer and I most frequently use IntelliJ IDEA (disclaimer: that's just for reference - I'm not looking to compare VS vs. IDEA).
EDIT: Revised to include Add Ins that enhance the experience. | If you plan to develop a C/C++ *WIN32 GUI* application then the major component that is missing is the *resource editor* (i.e. the GUI builder tool).
The express version will still compile resource files, but you will have to create the resource files by hand or use a third party resource editor. | The ability to use addins are sorely missed, for example Visual Assist, which is **the** productivity booster. | What Visual Studio 2008 productivity features are missing from C++ Express edition? | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
""
] |
I need to maintain a roster of connected clients that are very shortlived and frequently go up and down. Due to the potential number of clients I need a collection that supports fast insert/delete. Suggestions? | ## C5 Generic Collection Library
The best implementations I have found in C# and C++ are these -- for C#/CLI:
* <http://www.itu.dk/research/c5/Release1.1/ITU-TR-2006-76.pdf>
* <http://www.itu.dk/research/c5/>
It's well researched, has extensible unit tests, and since February they also have implemented the common interfaces in .Net which makes it a lot easier to work with the collections. They were featured on [Channel9](http://channel9.msdn.com/shows/Going+Deep/Peter-Sestoft-C5-Generic-Collection-Library-for-C-and-CLI/) and they've done extensive performance testing on the collections.
If you are using data-structures anyway these researchers have a [red-black-tree](http://en.wikipedia.org/wiki/Red-black_tree) implementation in their library, similar to what you find if you fire up Lütz reflector and have a look in System.Data's internal structures :p. Insert-complexity: O(log(n)).
## Lock-free C++ collections
Then, if you can [allow for some C++ interop](http://blog.rednael.com/2008/08/29/MarshallingUsingNativeDLLsInNET.aspx) and you absolutely need the speed and want as little overhead as possible, then these lock-free ADTs from Dmitriy V'jukov are probably the best you can get in this world, outperforming Intel's concurrent library of ADTs.
* <http://groups.google.com/group/lock-free>
I've read some of the code and it's really the makings of someone well versed in how these things are put together. VC++ can do native C++ interop without annoying boundaries. [http://www.swig.org/](http://groups.google.com/group/lock-free) can otherwise help you wrap C++ interfaces for consumption in .Net, or you can do it yourself through P/Invoke.
## Microsoft's Take
They have written tutorials, [this one implementing a rather unpolished skip-list in C#](http://msdn.microsoft.com/en-us/library/ms379573.aspx), and discussing other types of data-structures. (There's a better [SkipList at CodeProject](http://www.codeproject.com/KB/recipes/skiplist1.aspx), which is very polished and implement the interfaces in a well-behaved manner.) They also have a few data-structures bundled with .Net, namely the [HashTable/Dictionary<,>](http://msdn.microsoft.com/en-us/library/4yh14awz.aspx) and [HashSet](http://msdn.microsoft.com/en-us/library/bb397727.aspx). Of course there's the "ResizeArray"/List type as well together with a stack and queue, but they are all "linear" on search.
## Google's perf-tools
If you wish to speed up the time it takes for memory-allocation you can use google's perf-tools. They are available at google code and they contain a [very interesting multi-threaded malloc-implementation (TCMalloc)](http://goog-perftools.sourceforge.net/doc/tcmalloc.html) which shows much more consistent timing than the normal malloc does. You could use this together with the lock-free structures above to really go crazy with performance.
## Improving response times with memoization
You can also use memoization on functions to improve performance through caching, something interesting if you're using e.g. [F#](https://rads.stackoverflow.com/amzn/click/com/1590598504). F# also allows C++ interop, so you're OK there.
## O(k)
There's also the possibility of doing something on your own using the research which has been done on [bloom-filters](http://en.wikipedia.org/wiki/Bloom_filter), which allow O(k) lookup complexity where k is a constant that depends on the number of hash-functions you have implemented. This is how google's BigTable has been implemented. These filter will get you the element if it's in the set or possibly with a very low likeliness an element which is not the one you're looking for (see the graph at wikipedia -- it's approaching P(wrong\_key) -> 0.01 as size is around 10000 elements, but you can go around this by implementing further hash-functions/reducing the set.
I haven't searched for .Net implementations of this, but since the hashing calculations are independent you can use [MS's performance team's implementation of Tasks to speed that up.](http://blogs.msdn.com/pfxteam/archive/2008/06/02/8567093.aspx)
## "My" take -- randomize to reach average O(log n)
As it happens I just did a coursework involving data-structures. In this case we used C++, but it's very easy to translate to C#. We built three different data-structures; a bloom-filter, a skip-list and [random binary search tree](http://gcu.googlecode.com/files/09BinarySearchTrees.pdf).
See the code and analysis after the last paragraph.
## Hardware-based "collections"
Finally, to make my answer "complete", if you truly need speed you can use something like [Routing-tables](http://en.wikipedia.org/wiki/Forwarding_information_base) or [Content-addressable memory](http://en.wikipedia.org/wiki/Content_addressable_memory) . This allows you to very quickly O(1) in principle get a "hash"-to-value lookup of your data.
## Random Binary Search Tree/Bloom Filter C++ code
I would really appreciate feedback if you find mistakes in the code, or just pointers on how I can do it better (or with better usage of templates). Note that the bloom filter isn't like it would be in real life; normally you don't have to be able to delete from it and then it much much more space efficient than the hack I did to allow the *delete* to be tested.
**DataStructure.h**
```
#ifndef DATASTRUCTURE_H_
#define DATASTRUCTURE_H_
class DataStructure
{
public:
DataStructure() {countAdd=0; countDelete=0;countFind=0;}
virtual ~DataStructure() {}
void resetCountAdd() {countAdd=0;}
void resetCountFind() {countFind=0;}
void resetCountDelete() {countDelete=0;}
unsigned int getCountAdd(){return countAdd;}
unsigned int getCountDelete(){return countDelete;}
unsigned int getCountFind(){return countFind;}
protected:
unsigned int countAdd;
unsigned int countDelete;
unsigned int countFind;
};
#endif /*DATASTRUCTURE_H_*/
```
**Key.h**
```
#ifndef KEY_H_
#define KEY_H_
#include <string>
using namespace std;
const int keyLength = 128;
class Key : public string
{
public:
Key():string(keyLength, ' ') {}
Key(const char in[]): string(in){}
Key(const string& in): string(in){}
bool operator<(const string& other);
bool operator>(const string& other);
bool operator==(const string& other);
virtual ~Key() {}
};
#endif /*KEY_H_*/
```
**Key.cpp**
```
#include "Key.h"
bool Key::operator<(const string& other)
{
return compare(other) < 0;
};
bool Key::operator>(const string& other)
{
return compare(other) > 0;
};
bool Key::operator==(const string& other)
{
return compare(other) == 0;
}
```
**BloomFilter.h**
```
#ifndef BLOOMFILTER_H_
#define BLOOMFILTER_H_
#include <iostream>
#include <assert.h>
#include <vector>
#include <math.h>
#include "Key.h"
#include "DataStructure.h"
#define LONG_BIT 32
#define bitmask(val) (unsigned long)(1 << (LONG_BIT - (val % LONG_BIT) - 1))
// TODO: Implement RW-locking on the reads/writes to the bitmap.
class BloomFilter : public DataStructure
{
public:
BloomFilter(){}
BloomFilter(unsigned long length){init(length);}
virtual ~BloomFilter(){}
void init(unsigned long length);
void dump();
void add(const Key& key);
void del(const Key& key);
/**
* Returns true if the key IS BELIEVED to exist, false if it absolutely doesn't.
*/
bool testExist(const Key& key, bool v = false);
private:
unsigned long hash1(const Key& key);
unsigned long hash2(const Key& key);
bool exist(const Key& key);
void getHashAndIndicies(unsigned long& h1, unsigned long& h2, int& i1, int& i2, const Key& key);
void getCountIndicies(const int i1, const unsigned long h1,
const int i2, const unsigned long h2, int& i1_c, int& i2_c);
vector<unsigned long> m_tickBook;
vector<unsigned int> m_useCounts;
unsigned long m_length; // number of bits in the bloom filter
unsigned long m_pockets; //the number of pockets
static const unsigned long m_pocketSize; //bits in each pocket
};
#endif /*BLOOMFILTER_H_*/
```
**BloomFilter.cpp**
```
#include "BloomFilter.h"
const unsigned long BloomFilter::m_pocketSize = LONG_BIT;
void BloomFilter::init(unsigned long length)
{
//m_length = length;
m_length = (unsigned long)((2.0*length)/log(2))+1;
m_pockets = (unsigned long)(ceil(double(m_length)/m_pocketSize));
m_tickBook.resize(m_pockets);
// my own (allocate nr bits possible to store in the other vector)
m_useCounts.resize(m_pockets * m_pocketSize);
unsigned long i; for(i=0; i< m_pockets; i++) m_tickBook[i] = 0;
for (i = 0; i < m_useCounts.size(); i++) m_useCounts[i] = 0; // my own
}
unsigned long BloomFilter::hash1(const Key& key)
{
unsigned long hash = 5381;
unsigned int i=0; for (i=0; i< key.length(); i++){
hash = ((hash << 5) + hash) + key.c_str()[i]; /* hash * 33 + c */
}
double d_hash = (double) hash;
d_hash *= (0.5*(sqrt(5)-1));
d_hash -= floor(d_hash);
d_hash *= (double)m_length;
return (unsigned long)floor(d_hash);
}
unsigned long BloomFilter::hash2(const Key& key)
{
unsigned long hash = 0;
unsigned int i=0; for (i=0; i< key.length(); i++){
hash = key.c_str()[i] + (hash << 6) + (hash << 16) - hash;
}
double d_hash = (double) hash;
d_hash *= (0.5*(sqrt(5)-1));
d_hash -= floor(d_hash);
d_hash *= (double)m_length;
return (unsigned long)floor(d_hash);
}
bool BloomFilter::testExist(const Key& key, bool v){
if(exist(key)) {
if(v) cout<<"Key "<< key<<" is in the set"<<endl;
return true;
}else {
if(v) cout<<"Key "<< key<<" is not in the set"<<endl;
return false;
}
}
void BloomFilter::dump()
{
cout<<m_pockets<<" Pockets: ";
// I changed u to %p because I wanted it printed in hex.
unsigned long i; for(i=0; i< m_pockets; i++) printf("%p ", (void*)m_tickBook[i]);
cout<<endl;
}
void BloomFilter::add(const Key& key)
{
unsigned long h1, h2;
int i1, i2;
int i1_c, i2_c;
// tested!
getHashAndIndicies(h1, h2, i1, i2, key);
getCountIndicies(i1, h1, i2, h2, i1_c, i2_c);
m_tickBook[i1] = m_tickBook[i1] | bitmask(h1);
m_tickBook[i2] = m_tickBook[i2] | bitmask(h2);
m_useCounts[i1_c] = m_useCounts[i1_c] + 1;
m_useCounts[i2_c] = m_useCounts[i2_c] + 1;
countAdd++;
}
void BloomFilter::del(const Key& key)
{
unsigned long h1, h2;
int i1, i2;
int i1_c, i2_c;
if (!exist(key)) throw "You can't delete keys which are not in the bloom filter!";
// First we need the indicies into m_tickBook and the
// hashes.
getHashAndIndicies(h1, h2, i1, i2, key);
// The index of the counter is the index into the bitvector
// times the number of bits per vector item plus the offset into
// that same vector item.
getCountIndicies(i1, h1, i2, h2, i1_c, i2_c);
// We need to update the value in the bitvector in order to
// delete the key.
m_useCounts[i1_c] = (m_useCounts[i1_c] == 1 ? 0 : m_useCounts[i1_c] - 1);
m_useCounts[i2_c] = (m_useCounts[i2_c] == 1 ? 0 : m_useCounts[i2_c] - 1);
// Now, if we depleted the count for a specific bit, then set it to
// zero, by anding the complete unsigned long with the notted bitmask
// of the hash value
if (m_useCounts[i1_c] == 0)
m_tickBook[i1] = m_tickBook[i1] & ~(bitmask(h1));
if (m_useCounts[i2_c] == 0)
m_tickBook[i2] = m_tickBook[i2] & ~(bitmask(h2));
countDelete++;
}
bool BloomFilter::exist(const Key& key)
{
unsigned long h1, h2;
int i1, i2;
countFind++;
getHashAndIndicies(h1, h2, i1, i2, key);
return ((m_tickBook[i1] & bitmask(h1)) > 0) &&
((m_tickBook[i2] & bitmask(h2)) > 0);
}
/*
* Gets the values of the indicies for two hashes and places them in
* the passed parameters. The index is into m_tickBook.
*/
void BloomFilter::getHashAndIndicies(unsigned long& h1, unsigned long& h2, int& i1,
int& i2, const Key& key)
{
h1 = hash1(key);
h2 = hash2(key);
i1 = (int) h1/m_pocketSize;
i2 = (int) h2/m_pocketSize;
}
/*
* Gets the values of the indicies into the count vector, which keeps
* track of how many times a specific bit-position has been used.
*/
void BloomFilter::getCountIndicies(const int i1, const unsigned long h1,
const int i2, const unsigned long h2, int& i1_c, int& i2_c)
{
i1_c = i1*m_pocketSize + h1%m_pocketSize;
i2_c = i2*m_pocketSize + h2%m_pocketSize;
}
```
\*\* RBST.h \*\*
```
#ifndef RBST_H_
#define RBST_H_
#include <iostream>
#include <assert.h>
#include <vector>
#include <math.h>
#include "Key.h"
#include "DataStructure.h"
#define BUG(str) printf("%s:%d FAILED SIZE INVARIANT: %s\n", __FILE__, __LINE__, str);
using namespace std;
class RBSTNode;
class RBSTNode: public Key
{
public:
RBSTNode(const Key& key):Key(key)
{
m_left =NULL;
m_right = NULL;
m_size = 1U; // the size of one node is 1.
}
virtual ~RBSTNode(){}
string setKey(const Key& key){return Key(key);}
RBSTNode* left(){return m_left; }
RBSTNode* right(){return m_right;}
RBSTNode* setLeft(RBSTNode* left) { m_left = left; return this; }
RBSTNode* setRight(RBSTNode* right) { m_right =right; return this; }
#ifdef DEBUG
ostream& print(ostream& out)
{
out << "Key(" << *this << ", m_size: " << m_size << ")";
return out;
}
#endif
unsigned int size() { return m_size; }
void setSize(unsigned int val)
{
#ifdef DEBUG
this->print(cout);
cout << "::setSize(" << val << ") called." << endl;
#endif
if (val == 0) throw "Cannot set the size below 1, then just delete this node.";
m_size = val;
}
void incSize() {
#ifdef DEBUG
this->print(cout);
cout << "::incSize() called" << endl;
#endif
m_size++;
}
void decrSize()
{
#ifdef DEBUG
this->print(cout);
cout << "::decrSize() called" << endl;
#endif
if (m_size == 1) throw "Cannot decrement size below 1, then just delete this node.";
m_size--;
}
#ifdef DEBUG
unsigned int size(RBSTNode* x);
#endif
private:
RBSTNode(){}
RBSTNode* m_left;
RBSTNode* m_right;
unsigned int m_size;
};
class RBST : public DataStructure
{
public:
RBST() {
m_size = 0;
m_head = NULL;
srand(time(0));
};
virtual ~RBST() {};
/**
* Tries to add key into the tree and will return
* true for a new item added
* false if the key already is in the tree.
*
* Will also have the side-effect of printing to the console if v=true.
*/
bool add(const Key& key, bool v=false);
/**
* Same semantics as other add function, but takes a string,
* but diff name, because that'll cause an ambiguity because of inheritance.
*/
bool addString(const string& key);
/**
* Deletes a key from the tree if that key is in the tree.
* Will return
* true for success and
* false for failure.
*
* Will also have the side-effect of printing to the console if v=true.
*/
bool del(const Key& key, bool v=false);
/**
* Tries to find the key in the tree and will return
* true if the key is in the tree and
* false if the key is not.
*
* Will also have the side-effect of printing to the console if v=true.
*/
bool find(const Key& key, bool v = false);
unsigned int count() { return m_size; }
#ifdef DEBUG
int dump(char sep = ' ');
int dump(RBSTNode* target, char sep);
unsigned int size(RBSTNode* x);
#endif
private:
RBSTNode* randomAdd(RBSTNode* target, const Key& key);
RBSTNode* addRoot(RBSTNode* target, const Key& key);
RBSTNode* rightRotate(RBSTNode* target);
RBSTNode* leftRotate(RBSTNode* target);
RBSTNode* del(RBSTNode* target, const Key& key);
RBSTNode* join(RBSTNode* left, RBSTNode* right);
RBSTNode* find(RBSTNode* target, const Key& key);
RBSTNode* m_head;
unsigned int m_size;
};
#endif /*RBST_H_*/
```
\*\* RBST.cpp \*\*
```
#include "RBST.h"
bool RBST::add(const Key& key, bool v){
unsigned int oldSize = m_size;
m_head = randomAdd(m_head, key);
if (m_size > oldSize){
if(v) cout<<"Node "<<key<< " is added into the tree."<<endl;
return true;
}else {
if(v) cout<<"Node "<<key<< " is already in the tree."<<endl;
return false;
}
if(v) cout<<endl;
};
bool RBST::addString(const string& key) {
return add(Key(key), false);
}
bool RBST::del(const Key& key, bool v){
unsigned oldSize= m_size;
m_head = del(m_head, key);
if (m_size < oldSize) {
if(v) cout<<"Node "<<key<< " is deleted from the tree."<<endl;
return true;
}
else {
if(v) cout<< "Node "<<key<< " is not in the tree."<<endl;
return false;
}
};
bool RBST::find(const Key& key, bool v){
RBSTNode* ret = find(m_head, key);
if (ret == NULL){
if(v) cout<< "Node "<<key<< " is not in the tree."<<endl;
return false;
}else {
if(v) cout<<"Node "<<key<< " is in the tree."<<endl;
return true;
}
};
#ifdef DEBUG
int RBST::dump(char sep){
int ret = dump(m_head, sep);
cout<<"SIZE: " <<ret<<endl;
return ret;
};
int RBST::dump(RBSTNode* target, char sep){
if (target == NULL) return 0;
int ret = dump(target->left(), sep);
cout<< *target<<sep;
ret ++;
ret += dump(target->right(), sep);
return ret;
};
#endif
/**
* Rotates the tree around target, so that target's left
* is the new root of the tree/subtree and updates the subtree sizes.
*
*(target) b (l) a
* / \ right / \
* a ? ----> ? b
* / \ / \
* ? x x ?
*
*/
RBSTNode* RBST::rightRotate(RBSTNode* target) // private
{
if (target == NULL) throw "Invariant failure, target is null"; // Note: may be removed once tested.
if (target->left() == NULL) throw "You cannot rotate right around a target whose left node is NULL!";
#ifdef DEBUG
cout <<"Right-rotating b-node ";
target->print(cout);
cout << " for a-node ";
target->left()->print(cout);
cout << "." << endl;
#endif
RBSTNode* l = target->left();
int as0 = l->size();
// re-order the sizes
l->setSize( l->size() + (target->right() == NULL ? 0 : target->right()->size()) + 1); // a.size += b.right.size + 1; where b.right may be null.
target->setSize( target->size() -as0 + (l->right() == NULL ? 0 : l->right()->size()) ); // b.size += -a_0_size + x.size where x may be null.
// swap b's left (for a)
target->setLeft(l->right());
// and a's right (for b's left)
l->setRight(target);
#ifdef DEBUG
cout << "A-node size: " << l->size() << ", b-node size: " << target->size() << "." << endl;
#endif
// return the new root, a.
return l;
};
/**
* Like rightRotate, but the other way. See docs for rightRotate(RBSTNode*)
*/
RBSTNode* RBST::leftRotate(RBSTNode* target)
{
if (target == NULL) throw "Invariant failure, target is null";
if (target->right() == NULL) throw "You cannot rotate left around a target whose right node is NULL!";
#ifdef DEBUG
cout <<"Left-rotating a-node ";
target->print(cout);
cout << " for b-node ";
target->right()->print(cout);
cout << "." << endl;
#endif
RBSTNode* r = target->right();
int bs0 = r->size();
// re-roder the sizes
r->setSize(r->size() + (target->left() == NULL ? 0 : target->left()->size()) + 1);
target->setSize(target->size() -bs0 + (r->left() == NULL ? 0 : r->left()->size()));
// swap a's right (for b's left)
target->setRight(r->left());
// swap b's left (for a)
r->setLeft(target);
#ifdef DEBUG
cout << "Left-rotation done: a-node size: " << target->size() << ", b-node size: " << r->size() << "." << endl;
#endif
return r;
};
//
/**
* Adds a key to the tree and returns the new root of the tree.
* If the key already exists doesn't add anything.
* Increments m_size if the key didn't already exist and hence was added.
*
* This function is not called from public methods, it's a helper function.
*/
RBSTNode* RBST::addRoot(RBSTNode* target, const Key& key)
{
countAdd++;
if (target == NULL) return new RBSTNode(key);
#ifdef DEBUG
cout << "addRoot(";
cout.flush();
target->print(cout) << "," << key << ") called." << endl;
#endif
if (*target < key)
{
target->setRight( addRoot(target->right(), key) );
target->incSize(); // Should I?
RBSTNode* res = leftRotate(target);
#ifdef DEBUG
if (target->size() != size(target))
BUG("in addRoot 1");
#endif
return res;
}
target->setLeft( addRoot(target->left(), key) );
target->incSize(); // Should I?
RBSTNode* res = rightRotate(target);
#ifdef DEBUG
if (target->size() != size(target))
BUG("in addRoot 2");
#endif
return res;
};
/**
* This function is called from the public add(key) function,
* and returns the new root node.
*/
RBSTNode* RBST::randomAdd(RBSTNode* target, const Key& key)
{
countAdd++;
if (target == NULL)
{
m_size++;
return new RBSTNode(key);
}
#ifdef DEBUG
cout << "randomAdd(";
target->print(cout) << ", \"" << key << "\") called." << endl;
#endif
int r = (rand() % target->size()) + 1;
// here is where we add the target as root!
if (r == 1)
{
m_size++; // TODO: Need to lock.
return addRoot(target, key);
}
#ifdef DEBUG
printf("randomAdd recursion part, ");
#endif
// otherwise, continue recursing!
if (*target <= key)
{
#ifdef DEBUG
printf("target <= key\n");
#endif
target->setRight( randomAdd(target->right(), key) );
target->incSize(); // TODO: Need to lock.
#ifdef DEBUG
if (target->right()->size() != size(target->right()))
BUG("in randomAdd 1");
#endif
}
else
{
#ifdef DEBUG
printf("target > key\n");
#endif
target->setLeft( randomAdd(target->left(), key) );
target->incSize(); // TODO: Need to lock.
#ifdef DEBUG
if (target->left()->size() != size(target->left()))
BUG("in randomAdd 2");
#endif
}
#ifdef DEBUG
printf("randomAdd return part\n");
#endif
m_size++; // TODO: Need to lock.
return target;
};
/////////////////////////////////////////////////////////////
///////////////////// DEL FUNCTIONS ////////////////////////
/////////////////////////////////////////////////////////////
/**
* Deletes a node with the passed key.
* Returns the root node.
* Decrements m_size if something was deleted.
*/
RBSTNode* RBST::del(RBSTNode* target, const Key& key)
{
countDelete++;
if (target == NULL) return NULL;
#ifdef DEBUG
cout << "del(";
target->print(cout) << ", \"" << key << "\") called." << endl;
#endif
RBSTNode* ret = NULL;
// found the node to delete
if (*target == key)
{
ret = join(target->left(), target->right());
m_size--;
delete target;
return ret; // return the newly built joined subtree!
}
// store a temporary size before recursive deletion.
unsigned int size = m_size;
if (*target < key) target->setRight( del(target->right(), key) );
else target->setLeft( del(target->left(), key) );
// if the previous recursion changed the size, we need to decrement the size of this target too.
if (m_size < size) target->decrSize();
#ifdef DEBUG
if (RBST::size(target) != target->size())
BUG("in del");
#endif
return target;
};
/**
* Joins the two subtrees represented by left and right
* by randomly choosing which to make the root, weighted on the
* size of the sub-tree.
*/
RBSTNode* RBST::join(RBSTNode* left, RBSTNode* right)
{
if (left == NULL) return right;
if (right == NULL) return left;
#ifdef DEBUG
cout << "join(";
left->print(cout);
cout << ",";
right->print(cout) << ") called." << endl;
#endif
// Find the chance that we use the left tree, based on its size over the total tree size.
// 3 s.d. randomness :-p e.g. 60.3% chance.
bool useLeft = ((rand()%1000) < (signed)((float)left->size()/(float)(left->size() + right->size()) * 1000.0));
RBSTNode* subtree = NULL;
if (useLeft)
{
subtree = join(left->right(), right);
left->setRight(subtree)
->setSize((left->left() == NULL ? 0 : left->left()->size())
+ subtree->size() + 1 );
#ifdef DEBUG
if (size(left) != left->size())
BUG("in join 1");
#endif
return left;
}
subtree = join(right->left(), left);
right->setLeft(subtree)
->setSize((right->right() == NULL ? 0 : right->right()->size())
+ subtree->size() + 1);
#ifdef DEBUG
if (size(right) != right->size())
BUG("in join 2");
#endif
return right;
};
/////////////////////////////////////////////////////////////
///////////////////// FIND FUNCTIONS ///////////////////////
/////////////////////////////////////////////////////////////
/**
* Tries to find the key in the tree starting
* search from target.
*
* Returns NULL if it was not found.
*/
RBSTNode* RBST::find(RBSTNode* target, const Key& key)
{
countFind++; // Could use private method only counting the first call.
if (target == NULL) return NULL; // not found.
if (*target == key) return target; // found (does string override ==?)
if (*target < key) return find(target->right(), key); // search for gt to the right.
return find(target->left(), key); // search for lt to the left.
};
#ifdef DEBUG
unsigned int RBST::size(RBSTNode* x)
{
if (x == NULL) return 0;
return 1 + size(x->left()) + size(x->right());
}
#endif
```
I'll save the SkipList for another time since it's already possible to find good implementations of a SkipList from the links and my version wasn't much different.
The graphs generated from the test-file are as follows:
**Graph showing time taken to add new items for BloomFilter, RBST and SkipList.**
[graph http://haf.se/content/dl/addtimer.png](http://haf.se/content/dl/addtimer.png)
**Graph showing time taken to find items for BloomFilter, RBST and SkipList**
[graph http://haf.se/content/dl/findtimer.png](http://haf.se/content/dl/findtimer.png)
**Graph showing time taken to delete items for BloomFilter, RBST and SkipList**
[graph http://haf.se/content/dl/deltimer.png](http://haf.se/content/dl/deltimer.png)
So as you can see, the random binary search tree was rather a lot better than the SkipList. The bloom filter lives up to its O(k). | Consider the hash-based collections for this, e.g. [`HashSet`](http://msdn.microsoft.com/en-us/library/bb397727.aspx), [`Dictionary`](http://msdn.microsoft.com/en-us/library/xfhwa508.aspx), [`HashTable`](http://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx), which provide constant time performance for adding and removing elements.
More information from the .NET Framework Developer's Guide:
* [Hashtable and Dictionary Collection Types](http://msdn.microsoft.com/en-us/library/4yh14awz.aspx)
* [HashSet Collection Type](http://msdn.microsoft.com/en-us/library/bb397727.aspx) | .net collection for fast insert/delete | [
"",
"c#",
".net",
"collections",
""
] |
My configuration:
* windows XP SP3
* JDBC 2005
* MS SQL Server 2008 Express, exposed via tcp/ip on port 1433
* sqljdbc.jar in class path
I tried:
```
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
con = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433/SQLEXPRESS2008;databaseName=Test;selectMethod=cursor", "sa", "");
}
catch (Exception e) {
e.printStackTrace();
}
```
But it always throws an exception:
```
java.sql.SQLException: No suitable driver
```
I also tried the following urls:
```
localhost:1433/SQLEXPRESS2008
localhost/SQLEXPRESS2008
localhost
```
Same results.
Any help? | You have the wrong URL.
I don't know what you mean by "JDBC 2005". When I looked on the microsoft site, I found something called the [Microsoft SQL Server JDBC Driver 2.0](http://www.microsoft.com/downloads/details.aspx?FamilyID=99b21b65-e98f-4a61-b811-19912601fdc9&displaylang=en). You're going to want that one - it includes lots of fixes and some perf improvements. [edit: you're probably going to want the latest driver. As of March 2012, the latest JDBC driver from Microsoft is [JDBC 4.0]](http://www.microsoft.com/en-us/download/details.aspx?id=11774)
Check the release notes. For this driver, you want:
```
URL: jdbc:sqlserver://server:port;DatabaseName=dbname
Class name: com.microsoft.sqlserver.jdbc.SQLServerDriver
```
It seems you have the class name correct, but the URL wrong.
Microsoft changed the class name and the URL after its initial release of a JDBC driver. The URL you are using goes with the original JDBC driver from Microsoft, the one MS calls the "SQL Server 2000 version". But that driver uses a different classname.
For all subsequent drivers, the URL changed to the form I have here.
This is in the release notes for the JDBC driver. | If your `databaseName` value is correct, then use this: `DriverManger.getconnection("jdbc:sqlserver://ServerIp:1433;user=myuser;password=mypassword;databaseName=databaseName;")` | How can I use the MS JDBC driver with MS SQL Server 2008 Express? | [
"",
"java",
"sql-server",
"jdbc",
""
] |
Assume that you are doing a banking application. If users are logged into your site, how to detect their inactivity and ask them to log out if they remain inactive for a period of time? Inactive here means they have either switch to other tabs, or not touching the browser application.
I guess think I can do this by registering every mouse movement or keyboard movement when users are doing on EVERY page of my application. But the code would be very ugly and hard to maintain. Is there other more elegant ways of doing this? | If the user is requesting new pages/data from your server on a regular basis, then adjusting the session timeout in PHP should work for this (assuming you are using PHP sessions).
If the concern is that they could be sitting on one page for a good length of time with no trips to the server (e.g. filling out a long form), and you want to distinguish between this and the user simply switching to another window, you could do something like use javascript to request some data using XMLHTTPRequest every five minutes or so to keep the session alive. You could use the window.focus and window.onblur events in javascript to stop and restart this mechanism (I think there are some differences for IE, there is a good explanation [here](http://www.thefutureoftheweb.com/blog/detect-browser-window-focus)). | This is the code I use. It is not mine, but I did modify it to it's 'perfection'.
```
// Add the following into your HEAD section
var timer = 0;
function set_interval() {
// the interval 'timer' is set as soon as the page loads
timer = setInterval("auto_logout()", 10000);
// the figure '10000' above indicates how many milliseconds the timer be set to.
// Eg: to set it to 5 mins, calculate 5min = 5x60 = 300 sec = 300,000 millisec.
// So set it to 300000
}
function reset_interval() {
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scroliing
//first step: clear the existing timer
if (timer != 0) {
clearInterval(timer);
timer = 0;
// second step: implement the timer again
timer = setInterval("auto_logout()", 10000);
// completed the reset of the timer
}
}
function auto_logout() {
// this function will redirect the user to the logout script
window.location = "your_logout_script.php";
}
// Add the following attributes into your BODY tag
onload="set_interval()"
onmousemove="reset_interval()"
onclick="reset_interval()"
onkeypress="reset_interval()"
onscroll="reset_interval()"
```
Good luck. | Force Logout users if users are inactive for a certain period of time | [
"",
"php",
"session",
""
] |
I have data in a MSSQL table (TableB) where [dbo].tableB.myColumn changes format after a certain date...
I'm doing a simple Join to that table..
```
Select [dbo].tableB.theColumnINeed from [dbo].tableA
left outer join [dbo].tableB on [dbo].tableA.myColumn = [dbo].tableB.myColumn
```
However, I need to join, using different formatting, based on a date column in Table A ([dbo].tableA.myDateColumn).
Something like...
```
Select [dbo].tableB.theColumnINeed from [dbo].tableA
left outer join [dbo].tableB on [dbo].tableA.myColumn =
IF [dbo].tableA.myDateColumn > '1/1/2009'
BEGIN
FormatColumnOneWay([dbo].tableB.myColumn)
END
ELSE
BEGIN
FormatColumnAnotherWay([dbo].tableB.myColumn)
END
```
I'm wondering if there's a way to do this.. or a better way I'm not thinking of to approach this.. | ```
SELECT [dbo].tableB.theColumnINeed
FROM [dbo].tableA
LEFT OUTER JOIN [dbo].tableB
ON [dbo].tableA.myColumn =
CASE
WHEN [dbo].tableA.myDateColumn <= '1/1/2009' THEN FormatColumnOneWay([dbo].tableB.myColumn)
ELSE FormatColumnAnotherWay([dbo].tableB.myColumn)
END
``` | Rather than having a CASE statement in the JOIN, which will prevent the query using indexes, you could consider using a UNION
```
SELECT [dbo].tableB.theColumnINeed
FROM [dbo].tableA
LEFT OUTER JOIN [dbo].tableB
ON [dbo].tableA.myDateColumn > '1/1/2009'
AND [dbo].tableA.myColumn = FormatColumnOneWay([dbo].tableB.myColumn)
UNION ALL
SELECT [dbo].tableB.theColumnINeed
FROM [dbo].tableA
LEFT OUTER JOIN [dbo].tableB
ON [dbo].tableA.myDateColumn <= '1/1/2009'
AND [dbo].tableA.myColumn = FormatColumnAnotherWay([dbo].tableB.myColumn)
```
but if the FormatColumnOneWay / FormatColumnAnotherWay are functions, or field expressions, that is probably going to exclude use of inxdexes on [myColumn], although any index on myDateColumn should still be used
However, it might help to understand what the FormatColumnOneWay / FormatColumnAnotherWay logic is, as knowning that may enable a better optimisation
Couple of things to note:
UNION ALL will not remove any duplicates (unlike UNION). Because the two sub-queries are mutually exclusive this is OK and saves the SORT step which UNION would make to enable it to remove duplicates.
You should not use '1/1/2009' style for string-dates, you should use 'yyyymmdd' style without and slashes or hyphens (you can also use CONVERT with an parameter to explicitly indicate that the string is in d/m/y or m/d/y style | Dynamic/Conditional SQL Join? | [
"",
"sql",
"sql-server",
"join",
""
] |
I need a method helping me, to reach variables named like "comboBox1", "comboBox2" etc each by each in a loop. I'd like to change code like:
```
//proceed comboBox1
//proceed comboBox2
//proceed comboBox3
//proceed comboBox4
//proceed comboBox5
//proceed comboBox6
```
Into:
```
for (int i = 1; i < numberOfBoxes; i++) {
//proceed comboBox(i)
}
```
I tried to find somthing like 'eval', but google didn't give anything matching. I also tried preprocessing the name with operator ## but it seems there's no way to put current integer value to the macro. | The simplest solution is to put them all in an array and iterator over that:
```
// I've made up a type, but you get the idea.
std::vector<ComboBox *> combos;
combos.insert(comboBox1);
combos.insert(comboBox2);
combos.insert(comboBox3);
combos.insert(comboBox4);
combos.insert(comboBox5);
combos.insert(comboBox6);
```
Now you can iterate over combos. The main problem is that c++ doesn't have reflection. So you can't generated a string at runtime and get the address of an object or function like you can in some other languages.
EDIT: I just saw that you are using Qt. In that case, you should use:
```
QList<T> qFindChildren ( const QObject * obj, const QString & name );
```
or
```
QList<T> qFindChildren ( const QObject * obj, const QRegExp & regExp);
```
This lets you **get a list based on runtime generated names**. For example:
```
QList<QComboBox *> combos = qFindChildren(ui, QRegExp("combo[0-9]+"));
```
then you can just iterate over that! | The only way I know how to do that is by creating them in the code/dynamically and in an array. (Not through the wizard) You are not alone in finding this shortcoming of the MFC (I presume) wizard thing.
As an alternative, if your resources are sequential in the resource file (again I am assuming MFC-like implementation) you can iterate through the resource IDs to get the resources. This assumes they have sequential resource IDs. I have used this method lately. It workd fine. Not sure if it is what you are looking for or will work with your GUI. | How to reach iteratively few variables which names differ only by number in C++? | [
"",
"c++",
"variables",
"naming",
""
] |
Is there is Simple way to read and write Xml in Java?
I've used a SAX parser before but I remember it being unintuitive, I've looked at a couple of tutorials for JAXB and it just looks complicated.
I don't know if I've been spoilt by C#'s XmlDocument class, but All I want to do is create an Xml Document that represents a a set of classes and their members (some are attributes some are elements).
I would look into serialization but the XML has to have the same format as the output of a c# app which I am reverse engineering into Java. | I recommend [XOM](http://www.xom.nu/). Its API is clear and intuitive. | You should check out [Xstream](http://xstream.codehaus.org/). There is a 2 minute tutorial that is really [simple](http://xstream.codehaus.org/tutorial.html). To get the same format, you would model the classes the same. | Simple way to do Xml in Java | [
"",
"java",
"xml",
"serialization",
""
] |
I have been getting the error "The required version of the .NET Framework is not installed on this computer." (Event Id 4096 in Event log) when trying to install a VSTO application from both a ClickOnce deployment and a local copy. This is interesting as the .NET framework is installed (on my 32bit Windows 7 PC) and the VSTO application was developed on the self same machine (and works in Visual Studio 2008).
Does anybody has an idea why I could get this exception?
> Name: From:
> <http://localhost/BlaBla.vsto>
>
> "The required version of the .NET
> Framework is not installed on this
> computer."
>
> \*\*\*\*\*\*\*\*\*\*\*\*\*\* Exception Text \*\*\*\*\*\*\*\*\*\*\*\*\*\* Microsoft.VisualStudio.Tools.Applications.Deployment.InstallAddInFailedException:
> "The required version of the .NET
> Framework is not installed on this
> computer." at
> Microsoft.VisualStudio.Tools.Applications.Deployment.ClickOnceAddInDeploymentManager.InstallAddIn()
> at
> Microsoft.VisualStudio.Tools.Office.Runtime.SolutionInstaller.<>c\_\_DisplayClass7.b\_\_0() | After checking of the obvious causes (see comments) it seems to leave Windows 7 as the cause. Despite lots of people 'switching' to Win7 it's still a beta.
A few points come to mind:
* can you check the clickonce install on XP or Vista?
* do you have AutoUpdates turned on? | Hey all, I was updating one of my own plugins and ran into this as well, so I thought I'd ask some friends internally :-). Here's the skinny...
The following file is missing in Win7RC .NET distribution (this is known and being addressed):
%ProgramFiles%\Reference Assemblies\Microsoft\Framework\v3.5\RedistList\FrameworkList.xml
Copy that file from a non Win7 machine (same location) to the Win7 box and your publish should work.
I'm traveling and haven't verified yet (don't have a non Win7 box near me), but wanted to post this for you all.
Hope this helps!
-th | ClickOnce: The required version of the .NET Framework is not installed on this computer | [
"",
"c#",
".net-3.5",
"clickonce",
"vsto",
""
] |
Does anyone know how to set font and color on a static text and other controls of MFC dialog for Windows Mobile?
Where can I get the list of supported fonts?
Thanks! | Colors are changed via [SetBkColor](http://msdn.microsoft.com/en-us/library/aa920825.aspx) and [SetTextColor](http://msdn.microsoft.com/en-us/library/aa911461.aspx).
[Here is an example](http://blog.opennetcf.com/ctacke/2007/06/22/EnumeratingAndAddingFontsInWindowsCE.aspx) of enumerating fonts. | It depends on the control, but take a look at the Windows messages starting with WM\_CTLCOLOR (e.g., WM\_CTLCOLORSTATIC). For the fonts, use EnumFontFamilies. | How to change font/color on MFC dialog for Windows Mobile? | [
"",
"c++",
"windows-mobile",
"mfc",
""
] |
So I am making a piece of software in WPF, and I want to be able to make graphs out of the data I am storing. Just line graphs with x and y axises. Ideally I would want them to have a nice elegant simplicity to them.
I know WPF doesn't come with graphs, and I have tried ZedGraph in a WinForms project, but I thought frankly it looked ugly.
What is the best way to make simple, elegant graphs in WPF? | The WPF Toolkit is available. It is free from CodePlex. It contains some nice charting classes.
It can be downloaded [here](http://wpf.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=29117).
There is some commentary [here](http://blogs.msdn.com/delay/archive/2009/06/25/wpf-charting-it-s-official-june-2009-release-of-the-wpf-toolkit-is-now-available.aspx). | Try [VisiFire](http://www.VisiFire.com). It looks good. It works well.
 | What is the best way to make a graph in WPF? (or in general that would apply to WPF as well) | [
"",
"c#",
".net",
"wpf",
""
] |
What I am trying to do is save a Move objects into a Vector called topMoves. There will be many Move objects which is why I create the object within the loop.
The pastPriceMap stores prices for stocks at some past time (in this case one minute ago). The currPriceMap stores price for stocks some time within the last second.
I get the following exception:
Exception in thread "Timer-0" java.util.NoSuchElementException
This is the line that is causing the problem:
amove.setInitPrice(pastPriceMap.get(iter.next()));
The code snippet is below. When I do the System.out.println statements I get the expected output:
```
Iterator<String> iter = sortedTopCodes.iterator();
while(iter.hasNext()){
System.out.println(currPriceMap.get(iter.next()));
System.out.println(pastPriceMap.get(iter.next()));
Move amove = new Move();
amove.setSecCode(iter.next());
amove.setPrice(currPriceMap.get(iter.next()));
amove.setInitPrice(pastPriceMap.get(iter.next()));
topMoves.add(amove);
}
return topMoves;
```
---
The Move class looks like this:
```
private String secCode;
private double price;
private double initPrice;
public String getSecCode() {
return secCode;
}
public void setSecCode(String secCode) {
this.secCode = secCode;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getInitPrice() {
return initPrice;
}
public void setInitPrice(double lastPrice) {
this.initPrice = lastPrice;
}
``` | Short answer:
For each call to **hasNext()** there should be only one call to **next()**
In your code you have 5 **next()** with only one **hasNext()**
Here, read this: <http://java.sun.com/javase/6/docs/api/java/util/Iterator.html>
**EDIT**
Longer answer:
Basically an iterator is used to ... well iterate the elements of "something" tipically a collection but it could be anything ( granted that anything returns an Iterator ).
Since you may not know **how many elements** does that "anything" have, there must be a way to stop iterating right? ( if it was an array, you can tell by the length property, but the iterator is used to "encapsulate" the data structure used in the implementation ) Anyway.
The iterator API defines these two methods
```
-hasNext(): boolean
-next(): Object ( or <E> since Java 1.5 )
```
So the typical idiom is this:
```
while( iterator.hasNext() ) { // reads: while the iterator has next element
Object o = iterator.next(); // give me that element
}
```
What happens if the iterator has only two items?
```
while( iterator.hasNext() ) { // the first time will return true, so the next line will be executed.
Object o = iterator.next(); // give me that item. ( 1st element )
Object b = iterator.next(); // oops dangerous by may work ... ( 2nd element )
Object c = iterator.next(); // eeeerhhh... disaster: NoSuchElementException is thrown.
}
```
This is what is happening to you. You did not verify if the iterator has another element, you just retrieve it. If the iterator happens to have some elements, it may work for a while but there will be a time ( as you just saw ) when it fails.
By the way, **DO NOT** even think in catching NoSuchElementException. That's a runtime exception and it indicates that something in your code logic should be fixed.
See [this answer](https://stackoverflow.com/questions/462501/exception-other-than-runtimeexception/462745#462745) to know more about the exceptions. | Here is a version using the new for loops:
```
for ( String secCode : secCodeList ) {
System.out.println(currPriceMap.get(secCode));
System.out.println(pastPriceMap.get(secCode));
Move amove = new Move();
amove.setSecCode(secCode);
amove.setPrice(currPriceMap.get(secCode));
amove.setInitPrice(pastPriceMap.get(secCode));
topMoves.add(amove);
}
```
in the older fashion :
```
String secCode = null;
for ( Iterator<String> it = secCodeList.iterator(); it.hasNext() ) {
secCode = it.next();
System.out.println(currPriceMap.get(secCode));
System.out.println(pastPriceMap.get(secCode));
Move amove = new Move();
amove.setSecCode(secCode);
amove.setPrice(currPriceMap.get(secCode));
amove.setInitPrice(pastPriceMap.get(secCode));
topMoves.add(amove);
}
``` | NoElementException but I print the element and get the expected result | [
"",
"java",
"exception",
"vector",
"logic",
""
] |
I'm currently writing a Simulated Annealing code to solve a traveling salesman problem and have run into difficulties with storing and using my read data from a txt file. Each row & column in the file represents each city, with the distance between two different cities stored as a 15 x 15 matrix:
```
0.0 5.0 5.0 6.0 7.0 2.0 5.0 2.0 1.0 5.0 5.0 1.0 2.0 7.1 5.0
5.0 0.0 5.0 5.0 5.0 2.0 5.0 1.0 5.0 6.0 6.0 6.0 6.0 1.0 7.1
5.0 5.0 0.0 6.0 1.0 6.0 5.0 5.0 1.0 6.0 5.0 7.0 1.0 5.0 6.0
6.0 5.0 6.0 0.0 5.0 2.0 1.0 6.0 5.0 6.0 2.0 1.0 2.0 1.0 5.0
7.0 5.0 1.0 5.0 0.0 7.0 1.0 1.0 2.0 1.0 5.0 6.0 2.0 2.0 5.0
2.0 2.0 6.0 2.0 7.0 0.0 5.0 5.0 6.0 5.0 2.0 5.0 1.0 2.0 5.0
5.0 5.0 5.0 1.0 1.0 5.0 0.0 2.0 6.0 1.0 5.0 7.0 5.0 1.0 6.0
2.0 1.0 5.0 6.0 1.0 5.0 2.0 0.0 7.0 6.0 2.0 1.0 1.0 5.0 2.0
1.0 5.0 1.0 5.0 2.0 6.0 6.0 7.0 0.0 5.0 5.0 5.0 1.0 6.0 6.0
5.0 6.0 6.0 6.0 1.0 5.0 1.0 6.0 5.0 0.0 7.0 1.0 2.0 5.0 2.0
5.0 6.0 5.0 2.0 5.0 2.0 5.0 2.0 5.0 7.0 0.0 2.0 1.0 2.0 1.0
1.0 6.0 7.0 1.0 6.0 5.0 7.0 1.0 5.0 1.0 2.0 0.0 5.0 6.0 5.0
2.0 6.0 1.0 2.0 2.0 1.0 5.0 1.0 1.0 2.0 1.0 5.0 0.0 7.0 6.0
7.0 1.0 5.0 1.0 2.0 2.0 1.0 5.0 6.0 5.0 2.0 6.0 7.0 0.0 5.0
5.0 7.0 6.0 5.0 5.0 5.0 6.0 2.0 6.0 2.0 1.0 5.0 6.0 5.0 0.0
```
To read this I have a LoadCities() function as shown below:
```
#include "iostream"
#include "fstream"
#include "string"
using namespace std;
double distances [15][15];
void LoadCities()
{
ifstream CityFile;
if (!CityFile.is_open()) //check is file has been opened
{
CityFile.open ("Cities.txt", ios::in | ios::out);
if (!CityFile)
{
cerr << "Failed to open " << CityFile << endl;
exit(EXIT_FAILURE); //abort program
}
}
int length;
char * buffer;
string cities;
CityFile.seekg(0, ios::end);
length = CityFile.tellg();
CityFile.seekg (0, ios::beg);
buffer = new char [length];
cities = CityFile.read (buffer,length);
string rows = strtok(cities, "\n");
distances = new double[rows.length()][rows.length()];
for (int i = 0; i < (string) rows.length(); i++)
{
string distance = strtok(rows[i], " ");
for (int j = 0; j < distance.length(); j++)
{
distances[i][j] = (double) Parse(distance[j]);
}
}
CityFile.close();
}
```
I've attempted an alternative istreambuf\_iterator method to get to the point of manipulating the read material into arrays, however I always seem to run into complications:
```
ifstream CityFile("Cities.txt");
string theString((std::istreambuf_iterator<char>(CityFile)), std::istreambuf_iterator<char>());
```
Any help would be much appriciated. Been bashing my head against this with little success!
################ EDIT / Update
@ SoapBox - Some Detail of the SA code, functions and main(). This is not clean, efficient, tidy and isn't ment to be at this stage, just needs to work for the moment. This version (below) works and is setup to solve polynomials (simplest problems). What needs to be done to convert it to a Traveling Salesman Problem is to:
1. Write the LoadCities() function to gather the distance data. (Current)
2. Change Initialise() to get the Total of the distances involved
3. Change E() to the TSP function (e.g. Calculate distance of a random route)
The latter two I know I can do, however I require LoadCities() to do it. Nothing else needs to be changed in the following script.
```
#include "math.h"
#include "iostream"
#include "fstream"
#include "time.h" // Define time()
#include "stdio.h" // Define printf()
#include "randomc.h" // Define classes for random number generators
#include "mersenne.cpp" // Include code for the chosen random number generator
using namespace std; // For the use of text generation in application
double T;
double T_initial;
double S;
double S_initial;
double S_current;
double S_trial;
double E_current;
int N_step; // Number of Iterations for State Search per Temperature
int N_max; //Number of Iterations for Temperature
int Write;
const double EXP = 2.718281828;
//------------------------------------------------------------------------------
//Problem Function of Primary Variable (Debugged 17/02/09 - Works as intended)
double E(double x) //ORIGNINAL
{
double y = x*x - 6*x + 2;
return y;
}
//------------------------------------------------------------------------------
//Random Number Generation Function (Mod 19/02/09 - Generated integers only & fixed sequence)
double Random_Number_Generator(double nHigh, double nLow)
{
int seed = (int)time(0); // Random seed
CRandomMersenne RanGen(seed); // Make instance of random number generator
double fr; // Random floating point number
fr = ((RanGen.Random() * (nHigh - nLow)) + nLow); // Generatres Random Interger between nLow & nHigh
return fr;
}
//------------------------------------------------------------------------------
//Initializing Function (Temp 17/02/09)
void Initialize() //E.g. Getting total Distance between Cities
{
S_initial = Random_Number_Generator(10, -10);
cout << "S_Initial: " << S_initial << endl;
}
//------------------------------------------------------------------------------
//Cooling Schedule Function (make variables) (Completed 16/02/09)
double Schedule(double Temp, int i) // Need to find cooling schedule
{
double CoolingRate = 0.9999;
return Temp *= CoolingRate;
}
//------------------------------------------------------------------------------
//Next State Function (Mod 18/02/09)
double Next_State(double T_current, int i)
{
S_trial = Random_Number_Generator(pow(3, 0.5), pow(3, 0.5)*-1);
S_trial += S_current;
double E_t = E(S_trial);
double E_c = E(S_current);
double deltaE = E_t - E_c; //Defines gradient of movement
if ( deltaE <= 0 ) //Downhill
{
S_current = S_trial;
E_current = E_t;
}
else //Uphill
{
double R = Random_Number_Generator(1,0); //pseudo random number generated
double Ratio = 1-(float)i/(float)N_max; //Control Parameter Convergence to 0
double ctrl_pram = pow(EXP, (-deltaE / T_current)); //Control Parameter
if (R < ctrl_pram*Ratio) //Checking
{
S_current = S_trial; //Expresses probability of uphill acceptance
E_current = E_t;
}
else
E_current = E_c;
}
return S_current;
}
//------------------------------------------------------------------------------
//Metropolis Function (Mod 18/02/09)
double Metropolis(double S_start, double T_current, int N_Steps, int N_temperatures)
{
S_current = S_start; //Initialised S_initial equated to S_current
for ( int i=1; i <= N_step; i++ ) //Iteration of neighbour states
S_current = Next_State(T_current, N_temperatures); //Determines acceptance of new states
return S_current;
}
//------------------------------------------------------------------------------
//Write Results to Notepad (Completed 18/02/09)
void WriteResults(double i, double T, double x, double y)
{
//This function opens a results file (if not already opened)
//and stores results for one time step
static ofstream OutputFile;
const int MAXLENGTH = 80;
if (!OutputFile.is_open()) //check is file has been opened
{
//no it hasn't. Get a file name and open it.
char FileName[MAXLENGTH];
//read file name
cout << "Enter file name: ";
do
{
cin.getline(FileName, MAXLENGTH);
}
while (strlen(FileName) <= 0); //try again if length of string is 0
//open file
OutputFile.open(FileName);
// check if file was opened successfully
if (!OutputFile)
{
cerr << "Failed to open " << FileName << endl;
exit(EXIT_FAILURE); //abort program
}
OutputFile << "Iterations" << '\t' << "Temperatures" << '\t' << "X-Value" << '\t' << "Y-Value" << endl;
OutputFile << endl;
}
//OutputFile.width(10);
OutputFile << i << '\t' << T << '\t' << x << '\t' << y << endl;
if (i == N_max)
{
OutputFile << endl
<< "Settings: " << endl
<< "Initial Temperature: " << T_initial << endl
<< "Temperature Iterations: " << N_max << endl
<< "Step Iterations: " << N_step << endl
<< endl
<< "Results: " << endl
<< "Final Temperature: " << T << endl
<< "Minimum: " << S << endl;
OutputFile.close();
}
}
//------------------------------------------------------------------------------
//Main SA Function (Mod 17/02/09)
void SA(int W)
{
S = S_initial;
T = T_initial;
for ( int N_temperatures = 1 ; N_temperatures <= N_max ; N_temperatures++ )
{
S = Metropolis( S, T, N_step, N_temperatures);
T = Schedule(T, N_temperatures);
if (W == 1)
WriteResults(N_temperatures, T, S, E_current);
}
cout << "Result" << endl
<< "Y-value> " << S << endl
<< "Temperature> " << T << endl;
}
//------------------------------------------------------------------------------
//Execution of Traveling Salesman Problem (Progress 18/02/09)
int main()
{
cout << "Quadratic Function" << endl
<< "Solving method: Simulated Annealing" << endl;
cout << "" << endl;
cout << "Select desired Initial Temperature:" << endl
<< "> ";
cin >> T_initial;
cout << "Select desired number of Temperature Iterations:" << endl
<< "> ";
cin >> N_max;
cout << "Select desired number of step Iterations:" << endl
<< "> ";
cin >> N_step;
Initialize();
cout << "Write to file: (1 / 0) " << endl
<< "> ";
cin >> Write;
SA(Write);
system ("PAUSE");
return 0;
}
```
@ strager - I know its bad code, but unfortunatly with the time constraints involved for my project and the consiquental learning curve, results are what are needed! :) It'll be tidied up at latter stages.
@ dirkgently - That was the initial reason for doing it this way, and hence why my first attempt is to go at it like so. | How about this? ([KISS](http://en.wikipedia.org/wiki/KISS_principle) solution)
```
void LoadCities() {
int x, y;
ifstream in("Cities.txt");
if (!in) {
cout << "Cannot open file.\n";
return;
}
for (y = 0; y < 15; y++) {
for (x = 0; x < 15; x++) {
in >> distances[x][y];
}
}
in.close();
}
```
Works for me. Might not be that complex and perhaps isn't very performant, but as long as you aren't reading a 1000x1000 array, you won't see any difference. | You probably want something simpler, like this:
```
std::vector<std::vector<std::string> > LoadCities(const std::string &filename)
{
using namespace std;
ifstream file;
file.open(filename, ios::in | ios::out);
if(!file.is_open()) {
// error
return vector<vector<double> >();
}
vector<vector<double> > data;
string line;
while(!std::getline(file, line, '\n').eof()) {
istringstream reader(line);
vector<double> lineData;
string::const_iterator i = line.begin();
while(!reader.eof()) {
double val;
reader << val;
if(reader.fail())
break;
lineData.push_back(val);
}
data.push_back(lineData);
}
return data;
}
```
Basically you use streams to input the data. I'm probably doing something wrong (I have never dealt with iostreams ;P) but this should give you the general idea of how to structure a matrix reader. | Reading a Matrix txt file and storing as an array | [
"",
"c++",
"matrix",
"ifstream",
""
] |
I want to know why we can't have "char" as underlying enum type.
As we have byte,sbyte,int,uint,long,ulong,short,ushort as underlying
enum type.
Second what is the default underlying type of an enum? | The default type is int. More information at the C# [reference](http://msdn.microsoft.com/en-us/library/sbbt4032.aspx) at MSDN. You can also find a link to the [C# language specification](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx) at MSDN. I think the reason for the restriction probably derives from these statements in the language specification, section 4.1.5.
> The char type is classified as an
> integral type, but it differs from the
> other integral types in two ways:
>
> • There are no implicit conversions
> from other types to the char type. In
> particular, even though the sbyte,
> byte, and ushort types have ranges of
> values that are fully representable
> using the char type, implicit
> conversions from sbyte, byte, or
> ushort to char do not exist.
>
> • Constants of the char type must be
> written as character-literals or as
> integer-literals in combination with a
> cast to type char. For example,
> (char)10 is the same as '\x000A'. | I know this is an older question, but this information would have been helpful to me:
It appears that there is no problem using char as the value type for enums in C# .NET 4.0 (possibly even 3.5, but I haven't tested this). Here's what I've done, and it completely works:
```
public enum PayCode {
NotPaid = 'N',
Paid = 'P'
}
```
Convert Enum to char:
```
PayCode enumPC = PayCode.NotPaid;
char charPC = (char)enumPC; // charPC == 'N'
```
Convert char to Enum:
```
char charPC = 'P';
if (Enum.IsDefined(typeof(PayCode), (int)charPC)) { // check if charPC is a valid value
PayCode enumPC = (PayCode)charPC; // enumPC == PayCode.Paid
}
```
Works like a charm, just as you would expect from the char type! | Why we can't have "char" enum types | [
"",
"c#",
"enums",
"char",
""
] |
I have a C# app and I need to convert between 3 different units (say for example: litres, gallons, and pints).
The app needs to know about certain volumes of liquid, say: 1 pint, 10 pints, 20 pints and 100 pints. I intend to do the calculations and hard code the values (not ideal but necessary),
I'm looking for a data structure that will allow me to easily convert from one unit to another.
Any suggestions?
Please note: I'm not *actually* using volumes of liquid, its just an example! | You can store a matrix of conversion factors where
* a: Is litres
* b: Is pints
* c: Are gallons
You'd have (not accurate, but assuming there are two pints to a litre and 4 litres to a gallon)
```
a b c
a 1 2 0.25
b 0.5 1 0.125
c 4 8 1
```
Alternatively, you can decide that everything is converted to a base value (litres) before being converted to another type, then you just need the first line.
Wrap this in a method that takes a number of units and "from" type and "two" type for the conversion.
Hope this helps
**EDIT:** some code, as requested
```
public enum VolumeType
{
Litre = 0,
Pint = 1,
Gallon = 2
}
public static double ConvertUnits(int units, VolumeType from, VolumeType to)
{
double[][] factor =
{
new double[] {1, 2, 0.25},
new double[] {0.5, 1, 0.125},
new double[] {4, 8, 1}
};
return units * factor[(int)from][(int)to];
}
public static void ShowConversion(int oldUnits, VolumeType from, VolumeType to)
{
double newUnits = ConvertUnits(oldUnits, from, to);
Console.WriteLine("{0} {1} = {2} {3}", oldUnits, from.ToString(), newUnits, to.ToString());
}
static void Main(string[] args)
{
ShowConversion(1, VolumeType.Litre, VolumeType.Litre); // = 1
ShowConversion(1, VolumeType.Litre, VolumeType.Pint); // = 2
ShowConversion(1, VolumeType.Litre, VolumeType.Gallon); // = 4
ShowConversion(1, VolumeType.Pint, VolumeType.Pint); // = 1
ShowConversion(1, VolumeType.Pint, VolumeType.Litre); // = 0.5
ShowConversion(1, VolumeType.Pint, VolumeType.Gallon); // = 0.125
ShowConversion(1, VolumeType.Gallon, VolumeType.Gallon);// = 1
ShowConversion(1, VolumeType.Gallon, VolumeType.Pint); // = 8
ShowConversion(1, VolumeType.Gallon, VolumeType.Litre); // = 4
ShowConversion(10, VolumeType.Litre, VolumeType.Pint); // = 20
ShowConversion(20, VolumeType.Gallon, VolumeType.Pint); // = 160
}
``` | I have done this in an other language by providing the correct access methods (properties):
```
for the class Volume:
AsLitre
AsGallon
AsPint
for the class Distance:
AsInch
AsMeter
AsYard
AsMile
```
One additional advantage is that the internal format does not matter. | C# data structure for multiple unit conversions | [
"",
"c#",
"data-structures",
"units-of-measurement",
""
] |
I am in a situation where I need to expose a Java method as a web service, and I need to choose the technology to do so and I am basically a bit bewildered.
The requirements are:
* Must be runnable in an IBM Java 5.
* Must be deployable as a web application inside an embedded Jetty (currently version 6)
* Must be detachable from an IDE (has previously used the XFire in MyEclipse 5, I'd like a stand-alone version)
* Must be well supported, reasonably fast, and preferrably Open Source.
* Would be really really nice if it was simple to use.
I've seen a multitude of possibilities, CFX (and XFire), Axis 1 and 2, Netbeans 6 (wants Glassfish), JAX-WS (apparently have features with Java 6 which are nice but probably not an option unless it can be retrocompiled), JDeveloper has something, and Eclipse, and I have a hard time getting enough information to make a decision.
I'd appreciate pointers, experiences, recommendations and warnings.
---
The chosen approach is to use Metro 1.4 which works well.
---
I have told others about my experiences with it in <http://archive.midrange.com/java400-l/200902/msg00074.html> and in more detail on <http://archive.midrange.com/java400-l/200904/msg00071.html>
The information is valid for any Servlet 2.4 compatible container (this is probably the most important single technological decision taken in the whole Metro project IMHO :) ) | The JAX-WS [Metro](https://jax-ws.dev.java.net/) stack (the same one that ships with J2EE 1.5+ or J2SE 6+) can be downloaded and used independently of Glassfish. It makes it fairly easy to expose services, as it uses the @Webservice annotation.
The Metro site also has a [page](https://jax-ws.dev.java.net/guide/Developing_with_Eclipse.html) about using it with Eclipse. I also found a [blog post](http://gorik.wordpress.com/2008/03/15/jax-ws-and-jetty/) about getting it to work with Jetty... apparently Jetty embedded can [still be used](http://gorik.wordpress.com/2007/05/12/jax-ws-and-jetty-embedded/) with jetty.xml | A requirement like "expose a Java method as a web service" in most cases means that some kind of remote access is desired, not necessarily Web Services, with the bloated SOAP, WSDL that eventually will make the solution more complicated than it need to be. If the goal is to really create a web service than ideally you should start from WSDL (Contract First). [Even Spring recommends that](http://static.springframework.org/spring-ws/sites/1.5/reference/html/why-contract-first.html).
If you have control over Client and Server side and both are Java, then I would recommend some kind of Remoting. I like Spring Remoting, specially the [binary protocols from Cauho](http://static.springframework.org/spring/docs/2.0.x/reference/remoting.html#remoting-caucho-protocols). The interoperability is very easy, you'll be working with Pojos and, because the data is transfered in binary form, the performance will also be better than a Web Service with XML.
If you don't have control over the client side, then a Simple XML or JSON over HTTP kind of service would be my choice, since XML provides the interoperability. I have used [XStream](http://xstream.codehaus.org/) with success in the past to create a simple XML representation of a Java Object. | Simplest way to expose a given method as a web service - result must be runnable in web container under Java 5 | [
"",
"java",
"web-services",
"jakarta-ee",
""
] |
How can we create a software package, so that
after extracting our software tar ball user can do
the typical steps?
```
$ gunzip < mycode.tar.gz | tar xvf -
$ ./configure
$ make
$ make install
``` | An alternative to the hard to understand GNU/Autools is CMake.
<http://www.cmake.org/cmake/help/examples.html>
e.g. KDE is using it. | Look into the GNU autoconf/automake toolchain. [Here's a free tutorial/book.](http://sourceware.org/autobook/) | Howto create software package in Unix/Linux? | [
"",
"c++",
"unix",
"boilerplate",
"software-packaging",
""
] |
I have following questions regarding strings in C++:
1>> which is a better option(considering performance) and why?
1.
```
string a;
a = "hello!";
```
OR
2.
```
string *a;
a = new string("hello!");
...
delete(a);
```
2>>
```
string a;
a = "less";
a = "moreeeeeee";
```
how exactly memory management is handled in c++ when a bigger string is copied into a smaller string? Are c++ strings mutable? | All the following is what a naive compiler would do. Of course as long as it doesn't change the behavior of the program, the compiler is free to make any optimization.
```
string a;
a = "hello!";
```
First you initialize a to contain the empty string. (set length to 0, and one or two other operations). Then you assign a new value, overwriting the length value that was already set. It may also have to perform a check to see how big the current buffer is, and whether or not more memory should be allocated.
```
string *a;
a = new string("hello!");
...
delete(a);
```
Calling new requires the OS and the memory allocator to find a free chunk of memory. That's slow. Then you initialize it immediately, so you don't assign anything twice or require the buffer to be resized, like you do in the first version.
Then something bad happens, and you forget to call delete, and you have a memory leak, *in addition* to a string that is extremely slow to allocate. So this is bad.
```
string a;
a = "less";
a = "moreeeeeee";
```
Like in the first case, you first initialize a to contain the empty string. Then you assign a new string, and then another. Each of these *may* require a call to new to allocate more memory. Each line also requires length, and possibly other internal variables to be assigned.
Normally, you'd allocate it like this:
```
string a = "hello";
```
One line, perform initialization once, rather than first default-initializing, and then assigning the value you want.
It also minimizes errors, because you don't have a nonsensical empty string anywhere in your program. If the string exists, it contains the value you want.
About memory management, google RAII.
In short, string calls new/delete internally to resize its buffer. That means you *never* need to allocate a string with new. The string object has a fixed size, and is designed to be allocated on the stack, so that the destructor is *automatically* called when it goes out of scope. The destructor then guarantees that any allocated memory is freed. That way, you don't have to use new/delete in your user code, which means you won't leak memory. | It is almost never necessary or desirable to say
```
string * s = new string("hello");
```
After all, you would (almost) never say:
```
int * i = new int(42);
```
You should instead say
```
string s( "hello" );
```
or
```
string s = "hello";
```
And yes, C++ strings are mutable. | Performance on strings initialization in C++ | [
"",
"c++",
"string",
"mutable",
""
] |
I have a program that needs a lot of memory, and it crashes as soon as the 2GB virtual address space is reached. Sysinternals process explorer displays this as "virtual size" column.
How can I determine this "virtual size" with C (or C++) code?
Ok, I have to query a performance counter for "Virtual Bytes". Perfmon shows the query string (or how it is called) as, for example, '\Process(firefox)\Virtuelle Größe' on my German Win XP installation.
How do I determine the query string for the 'current process', and is there a non-localized name for it? | According to [MSDN: Memory Performance Information](http://msdn.microsoft.com/en-us/library/aa965225(VS.85).aspx) `PROCESS_MEMORY_COUNTERS_EX.PrivateUsage` is the same as VM Size in Task Manager in Windows XP. [GetProcessMemoryInfo](http://msdn.microsoft.com/en-us/library/ms683219(VS.85).aspx) should work:
```
PROCESS_MEMORY_COUNTERS_EX pmcx = {};
pmcx.cb = sizeof(pmcx);
GetProcessMemoryInfo(GetCurrentProcess(),
reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmcx), pmcx.cb);
```
Now `pmcx.PrivateUsage` holds the VM Size of the process. | You query a performance counter.
There is a complete API for this in the win32 API, [read about it here](http://msdn.microsoft.com/en-us/library/aa373083(VS.85).aspx).
You can look at all the performance counters if you run a program called 'perfmon.exe' | How to determine a process "virtual size" (WinXP)? | [
"",
"c++",
"c",
"windows",
"memory-management",
""
] |
I know *find* method finds the supplied key in *std::map* and return an iterator to the element. Is there anyway to find the value and get an iterator to the element? What I need to do is to check specified value exist in std::map. I have done this by looping all items in the map and comparing. But I wanted to know is there any better approach for this.
Here is what I have wrote
```
bool ContainsValue(Type_ value)
{
bool found = false;
Map_::iterator it = internalMap.begin(); // internalMap is std::map
while(it != internalMap.end())
{
found = (it->second == value);
if(found)
break;
++it;
}
return found;
}
```
**Edit**
How about using another map internally which stores value,key combination. So I can call find on it? Is *find()* in std::map doing sequential search?
Thanks | You can use [boost::multi\_index](http://www.boost.org/doc/libs/1_37_0/libs/multi_index/doc/index.html) to create a [bidirectional map](http://www.boost.org/doc/libs/1_37_0/libs/multi_index/doc/examples.html) - you can use either value of the pair as a key to do a quick lookup. | If you have access to the excellent [boost](http://www.boost.org/) library then you should be using [boost::multi\_index](http://www.boost.org/doc/libs/1_37_0/libs/multi_index/doc/index.html) to create [bidirectional map](http://www.boost.org/doc/libs/1_37_0/libs/multi_index/doc/examples.html) as Mark says. Unlike a std::map this allows you to look up by either the key or the value.
If you only have the STL to hand the following code will do the trick (templated to work with any kind of map where the mapped\_type supports operator==):
```
#include <map>
#include <string>
#include <algorithm>
#include <iostream>
#include <cassert>
template<class T>
struct map_data_compare : public std::binary_function<typename T::value_type,
typename T::mapped_type,
bool>
{
public:
bool operator() (typename T::value_type &pair,
typename T::mapped_type i) const
{
return pair.second == i;
}
};
int main()
{
typedef std::map<std::string, int> mapType;
mapType map;
map["a"] = 1;
map["b"] = 2;
map["c"] = 3;
map["d"] = 4;
map["e"] = 5;
const int value = 3;
std::map<std::string, int>::iterator it = std::find_if( map.begin(), map.end(), std::bind2nd(map_data_compare<mapType>(), value) );
if ( it != map.end() )
{
assert( value == it->second);
std::cout << "Found index:" << it->first << " for value:" << it->second << std::endl;
}
else
{
std::cout << "Did not find index for value:" << value << std::endl;
}
}
``` | Checking value exist in a std::map - C++ | [
"",
"c++",
"iterator",
"find",
"stdmap",
""
] |
Is it possible to hide the parameterless constructor from a user in C#?
I want to force them to always use the constructor with parameters
e.g. this Position struct
```
public struct Position
{
private readonly int _xposn;
private readonly int _yposn;
public int Xposn
{
get { return _xposn; }
}
public int Yposn
{
get { return _yposn; }
}
public Position(int xposn, int yposn)
{
_xposn = xposn;
_yposn = yposn;
}
}
```
I only want users to be able to new up a Position by specifying the x and y coordinates.
However, the parameterless constructor is ALWAYS available.
I cannot make it private. Or even define it as public.
I have read this:
[Why can't I define a default constructor for a struct in .NET?](https://stackoverflow.com/questions/333829/why-cant-i-define-a-default-constructor-for-a-struct-in-net)
but it doesn't really help.
If this is not possible - what is the best way to detect if the Position I am being passed has values?
Explicitly checking each property field? Is there a slicker way? | No, you can't do this. As you said, [similar question](https://stackoverflow.com/questions/333829) has been asked before - and I thought the answer was fairly clear that you couldn't do it.
You *can* [create a private parameterless constructor for a struct](http://codeblog.jonskeet.uk/2008/12/10/value-types-and-parameterless-constructors), but not in C#. However, even if you do that it doesn't really help - because you can easily work around it:
```
MyStruct[] tmp = new MyStruct[1];
MyStruct gotcha = tmp[0];
```
That will be the default value of MyStruct - the "all zeroes" value - without ever calling a constructor.
You could easily add a Validate method to your struct and call that each time you received one as a parameter, admittedly. | Nope can't hide it. Structs cannot redefine zero arg constructor, so therefore its visibility can't be redefined. | Hide parameterless constructor on struct | [
"",
"c#",
".net",
"struct",
""
] |
I know that Python has a [global lock](http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock) and i've read Glyph's explaination of [python multithreading](https://stackoverflow.com/questions/203912/does-python-support-multiprocessor-multicore-programming/204150#204150). But I still want to try it out. What I decided to do as an easy (conceptually) task was to do horizontal and vertical edge detection on a picture.
Here's what's happening (pseudocode):
```
for pixels in picture:
apply sobel operator horizontal
for pixels in picture:
apply sobel operator vertical
```
[info on sobel operator](http://en.wikipedia.org/wiki/Sobel_operator).
These two loops can run completely independent of each other, and so would be prime candidates for multithreading. (running these two loops on any significantly large picture can take 10+ seconds). However, when I have tried to use the `threading` module in python, it takes twice as long because of the global lock. My question is should I abandon all hope of doing this in two threads in python and try in another language? If i can forge ahead, what module(s) should I use? If not, what language should I experiment in? | Python 2.6 now includes the [**mulitprocessing**](http://docs.python.org/library/multiprocessing.html) module (formerly [**processing**](http://pyprocessing.berlios.de/doc/index.html) module on older versions of Python).
It has essentially the same interface as the **threading** module, but launches the execution into separate processes rather than threads. This allows Python to take advantage of multiple cores/CPUs and scales well for CPU-intensive tasks compared to the threading module approach. | If the sobel operator is CPU-bound, then you won't get any benefit from multiple threads because python does not take advantage of multiple cores.
Conceivably you could spin off multiple processes, though I'm not sure if that would be practical for working on a single image.
10 seconds doesn't seem like a lot of time to waste. If you're concerned about time because you'll be processing many images, then it might be easier to run multiple processes and have each process deal with a separate subset of the images. | practice with threads in python | [
"",
"python",
"multithreading",
"image-manipulation",
""
] |
Is there a way (ideally easy) to make headings and sections autonumber in HTML/CSS? Perhaps a JS library?
Or is this something that is hard to do in HTML?
I'm looking at an application for a corporate wiki but we want to be able to use heading numbers like we always have in word processors. | 2016 update. Please see [Stephen's answer](https://stackoverflow.com/a/535390/35935) below for a proper method in CSS. My answer made sense in 2009 when the browsers and libraries were different. We are now living in a whole new world and the method presented here is outdated. I'm leaving it for the poor souls that are still living in corporate microcosms made of IE7 and tears.
---
See [this other question](https://stackoverflow.com/questions/349060/report-section-style-list-numbering-in-css) if you're wondering how to do it in CSS, the answer might be what you are looking for. But titel has a good proposition too, depending how your HTML document is made.
It should be noted that, as Triptych said in another comment, this is of interest only if it's for an internal tool where you have control over which browsers are used and using CSS is worth it because modifying the HTML would be hard for example. Support of this CSS feature is limited.
It would of course be easy to use something like [jQuery](http://jquery.com/) to do the increment also. Something like this untested snippet:
```
$(document).ready(function() {
$('h1').each(function(index) {
$(this).html((index + 1) + '. ' + $(this).html());
});
});
```
Don't forget to include the jquery.js file in your document of course. | Definitely possible using css counters - just make sure you watch out for browser compatibility...:
This will make h2 get 1., 2., h3 gets 1.1, 2.1, 2.2 etc...
```
<style>
body{counter-reset: section}
h2{counter-reset: sub-section}
h3{counter-reset: composite}
h4{counter-reset: detail}
h2:before{
counter-increment: section;
content: counter(section) " ";
}
h3:before{
counter-increment: sub-section;
content: counter(section) "." counter(sub-section) " ";
}
h4:before{
counter-increment: composite;
content: counter(section) "." counter(sub-section) "." counter(composite) " ";
}
h5:before{
counter-increment: detail;
content: counter(section) "." counter(sub-section) "." counter(composite) "." counter(detail) " ";
}
</style>
```
As lpfavreau says, [it's the same as another question](https://stackoverflow.com/questions/349060/report-section-style-list-numbering-in-css) I believe.
Also note that using css will *not* change the heading (e.g. selected text will give you the heading without the numbers). This may or may not be desirable. lpfavreau's (accepted) answer will give you the jquery code to modify the heading text.
See [MDN: Using CSS counters](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters) for details.
## 3rd Party Edit
I created an [example with the css above](http://plnkr.co/edit/iBNtm5g3tOzvG0CFQhKR?p=preview) | HTML / CSS autonumber headings? | [
"",
"javascript",
"html",
"css",
""
] |
In java there is a possibility of re-throwing the exception but there is any advantage in it? | Sometimes, you want a specific type of Exception to be thrown by a method, but there are rare instances that cause other Exceptions to be thrown within the method. I often wrap the causal Exception with my desired Exception and then rethrow the desired Exception.
This is really useful when you can't determine that the Exception has caused your operation to fail until control is passed to the calling method (or one of its ancestors), since if the process does eventually fail, I can trace back in the stacktrace to see why. | One example of when you want to rethrow an exception is when you don't really know how to handle it yourself, but you'd like to log that the exception was thrown. Rethrowing it allows you to both capture the stack information that you need to log, and pass the exception up the call stack for the caller to handle. | Re-throwing exceptions in Java | [
"",
"java",
""
] |
What's the most reliable, generic way to construct a self-referential URL? In other words, I want to generate the <http://www.site.com[:port]> portion of the URL that the user's browser is hitting. I'm using PHP running under Apache.
A few complications:
* Relying on $\_SERVER["HTTP\_HOST"] is dangerous, because that seems to come straight from the HTTP Host header, which someone can forge.
* There may or may not be virtual hosts.
* There may be a port specified using Apache's Port directive, but that might not be the port that the user specified, if it's behind a load-balancer or proxy.
* The port may not actually be part of the URL. For example, 80 and 443 are usually omitted.
* PHP's $\_SERVER["HTTPS"] doesn't always give a reliable value, especially if you're behind a load-balancer or proxy.
* Apache has a UseCanonicalName directive, which affects the values of the SERVER\_NAME and SERVER\_PORT environment variables. We can assume this is turned on, if that helps. | The most reliable way is to provide it yourself.
The site should be coded to be hostname neutral, but to know about a special configuration file. This file doesn't get put into source control for the codebase because it belongs to the webserver's configuration. The file is used to set things like the hostname and other webserver-specific parameters. You can accomodate load balancers, changing ports, etc, because you're saying if an HTTP request hits that code, then it can assume however much you will let it assume.
This trick also helps development, incidentally. :-) | As I recall, you want to do something like this:
```
$protocol = 'http';
if ( (!empty($_SERVER['HTTPS'])) || ($_SERVER['HTTPS'] == 'off') ) {
$protocol = 'https';
if ($_SERVER['SERVER_PORT'] != 443)
$port = $_SERVER['SERVER_PORT'];
} else if ($_SERVER['SERVER_PORT'] != 80) {
$port = $_SERVER['SERVER_PORT'];
}
// Server name is going to be whatever the virtual host name is set to in your configuration
$address = $protocol . '://' . $_SERVER['SERVER_NAME'];
if (!empty($port))
$address .= ':' . $port
$address .= $_SERVER['REQUEST_URI'];
// Optional, if you want the query string intact
if (!empty($_SERVER['QUERY_STRING']))
$address .= '?' . $_SERVER['QUERY_STRING'];
```
I haven't tested this code, because I don't have PHP handy at the moment. | Self-referential URLs | [
"",
"php",
"apache",
"http",
"cgi",
""
] |
I was looking at the String and Int32 types through the reflector but couldn't find any operators that are defined.
If they aren't defined, how do +/-, etc works on these types? | The numeric operators are part of IL itself. The "+" operator on strings is a bit special though - it's not overloaded by the string type itself, it's done by the compiler. The C# compiler translates:
```
string x = a + "hello" + b;
```
into:
```
string x = string.Concat(a, "hello", b);
```
This is more efficient than if the concatenation had been done using normal operators, because otherwise a new string would have to be created at each concatenation. | The String class has only two, they have CLS compliant names: op\_Equality and op\_Inequality. The compiler has lots of built-in knowledge of the System.String class. Necessary in order to be able to use the Ldstr opcode for one. Likewise, it translates the + operator into String.Concat().
Pretty much the story for Int32, there are direct matches between operators and IL opcodes. | Where are the operations for String , Int32, etc are defined? | [
"",
"c#",
".net",
"string",
""
] |
If you have a disabled button on a winform how can you show a tool-tip on mouse-over to inform the user why the button is disabled? | Sam Mackrill, thanks for your answer, great idea to use the Tag to know what Control you are leaving. However you still need the IsShown flag as per BobbyShaftoe's answer. If you have the mouse in the wrong spot, if the ToolTip comes up under it, it can fire another MouseMove event (even though you did not physically move the mouse). This can cause some unwanted animation, as the tooltip continually disappears and reappears.
Here is my code:
```
private bool toolTipShown = false;
private void TimeWorks_MouseMove(object sender, MouseEventArgs e)
{
var parent = sender as Control;
if (parent == null)
{
return;
}
var ctrl = parent.GetChildAtPoint(e.Location);
if (ctrl != null)
{
if (ctrl.Visible && toolTip1.Tag == null)
{
if (!toolTipShown)
{
var tipstring = toolTip1.GetToolTip(ctrl);
toolTip1.Show(tipstring.Trim(), ctrl, ctrl.Width / 2, ctrl.Height / 2);
toolTip1.Tag = ctrl;
toolTipShown = true;
}
}
}
else
{
ctrl = toolTip1.Tag as Control;
if (ctrl != null)
{
toolTip1.Hide(ctrl);
toolTip1.Tag = null;
toolTipShown = false;
}
}
}
``` | Place the button (or any control that fits this scenario) in a container (panel, tableLayoutPanel), and associate the tooltip to the appropriate underlying panel cell. Works great in a number of scenarios, flexible. Tip: make the cell just large enough to hold the bttn, so mouseover response (tooltip display) doesn't appear to "bleed" outside the bttn borders. | How can I show a tooltip on a disabled button? | [
"",
"c#",
".net",
"winforms",
""
] |
Can anyone please explain me use of throw in exception handling?
What happens when i throw an exception? | It means to "cause" an exception. When you "throw" an exception you are saying "something has gone wrong, here's some details".
You can then "catch" a "thrown" exception to allow your program to degrade gracefully instead of erroring and dying. | "Throwing" an exception is what triggers the entire process of exception handling.
In the course of normal execution, lines in a program are executed sequentially with loops and branches. When an error of some sort happens, an exception is created and then thrown.
A thrown exception will modify the usual order of operations in a program in such a way that no "normal" instructions will be executed until the exception is handled within a "catch" block somewhere. Once an exception is caught in a catch block, and the code within that catch block is executed ("Handling" the exception), normal program execution will resume immediately following the catch block.
```
// Do some stuff, an exception thrown here won't be caught.
try
{
// Do stuff
throw new InvalidOperationException("Some state was invalid.");
// Nothing here will be executed because the exception has been thrown
}
catch(InvalidOperationException ex) // Catch and handle the exception
{
// This code is responsible for dealing with the error condition
// that prompted the exception to be thrown. We choose to name
// the exception "ex" in this block.
}
// This code will continue to execute as usual because the exception
// has been handled.
``` | What is "throw" | [
"",
"c#",
"exception",
"throw",
""
] |
Sorry if this is too little of a challenge to be suited as a stack overflow question, but I'm kind of new to Regular Expressions.
My question is, what is the regular expression that returns the string "token" for all the examples bellow?
* token.domain.com
* token.domain.com/
* token.domain.com/index.php
* token.domain.com/folder/index.php
* token.domain.com/folder/subfolder
* token.domain.com/folder/subfolder/index.php
* **(added after edit)**
* domain.com
* domain.com/
Im trying to use inside an preg\_replace function in order to find out the subdomain of the current page from the $\_SERVER['SERVER\_NAME'] variable.
Thank you in advance,
titel
**Edit note:** Sorry chaos and sebnow , I edited my question, what I initially meant, but forgot to write, was that this would work without any subdomain at all - case in which it would return an empty sting or NULL | ```
preg_replace('/^(?:([^\.]+)\.)?domain\.com$/', '\1', $_SERVER['SERVER_NAME'])
```
**Edit:** What does the following output for you:
```
<?php
echo preg_replace('/^(?:([^\.]+)\.)?domain\.com$/', '\1', "sean.domain.com") . "<br />";
echo preg_replace('/^(?:([^\.]+)\.)?domain\.com$/', '\1', "titel.domain.com") . "<br />";
echo preg_replace('/^(?:([^\.]+)\.)?domain\.com$/', '\1', "domain.com") . "<br />";
?>
``` | The following regex would capture any string before a full stop (the subdomain) and the rest of the domain:
```
^([^.]+)\..*$
```
I don't see the need for regex to do this though. It would be much easier to split by the full stop and get the first element:
```
list($subdomain, $rest) = explode('.', $_SERVER['SERVER_NAME'], 2);
``` | Find out subdomain using Regular Expression in PHP | [
"",
"php",
"regex",
"pcre",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.