Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm calling a method via interop that returns an `out IntPtr` parameter. How can I get a `byte*` for this `IntPtr` so I can operate on it? I tried the following:
```
fixed(byte* ptr = (byte)myIntPtr)
```
but it didn't work. Any help would be appreciated! | You can simply write:
```
byte* ptr = (byte*)int_ptr;
```
You don't have to use the *fixed* keyword. You don't want to pin the IntPtr, do you? | `myIntPtr.ToPointer()` | How to cast IntPtr to byte* | [
"",
"c#",
""
] |
Hi I am trying to redirect all links to any pdf file in my site to a page with a form in it that collects user info before they can proceed to download/view the pdf.
Eg
I want to redirect \*.pdf files in web site to request.php?file=name\_of\_pdf\_being\_redirected
Where request.php is the page with the form on it asking for a few details before proceeding.
All pdf's in the site are held inside /pdf folder.
Any ideas?
EDIT: sorry I'm using Apache on the server.
OK I'M GETTING THERE:
I have it working now using:
RewriteEngine on
RewriteRule ^pdf/(.+.pdf)$ request.php?file=/$1 [R]
But now when it goes to the download page when i want to let the person actually download the file my new rule is spitting the download link back to the form :-P haha so is there anyway to let it download the file once the form has been submitted and you're on download.php? | You can try this:
* Move your files to a folder "outside" your web root so that no one can access it thru a browser
* Use sessions to detect whether a person has completed the form or not
* Use a php powered file download script. In its naivest form, it might look like this:
```
if ( isset( $_SESSION[ 'OK_TO_DOWNLOAD' ] ) == false )
{
header( "Location: must_fill_this_first.php" );
exit( 0 );
}
header( "Content-type: application/pdf" );
// double check the above, google it as i am not sure
echo file_get_contents( 'some_directory_inaccessible_thru_www/' . $_GET[ 'pdf_name' ] );
// ideally a binary-safe function needs to be used above
```
This is a tried and tested technique I used on a website. The code example is a draft outline and needs refinement. | Ideas? You could start by telling us which web/app server you're using, that might help :-)
In Apache, you should be able to use a RewriteRule to morph the request into a different form. For example, turning `/pub/docs/x.pdf` into `request.php?file=/pub/docs/x.pdf` could be done with something like:
```
RewriteRule ^/pdf/(.*)\.pdf/ request.php?file=/$1.pdf
```
Keep in mind this is from memory (six years since I touched Apache and still clean :-), the format may be slightly different.
**Update:**
Now you've got that sorted, here's a couple of options for your next problem.
1/ Rename the PDFs to have a different extension so that they're not caught by the rewrite rule. They should be configured to push out the same MIME type to the client so that they open in the clients choice of viewer.
2/ Do the download as part of the script as well, not as a direct access to the PDF. Since the submission of the form is a HTTP request, you should be able to answer it immediately with the PDF contents rather than re-directing them *again* to the download page.
That second option would be my choice since it:
* stops people figuring out they can get to the PDFs just by requesting xx.pdfx instead of xx.pdf.
* makes it quicker for the person to get the PDF (they don't have to click on the link again). | Redirect files to simple form before downloading | [
"",
"php",
"pdf",
".htaccess",
"redirect",
"url-rewriting",
""
] |
What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: `values` is a list that is not related to any dictionary.
```
for value in values:
new_dict[key_from_value(value)] = value
``` | ```
>>> l = [ 1, 2, 3, 4 ]
>>> dict( ( v, v**2 ) for v in l )
{1: 1, 2: 4, 3: 9, 4: 16}
```
In Python 3.0 you can use a "dict comprehension" which is basically a shorthand for the above:
```
{ v : v**2 for v in l }
``` | At least it's shorter:
```
dict((key_from_value(value), value) for value in values)
``` | Is there a more pythonic way to build this dictionary? | [
"",
"python",
""
] |
I've seen time and time again API (particularly in the .NET framework) that uses `Func<TObject, bool>` when `Predicate<TObject>` is seemingly a perfectly responsible option. What *good* reasons might an API designer have for doing so? | In LINQ, `Func<T, bool>` is used for things like `Where` so that the other overload which takes the index as well as the element is consistent:
```
IEnumerable<T> Where(IEnumerable<T> source, Func<T, bool> predicate)
IEnumerable<T> Where(IEnumerable<T> source, Func<T, int, bool> predicate)
```
Personally I think the name `Predicate` is more descriptive, so *I* would use it in situations where there's no consistency issue like the one above. Mind you, there's something to be said for only needing to know about the `Action` and `Func` delegate types... | Consistency with the rest of LINQ?
(The "anomaly" has been noted, but with anonymous delegates and lambda functions it makes no difference, so almost never need to be aware of the difference.) | Func<TObject, bool> or Predicate<TObject>? | [
"",
"c#",
"linq",
"delegates",
"lambda",
""
] |
I have a library called HelloWorld.so and a program HelloWorld.java with this content:
```
class HelloWorld {
private native void print();
public static void main(String[] args) {
new HelloWorld().print();
}
static {
System.loadLibrary("HelloWorld");
}
}
```
Now when I try to run HelloWorld.java I get this error:
```
$ /usr/java1.4/bin/java HelloWorld
Exception in thread "main"
java.lang.UnsatisfiedLinkError: no HelloWorld in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1491)
at java.lang.Runtime.loadLibrary0(Runtime.java:788)
at java.lang.System.loadLibrary(System.java:834)
at HelloWorld.<clinit>(HelloWorld.java:7)
```
Any tips? | @mmyers Thank you for responding. We found out that all we had to do was change System.loadLibrary to System.load and pass the full path + filename as argument, worked like a charm.
Even before doing so, we tried using the "-D" parameter and setting LD\_LIBRARY\_PATH but we weren't successful.
Go figure! :)
Thanks again,
Karen | I had this problem and fixed it by renaming my library to `libHelloWorld.so` and following Michael Myers's suggestion. I'm on Arch Linux 64-bit.
`HelloWorld.c`:
```
#include <jni.h>
#include <stdio.h>
#include "HelloWorld.h"
/* shamelessly stolen from the book 'The Java Native Interface: Programmer's
Guide and Specification' */
JNIEXPORT void JNICALL
Java_HelloWorld_print (JNIEnv *env, jobject obj) {
printf("Hello World!\n");
}
```
`HelloWorld.java`:
```
class HelloWorld {
private native void print();
public static void main(String[] args) {
new HelloWorld().print();
}
static {
System.loadLibrary("HelloWorld");
}
}
```
Building and testing:
```
$ javac HelloWorld.java
$ javah -classpath . HelloWorld
$ gcc -shared -fPIC -I $JAVA_HOME/include -I $JAVA_HOME/include/linux HelloWorld.c -o libHelloWorld.so
$ java -classpath . -Djava.library.path=. HelloWorld
Hello World!
```
**tl;dr: put `lib` at the beginning of the library's filename** | Why am I getting this UnsatisfiedLinkError with native code? | [
"",
"java",
"native",
""
] |
I would love to use closures in Java. I have read that they may or may not make it into Java 7. But an open-source project called [functional-java](http://code.google.com/p/functionaljava/) has implemented functional features including closures.
How safe would it be to use such a library in an enterprise production app?
Is there a better way to add closures to Java currently? | Closures will definitely not make it into Java 7, due to a lack of consensus around a single implementation. [See here.](http://hamletdarcy.blogspot.com/2008/12/java-7-update-from-mark-reinhold-at.html)
The Functional Java library is thoroughly tested and actively developed. If you browse the source you will see that it's just simple bog-standard Java, and there's not a lot that could go wrong. I know at least one mission-critical enterprise app that uses it in production. This application has more than a million users.
Go for it. | Functional Java does not requires that you use closures -- the source compiles with any Java 1.5 compiler. Functional Java is far more complete than Google collections and just happens to allow you to use it well with BGGA.
Hope this helps. | How safe would it be to use functional-java to add closures to a Java production project? | [
"",
"java",
"functional-programming",
"closures",
"functional-java",
""
] |
1) What is the convention used in practice when typedef'ing
something like
```
typedef std::map<SomeClass*, SomeOtherClass> [SomeStandardName>]
typedef std::map<SomeClass*, std<SomeOtherClass> > <[SomeStandardName]
```
2) Where do you usually put typedef: header files globally, local to the class?
3) Do you typedef iterators or const map<> version?
4) Say you have map that used by two different concepts, do you create two separate typedefs them?
```
typedef map<string, SomeClass *> IDToSomeClassMap;
typedef map<string, SomeClass *> DescriptionToSomeClassMap;
```
Thanks
---
**Edit #1**
I am interested specifically in typedef STL maps, such as
```
typedef map<int, string> IdToDescriptionMap
```
or
```
typedef map<int, string> IdToDescription
```
What are common practices? | I prefer the following convention:
```
typedef std::map< Foo, Bar > FooToBarMap
```
I purposely avoid typedef'ing the iterators, I prefer explicitly referring to them as:
```
FooToBarMap::const_iterator
```
Since the iterators are already a *de facto* standard typename. And FooToBarMapConstIter is actually less clear to read when skimming code, I find. | There is no generally agreed rule on these names. What I usually do is to use the name of the "value" class suffixed with Map. In your example that would be *SomeOtherClassMap*. I use this convention because it is usually more interesting that your map contains "value" objects of type *SomeOtherClass* then that you look them up with "keys" of *SomeClass*. | What is the naming convention when typdef complex STL maps? | [
"",
"c++",
"stl",
""
] |
I have triggers that manipulate and insert a lot of data into a **Change tracking** table for audit purposes on every insert, update and delete.
This trigger does its job very well, by using it we are able to log the desired oldvalues/newvalues as per the business requirements for every transaction.
However in *some* cases where the source table has a lot columns, it can take up to 30 seconds for the transaction to complete which is unacceptable.
*Is there a way to make the trigger run asynchronously?* Any examples. | You can't make the trigger run asynchronously, but you could have the trigger synchronously send a message to a [SQL Service Broker](http://msdn.microsoft.com/en-us/library/ms345108(SQL.90).aspx) queue. The queue can then be processed asynchronously by a stored procedure. | these articles show how to use service broker for async auditing and should be useful:
[Centralized Asynchronous Auditing with Service Broker](http://weblogs.sqlteam.com/mladenp/archive/2007/07/16/60258.aspx)
[Service Broker goodies: Cross Server Many to One (One to Many) scenario and How to troubleshoot it](http://weblogs.sqlteam.com/mladenp/archive/2007/08/21/Service-Broker-goodies-Cross-Server-Many-to-One-One-to.aspx) | Asynchronous Triggers in SQL Server 2005/2008 | [
"",
"sql",
"sql-server",
"sql-server-2005",
"triggers",
""
] |
Is it possible to make a C++ header file (.h) that declares a class, and its public methods, but does not define the private members in that class? I found a [few pages](http://www.eventhelix.com/realtimemantra/HeaderFileIncludePatterns.htm) that say you should declare the class and all its members in the header file, then define the methods separately in you cpp file. I ask because I want to have a class that is defined in a Win32 DLL, and I want it to be properly encapsulated: the internal implementation of that class might change, including its members, but these changes should not affect code that uses the class.
I guess that if I had this, then it would make it impossible for the compiler to know the size of my objects ahead of time. But that should be fine, as long as the compiler is smart enough to use the constructor and just pass around pointers to the location in memory where my object is stored, and never let me run "sizeof(MyClass)".
**Update:** Thanks to everyone who answered! It seems like the pimpl idiom is a good way to achieve what I was talking about. I'm going to do something similar:
My Win32 DLL file will have a bunch of separate functions like this:
```
void * __stdcall DogCreate();
int __stdcall DogGetWeight(void * this);
void __stdcall DogSetWeight(void * this, int weight);
```
This is the typical way the Microsoft writes their DLL files so I think there is probably good reason for it.
But I want to take advantage of the nice syntax C++ has for classes, so I'll write a wrapper class to wrap up all of these functions. It will have one member, which will be "void \* pimpl". This wrapper class will be so simple that I might as well just declare it AND define it in the header file. But this wrapper class really has no purposes other than making the C++ code look pretty as far as I can tell. | I think what you are looking for is something called the "pimpl idiom". To understand how this works, you need to understand that in C++ you can forward declare something like so.
```
class CWidget; // Widget will exist sometime in the future
CWidget* aWidget; // An address (integer) to something that
// isn't defined *yet*
// later on define CWidget to be something concrete
class CWidget
{
// methods and such
};
```
So to forward declare means to promise to fully declare a type later. Its saying "there will be this thing called a CWidget, I promise. I'll tell you more about it later.".
The rules of forward declaration say that you can define a pointer or a reference to something that has been forward declared. This is because pointers and references are really just addresses-a number where this yet-to-be-defined thing will be. Being able to declare a pointer to something without fully declaring it is convenient for a lot of reasons.
Its useful here because you can use this to hide some of the internals of a class using the "pimpl" method. Pimpl means "pointer to implementation". So instead of "widget" you have a class that is the actual implementation. The class you are declaring in your header is just a pass-through to the CImpl class. Here's how it works:
```
// Thing.h
class CThing
{
public:
// CThings methods and constructors...
CThing();
void DoSomething();
int GetSomething();
~CThing();
private:
// CThing store's a pointer to some implementation class to
// be defined later
class CImpl; // forward declaration to CImpl
CImpl* m_pimpl; // pointer to my implementation
};
```
Thing.cpp has CThing's methods defined as pass-throughs to the impl:
```
// Fully define Impl
class CThing::CImpl
{
private:
// all variables
public:
// methods inlined
CImpl()
{
// constructor
}
void DoSomething()
{
// actual code that does something
}
//etc for all methods
};
// CThing methods are just pass-throughs
CThing::CThing() : m_pimpl(new CThing::CImpl());
{
}
CThing::~CThing()
{
delete m_pimpl;
}
int CThing::GetSomething()
{
return m_pimpl->GetSomething();
}
void CThing::DoSomething()
{
m_impl->DoSomething();
}
```
tada! You've hidden all the details in your cpp and your header file is a very tidy list of methods. Its a great thing. The only thing you might see different from the template above is that people may use boost::shared\_ptr<> or other smart pointer for the impl. Something that deletes itself.
Also, keep in mind this method comes with some annoyances. Debugging can be a tad bit annoying (extra level of redirection to step through). Its also a lot of overhead for creating a class. If you do this for every class, you'll get tired of all the typing :). | Use [**pimpl**](http://www.gotw.ca/gotw/024.htm) idiom. | C++ Header file that declares a class and methods but not members? | [
"",
"c++",
"file",
"class",
"header",
"encapsulation",
""
] |
I am just curious if there is an elegant way to solve following problem in c++:
I have a simulator app which contains several components connected by channels. The channels may be either network channels (two instances of the app are needed) or dummy local channel. There are two interfaces: `IChannelIn` and `IChannelOut` and two corresponding variables:
```
IChannelIn* in;
IChannelOut* out;
```
The `DummyChannel` is both `IChannelIn` and `IChannelOut`. It just copies input to output. There is also `TCPChannelIn: public IChannelIn` and separate `TCPChannelOut: public IChannelOut`.
Now, according to user's choice , I either create one `DummyChannel`
```
DummyChannel* d = new DummyChannel;
in = d;
out = d;
```
or two separate objects: `in = new TCPChannelIn; out = new TcpChannelOut`
The question is: what should the destructor do?
```
~App::App()
{
delete in;
delete out;
}
```
ends in an error because `delete in;` deleted also the dummy channel `d` so that `delete out` deletes already deleted thing.
Is there an elegant way out of this? | How does your class *know* that this is a freestore pointer? E.g. what speaks against the following code?
```
DummyChannel d;
in = &d;
out = &d;
```
This is an entirely sensible piece of code but your destructor **will** crash when trying to delete either of the pointers.
Long story short: reclaiming resources is the job of whoever has allocated the resources in the first place. If your class gets passed a pointer, the class cannot know and does not care about deallocation. This is strictly the responsability of the caller.
Elegant ways to solve this dilemma without making the client to a lot of work are smart pointers, as mentioned before. | You'll need something along the lines of:
```
~App::App()
{
if (in != out)
{
delete out;
}
delete in;
}
```
As when the channels are different the pointers will be different.
However, as danatel has pointed out in the comments `in` and `out` are not comparable. A safe (but inelegant) solution would be to use a `dummy` flag. Set if `in` and `out` are set to the dummy channel, the destructor would become:
```
~App::App()
{
if (!dummy)
{
delete out;
}
delete in;
}
```
Though I wouldn't be happy with this.
The only other solution I can see at the moment is to change the definitions of `IChannelIn` and `IChannelOut` so that they can be compared safely. | c++ delete object referenced by two pointers | [
"",
"c++",
""
] |
I have a console application in C# in which I run various arcane automation tasks. I am well aware that this should really be a **Windows Service** since it needs to run continuously, but I **don't** want to do that at this time. (So, don't suggest that as an answer).
In the meantime, I need some sample C# code that will allow me to determine if there's already an instance of the Application running.
In the old VB6.0 days, I would have used `App.PrevInstance()`
I want to be able to do this in my Main method:
```
static void Main()
{
if(!MyApp.IsAlreadyRunning())
{
while(true)
{
RockAndRollAllNightAndPartyEveryDay();
}
}
}
``` | Jeroen already answered this, but the best way by far is to use a Mutex... not by Process. Here's a fuller answer with code.
I've updated this answer after seeing some comments about a race condition to address that by instead using the [Mutex Constructor](https://learn.microsoft.com/en-us/dotnet/api/system.threading.mutex.-ctor?view=net-5.0#System_Threading_Mutex__ctor_System_Boolean_System_String_System_Boolean__)
```
Boolean createdNew;
Mutex mutex;
try
{
mutex = new Mutex(false, "SINGLEINSTANCE" out createdNew);
if (createdNew == false)
{
Console.WriteLine("Error : Only 1 instance of this application can run at a time");
Application.Exit();
}
// Run your application
}
catch (Exception e)
{
// Unable to open the mutex for various reasons
}
finally
{
// If this instance created the mutex, ensure that
// it's cleaned up, otherwise we can't restart the
// application
if (mutex && createdNew)
{
mutex.ReleaseMutex();
mutex.Dispose();
}
}
```
Notice the `try{} finally{}` block. If you're application crashes or exits cleanly but you don't release the Mutex then you may not be able to restart it again later. | The proper way to use a mutex for this purpose:
```
private static Mutex mutex;
static void Main()
{
// STEP 1: Create and/or check mutex existence in a race-free way
bool created;
mutex = new Mutex(false, "YourAppName-{add-your-random-chars}", out created);
if (!created)
{
MessageBox.Show("Another instance of this application is already running");
return;
}
// STEP 2: Run whatever the app needs to do
Application.Run(new Form1());
// No need to release the mutex because it was never acquired
}
```
The above won't work for detecting if several users on the same machine are running the app under different user accounts. A similar case is where a process can run *both* under the service host *and* standalone. To make these work, create the mutex as follows:
```
var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
var mutexsecurity = new MutexSecurity();
mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow));
mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny));
mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny));
_mutex = new Mutex(false, "Global\\YourAppName-{add-your-random-chars}", out created, mutexsecurity);
```
Two differences here - firstly, the mutex needs to be created with security rights that allow other user accounts to open/acquire it. Second, the name *must* be prefixed with "Global" in the case of services running under the service host (not sure about other users running locally on the same machine). | How to determine if a previous instance of my application is running? | [
"",
"c#",
".net",
""
] |
How can I make this two queries in one ?
```
$query = "SELECT * FROM `amb_prod` WHERE idAmbiente='".$ambId."';";
$result_set = mysql_query($query);
while($member = mysql_fetch_array($result_set)){
$query2 = "SELECT * FROM `produto`, `pt` WHERE
produto.refPT = pt.ref AND
produto.refPT = $member['idProduto'] ;";
$result_set2 = mysql_query($query2);
}
```
**I have have tried this but it didn't work..**
```
$query = "SELECT * FROM `produto`, `pt` WHERE
produto.refPT = pt.ref AND
produto.refPT = (SELECT `idProduto` FROM `amb_prod` WHERE idAmbiente='".$ambId.");";
``` | This should work:
```
$query = "SELECT * FROM `produto`, `pt` WHERE
produto.refPT = pt.ref AND
produto.refPT IN (SELECT `idProduto` FROM `amb_prod` WHERE idAmbiente='".$ambId.");";
```
I'm not sure about the table structure, but a join may work as well. | With a join instead of subquery:
```
$query = "SELECT pr.*, pt.*
FROM amb_prod ap
JOIN producto pr ON (ap.idProduto = pr.refPT)
JOIN pt ON (pr.refPT = pt.ref)
WHERE idAmbiente='${ambId}'";
``` | How can I make two queries in one? | [
"",
"php",
"mysql",
""
] |
I started to use the `unordered_set` class from the `tr1` namespace to speed-up access against the plain (tree-based) STL `map`. However, I wanted to store references to threads ID in boost (`boost::thread::id`), and realized that the API of those identifiers is so opaque that you cannot clearly obtain a hash of it.
Surprisingly, boost implements parts of the `tr1` (including `hash` and `unordered_set`), but it does not define a hash class that is able to hash a thread ID.
Looking at the documentation of `boost::thread::id` I found that thread IDs can be output to a stream, so my solution for doing hashing was kind of:
```
struct boost_thread_id_hash
{
size_t operator()(boost::thread::id const& id) const
{
std::stringstream ostr;
ostr << id;
std::tr1::hash<std::string> h;
return h(ostr.str());
}
};
```
That is, serialize it, apply the hash to the resulting string. However, this seems to be less efficient than actually using the STL `map<boost::thread::id>`.
So, my questions: Do you find a better way of doing this? Is it a clear inconsistency in both boost and tr1 not to force the existence of a `hash<boost::thread::id>` class?
Thanks. | The overhead of stringifying `thread::id` (only to compute the string hash afterward) is, as you almost said yourself, astronomical compared to any performance benefits a `tr1::unordered_map` might confer vis-a-vis `std::map`. So the short answer would be: **stick with std::map< thread::id, ... >**
If you *absolutely* must use unordered containers, **try to use`native_handle_type`** instead of `thread::id` if possible, i.e. prefer `tr1::unordered_map< thread::native_handle_type, ... >`, invoking `thread::native_handle()` instead of `thread::get_id()` when `insert`ing and `find`ing.
**DO NOT attempt anything like the following**:
```
struct boost_thread_id_hash {
// one and only member of boost::thread::id is boost::thread::id::thread_data
// of type boost::detail::thread_data_ptr;
// boost::thread::id::operator==(const id&) compares boost::thread::id::thread_data's
size_t operator()(boost::thread::id const& id) const {
const boost::detail::thread_data_ptr* pptdp = \
reinterpret_cast< boost::detail::thread_data_ptr* >(&id);
return h(pptdp->get());
}
};
```
It could work, but is extremely brittle and an almost guaranteed timebomb. It assumes intimate knowledge of the inner workings of the `thread::id` implementation. It will get you cursed at by other developers. Don't do it if maintainability is of any concern! Even patching `boost/thread/detail/thread.hpp` to add `size_t hash_value(const id& tid)` as a friend of `thread::id` is "better". :) | The obvious question is why would you want to actually use a hash ?
I understand the issue with `map` / `set` for performance critical code, indeed those containers are not very cache friendly because the items might be allocated at very different memory locations.
As KeithB suggested (I won't comment on using the binary representation since nothing guarantees that 2 ids have the same binary representation after all...), using a sorted `vector` can speed up the code in case there is very few items.
Sorted vectors / deques are much more cache-friendly, however they suffer from a *O(N)* complexity on insert/erase because of the copying involved. Once you reach a couple hundreds threads (never seen that many by the way), it could hurt.
There is however, a data structure that tries to associate the benefits from maps and sorted vectors: the [B+Tree](http://en.wikipedia.org/wiki/B%2B_tree).
You can view it as a map for which each node would contain more than one element (in sorted order). Only the leaf nodes are used.
To get some more performance you can:
* Link the leaves linearly: ie the root caches a pointer to the first and last leaf and the leaves are interconnected themselves, so that linear travel completely bypass the interal nodes.
* Cache the last accessed leaf in the root, after all it's likely that'll also be the next one accessed.
The asymptotic performances are the same than for the map, because it's implemented as a Balanced Binary Tree, but because the values are packed in groups, you're code can become faster by a constant.
The real difficulty is to tailor the size of each "bucket", you'll need some profiling for that so it would be better if your implementation allowed some customization there (as it will depend on the architecture on which the code is executed). | tr1::hash for boost::thread::id? | [
"",
"c++",
"boost",
"hash",
"boost-thread",
"unordered-set",
""
] |
I'm having a spot of trouble with generics in C#. I have to store a number of generic objects together but their type parameter differs so I have made a non-generic interface which they implement. What I'm looking for is a way to convert back to the generic version, given a type object. I know I can do it with reflection but I was wondering if there was a better/more elegant solution.
The following code illustrates the problem:
```
interface ITable
{
public Type Type { get; }
}
class Table<T> : ITable
{
public Type Type { get{ return typeof(T); } }
}
class Program
{
static void Main(string[] args)
{
var tables = new Dictionary<string, ITable>();
... //insert tables
DoStuffWithTable(tables["my table"]); //This doesn't work
}
public static void DoStuffWithTable<T>(Table<T> table)
{
...//Some work
}
}
```
Is there a clean way for me to invoke the generic `DoStuffWithTable` method based on the instance of the Type object I can get from its interface method? | If you are starting from a non-generic type (`ITable`), then the only way to do this is via reflection (`MakeGenericMethod`). It isn't very pretty or especially fast, but it works...
```
public static void DoStuffWithUntypedTable(ITable table)
{
typeof(Program).GetMethod("DoStuffWithTable")
.MakeGenericMethod(table.Type)
.Invoke(null, new object[] { table });
}
```
As an aside - note that there is a bit of risk in assuming that an `ITable` is actually a `Table<T>` - you should probably verify that, and maybe also use an interface (`ITable<T>`).
---
Edit: if it really must be a `Table<T>`, then you can enforce this (including subclass support, such as `FooTable : Table<Foo>` as:
```
public static void DoStuffWithUntypedTable(object table)
{
Type type = table.GetType();
while (type != typeof(object))
{
if (type.IsGenericType && type.GetGenericTypeDefinition()
== typeof(Table<>))
{
typeof(Program).GetMethod("DoStuffWithTable")
.MakeGenericMethod(type.GetGenericArguments()[0])
.Invoke(null, new object[] { table });
return;
}
type = type.BaseType;
}
throw new ArgumentException("Not a Table<T> or subclass");
}
``` | The problem is that you don't know the type at compile-time - which is what generics is tailored for.
To call a generic method where you only know the type argument at execution time, you basically need reflection - get the generic method, call [`MakeGenericMethod`](http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx) and then invoke the returned method. | How to convert a type to a generic version given its type? | [
"",
"c#",
"generics",
""
] |
What is the best audio playback api for C/C++ for Linux, preferably free/open source? I need it for embedded Linux, so I'm looking for something as lightweight as possible with not to many dependencies? | SDL is really nice | [PulseAudio](http://en.wikipedia.org/wiki/PulseAudio) has been adopted by the major distributions and it looks like it is the upcoming Linux Audio standard as it is more flexible than [ALSA](http://www.alsa-project.org/). Here's an article about [why you should care about PulseAudio](http://www.linux.com/feature/119926) (and how to start doing it). | Best audio playback api for C/C++ under Linux? | [
"",
"c++",
"linux",
"audio",
""
] |
Is it possible to make LinQ to SQL read and understand a pure SQL query such as the following?
```
SELECT * from myTable
```
My boss asked me to write directly to database the pure SQL querys in a certain table and this table will have a field named "typeOfSelect", for example.
And, in my application, I will have to read this field "typeOfSelect" and make LinQ understands what that means.
Thanks! | You can use the ExecuteCommand and ExecuteQuery methods on the DataContext.
```
var db = new MyDataContext();
IEnumerable<Table1> result = db.ExecuteQuery<Table1>("SELECT * FROM Table1");
db.ExecuteCommand("UPDATE Tabel1 SET Column1 = 'Foo'");
```
ExecuteQuery will work with any object that has property names that match the column names of the table. ExecuteCommand is used for SQL commands that don't return a result set.
Another way would be to use the Connection.CreateCommand() method on a DataContext which will return a DbCommand object. Then you simply set the CommandText property with the SQL you want to execute.
```
DbCommand command = myDataContext.Connection.CreateCommand();
command.CommandText = "SELECT * FROM Table1";
try {
command.Connection.Open();
DbDataReader reader = command.ExecuteReader();
// do something usefull with the reader like creating a DataTable
} finally {
command.Connection.Close();
command.Dispose();
}
```
You can also look at this [MSDN](http://msdn.microsoft.com/en-us/library/bb386906.aspx) link for some other examples. | If you want to write SQL it is easy to just create some wrapper classes so you want write something like this.
```
DataTable result = DBManager.Query("SELECT * FROM Table");
```
But I don't think this is generally considered good practice any more and would defeat the purpose of Linq. | Is it possible to make LinQ "understand" a classic SQL query? | [
"",
".net",
"sql",
"linq",
"linq-to-sql",
""
] |
I am learning C++ as a first language. I feel like I am about to hit a ceiling on my learning (I am not learning through a class) if I don't start looking at actual code soon. Here are my two main questions:
1. Where can I find source code
2. What is a good litmus test on code's quality (I've obviously never developed in a work environment)
I hope this is relevant to SO, but I can see the need to close this. Thanks for the help.
---
**Related:**
[Examples of "modern C++" in action?](https://stackoverflow.com/questions/534311/examples-of-modern-c-in-action) | I would recommend [Boost](http://www.boost.org/ "Boost"). Using Boost will simplify your program design. Reading Boost source code can show you how to use C++ to solve some challenging problems in a concise way.
This add on library is itself written in C++, in a peer-reviewed fashion, and has a high standard of quality. | I think your two best bets for finding C++ code are to go to the popuplar open source repositories.
* CodePlex: <http://codeplex.com>
* Google Code: <http://code.google.com>
* SourceForge: <http://sourceforge.net/>
These all have high quality C++ projects you can take a look at. I don't think there's a great metric for judging quality on a large scale. I would start with the more popular projects which may be more likely to have quality code. | Where can I find good C++ source code? | [
"",
"c++",
""
] |
I want to use JavaScript to restrict input on a text box to currency number formatting. For example:
```
<input type="text" value="2,500.00" name="rate" />
```
As given above, the text box should accept only numbers, commas and a period.
But, after the period it should accept two digits after numbers.
How do I accomplish this? Please clarify.
* Gnaniyar Zubair | [parseFloat](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Functions/ParseFloat) can convert a string to a float and [toFixed](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number/toFixed) can set how many decimal places to keep.
```
function numToCurrency(num){
return parseFloat(num).toFixed(2);
}
numToCurrency("4.2334546") // returns 4.23
``` | If you want to do validation for your textbox, you can use [Regular Expressions](http://www.evolt.org/article/Regular_Expressions_in_JavaScript/17/36435/). If you want to restrict the input from the user, you can trap the keystrokes and filter out the ones you want them to enter using the [onKeyDown](http://www.w3schools.com/jsref/jsref_onkeydown.asp) event of the textbox. | How do I use JavaScript for number formatting? | [
"",
"javascript",
"regex",
"formatting",
"numbers",
"isnumeric",
""
] |
I've got a search box that users can type terms into. I have a table setup with fulltext searching on a string column. Lets say a user types this: "word, office, microsoft" and clicks "search".
Is this the best way to deal with multiple search terms?
```
(pseudocode)
foreach (string searchWord in searchTerms){
select col1 from myTable where contains(fts_column, ‘searchWord’)
}
```
Is there a way of including the search terms in the sql and not iterating? I'm trying to reduce the amount of calls to the sql server. | FREETEXT might work for you. It will separate the string into individual words based on word boundaries (word-breaking). Then you'd only have a single SQL call.
[MSDN -- FREETEXT](http://msdn.microsoft.com/en-us/library/ms176078.aspx) | Well you could just build your SQL Query Dynamically...
```
string [] searchWords = searchTerm.Split(",");
string SQL = "SELECT col1 FROM myTable WHERE 1=2";
foreach (string word in searchWords)
{
SQL = string.Format("{0} OR contains(fts_column, '{1}')", SQL, word);
}
//EXEC SQL...
```
**Obviously this comes with the usual warnings/disclaimers about SQL Injection etc...** but the principal is that you would dynamically build up all your clauses and apply them in one query.
Depending on how your interacting with your DB, it might be feasible for you to pass the entire un-split search term into a SPROC and then split & build dynamic SQL inside the stored procedure. | Asp.net fulltext multiple search terms methodology | [
"",
"asp.net",
"sql",
"full-text-search",
""
] |
I've been all over the ifstream questions here on SO and I'm still having trouble reading a simple text file. I'm working with Visual Studio 2008.
Here's my code:
```
// CPPFileIO.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <fstream>
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream infile;
infile.open("input.txt", ifstream::in);
if (infile.is_open())
{
while (infile.good())
cout << (char) infile.get();
}
else
{
cout << "Unable to open file.";
}
infile.close();
_getch();
return 0;
}
```
I have confirmed that the *input.txt* file is in the correct "working directory" by checking the value of `argv[0]`. The Open method just won't work.
I'm also having trouble debugging- should I not be able to set a watch on `infile.good()` or `infile.is_open()`? I keep getting
```
Error: member function not present.
```
**EDIT:** Updated code listing with full code from .CPP file.
**UPDATE:** The file was NOT in the Current Working Directory. This is the directory where the *project file* is located. Moved it there and it works when debugging in VS.NET. | Try using the bitwise OR operator when specifying the open mode.
```
infile.open ("input.txt", ios::ate | ios::in);
```
The [openmode](http://www.cplusplus.com/reference/iostream/ios_base/openmode/) parameter is a bitmask. `ios::ate` is used to open the file for appending, and `ios::in` is used to open the file for reading input.
If you just want to read the file, you can probably just use:
```
infile.open ("input.txt", ios::in);
```
---
The default open mode for an ifstream is ios::in, so you can get rid of that altogether now. The following code is working for me using g++.
```
#include <iostream>
#include <fstream>
#include <cstdio>
using namespace std;
int main(int argc, char** argv) {
ifstream infile;
infile.open ("input.txt");
if (infile)
{
while (infile.good())
cout << (char) infile.get();
}
else
{
cout << "Unable to open file.";
}
infile.close();
getchar();
return 0;
}
``` | Sometimes Visual Studio puts your exe file away from your source code. By default VS may only look for the file starting from your exe file. This process is a simple step for getting the input txt file from the same directory as your source code. Should you not want to fix your IDE setup.
```
using namespace std;
ifstream infile;
string path = __FILE__; //gets source code path, include file name
path = path.substr(0,1+path.find_last_of('\\')); //removes file name
path+= "input.txt"; //adds input file to path
infile.open(path);
```
Hopefully this helps other people for a quick solution. It took me a while to find this setup myself. | ifstream::open not working in Visual Studio debug mode | [
"",
"c++",
"visual-studio",
"ifstream",
""
] |
I have a object that dynamically creates a number of child objects. These child objects are derived from UserControl. What is the best method to pass information to pass information back to the parent? In the past I have used the delegate event but recently I have been just using a reference to the parent in the constructer of the child objects.
I do have reservations to tight coupling as I am concerned that the child object may be tied up if the parent fails to execute the referenced method in a timely fashion.
I didn't want to start a new question so I'll ask here.
If I have events wired for the dynamically created objects and the object is disposed of at a later time, should I be unwiring the event prior to disposing of the event.
and ... if I am keeping my dynamically created objects in an array or hashtable would simply removing that list item dispose of the item from memory. | It will depend on the situation. Events are appropriate if one object wants to observe another and react to particular changes. Simply keeping a reference to the parent is suitable in other situations. If you want advice for a very specific case, please give details of that case. | Depends on your attitude towards tight coupling and the exact situation in hand.
Personally speaking I think that the delegate/event approach is a lot cleaner.
Passing in a reference implies that the child needs understanding of the type of the parent object? OK, you could probably use a base class or interface, but it's still required.
The upside of the delegate/event model is that the child object can just publish events and whoever is registered will receive the events. Classic observer pattern. | what is the best method for passing information from a child to a parent object in c# | [
"",
"c#",
""
] |
I have a MS SQL DB with about 2,600 records (each one information on a computer.) I need to write a SELECT statement that selects about 400 of those records.
What's the best way to do that when they don't have any common criteria? They're all just different random numbers so I can't use wildcards or anything like that. Will I just have to manually include all 400 numbers in the query? | Maybe you have found a deficiency in the database design. That is, there is something common amongst the 400 records you want and what you need is another column in the database to indicate this commonality. You could then select against this new column. | **If you need 400 specific rows where their column match a certain number:**
Yes include all 400 numbers using an IN clause. It's been my experience (via code profiling) that using an IN clause is faster than using where column = A or column = B or ...
400 is really not a lot.
```
SELECT * FROM table WHERE column in (12, 13, 93, 4, ... )
```
**If you need 400 random rows:**
```
SELECT TOP 400 * FROM table
ORDER BY NEWID()
``` | How do I query a SQL database for a lot of results that don't have any common criteria? | [
"",
"sql",
"sql-server",
""
] |
Most MVVM examples I have worked through have had the *Model* implement `INotifyPropertyChanged`, but in [Josh Smith's CommandSink example](http://www.codeproject.com/KB/WPF/VMCommanding.aspx) **the ViewModel implements `INotifyPropertyChanged`**.
I'm still cognitively putting together the MVVM concepts, so I don't know if:
* You have to put the `INotifyPropertyChanged` in the ViewModel to get `CommandSink` to work
* This is just an aberration of the norm and it doesn't really matter
* You should always have the Model implement `INotifyPropertyChanged` and this is just a mistake which would be corrected if this were developed from a code example to an application
What have been others' experiences on MVVM projects you have worked on? | I'd say quite the opposite, I always put my `INotifyPropertyChanged` on my ViewModel - you really don't want to be polluting your model with a fairly WPF specific feature like `INotifyPropertyChanged`, that stuff should sit in the ViewModel.
I'm sure others would disagree, but that's the way I work. | I strongly disagree with the concept that the Model should not implement the `INotifyPropertyChanged`. This interface is not UI specific! It simply informs of a change. Indeed, WPF heavily uses this to identify changes, but that doesn't mean it is an UI interface.
I would compare it to the following comment: "*A tire is a car accessory*". Sure it is, but bikes, buses, etc. also use it. **In summary, do not take that interface as an UI thing.**
Having said that, it doesn't necessarily mean I believe that the Model should be providing notifications. **In fact, as a rule of thumb, the model should not implement this interface, unless it is necessary.** In most cases where no server data is pushed to the client app, the model can be stale. But if listening to financial market data, then I do not see why the model cannot implement the interface. As an example, what if I have non-UI logic such as a service that when it receives a Bid or Ask price for a given value it issues an alert (ex. through an email) or places an order? This could be a possible clean solution.
However, there are different ways of achieving things, but I would always argue in favor of simplicity and avoid redundancy.
What is better? Defining events on a collection or property changes on the view model and propagating it to the model or having the view intrinsically update the model (through the view model)?
The bottom line whenever you see someone claiming that "*you can't do this or that*" it is a sign they do not know what they are talking about.
**It really depends on your case and in fact MVVM is a framework with lots of issues and I am yet to see a common implementation of MVVM across the board.**
I wish I had more time to explain the many flavors of MVVM and some solutions to common problems - mostly provided by other developers, but I guess I will have to do it another time. | In MVVM should the ViewModel or Model implement INotifyPropertyChanged? | [
"",
"c#",
".net",
"wpf",
"mvvm",
"inotifypropertychanged",
""
] |
I am writing a php app on the websever I set up at my house. It is a fedora10 machine, running php5 and mysql. I have code like this:
```
<?php echo $var->function(); ?>
```
But for some reason the -> is closing the php tag, so the output has 'function(); ?' added to it...is there something I need to change in my php or webserver configuration? | I dont think that you have mod\_php enabled in your apache config file, or else you would never see the php code in the output. [Here is a good tutorial](http://dan.drydog.com/apache2php.html) on setting up php 5 in apache. | I ran into a similar problem the other day but I was using
bar ?>
instead of
bar; ?>
It turned out that the `short_open_tag` option was disabled in my PHP configuration. | PHP arrow operator closing tags | [
"",
"php",
"apache",
""
] |
What is the easiest way to check if a socket was closed on the remote side of the connection? `socket::is_open()` returns true even if it is closed on the remote side (I'm using `boost::asio::ip::tcp::socket`).
I could try to read from the stream and see if it succeeds, but I'd have to change the logic of my program to make it work this way (I do not want data to be extracted from the stream at the point of the check). | If the connection has been cleanly closed by the peer you should get an EOF while reading. Otherwise I generally ping in order to figure out if the connection is really alive. | Just check for `boost::asio::error::eof` error in your `async_receive` handler. It means the connection has been closed. That's the only proper way to do this. | How to check if socket is closed in Boost.Asio? | [
"",
"c++",
"boost",
"sockets",
"boost-asio",
""
] |
I have a servlet that write a pdf file as a ByteArrayOutputStream to the servlet's output stream.
If I open the servlet URL the browser opens the file.
But if occur an error on the servlet, the browser opens an empty pdf with an error message.
Sending an error through the ServletResponse the browser opens the default error page.
I want to send an error message without redirecting to an error page or opening an invalid pdf file.
I tried:
```
new Ajax.Request('/pdfservlet', {
onSuccess: function(response) {
docWindow = window.open('','title');
docWindow.document.open('application/pdf');
docWindow.document.write(response);
docWindow.document.close();
},
onFailure: function(response) {
alert(response);
}
});
```
But, onSuccess opens a page with
[object object]
How can I open a PDF file using JavaScript? | Note: I'm assuming you're using the Prototype framework from the [`Ajax.Request`](http://www.prototypejs.org/api/ajax/request) call.
The [response object](http://www.prototypejs.org/api/ajax/response) isn't meant to be written directly, it does however, have the `responseText` property which should contain the returned PDF.
Have you tried:
```
new Ajax.Request('/pdfservlet', {
onSuccess: function(response) {
docWindow = window.open('','title');
docWindow.document.open('application/pdf');
document.write(response.responseText);
docWindow.document.close();
},
onFailure: function(response) {
alert(response);
}
});
```
(Notice the added `.responseText`)
**Edit:** Okay, so that didn't work... Try something like this:
```
new Ajax.Request('/pdfservlet', {
onSuccess: function(response) {
window.open('/pdfservlet');
},
onFailure: function(response) {
alert(response);
}
});
```
What this will do is create the ajax request, and if successful open it in a new window. Opening the new window should be fast and not actually require requesting the PDF again since the browser should have cached it during the Ajax.Request call. | You could try a "two-pass" approach. You use the Ajax to call the servlet ( and if it generates a PDF on the fly, have it cache it ). If it succeeds, redirect the user to the servlet with a parameter to load the cached PDF.
There are other options, but it depends on how you are using PDFs.
My $0.02.. | How to open a file using JavaScript? | [
"",
"javascript",
"ajax",
"pdf",
"prototypejs",
""
] |
Can anyone suggest any good payment processing libraries for python/django? | The most developed Django solution is [Satchmo](http://www.satchmoproject.com/docs/svn/) with support for Authorize.Net, TrustCommerce, CyberSource, PayPal, Google Checkout, and Protx.
The new kid on the Django block is [django-lfs](http://code.google.com/p/django-lfs/) which looks like only support for PayPal at the moment, and even that may not be complete.
For general Python the main player is [getpaid](http://code.google.com/p/getpaid/) | There is [Django payments application called Mamona](http://github.com/emesik/mamona) which currently supports only PayPal. It can be used with any existing application without changing it's code. Basically, it can use **any exiting model** as order. | Django payment processing | [
"",
"python",
"django",
""
] |
I've been asked by a client to make an online tracking system for work we do for them (we will be typesetting a high volume of books for this client). Basically, it would be a database showing the books we are currently working on, with information on what stage of the project we are at, and estimated completion dates. The only people with access to this system would be us and employees of the client company.
I've worked in MySQL and PHP before; should I just go with what I know? [This answer](https://stackoverflow.com/questions/326364/easiest-most-maintainable-online-db-solution/326388#326388) to a similar question suggests using Google Apps. I don't have any experience with Python, but happy to learn... | You're the only one using this therefore I see no reason to use Google Apps. I'm usually weary of people suggesting Google Apps, Amazon's s3, Microsoft Azure, etc. Also, you're going to be using a radically different data store. Unless you want an excuse to learn to do Google Apps and Python, I'd say go with MySQL+PHP and be done with it! In short, there aren't really any technical reasons for you to go with Google Apps here. | Sticking with what you know is always a good solution when dealing with delivering products to customers. No customer likes to be your guinea pig while you learn a new technology, although that's often how it's done. If you are comfortable with MySQL and PHP then stick with it if it satisfies your requirements, if it seems not to then look for libraries, frameworks and components written in PHP that might help you reach that goal. If you still have difficulties (unlikely given the scope of the project given) then ask questions here :) & search the web for solutions and patterns.
If all that fails and you can clearly solve your problem with another technology, then look at moving but make sure your customer is aware of how that's going to affect you timeframes.
When you've implemented this project and have some spare time, if there's a new direction you'd like to explore then use this project as your base and set to work without the stress of a deadline.
That's my 2p worth... good luck! | Easiest way to implement an online order tracking database | [
"",
"php",
"mysql",
"database",
"google-app-engine",
""
] |
Is it somehow possible to send a function to another function for it to run.
For instance...I want to have an attribute on a field where I can specify a method that will be sent to another method where the method passed in will be run.
Not sure if that makes any sense but here's a small example.
```
[ValidateIf(x=>x.test())]
public string test { get; set; }
```
**Update:**
Basically I want to use DataAnnotations for validation but sometimes depending on the system settings a field may not be mandatory...Do you have any suggestions on the direction I should head? | Unfortunately you can't use delegates as properties for attributes. You'd have to specify the method name and then create the delegate using reflection at execution time - which obviously isn't ideal in terms of finding typos at compile time.
It *might* be possible in IL (specifying a `MethodInfo` using an equivalent to `typeof`) but C# doesn't expose any way of doing this :( Maybe one day we'll get the `infoof` operator... quite how it would be exposed, I'm not sure. (It would be good to keep the delegate type information in the attribute.) | I don't know if this will meet your specific goal, but in general if you are looking to add data annotations to your language, I recomend you look at Spec#. This is an extension of the C# language that allows you to add data contracts to your program and appears to accomplish the goal you're looking for.
<http://research.microsoft.com/en-us/projects/specsharp/> | Passing a method to another method | [
"",
"c#",
"asp.net-mvc",
"attributes",
"lambda",
""
] |
There doesn't seem to be any method of Socket, or ListenSocket that will allow me to conditionally accept connections.
When I recieve a SYN, I want to be able decide if I want this connection depending on the source, if I send a SYN/ACK back (accept connection) or a RST (a forceful reject).
Is there any want to achieve this? Unfortunately, I can't just immediate close the connection after the accept, it needs to not be opened at all. I would also like to avoid having to work with it as a RAW socket. | Unfortunately this is not possible. There is no way to conditionally accept using a TCP socket connection. You can only filter a connection once it's been established.
But what exactly are you trying to filter on? At the point you get the SYN packet all you know is the IP address of the source and the port they are trying to connect to. It seems like it would be much better to filter based on this data using the firewall. I realize this isn't controlled via your app but it's an alternative to consider. | It seems it is not possible without going into RAW mode. Once the socket goes into Winsock's listen mode, it will accept anything and everything, even BEFORE Socket.Accept is called.
You must use RAW mode and parse the packets with your own TCP stack if you want this functionality. | .NET: Conditional Socket.Accept | [
"",
"c#",
".net",
"sockets",
"tcp",
""
] |
In oracle we would use rownum on the select as we created this table. Now in teradata, I can't seem to get it to work. There isn't a column that I can sort on and have unique values (lots of duplication) unless I use 3 columns together.
The old way would be something like,
```
create table temp1 as
select
rownum as insert_num,
col1,
col2,
col3
from tables a join b on a.id=b.id
;
``` | This is how you can do it:
```
create table temp1 as
(
select
sum(1) over( rows unbounded preceding ) insert_num
,col1
,col2
,col3
from a join b on a.id=b.id
) with data ;
``` | Teradata has a concept of identity columns on their tables beginning around V2R6.x. These columns differ from Oracle's sequence concept in that the number assigned is not guaranteed to be sequential. The identity column in Teradata is simply used to guaranteed row-uniqueness.
Example:
```
CREATE MULTISET TABLE MyTable
(
ColA INTEGER GENERATED BY DEFAULT AS IDENTITY
(START WITH 1
INCREMENT BY 20)
ColB VARCHAR(20) NOT NULL
)
UNIQUE PRIMARY INDEX pidx (ColA);
```
Granted, ColA may not be the best primary index for data access or joins with other tables in the data model. It just shows that you *could* use it as the PI on the table. | Add a sequential number on create / insert - Teradata | [
"",
"sql",
"teradata",
"row-number",
""
] |
I have a URL that also might have a query string part, the query string might be empty or have multiple items.
I want to replace one of the items in the query string or add it if the item doesn't already exists.
I have an URI object with the complete URL.
My first idea was to use regex and some string magic, that should do it.
But it seems a bit shaky, perhaps the framework has some query string builder class? | Maybe you could use the `System.UriBuilder` class. It has a `Query` property. | I found this was a more elegant solution
```
var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());
qs.Set("item", newItemValue);
Console.WriteLine(qs.ToString());
``` | Replace item in querystring | [
"",
"c#",
"asp.net",
"query-string",
""
] |
I'm using linq to filter a selection of MessageItems. The method I've written accepts a bunch of parameters that might be null. If they are null, the criteria for the file should be ignored. If it is not null, use it to filter the results.
It's my understanding that when doing an || operation is C#, if the first expression is true, the second expression should not be evaluated.
e.g.
```
if(ExpressionOne() || ExpressionTwo())
{
// only ExpressionOne was evaluated because it was true
}
```
now, in linq, I'm trying this:
```
var messages = (from msg in dc.MessageItems
where String.IsNullOrEmpty(fromname) || (!String.IsNullOrEmpty(fromname) && msg.FromName.ToLower().Contains(fromname.ToLower()))
select msg);
```
I would have thought this would be sound, because `String.IsNullOrEmpty(fromname)` would equal true and the second part of the || wouldn't get run.
However it does get run, and the second part
```
msg.FromName.ToLower().Contains(fromname.ToLower()))
```
throws a null reference exception (because `fromname` is null)!! - I get a classic "Object reference not set to an instance of an object" exception.
Any help? | Have a read of [this documentation](http://msdn.microsoft.com/en-us/library/bb386909.aspx) which explains how linq and c# can experience a disconnect.
Since Linq expressions are expected to be reduced to something other than plain methods you may find that this code breaks if later it is used in some non Linq to Objects context.
That said
```
String.IsNullOrEmpty(fromname) ||
( !String.IsNullOrEmpty(fromname) &&
msg.FromName.ToLower().Contains(fromname.ToLower())
)
```
Is badly formed since it should really be
```
String.IsNullOrEmpty(fromname) ||
msg.FromName.ToLower().Contains(fromname.ToLower())
```
which makes it nice and clear that you are relying on msg and msg.FromName to both be non null as well.
To make your life easier in c# you could add the following string extension method
```
public static class ExtensionMethods
{
public static bool Contains(
this string self, string value, StringComparison comparison)
{
return self.IndexOf(value, comparison) >= 0;
}
public static bool ContainsOrNull(
this string self, string value, StringComparison comparison)
{
if (value == null)
return false;
return self.IndexOf(value, comparison) >= 0;
}
}
```
Then use:
```
var messages = (from msg in dc.MessageItems
where msg.FromName.ContainsOrNull(
fromname, StringComparison.InvariantCultureIgnoreCase)
select msg);
```
However this is not the problem. The problem is that the Linq to SQL aspects of the system are trying to use the `fromname` value to construct the *query* which is sent to the server.
Since `fromname` is a variable the translation mechanism goes off and does what is asked of it (producing a lower case representation of `fromname` even if it is null, which triggers the exception).
in this case you can either do what you have already discovered: keep the query as is but make sure you can always create a non null fromname value with the desired behaviour even if it is null.
Perhaps better would be:
```
IEnumerable<MessageItem> results;
if (string.IsNullOrEmpty(fromname))
{
results = from msg in dc.MessageItems
select msg;
}
else
{
results = from msg in dc.MessageItems
where msg.FromName.ToLower().Contains(fromname)
select msg;
}
```
This is not so great it the query contained other constraints and thus invovled more duplication but for the simple query actually should result in more readable/maintainable code. This is a pain if you are relying on anonymous types though but hopefully this is not an issue for you. | Okay. I found ***A*** solution.
I changed the offending line to:
```
where (String.IsNullOrEmpty(fromemail) || (msg.FromEmail.ToLower().Contains((fromemail ?? String.Empty).ToLower())))
```
It works, but it feels like a hack. I'm sure if the first expression is true the second should not get evaluated.
Would be great if anyone could confirm or deny this for me...
Or if anyone has a better solution, please let me know!!! | The || (or) Operator in Linq with C# | [
"",
"c#",
".net",
"linq",
"linq-to-sql",
"null",
""
] |
I know this is probably just a terminology mismatch but if i'm not mistaken i believe c# is? unless i'm missing something obvious??
```
...
private const uint URL_COUNT = 18;
private string[] _urls;
public Redirector()
{
this._urls = new string[URL_COUNT];
...
}
...
```
Results in “A constant value is expected “ and underlines URL\_COUNT in the array definition??
Whats URL\_COUNT if it isn’t a **const** -ant value?!?!
**EDIT**
Phew, i thought for a second then i was going mad. I'm glad no one could repro this as that means it's just a local thing.
Thanks for your help guys. | This will only fail to compile when you supply both the dimension lengths and an array initializer. For example:
```
this._urls = new string[URL_COUNT];
```
will be fine, but:
```
this._urls = new string[URL_COUNT] { "One", "Two" };
```
will not. The latter requires a constant *expression*. Note that a const variable is not a constant expression, just a constant value. From the C# specification (3.0) par 12.6:
> When an array creation expression
> includes both explicit dimension
> lengths and an array initializer, the
> lengths must be constant expressions
> and the number of elements at each
> nesting level must match the
> corresponding dimension length. | It is a constant and should work fine. The following code compiled fine for me with the C# 3 compiler:
```
using System;
class Foo
{
private const uint URL_COUNT = 18;
private string[] _urls;
public Foo()
{
this._urls = new string[URL_COUNT];
}
}
``` | How can this not be a constant value? | [
"",
"c#",
"constants",
""
] |
This is such a dumb question it's frustrating even asking it. Please, bear with me, I'm feeling particularly dumb over this one today....
I've got a library with a certain typedef struct. basically:
```
typedef struct {int x; int y;} coords;
```
What I really wanted to do was declare in my header a variable array of this:
```
coords MyCoords[];
```
(I recently switched it to just `coords *MyCoords;` and then ran a `MyCoords = new coords[4];`)
and then in my init I wanted to hardcode some values in it.
```
MyCoords[] = {{0, 0}, {2, 2} etc.
```
I must just be brainfarting today because it's not letting me do any manner of simply putting in even something simple like `MyCoords[0] = {0, 0}`
sorry about some of the syntax above. Thanks for any help. I don't even care about hard-coding all the values at once. I'm now fine with just geting `MyCoords[0] = {0, 0}` working. I could do `MyCoords[0].x = 0; MyCoords[0].y = 0` but then I'd never figure out what I'm doing wrong. Thanks a lot anyone.. | Well, what you created is not a variable array. It's an array whose size is not known. That array has an incomplete type, and can thus not be defined in C++. What you can do is to make it just a declaration by putting `extern` before it.
```
extern coords MyCoords[];
```
Then, in the .cpp file that initializes it, you can then create (define) that array - beware you should do it at namespace scope, outside any function, of course:
```
coords MyCoords[] = {{1, 2}, {3, 4}, ... };
```
If what you want is an array whose size is not known at compile time yet, but rather at runtime, you should use a `std::vector`:
```
std::vector< coords > MyCoords;
```
Then later if you fill it, do
```
MyCoords.push_back( coords(1, 2) );
MyCoords.push_back( coords(3, 4) );
....
```
Or create a local array and then initialize the vector using a copy of the elements of that array:
```
coords c[] = ....;
MyCoords.insert(MyCoords.end(), c, c + sizeof c / sizeof *c);
```
Well, in C, it is slightly different than in C++. You *can* define an array whose dimension isn't known. What happens is that it's taken to be a "tentative" definition. If at the end of the file (more precisely, of its translation unit, which is that file, and all the files it includes - meaning everything the compiler translates together) there is not a subsequent definition of it that includes the size, then the size is taken to be `1`. However, in C++ there are no tentative definitions, and a definition that does not include the size and does not contain an initializer that can tell the size is an invalid C++ program.
For the reason why your code goes grazy, you are doing
```
MyCoords[0] = {0, 0}
```
Which the compiler will read as:
```
-> Set LHS to RHS
-> -> LHS is a variable of type `coords`. Fine
-> -> RHS is... hmm, `{0, 0}`. What the heck is it??
```
You see, the compiler has no clue what the right hand side is supposed to mean. C99, for that reason (1999 version of C) introduced so-called compound literals. It allows you to write
```
MyCoords[0] = (coords){0, 0};
```
And it will actually do what you want it to do - creating a right hand side value of type `coord` and assigns it to the left hand side. But you should just, already from a compatibility reason (many C compilers are not reasonable C99 compliant - and neither C++ nor C89 supports compound literals), use one of the previous ways i showed you. | You can only initialize an array at the same spot you declare it. The form that will work is:
```
coords MyCoords[] = {{0, 0}, {2, 2}};
```
If you need to declare MyCoords in a header so that many modules can access it, I think the following will work:
```
extern coords MyCoords[];
``` | C hard coding an array of typedef struct | [
"",
"c++",
"c",
"arrays",
"struct",
"declaration",
""
] |
I have a texture which has only 1 channel as it's a grayscale image. When I pass the pixels in to glTexImage2D, it comes out red (obviously because channel 1 is red; RGB).
```
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA,
dicomImage->GetColumns(), dicomImage->GetRows(),
0, GL_RGBA, GL_UNSIGNED_BYTE, pixelArrayPtr);
```
Do I change GL\_RGBA? If so, what to? | Change it to GL\_LUMINANCE. See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml> | in the FragmentShader, you can write:
```
uniform sampler2D A;
vec3 result = vec3(texture(A, TexCoord).r);
```
in the cpp file,you can write:
```
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RED,
dicomImage->GetColumns(), dicomImage->GetRows(),
0, GL_RED, GL_UNSIGNED_BYTE, pixelArrayPtr);
``` | Can I use a grayscale image with the OpenGL glTexImage2D function? | [
"",
"c++",
"opengl",
"textures",
""
] |
OK here is my problem. I have a linked list of card objects.
I have the following method
```
public void removeCard(Card card){
cards.remove(card);
}
```
if I create Card c = new Card(5,C); for example
and there is a card with the exact same values 2, and C in the linked list (cards).
If I call the method CardPile.remove(card)
I dont get any errors, but the element that's equal to the parameter card is not removed.
Any ideas why this is not happening?
```
import java.util.LinkedList;
public class CardPile {
final char [] suit = {'C','D','H','S'};
final char [] rank = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'};
LinkedList<Card> cards;
public CardPile(){
cards = new LinkedList<Card>();
}
public void addCard(Card card){
cards.addLast(card);
}
public void removeCard(Card card){
cards.remove(card);
}
public void removeSpecial(Card card){
LinkedList<Card> temp = new LinkedList<Card>();
for(int i=0; i<cards.size(); i++){
if(cards.get(i).equals(card)){
temp.add(cards.get(i));
}
}
cards = temp;
}
public void listCards(){
for(int i=0; i<cards.size(); i++){
System.out.print(cards.get(i).toString()+" ");
}
System.out.println();
}
public boolean isEmpty(){
if(cards.size()==0)
return true;
else
return false;
}
public Card drawCard(){
return cards.removeLast();
}
public boolean hasCard(Card card){
int index = 0;
boolean contained = false;
if(cards.size()==0){
System.out.println("error, cards size is 0");
return false;
}
else{
while(index<cards.size() && !contained){
if(cards.get(index).isEqual(card)){
System.out.println("Card found");
contained=true;
}
index++;
}
}
return contained;
}
}
``` | Probably they are not equal then.
Check the equals() method on Card. | I bet the Card class doesn't override equals() and hashcode() method.
The default implementation by Object class simply checks "==", i.e. if two variables point to the same object instance. You need to override equals() and hashcode() to provide proper equal-ness check. See excellent discussion on the topic here - <http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf>
With proper equals() and hashcode(), your code can be further simplied. For example, the hasCard() method can simply call List method contains(). | Remove element from linked list JAVA | [
"",
"java",
""
] |
I have a `ChoiceField`, now how do I get the *label* when I need it?
```
class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=[("feature", "A feature"),
("order", "An order")],
widget=forms.RadioSelect)
```
`form.cleaned_data["reason"]` only gives me the `feature` or `order` *values* or so. | This may help:
```
reason = form.cleaned_data['reason']
reason = dict(form.fields['reason'].choices)[reason]
``` | See the docs on [Model.get\_FOO\_display()](http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display). So, should be something like :
```
ContactForm.get_reason_display()
```
In a template, use like this:
```
{{ OBJNAME.get_FIELDNAME_display }}
``` | How to get the label of a choice in a Django forms ChoiceField? | [
"",
"python",
"django",
"choicefield",
""
] |
I have a set of call detail records, and from those records, I'm supposed to determine the average concurrent active calls per system, per hour (at a precision of one minute). If I query 7pm to 8pm, I should see the average concurrent calls for the hour (averaging the concurrent calls for each minute) within that hour (for each system).
So, I need a way to check for a count of active calls for 7:00-7:01, 7:01-7:02, etc then average those numbers. A call is considered active if the call's time and duration fall within the current minute being checked.
What makes this even more difficult is that it needs to span SQL 7.0 and SQL 2000 (some functions in 2000 aren't available in 7.0, such as GetUTCTime()), if I can just get 2000 working I'll be happy.
## What approaches to this problem can I take?
I thought about looping through minutes (60) in the hour being checked and adding the count of calls that fall between that minute and then somehow cross referencing the duration to make sure that a call that starts at 7:00 pm and has a duration of 300 seconds shows active at 7:04, but I can't imagine how to approach the problem. I tried to figure out a way to weight each call against particular minute that would tell me if the call was active during that minute or not, but couldn't come up with an effective solution.
The data types here are the same as I have to query against. I don't have any control over the schema (other than possibly converting the data and inserting into another table with more appropriate data types). I've provided some example data that I know has concurrent active calls.
```
CREATE TABLE Records(
seconds char(10),
time char(4),
date char(8),
dur int,
system int,
port int,
)
--seconds is an stime value. It's the difference of seconds from UTC 1/1/1970 00:00:00 to the current UTC time, we use it as an identifier (like epoch).
--time is the time the call was made.
--date is the day the call was made.
--dur is the duration of the call in seconds.
--system is the system number.
--port is the port on the system (not particularly relevant for this question).
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924228','1923','20090416',105,2,2)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239923455','1910','20090416',884,1,97)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924221','1923','20090416',116,2,15)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924259','1924','20090416',90,1,102)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239923458','1910','20090416',891,2,1)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924255','1924','20090416',99,2,42)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924336','1925','20090416',20,2,58)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924293','1924','20090416',64,2,41)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239923472','1911','20090416',888,2,27)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924347','1925','20090416',25,1,100)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924301','1925','20090416',77,2,55)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924332','1925','20090416',52,2,43)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924240','1924','20090416',151,1,17)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924313','1925','20090416',96,2,62)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924094','1921','20090416',315,2,16)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239923643','1914','20090416',788,2,34)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924447','1927','20090416',6,2,27)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924342','1925','20090416',119,2,15)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924397','1926','20090416',76,2,41)
INSERT INTO Records(seconds, time, date, dur, system, port) VALUES('1239924457','1927','20090416',23,2,27)
``` | I think MarkusQ has the answer, but let me develop an alternative that you may find easier to use. I'll use my [customary method](https://stackoverflow.com/questions/702500/sql-query-to-collapse-duplicate-values-by-date-range/712309#712309) of developing this as a series of simple transformations in views, an analogue of [functional decomposition](https://stackoverflow.com/questions/754527/best-way-to-test-sql-queries/754570#754570) in a procedural language.
First, let's put everything in common units. Recall that `record`'s column `s` is seconds since the *epoch*, midnight 1 January 1970. We can find the number of seconds since midnight of the day of the call, that call occurred, by just taking s modulus the number of seconds in a day: `s % (60 * 60 * 24)`.
```
select *,
s % (60 * 60 * 24) as start_secs_from_midnight,
s % (60 * 60 * 24) + dur - 1 as end_secs_from_midnight,
;
```
We subtract one from `s + dur` because a one second call that starts at 12:00:00 also ends on 12:00:00.
We can find minutes since midnight by dividing those results by 60, or just by `floor( s / 60 ) % (60 * 24)` :
```
create view record_mins_from_midnight as
select *,
floor( s / 60 ) % (60 * 24) as start_mins_fm,
floor( ( s + dur - 1) / 60 ) % (60 * 24) as end_mins_fm
from record
;
```
Now we create a table of minutes. We need 1440 of them, numbered from 0 to 1439. In databases that don't support arbitrary sequences, I *create an artificial range or sequence* like this:
```
create table artificial_range (
id int not null primary key auto_increment, idz int) ;
insert into artificial_range(idz) values (0);
-- repeat next line to double rows
insert into artificial_range(idz) select idz from artificial_range;
```
So to create a `minute` table:
```
create view minute as
select id - 1 as active_minute
from artificial_range
where id <= 1440
;
```
Now we just join `minute` to our record view
```
create view record_active_minutes as
select * from minutes a
join record_mins_from_midnight b
on (a.active_minute >= b.start_mins_fm
and a.active_minute <= b.end_mins_fm
;
```
This just cross products/multiplies record rows, so we have one record row for each whole minute over which the call was active.
Note that I'm doing this by defining active as "(part of) the call occurred during a minute". That is, a two second call that starts at 12:00:59 and ends at 12:01:01 by this definition occurs during two different minutes, but a two second call that starts at 12:00:58 and ends at 12:00:59 occurs during one minute.
I did that because you specified "So, I need a way to check for a count of active calls for 7:00-7:01, 7:01-7:02". If you prefer to consider only calls lasting more than sixty seconds to occur in more than one minute, you'll need to adjust the join.
Now if we want to find the number of active records for any granularity equal to or larger than minute granularity, we just group on that last view. To find average calls per hour we divide by 60 to turn minutes to hours:
```
select floor( active_minute / 60 ) as hour,
count(*) / 60 as avg_concurent_calls_per_minute_for_hour
from record_active_minutes
group by floor( active_minute / 60 ) ;
```
Note that that is the average per hour for *all calls*, over all days; if we want to limit it to a particular day or range of days, we'd add a `where` clause.
---
**But wait, there's more!**
If we create a version of `record_active_minutes` that does a left outer join, we can get a report that shows the average over all hours in the day:
```
create view record_active_minutes_all as
select *
from
minutes a
left outer join record_mins_from_midnight b
on (a.active_minute >= b.start_mins_fm
and a.active_minute <= b.end_mins_fm)
;
```
Then we again do our select, but against the new view:
```
select floor( active_minute / 60 ) as hour,
count(*) / 60 as avg_concurent_calls_per_min
from record_active_minutes_all
group by floor( active_minute / 60 ) ;
+------+------------------------------+
| hour | avg_concurrent_calls_per_min |
+------+------------------------------+
| 0 | 0.0000 |
| 1 | 0.0000 |
| 2 | 0.0000 |
| 3 | 0.0000 |
etc....
```
We can also index into this with a where. Unfortunately, the join means we'll have null values for the underlying `record` table where no calls exist for a particular hour, e.g.,
```
select floor( active_minute / 60 ) as hour,
count(*) / 60 as avg_concurent_calls_per_min
from record_active_minutes_all
where month(date) = 1 and year(date) = 2008
group by floor( active_minute / 60 ) ;
```
will bring back no rows for hours in which no calls occurred. If we still want our "report-like" view that shows all hours, we make sure we also include those hours with no records:
```
select floor( active_minute / 60 ) as hour,
count(*) / 60 as avg_concurent_calls_per_minute_for_hour
from record_active_minutes_all
where (month(date) = 1 and year(date) = 2008)
or date is null
group by floor( active_minute / 60 ) ;
```
Note that in the last two examples, I'm using a SQL date (to which the functions `month` and `year` can be applied), not the char(4) date in your record table.
Which brings up another point: both the date and time in your record table are superfluous and denormalized, as each can be derived from your column s. Leaving them in the table allows the possibility of inconsistent rows, in which `date(s) <> date` or `time(s) <> time`. I'd prefer to do it like this:
```
create table record ( id int not null primary key, s, duration) ;
create view record_date as
select *, dateadd( ss, s, '1970-01-01') as call_date
from record
;
```
In the `dateadd` function, the `ss` is an enumerated type that tells the function to add seconds; `s` is the column in record. | If I understand you correctly, you want to get a count of all records for which the start time is less then t+60 seconds and the start time plus the duration is less than or equal to t, for each t in the interval of interest (e.g., t=7:00, 7:01, 7:02...etc.).
Then it's just a matter of averaging these counts.
But what is an average? It's just the sum divided by the number of items, right? In this case, the number of items will always be equal to the time range in minutes, and the sum will be equal to the sum of the durations-minutes that fall within the interval, which you can compute in one go off the data given.
Sound less impossible now? In pseudo SQL:
```
select sum(
((time+duration rounded up to next minute, capped at end of period)
- (time rounded down, bottom-capped at start of period) - 1)
/(1 minute) )
from Records
where date is right
```
Then just divide that by the number of minutes in the period of interest. | How can I check for average concurrent events in a SQL table based on the date, time and duration of the events? | [
"",
"sql",
"sql-server",
"algorithm",
"sql-server-2000",
"sql-server-7",
""
] |
```
class One {
public One foo() { return this; }
}
class Two extends One {
public One foo() { return this; }
}
class Three extends Two {
public Object foo() { return this; }
}
```
`public Object foo() { return this; }` throws a compilation error. Why is that? Can someone explain why "Object" type is not possible? Is Object the base class of Class One, Two? If So why does it throws an error?
Please change the title of the question as I couldnt find a suitable title. | `Three.foo` is trying to override `Two.foo()`, but it doesn't do it properly. Suppose I were to write:
```
One f = new Three();
One other = f.foo();
```
Ignoring the fact that *actually* `Three.foo()` *does* return a `One`, the signature of `Three.foo()` doesn't guarantee it. Therefore it's not an appropriate override for a method which *does* have to return a `One`.
Note that you *can* change the return type and still override, but it has to be *more* specific rather than *less*. In other words, this would be okay:
```
class Three extends Two {
public Three foo() { return this; }
}
```
because `Three` is more specific than `One`. | You are changing the signature of the foo method in a way not supported. Polymorphism only works for different argument list, not for identical methods only different by the return type.
And if you think about it, it is quite natural... If it worked and someone who only knows about one of the two super classes would call Three.foo() he would expect it to return a One (because that is how it works in One and Two) but in Three you could actually return a HashMap and still behave correctly.
Jon (in the comment below) is correct, you can narrow the scope but then you would still follow the protocol that you will return a "One" (should you return a Three from Three.foo()) because subclasses will all implement the superclass interface.
However, return type is still not part of the polymorphism, hence you cannot have three different methods that only differs by return type. | Java class question | [
"",
"java",
"class",
""
] |
We develop a network library that uses TCP and UDP sockets.
This DLL is used by a testclient, which is started multiple times at the same PC for a load test.
In Windows Vista, it is no problem to start the testclient many times.
In Windows XP, starting it up to 5 times is no problem, but if we start it 6 times or more, and then closing one client, ALL of them crash with apparently random stack traces.
Yes, although we do not use any interprocess code (only sockets between the clients), the termination of one of the client leads to the crash of all of them.
Our DLL is compiled with MSVC and uses Boost and Crypto++ libs (statically linked).
Any idea why the different processes could influence each other? | An idea: You have some bug.
Seriously, there is no way to know what's your problem without any information what so ever.
When a process crashes it usually has a very good reason to do so. find out what that is.
Compile your dlls and executables in debug, attach a debugger and make sense of the stack trace you get. if you get a nonsense stack trace, find out why that is.
As with many problems, this one is likely to be solved by **"Just debugging it"** | We'll need a little bit more data in order to diagnose your problem. However considering that shutting down one client crashes all of the clients, you need to consider all the ways in which the clients can affect each other (inter process communication). Either implicitly or explicitly. So I would start by looking at
* What does the server do when the 6th client is closed. Does it send out a special packet that the other 5 clients just can't handle?
* Are you reading or writing anything to the file system?
* Do you use shared memory?
In general though, I've found that having a seemingly random stack trace in C++ is usually caused by one of the following
* Data Corruption
* Race Condition in the threading logic. | Problems with starting a program + DLL multiple times in Windows XP? | [
"",
"c++",
"dll",
"crash",
"visual-c++",
"interprocess",
""
] |
Why does the `java.util.Set` interface lack `get(int Index)`, or any similar `get()` method?
It seems that sets are great for putting things into, but I can't find an elegant way of retrieving a single item from them.
If I know I want the first item, I can use `set.iterator().next()`, but otherwise it seems I have to cast to an Array to retrieve an item at a specific index?
What are the appropriate ways of retrieving data from a set? (other than using an iterator)
I'm asking this question because I had a dbUnit test, where I could reasonably assert that the returned set from a query had only 1 item, and I was trying to access that item.
So, what's the difference between `Set` and `List`? | Because sets have no ordering. Some implementations do (particularly those implementing the `java.util.SortedSet` interface), but that is not a general property of sets.
If you're trying to use sets this way, you should consider using a list instead. | Actually this is a recurring question when writing JavaEE applications which use Object-Relational Mapping (for example with Hibernate); and from all the people who replied here, Andreas Petersson is the only one who understood the real issue and offered the correct answer to it: Java is missing a UniqueList! (or you can also call it OrderedSet, or IndexedSet).
Maxwing mentioned this use-case (in which you need ordered AND unique data) and he suggested the SortedSet, but this is not what Marty Pitt really needed.
This "IndexedSet" is NOT the same as a SortedSet - in a SortedSet the elements are sorted by using a Comparator (or using their "natural" ordering).
But instead it is closer to a LinkedHashSet (which others also suggested), or even more so to an (also inexistent) "ArrayListSet", because it guarantees that the elements are returned in the same order as they were inserted.
But the LinkedHashSet is an implementation, not an interface! What is needed is an IndexedSet (or ListSet, or OrderedSet, or UniqueList) interface! This will allow the programmer to specify that he needs a collection of elements that have a specific order and without duplicates, and then instantiate it with any implementation (for example an implementation provided by Hibernate).
Since JDK is open-source, maybe this interface will be finally included in Java 7... | Why doesn't java.util.Set have get(int index)? | [
"",
"java",
"list",
"data-structures",
"collections",
"set",
""
] |
I've got the following function:
```
public static extern uint FILES_GetMemoryMapping(
[MarshalAs(UnmanagedType.LPStr)] string pPathFile,
out ushort Size,
[MarshalAs(UnmanagedType.LPStr)] string MapName,
out ushort PacketSize,
ref Mapping oMapping,
out byte PagesPerSector);
```
Which I would like to call like this:
```
FILES_GetMemoryMapping(MapFile, out size, MapName,
out PacketSize, null, out PagePerSector);
```
Unfortunately, I cannot pass `null` in a field that requires type `ref Mapping` and no cast I've tried fixes this.
Any suggestions? | I'm assuming that Mapping is a structure? If so you can have two versions of the `FILES_GetMemoryMapping()` prototype with different signatures. For the second overload where you want to pass `null`, make the parameter an `IntPtr` and use `IntPtr.Zero`
```
public static extern uint FILES_GetMemoryMapping(
[MarshalAs(UnmanagedType.LPStr)] string pPathFile,
out ushort Size,
[MarshalAs(UnmanagedType.LPStr)] string MapName,
out ushort PacketSize,
IntPtr oMapping,
out byte PagesPerSector);
```
Call example:
```
FILES_GetMemoryMapping(MapFile, out size, MapName,
out PacketSize, IntPtr.Zero, out PagePerSector);
```
If Mapping is actually a class instead of a structure, just set the value to null before passing it down. | The reason you cannot pass `null` is because a `ref` parameter is given special treatment by the C# compiler. Any `ref` parameter must be a reference that can be passed to the function you are calling. Since you want to pass `null` the compiler is refusing to allow this since you are not providing a reference that the function is expecting to have.
Your only real option would be to create a local variable, set it to `null`, and pass that in. The compiler will not allow you to do much more than that. | C#: How to pass null to a function expecting a ref? | [
"",
"c#",
"null",
"pinvoke",
"parameters",
"ref",
""
] |
I'm trying to write a simple server-client program, but I have a problem:
I can send data from client to server, but I can't send data from the server (I can't recive it in the client) :(
So how to send data from the server, and recive it in the client?
Server:
```
//this is in a thread
try {
server = new ServerSocket(1365);
} catch (IOException e) {
e.printStackTrace();
}
while (!exit) {
try {
clientSocket = server.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
while ((line = is.readLine()) != null) {
System.out.println("Message from client: " + line);
//if (line.equals("exit")) {
// exit = true;
//}
if (line.equals("say something")) {
os.write("something".getBytes());
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
os.close();
}
```
Client:
```
try {
socket = new Socket(host, 1365);
os = new DataOutputStream(socket.getOutputStream());
is = new DataInputStream(socket.getInputStream());
} catch (UnknownHostException e) {}
if (socket != null && os != null && is != null) {
try {
os.writeBytes("say something");
//get the answer from server
os.close();
is.close();
socket.close();
} catch (IOException e) {}
}
```
(sorry for the long code)
Thank you in advance. | Your server's OutputStream is a PrintStream, but your client's InputStream is a DataInputStream. Try changing the server to use a **DataOutputStream** like your client.
Even better might be to change both to use PrintWriter and BufferedReader, like the example client/server pair in [Sun's Socket Tutorial](http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html).
---
Just to explain a little about *why* your code didn't work: You can think of Stream objects as filters that your data passes through. The filter changes your data, formatting it so that the *matching* filter at the other end can understand it. When you send data through one type of OutputStream, you should receive it at the other end with the matching InputStream.
Just as you can't store a String object in a double, or a double in a String (not without converting it), you can't send data from one type of OutputStream (in this case a PrintStream) to a different type of InputStream. | I think an other problem was that I didn't send "\n" after the text, but I used readLine() method. | Java socket question | [
"",
"java",
"sockets",
""
] |
I'm trying to derive from List and selectively turn the *IsReadOnly* property on and off. I was hoping that the Add/Remove/[] functions would honor this property, but they don't.
What's the right way of doing this?
My derived class has some additional properties, so I can't unfortunately just wrap the list in ReadOnlyCollection. | Use encapsulation instead of inheritance in this case.
You should just make your class implement IList<T>, and have a private List<T> variable.
You can pass through any functions you wish, but also can completely override them, change behavior, etc. This gives you complete control (at the expense of having many methods that does nothing but call this.List.method(...) ).
In general, I don't think it's a good idea to inherit from the BCL collection classes in any case. I prefer to make them an implementation detail internal in my class. | You could call the "AsReadOnly" method on list which should return to you an IList instance that should honor that it is...err...read-only.
...OK, I just read your last sentence, my bad. In which case maybe you just want to implement the IList interface or any friend and just route most of the interface to a list you keep internally. Then you can build this behaviour. Even so, I would do a similar pattern, provide some "AsReadOnly" method that explicitly gives you something that is read-only. | How to override List<T>.IsReadOnly in C# | [
"",
"c#",
"properties",
"overriding",
"readonly",
""
] |
I have a job that runs which sends out emails to our users to which starts off a work flow process in our company. Periodically, a user will swear up and down that they didn't receive the email - though, when we go to the mail administrator to pull an exchange report, 10 times out of 10 it's in their deleted items. :P
I'd like to be able to programmatically verify that messages sent via .net C# (System.Net.Mail I think) reached the user's mail box.
It's exchange 2007 and all messages are internal. | You can't with System.Net.Mail. You'll have to dig through Exchange's APIs to determine if an email is present in someone's email account.
<http://support.microsoft.com/kb/813349> | Set an account for catching all bounce backs. In this way you will know which ones reached and which ones did not. This is the best way to ensure emails reached.
Alternatively you can add read reciepts via message headers(by setting the Disposition-Notification-To). but again, user can chose not to read it... | Programmatically Verify an email message reached an exchange mail box | [
"",
"c#",
"exchange-server-2007",
"system.net.mail",
""
] |
I have a page to edit user information, and I wish to show the current information and allow it for editing, to avoid overwriting existing information.
At the moment, I am fetching the data and displaying it in a text area like so:
```
$usernameQuery = "select username, firstname from USERS where username = '" . $con->escape_string($username) . "'";
$xblah = $con->query($usernameQuery);
while ($row = mysqli_fetch_assoc($xblah))
{
$checkUsername = $row['username'];
$checkFirstName = $row['firstname'];
}
echo "<form name=\"userForm\">
<h1>Editing information for: ".$username."</h1>
<p>
First name:
<textarea rows=\"1\" id=\"firstname\">".$checkFirstName."</textarea>
<br />
</form>"
```
This text area does not display correctly in firefox, due to a [bug](https://bugzilla.mozilla.org/show_bug.cgi?id=33654) of displaying two rows when one is specified. Is there any way to do the same thing with input type=text?
Also, at present, the contents of firstname in the database is john for my testrecord, but var\_dump($checkFirstName) shows just s. What must I do to get the actual contents of the field? | > Is there any way to do the same thing with input type=text?
```
<input type="text" name="firstname" value="<?= $checkFirstName ?>" />
```
As for your other issue, is there another user that has a first name of 's', but also has the same username as the user with the first name of 'john'? The reason I'm saying this is that you use a `while` loop to fetch your data, so if there are multiple matches, you are going to be left with the last row that matched your query.
Possible ways to resolve this issue include not using a `while` loop (which implies that you want to fetch/process multiple rows of data) and making sure that all usernames are unique.
Other than that, I don't see why the value fetched from `'firstname'` wouldn't match what is in the database. | Use the 'value' attribute of the input tag.
```
First name: <input type=\"text\" name=\"name\" value=\"$checkFirstName\"/><br />
``` | populating a text area/field with existing data | [
"",
"php",
"html",
""
] |
My PHP application will need to be able to export to (and import from) a range of different data formats, mostly XML based.
I have the option of
* In PHP, use DOM to export to some XML based format that is a superset of all the data needed by the others, and create a separate XSLT stylesheet for each output format I want to support, running the DOM output through PHP's XSL extension.
or
* Not using PHP's XSL extension, but implementing each output format as a class in native PHP that translates directly from the internal objects/structures to a given XML format using DOM, each such class implementing the same interface so they are interchangeable.
The app will be used by universities and is a tool that manages 'people' records in various ways, and imports/exports from various sources like their HR system, etc. I'll be implementing the set of input and output formats myself, but in future there is the chance that someone using it will want to modify it to support their own format.
One reason I'm considering NOT using XSLT is that if anybody else is going to maintain the app in future other than me, it seems that very few people even know XSLT - a lot more people seem to know PHP.
Another is that the second seems like a more efficient and 'programmery' solution, and more flexible in the sense that I'd be able to output to and import from non-XML formats like CSV or column based text just as easily by overloading the necessary parts of the class, not that that would often be necessary.
A third, but very small and insignificant reason is that PHP needs recompiling to enable XSL whereas DOM is enabled by default, so it would be a tiny bit more portable. However this isn't too much of a problem as it's easy to reconfigure PHP.
What do you think of my reasoning? | My personal opinion is that your decision should be based strongly on the fact how you'd judge the XSLT knowledge in your intended audience. If it's clear that XSLT is somehow "terra incognita" among the people having to work with the system (that includes yourself), you can rule out the XSLT-solution. The need and the effort to learn XSLT will negate the advantages (very elegant - especially when transforming XML to XML, no need to mess with PHP code, no PHP knowledge needed) you'll get from the XSLT-solution.
Perhaps a two-way solution could be the right thing to go with. You could build an adapter-system for importing and exporting that uses XSLT for the XML data formats and provides the ability to use PHP code for all the data formats that aren't XML based. This way every developer can choose the way he's more comfortable with.
```
interface My_DataConverter_Interface
{
/**
* @param string $file
* @return My_DataObject
*/
function import($file);
/**
* @param My_DataObject $data
* @param string $file
*/
function export(My_DataObject $data, $file);
}
abstract class My_DataConverter_Xslt implements My_DataConverter_Interface
{ /* ... */ }
class My_DataConverter_XmlFormat1 extends My_DataConverter_Xslt
{ /* ... */ }
class My_DataConverter_XmlFormat2 extends My_DataConverter_Xslt
{ /* ... */ }
class My_DataConverter_Csv implements My_DataConverter_Interface
{ /* ... */ }
``` | I think your reasoning is sound and it's the way I would go as well.
Basically what you're talking about are bridge/adapter/facade classes. They are (imho) more flexible and easier to understand than XSL templates.
The third reason isn't really one because XSL support involves nothing more than uncommenting a PHP extension.
I'm also glad to see you want to do this via the DOM extensions (or equivalent library) rather than writing XML as text, which introduces all the escaping issues and whatnot you'll avoid your way.
Personally I also think that XSL templates are more fragile to change (by virtue of them being somewhat more cryptic to the vast majority of programmers) so if your superset format ever changes (which, let's face it, it will) you'll potentially need to change all your templates. Of course you may have to do this with code too but code will probably be easier to maintain. | My PHP app needs to export to a range of different XML formats: should I use XSLT or native PHP? | [
"",
"php",
"xml",
"xslt",
"data-formats",
""
] |
I have a developer tool that I want to run from an internal site. It scans source code of a project and stores the information in a DB. I want user to be able to go to the site, chose their project, and hit run.
I don't want the code to be uploaded to the site because the projects can be large. I want to be able to run my assembly locally on their machine. Is there an easy way to do this?
EDIT: I should note, for the time being, this needs to be accomplished in VS2005.
EDIT 2: I am looking for similar functionality to [TrendMicro's Housecall](http://housecall.trendmicro.com/). I want the scan to run locally, but the result to be displayed in the web page | You could use a ClickOnce project (winform/wpf) - essentially a regular client app, deployed via a web-server. At the client, it can do whatever it needs. VS2005/VS2008 have this (for winform/wpf) as "Publish" - and results in a ".application" file that is recognised by the browser (or at least, some browsers ;-p).
You **might** be able to do the same with Silverlight, but that has a stricter sandbox, etc. It would also need to ask the web-server to do all the db work on its behalf. | > I want to be able to run my assembly
> locally on their machine
Sounds like you want them to download the tool and run it from their local machine, does that work for you? | Best way to run a tool from ASP.Net page | [
"",
"c#",
"asp.net",
"executable",
""
] |
I realize there are similar questions on SO, but they don't quite solve my problem.
I would like a method that, given a Class object, will invoke the "main" method, that is to say, public static void main, on that Class (if it exists) and capture the console output of that main method. The class doing the invocation is a non-daemon thread.
I have part of the code already, but I'm not sure how to capture the console output, and on top of that, how to only capture it for \*this specific thread. Here's what I have so far:
```
public class Output extends Thread {
private Class testClass;
public Output(Class clazz) {
this.testClass = clazz;
}
private Method getMainMethod(Class clazz) {
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (isMainMethod(method)) {
return method;
}
}
return null;
}
private Boolean isMainMethod(Method method) {
return (method.getName().equals("main") &&
Modifier.isStatic(method.getModifiers()) &&
method.getReturnType().equals(Void.class));
}
public void run() {
Method mainMethod = null;
if ((mainMethod = getMainMethod(this.testClass)) == null) {
//if there's no static void main method, throw exception
throw new YouFuckedItUpException();
}
mainMethod.invoke(this.testClass, new String[0]);
return heresWhereImStuckIWantToCaptureTheConsoleOutputAndReturnIt();
}
}
```
All I need is some code to, or a link to an answer on how to, capture the System.out and System.err output of the method being invoked. Any help someone can give would be much appreciated.
Thanks in advance!
**EDIT:** This is NOT for testing only, this will eventually be something put into production.
**EDIT 2**: This will need to be thread-safe. Multiple main methods will be invoked by other threads possibly at the same time, and I want each thread to only capture its own specific output. | Since you use the `main()` method - do you need it to be in the same process? If not, you may try to create it as a new Process ([`java.lang.Process`](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Process.html)).
The `Process` class provides the necessary methods to capture `StdOut`, `StdErr` and/or `StdIn`.
*Note* Since everything runs in it's own process, there should be no issues with thread-safety. However you will still have to find the location, the .class file (or at least the root) is located in, so that you can run/create the Process with `java here.goes.your.ClassName`. | Use [System.setOut](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#setOut(java.io.PrintStream)) and then write a subclass of printstream that overrides all print/write methods and logs the data if it comes from a thread you want to monitor.
Pseudocode:
```
public class HackedPrintStream extends PrintStream {
private PrintStream originalStream;
private HashMap<Thread, PrintStream> loggerStreams = new HashMap<Thread, PrintStream>();
public HackedPrintStream(PrintStream originalStream) {
this.originalStream = originalStream;
}
public synchronized void logForThread(Thread threadToLogFor, PrintStream streamToLogTo) {
loggerStreams.put(threadToLogFor, streamToLogTo);
}
/** example overridden print method, you need to override all */
public synchronized void println(String ln) {
PrintStream logPS = loggerStreams.get(Thread.currentThread());
if (logPS != null) { logPS.println(ln); }
originalStream.println(ln);
}
}
```
Then you can create and use this stream with
```
HackedPrintStream hps = new HackedPrintStream(System.out);
System.setOut(hps);
```
I would really advise you to look hard for another solution though, as this is not pretty. | Capture Console Output of a Specific Thread in Java | [
"",
"java",
"multithreading",
"console",
""
] |
I have this code:
```
function render_message(id)
{
var xmlHttp;
xmlHttp=new XMLHttpRequest();
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById('message').innerHTML=xmlHttp.responseText;
document.getElementById('message').style.display='';
}
}
var url="include/javascript/message.php";
url=url+"?q="+id;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
```
For some reason it does not work in IE and an error is being reported on this line "document.getElementById('message').innerHTML=xmlHttp.responseText;" with an "Unknown Runtime Error".
Can anyone help?
Edit: The code being added to the div is valid code ect.
Here is the response:
```
<div style="margin-left:auto;margin-right:auto;width:400px;">
<img src="/forum/img/avatars/2.gif" width="90" height="89" style="float:left;">
<div style="margin-left:100px;">
<span style="font-size:16pt;">Sam152</a></span><br>
<span style="font-size:10pt;text-transform:uppercase;font-weight:bold;">From Sam152</span><br>
<span style="font-size:10pt;font-weight:bold;">Recieved April 17, 2009, 9:44 am</span><br>
<br><br>
</div>
</div>
<div style="margin-left:auto;margin-right:auto;width:400px;">
asd</div>
<div style="margin-left:auto;margin-right:auto;width:400px;text-align:right;padding-top:10px;">
<span onClick="requestPage('http://www.gametard.com/include/scripts/delete_message.php?id=14');document.getElementById('message14').style.display='none';document.getElementById('message').style.display='none';" class="button">Delete</span>
<span onClick="document.getElementById('message').style.display='none';" class="button">Close</span>
<span onClick="document.getElementById('to').value ='Sam152';document.getElementById('to').style.color ='#000';document.getElementById('newmessage').style.display='';" class="button">Reply</span>
</div>
``` | Trust me on this: use an Ajax framework.
jQuery or prototype or any of the others.
Don't roll your own - you're only seeing the tip of the cross-browser iceberg with this issue.
If you must do it yourself check `xmlHttp.status` before getting your message. Bear in mind that IE sometimes returns Windows error codes instead of HTTP status here, and older FX throws an exception if the error is a lost connection rather than a HTTP status.
Oh, and IE6 is still about 30% of the web market and 60% of the corporate one, so @Paul Whelan's advice is worth checking too. | Not sure if the following applies to you as you don't mention what version of ie you are using.
works only in ie7 upwards
```
var xmlhttp=new XMLHttpRequest();
```
In Internet Explorer 5 and 6 you must use
```
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
``` | Javascript AJAX function not working in IE? | [
"",
"javascript",
"internet-explorer",
"xmlhttprequest",
""
] |
The question field is a bit too short to pose my real question. If anyone can recapitulate it better, please feel free.
My real question is this: I'm reading a lot of other people's code in C# these days, and I have noticed that one particular form of iteration is widely spread, (see in code).
My first question is:
Are all these iterations equivalent?
And my second is: why prefer the first? Has it something to do with readibility? Now I don't believe the first form is more readable then the for-form once you get used to it, and readibility is far too much a subjective item in these constructs, of course, what you use the most will seem more readable, but I can assure everyone that the for-form is at least as readable, since it has all in one line, and you can even read the initializing in the construct.
Thus the second question: why is the 3rd form seen much less in code?
```
// the 'widespread' construct
int nr = getNumber();
while (NotZero(nr))
{
Console.Write(1/nr);
nr = getNumber();
}
// the somewhat shorter form
int nr;
while (NotZero(nr = getNumber()))
Console.Write(1 / nr);
// the for - form
for (int nr = getNumber(); NotZero(nr); nr = getNumber())
Console.Write(1 / nr);
``` | The first and third forms you've shown repeat the call to GetNumber. I prefer the second form, although it has the disadvantage of using a side-effect within a condition of course. However I pretty much *only* do that with a while loop. Usually I don't end up passing the result as an argument though - the common situations I find myself in are:
```
string line;
while ( (line = reader.ReadLine()) != null)
...
```
and
```
int bytesRead;
while ( (bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
...
```
Both of these are now so idiomatic to me that they don't cause me any problems - and as I say, they allow me to only state each piece of logic once.
If you don't like the variable having too much scope, you can just introduce an extra block:
```
{
int bytesRead;
while ( (bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
// Body
}
}
```
Personally I don't tend to do this - the "too-wide" scope doesn't bother me *that* much.
I suspect it wouldn't be too hard to write a method to encapsulate all of this. Something like:
```
ForEach(() => reader.ReadLine(), // Way to obtain a value
line => line != null, // Condition
line =>
{
// body
};
```
Mind you, for line reading I have a class which helps:
```
foreach (string line in new LineReader(file))
{
// body
}
```
(It doesn't just work with files - it's pretty flexible.) | > Are all this iterations equivalents?
yes
> why prefer the first? Has it sth. to do with readibility?
because you may want to extend the scope of the nr var beyond the while loop?
> why is the 3th form seen much less in code?
it is equivalent, same statements!
You may prefer the latter because you don't want to extend the scope of the nr variable | Why is "while" so popular in C#? | [
"",
"c#",
"for-loop",
"iteration",
"while-loop",
""
] |
This example demonstrates using Scanner to read a file line by line (it does not perform a write operation) I don't know why I get an error when I try to compile. Could somebody explain the reason to me?. I'm using jcreatorLE and JDK 1.6 to run my program:
```
import java.io.*;
import java.util.Scanner;
public final class File_read {
public static void main(String... aArgs) throws FileNotFoundException {
ReadWithScanner parser = new ReadWithScanner("C:\\Temp\\test.txt");
parser.processLineByLine();
log("Done.");
}
/**
* @param aFileName full name of an existing, readable file.
*/
public ReadWithScanner(String aFileName){
fFile = new File(aFileName);
}
/** Template method that calls {@link #processLine(String)}. */
public final void processLineByLine() throws FileNotFoundException {
Scanner scanner = new Scanner(fFile);
try {
//first use a Scanner to get each line
while ( scanner.hasNextLine() ){
processLine( scanner.nextLine() );
}
}
finally {
//ensure the underlying stream is always closed
scanner.close();
}
}
/**
* Overridable method for processing lines in different ways.
*
* <P>This simple default implementation expects simple name-value pairs, separated by an
* '=' sign. Examples of valid input :
* <tt>height = 167cm</tt>
* <tt>mass = 65kg</tt>
* <tt>disposition = "grumpy"</tt>
* <tt>this is the name = this is the value</tt>
*/
protected void processLine(String aLine){
//use a second Scanner to parse the content of each line
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter("=");
if ( scanner.hasNext() ){
String name = scanner.next();
String value = scanner.next();
log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim()) );
}
else {
log("Empty or invalid line. Unable to process.");
}
//(no need for finally here, since String is source)
scanner.close();
}
// PRIVATE //
private final File fFile;
private static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
private String quote(String aText){
String QUOTE = "'";
return QUOTE + aText + QUOTE;
}
}
```
This is the result from running it:
```
--------------------Configuration: <Default>--------------------
C:\Users\administrador\Documents\File_read.java:15: invalid method declaration; return type required
public ReadWithScanner(String aFileName){
^
1 error
Process completed.
``` | When you lifted that code from [here](http://www.javapractices.com/topic/TopicAction.do?Id=42) :-), you renamed the class but not the constructor. Only constructors are allowed to not have return types.
I suggest you either rename the class back or rename the constructor.
I hope this isn't homework. As it stands, your educator would have an easy time proving plagiarism. You'll need to at least change the variable names as well as class names, you might want to also reformat it a bit including changing the order of methods in the class.
That's if it's homework. Which it's not, right? :-) | Your "ReadWithScanner" constructor needs to match the name of the class ("File\_read")
```
public File_read(String aFileName){
fFile = new File(aFileName);
}
``` | read a file using Scanner: Why am I getting an error when using Scanner for read files in java? | [
"",
"java",
"file",
"java.util.scanner",
""
] |
i have a COM object that i am using in dotnet and i have to call it always on the same thread. The issue is that conceptually it is being for multiple things throughout the program. What is the best way for ensuring that all uses of this object on called on this one specific background thread? Example code would be great. | You could start a thread at program startup, which should handle all the COM interaction. Then you could have a wrapper object which pushes tasks onto a queue for the thread to handle.
The wrapper could contain synchronization code in order to hide the multi-threadedness to callers (ie. expose the wrapped calls as synchronous methods).
If this is a WinForms project, perhaps you could cut corners by simply using the GUI thread and the Control.Invoke method. (But if the calls take a long time, it is not a good idea, since you would be blocking the UI during the call). | If you can the object under STA then it is granted to be called on the same thread.
For that you need to add [STAThreadAttribute](http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx) on your Main.
The only problem is that **ALL** COM objects will be handled that way. | using an object from one specific thread | [
"",
"c#",
"multithreading",
"com",
""
] |
Is there an easy way to format SQL Server **numeric(18,6)** data type to format similar to c#'s **{0:#.00####}** but in T-SQL?
E.g.
1. 12.550000 should produce 12.55.
2. 14.456700 should produce 14.4567.
3. 15.00 should produce 15.00. | As HLGEM says, it's best to do this kind of stuff on the front end, but for kicks, the following code seems to work. There's probably a better way to do it though.
```
REPLACE(
RTRIM(
REPLACE(
CAST(@test AS VARCHAR), '0', ' '
)
), ' ', '0'
) +
CASE
WHEN @test = FLOOR(@test) THEN '00'
WHEN FLOOR(@test*10) = @test * 10 THEN '0'
ELSE ''
END
``` | Frankly that type of formatting is best done by the application not in the SQL. SQl is for data access and for affecting the content of the data, it is not really good at any formatting. | T-SQL: formatting "numeric" to format similar to c# style {0:#.00####} | [
"",
"sql",
"sql-server",
""
] |
What can I do to prevent `slugify` filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)
[cnprog.com](http://cnprog.com) has Chinese characters in question URLs, so I looked in their code. They are not using `slugify` in templates, instead they're calling this method in `Question` model to get permalinks
```
def get_absolute_url(self):
return '%s%s' % (reverse('question', args=[self.id]), self.title)
```
Are they slugifying the URLs or not? | There is a python package called [unidecode](http://pypi.python.org/pypi/Unidecode) that I've adopted for the askbot Q&A forum, it works well for the latin-based alphabets and even looks reasonable for greek:
```
>>> import unidecode
>>> from unidecode import unidecode
>>> unidecode(u'διακριτικός')
'diakritikos'
```
It does something weird with asian languages:
```
>>> unidecode(u'影師嗎')
'Ying Shi Ma '
>>>
```
Does this make sense?
In askbot we compute slugs like so:
```
from unidecode import unidecode
from django.template import defaultfilters
slug = defaultfilters.slugify(unidecode(input_text))
``` | With **Django >= 1.9**, [`django.utils.text.slugify`](https://docs.djangoproject.com/en/stable/ref/utils/#django.utils.text.slugify) has a `allow_unicode` parameter:
```
>>> slugify("你好 World", allow_unicode=True)
"你好-world"
```
If you use Django <= 1.8 (which you should not since April 2018), you can [pick up the code from Django 1.9](https://github.com/django/django/blob/1.9/django/utils/text.py#L413-L427). | How to make Django slugify work properly with Unicode strings? | [
"",
"python",
"django",
"unicode",
"django-templates",
"slug",
""
] |
This seems to be a question where the answer is implicit, hence I can't find anything explicit.
Does Google Web Toolkit only support custom layout managers, or a sub-set of the Java layout managers?
For example, is it *possible* to take a Java Swing application using GroupLayout and get it to work with GWT? | GWT layout support is done through subclasses of 'Panel'. Some of them like 'DockPanel' behave a little bit like Swing layouts (BorderLayout) but there's no way you'll ever be able to take Swing code and compile it into GWT.
This is a common mis-understanding when it comes to GWT. It's written in Java solely because Java is statically type and widely supported with world class editors. The fact that it's written in Java has nothing to do with any desire by the GWT team to allow you to port SWT/AWT/Swing to GWT. The web is a different environment to the desktop, and since your code ends up compiled into javascript it would never make sense to take any kind of Java Desktop application and hit the convert button. That's what Applets tried to do many years back...and we all know how that turned out ;) | No, GWT doesn't support Layout managers from Swing/AWT. These are not compatible.
Source of incompatibility is that those are totally different technologies with different APIs. Swing/AWT is pixel-based, while GWT renders to HTML. GWT layouts simply output different HTML tags (div/table/inline elements, ...), while Swing/AWT layouts do actually compute position of children components. In GWT, position of children is computed by browser, when they are displayed. | How much support does GWT have for Java layout managers? | [
"",
"java",
"gwt",
"layout-manager",
""
] |
Is there a way to set heap size from a running Java program? | No.
What you can do with an app that has very variable heap requirements is to set your max heap size very high with `-Xmx` and tune `-XX:MaxHeapFreeRatio` and `-XX:MinHeapFreeRatio` so that the app will not hang on to a lot of memory when the heap shrinks (it does that with default settings).
But note that this may cause performance problems when the memory actually used by the app varies both strongly and quickly - in that case you're better off having it hang on to all the memory rather than give it back to the OS only to claim it again a second later. You might also want to fiddle with the [GC options](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp) to ensure that the GC doesn't leave too much unclaimed objects lying around, which it tends to do when there's a lot of room for the heap to grow, and which would defeat the goal of wanting the heap size to adjust to the app's needs. | According to <http://www.dreamincode.net/forums/showtopic96263.htm>, you can't do this at runtime, but you can spawn another process with a different heap size. | Setting JVM heap size at runtime | [
"",
"java",
"jvm",
"runtime",
"heap-memory",
""
] |
I have a query that takes input from the end user and compares it to 2 columns individually, and the two columns concatenated.
```
SELECT f_name, l_name, (f_name + ' ' + l_name) AS full_name
FROM users_table
WHERE f_name = user-input
OR l_name = user-input
OR 'full_name' = user-input
```
Excuse the massive syntax fail, but I assure you it's correct in the program.
It is written in PHP, querying a SQL SERVER 2005 database, and is case insensitive.
Typing one name (first or last) will return correct results, but typing first, then space, then last, returns an empty set.
Any ideas? | that is because 'full\_name' is a literal and not a column name, it does not exists at the WHERE clause level
you need to add
```
OR f_name + ' ' + l_name = user-input
```
instead of
OR 'full\_name' = user-input | Under the "teach a man to fish" theory ...
You cannot use a column alias in a where or group by clause. You can use it in an order by clause. To use a column alias the way you want to, you would have to do something like ...
```
SELECT [Full Name] FROM
(SELECT f_name, l_name, f_name + ' ' + l_name AS [Full Name]
FROM users_table)
WHERE [Full_Name] = @paramVal
``` | SQL concatenating strings? | [
"",
"sql",
"sql-server",
""
] |
HEllo,
I am trying to rotate a circular image around the center and then cut off the sides. I see the imagerotate function, but it does not seem to rotate about centre.
Anyone have any suggestions?
Thank you.
Update: Since it is a circle, I want to cut off the edges and keep my circle in the same dimensions. | The [documentation](https://www.php.net/manual/en/function.imagerotate.php) says that it *does* rotate around the center.
Unfortunately it also says that it will scale the image so that it still fits. That means that whatever you do this function will change the size of your internal circular image.
You could (relatively easily) calculate how much scaling down will happen and then prescale the image up appropriately beforehand.
If you have the PHP "ImageMagick" functions [available](https://www.php.net/manual/en/function.imagick-rotateimage.php) you can use those instead - they apparently don't scale the image. | I faced successfully that problem with the following code
```
$width_before = imagesx($img1);
$height_before = imagesy($img1);
$img1 = imagerotate($img1, $angle, $mycolor);
//but imagerotate scales, so we clip to the original size
$img2 = @imagecreatetruecolor($width_before, $height_before);
$new_width = imagesx($img1); // whese dimensions are
$new_height = imagesy($img1);// the scaled ones (by imagerotate)
imagecopyresampled(
$img2, $img1,
0, 0,
($new_width-$width_before)/2,
($new_height-$height_before)/2,
$width_before,
$height_before,
$width_before,
$height_before
);
$img1 = $img2;
// now img1 is center rotated and maintains original size
```
Hope it helps.
Bye | Php Gd rotate image | [
"",
"php",
"gd",
""
] |
Is there anything readily available in JavaScript (i.e. not through "plugins") that allows me to do something like `setTimeout`, but instead of saying in how many milliseconds something should happen, I give it a date object telling it when to do something?
```
setToHappen(function () {
alert('Wake up!');
}, new Date("..."));
```
And yes, I know I can do this by simply subtracting `new Date()` with my existing date object (or maybe it's the other way around) to get the amount of milliseconds, but I'd still like to know. | You have to compute the number of milliseconds between now and your date object:
```
function setToHappen(fn, date){
return setTimeout(fn, date - Date.now());
}
```
**NB** Please note [@calvin's answer](https://stackoverflow.com/a/781079/1582182): this will not work if the number of milliseconds is greater than `2147483647`. | Since people are talking about calculating timeout intervals using `date` objects, it should be noted that [the max value `setTimeout()` will accept for the interval parameter is 2147483647 (2^31 - 1)](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#maximum_delay_value) as `PRIntervalTime` is a signed 32-bit integer. That comes out to just under 25 days. | setTimeout but for a given time | [
"",
"javascript",
"datetime",
"settimeout",
""
] |
I am nearly done with my site and am optimising it at the moment; I would like to know the best and fastest way to include all my external javascript files. I want the site to download as quick as possible, but it has quite a few (10 or so) external javascript files that need to be loaded; some are jQuery library files from Google's AJAX API and some are mine.
I'm sure I read a while ago that I could call all external scripts using a bit of javascript code, in effect, only calling one external file from the browsers point of view.
Do you see what I mean?
Many thanks | 1. Combine all your Javascript into one external file (you can do this dynamically and save the cached result);
2. Minify that file;
3. Version that file (I use the mtime of a preconfigured file for this);
4. Gzip the file if the client supports that; and
5. Use a far futures Expires header on the file.
What you're referring to (using Google's AJAX Libraries service) is another way to handle this that falls under the heading of a CDN (Content Delivery Network). The idea being that the file is stored in multiple plallllces and the client will download the closest (and that result will be saved).
That's hard or just awkward to combine with other techniques and I've found that doing multiple external loads this way completely erodes any perceived benefit (unless that's your only external load) so I use the method listed above instead. | My guess is to combine the library files to just one file (except the ones hosted at Google). Each call to your server takes quite some resources, so you're better off with just one call. You can even combine the files online:
<http://yui.2clics.net/> | What is the best/fastest way to include my external javascripts? I use jQuery | [
"",
"javascript",
"jquery",
"jscompress",
""
] |
I recently saw a C# constructor that look something like this...
```
public Class foo
{
public foo() : this(new bar())
{}
}
```
Can anybody help me interpret this? where does the bar() fit in?
If you could help me complete the class by inserting the bar() in its proper place so that I can compile/debug and see the whole picture.
Thanks in advance.
Nikos | The foo class should contain another constructor, that takes a bar object as a parameter.
```
public class foo
{
public foo()
: this(new bar())
{ }
public foo(bar b)
{
}
}
public class bar
{
}
``` | There will be a second constructor on class foo with a signature like this
```
public foo(bar Bar)
{
... do something with bar here;
}
``` | C# Constructor | [
"",
"c#",
"constructor",
""
] |
I have a question on programming style and C# language design in general, I'd love to know if there is a better way to do what I'm doing.
If you have a complex data object, with properties that can be null but you want to check or operate on data if it is there, you cannot write a line like so
```
if(Myobject.MyNestedObject != null || Myobject.MyNestedObject.Property != null)
{
//code
}
```
Because the compiler will actually call both lines of code to evaluate the if statement.
Instead you must (I believe) write :
```
if(Myobject.MyNestedObject != null)
{
if(Myobject.MyNestedObject.Property != null)
{
//code
}
}
```
Is there a better style than this? I'm trying to think of how to use null coalesce (??) but it would still throw if you try to use anything of MyNestedObject in the same statement.
More info:
```
L_01b4: ldarg.1
L_01b5: callvirt instance class [Myassembly]MyClass.MyObject [MyAssembly]MyClass::get_MyObject()
L_01ba: brtrue.s L_01cc
L_01bc: ldarg.1
L_01bd: callvirt instance class [MyAssembly]MyClass.MyObject [MyAssembly]MyClass::get_MyObject()
L_01c2: callvirt instance class [MyAssembly]MyClass.MyNestedObject [MyAssembly]MyClass.MyNestedObject::get_MyNestedObject()
L_01c7: ldnull
L_01c8: ceq
L_01ca: br.s L_01cd
L_01cc: ldc.i4.0
L_01cd: stloc.2
L_01ce: ldloc.2
L_01cf: brtrue L_0285
L_01d4: nop
```
From my understanding it's saying that at L\_01ba if the call returns true, not null or non-0 (i.e if the object is null, the branch isn't taken and then control flow continues linearly). This then will of course execute L\_01c2 which will throw a null reference exception, as Myclass.MyObject is null.
Have I missed something. This is the .net 3.5 C# compiler. | Combining @Chris and @aJ answer:
I think you want the && operator, not ||.
```
if (Myobject.MyNestedObject != null &&
Myobject.MyNestedObject.Property != null)
{
//code
}
```
And C#'s && operator use short-circuit evaluation, so if the first expression returns false, the second expression will not be evaluated.
... | ```
if( Myobject.MyNestedObject != null &&
Myobject.MyNestedObject.Property != null)
{
//code
}
``` | C# Nested null checks in if statements | [
"",
"c#",
"coding-style",
"null",
"language-features",
""
] |
I've got a table and I have a text field with a URL again, I don't want any rows with duplicate URL's but I'd rather not do a check before inserting, is there no way to make a text field unique or could you suggest another field type to use? | If your text field in the database is set to unique or a primary key or however you have it set up, than an insert statement will fail upon trying to input a duplicate. That way all you should have to do is properly handle the failed insert and there you have it.
As pointed out elsewhere, you can't have an actual TEXT field be unique, but if you are using a varchar field it is doable. This may not be important at all (may just be a miscommunication), because if you are storing URL's in a TEXT field, you have other problems to worry about as well. | The solution is basically add a extra field on database like field\_hash, make it VARCHAR and Index give unique.
```
CREATE TABLE 'info' (
'text' text NOT NULL,
'text_hash' varchar(40) NOT NULL,
PRIMARY KEY ('id'),
UNIQUE KEY 'text_hash' ('text_hash')
);
$text = 'Full Text';
$text_hash = sha1($text);
mysql_query("INSERT INTO info (text, text_hash) VALUES ('$text', '$text_hash')");
``` | PHP Unique Text Field? | [
"",
"php",
"mysql",
""
] |
I'm combing a webapp's log file for statements that stand out.
Most of the lines are similar and uninteresting. I'd pass them through Unix `uniq`, however that filters nothing, as all the lines are slightly different: they all have a different timestamp, similar statements might print a different user ID, etc.
What's a way and/or tool to get just the lines that are notably different from any other? (But, again, not precise duplicates)
I was thinking about playing with Python's [difflib](http://docs.python.org/library/difflib.html) but that seems geared toward diffing two files, rather than all pairs of lines in the same file.
[EDIT]
I assumed the solution would give a uniqueness score for each line. So by "notably different" I meant, I choose a threshold that the uniqueness score must exceed for any line to be included in the output.
Based on that, if there are other viable ways to define it, please discuss. Also, the method doesn't have to have 100% accuracy and recall.
[/EDIT]
Examples:
I'd prefer answers that are as general purpose as possible. I know I can strip away the timestamp at the beginning. Stripping the end is more challenging, as its language may be absolutely unlike anything else in the file. These sorts of details are why I shied from concrete examples before, but because some people asked...
Similar 1:
```
2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:04:02 INFO com.foo.Bar - URL:/graph?id=asdfghjk
```
Similar 2:
```
2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
2009-04-20 00:06:00 INFO com.baz.abc.Accessor - Cache /path/to/some/different/dir hits: 4352685 / 271315, 0.004423% misses
```
Different 1:
```
2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
```
In the Different 1 case, I'd like both lines returned but not other lines like them. In other words, those 2 lines are distinct types (then I can later ask for only statistically rare line types). The edit distance is much bigger between those two, for one thing. | I don't know a tool for you but if *I* were going to roll my own, I'd approach it like this:
Presumably the log lines have a well defined structure, no? So
* parse the lines on that structure
* write a number of very basic relevance filters (functions that just return a simple number from the parsed structure)
* run the parsed lines through a set of filters, and cut on the basis of the total score
* possibly sort the remaining lines into various bins by the results of more filters
* generate reports, dump bins to files, or other output
If you are familiar with the unix tool `procmail`, I'm suggesting a similar treatment customized for your data.
---
As zacherates notes in the comments, your filters will typically ignore time stamps (and possibly IP address), and just concentrate on the content: for example *really* long http requests might represent an attack...or whatever applies to your domain.
Your binning filters might be as simple as a hash on a few selected fields, or you might try to do something with [Charlie Martin's suggestion](https://stackoverflow.com/questions/769775/the-lines-that-stand-out-in-a-file-but-arent-exact-duplicates/769790#769790) and used edit distance measures. | Define "notably different". Then have a look at ["edit distance" measures](http://en.wikipedia.org/wiki/Edit_distance). | The lines that stand out in a file, but aren't exact duplicates | [
"",
"python",
"algorithm",
"unix",
"grep",
"nlp",
""
] |
We have a setup where we have one httpd (apache) with mod\_jk talking in a load balance setup to three tomcat servers. We have to recycle each tomcat instance envery three hours. So tomcat1 will restart at 1, and tomcat2 at 2 and ... until tomcat1 recycles again at 4.
We want to configure a script or a type of program to disable the worker node that is going through a recylce to minimize session errors at the user using our application.
Any suggestions. | Chris thanks or your answer. I am sure it will work, but I wanted to trigger the change at run time, even though the graceful restart is very similar. I was able to accomplish my describe task the following way.
In your httpd.conf file you should add the following lines to enable the jkmanager for mod\_jk module.
```
<Location /jkmanager/>
JkMount jkstatus
order deny,allow
allow from <your ip address>
allow from 127.0.0.1
deny from all
</Location>
<IfModule mod_jk.c>
...
JkMount /jkmanager/* jkstatus
...
</IfModule>
```
The changes on the "workers.properties" file are:
```
worker.list=router,tomcat1,tomcat2,...,tomcatn,jkstatus
worker.jkstatus.type=status
```
After these changes are done, you are able to see the jkmanager by typing your url followed by /jkmanager/ at the end. You should get something similar to the following picture.
[](https://i.stack.imgur.com/I21Pz.png)
In order to disable workers at run time just run the following URLs against the jkmanger. You can even read status in an xml format.
To disable tomcat1 just hit:
```
http://your.web.server/jkmanager/?cmd=update&w=router&opt=256&from=list&att=vwa&val0=1&val1=0&val2=0
```
To enable tomcat1 back hit:
```
http://your.web.server/jkmanager/?cmd=update&w=router&opt=256&from=list&att=vwa&val0=0&val1=0&val2=0
```
I posted a complete article in my blog explaining the setup in case someone needs to know.
[Cloud Computing Blog](http://www.kiragiannis.com/cloud-computing/growing-and-shrinking-tomcat-workers-in-the-cloud/) | mod\_jk re-reads workers.properties on an "apachectl graceful", so you if your workers.properties looks like this:
```
worker.loadbalancer.type=lb
worker.loadbalancer.balanced_workers=tomcat1, tomcat2, tomcat3
...
```
You could just write a script which replaces the balanced\_workers list with the ones you want, and then graceful's apache
*Update* here's a script to do just that, which I cobbled together from some bits I had lying around. I wouldn't suggest using it in production, but it might give you some ideas for your own version.
```
#!/bin/bash
# set some paths
WORKERS_PROPERTIES="./workers.properties"
APACHECTL="/usr/sbin/apache2ctl"
# what does the loadbalancer config line look like?
WORKER_LINE_START="worker.loadbalancer.balanced_workers="
# full list of workers
ALL_WORKERS="tomcat1 tomcat2 tomcat3"
# first command line arg is the worker to remove.
remove=$1
# build up the new line listing the active workers
worker_line=$WORKER_LINE_START
sep=""
for worker in $ALL_WORKERS
do
if [ ${remove} != ${worker} ]
then
worker_line="${worker_line}$sep $worker"
sep=","
fi
done
# sed hackery to replace the current line with the one we just built.
# needs gnu sed (or another one that supports in-place editing)
sed -i.bak "s/^$WORKER_LINE_START.*$/$worker_line/" $WORKERS_PROPERTIES
# restart apache
$APACHECTL graceful
``` | How to programmatically adjust the disable directive in the mod_jk load balancer configuration? | [
"",
"java",
"apache",
"tomcat",
"mod-jk",
""
] |
What are the advantages of using boost.any library ? Could you please give me some real life examples ? Why the same functionality couldn't be achieved by having some generic type in the root of object's hierarchy and creating containers with that base type ? | I consider that Boost.Variant should always be preferred as it's non-intrusive and still calls for very structured programming.
But i guess the main idea behind boost.any is to provide the equivalent of java and c# object types. It's a way of saying "yes we can" ! :-) | boost::any will happily store ints and floats, types that clearly have no base classes. A real-life example where you can use it is a virtual machine for a high-level interpreted language. Your "function" objects will need an array of arguments. This can easily be implemented with a `std::list<boost::any>` behind the scenes. | What is the typical usage of boost any library? | [
"",
"c++",
"boost",
""
] |
I am building a C# application, using the server-client model, where the server is sending an image (100kb) to the client through a socket every 50ms...
I was using TCP, but besides the overhead of this protocol, sometimes the client ended up with more than one image on the socket. And I still haven't though of a clever mechanism to split the bytes of each image (actually, I just need the most recent one).
I tried using UDP, but got to the conclusion that I can't send 100kb dgrams, only 64kb ones. And even so, I shouldn't use more than 1500bytes; otherwise the packet would be divided along the network and the chances of losing parts of the packet would be greater.
So now I'm a bit confused. Should I continue using TCP and put some escaping bytes in the end of each image so the client can separate them? Or should I use UDP, send dgrams of 1500 bytes and come up with a mechanism for ordering and recovering?
The key goal here is transmitting the images very fast. I don't mind losing some on the way as long as the client keeps receiving newer ones.
Or should I use another protocol? Thanks in advance! | I'd recommend using UDP if:
* Your application can cope with an image or small burst of images not getting through,
* You can squeeze your images into 65535 bytes.
If you're implementing a video conferencing application then it's worth noting that the majority use UDP.
Otherwise you should use TCP and implement an approach to delimit the images. One suggestoin in that regard is to take a look at the [RTP](http://www.ietf.org/rfc/rfc3550.txt) protocol. It's sepcifically designed for carrying real-time data such as VoIP and Video.
Edit: I've looked around quite a few times in the past for a .Net RTP library and apart from wrappers for non .Net libraries or half completed ones I did not have much success. I just had another quick look and this may be of this one [ConferenceXP](http://www.codeplex.com/ConferenceXP) looks a bit more promising. | You should consider using Real-time Transport Protocol (aka [RTP](http://en.wikipedia.org/wiki/Real-time_Transport_Protocol)).
The underlying IP protocol used by RTP is UDP, but it has additional layering to indicate time stamps, sequence order, etc.
RTP is the main media transfer protocol used by VoIP and video-over-IP systems. I'd be quite surprised if you can't find existing C# implementations of the protocol.
Also, if your image files are in JPEG format you should be able to produce an RTP/MJPEG stream. There are quite a few video viewers that already have native support for receiving and displaying such a stream, since some IP webcams output in that format. | To send an image every 50 ms., should I use TCP or UDP? | [
"",
"c#",
"image",
"tcp",
"udp",
""
] |
Using C# 2.0 and the MethodInvoker delegate, I have a GUI application receiving some event from either the GUI thread or from a worker thread.
I use the following pattern for handling the event in the form:
```
private void SomeEventHandler(object sender, EventArgs e)
{
MethodInvoker method = delegate
{
uiSomeTextBox.Text = "some text";
};
if (InvokeRequired)
BeginInvoke(method);
else
method.Invoke();
}
```
By using this pattern I do not duplicate the actual UI code but what I'm not sure about is if this method is good.
In particular, the line
```
method.Invoke()
```
does it use another thread for invoking or does it translate somewhat to a direct call to the method on the GUI thread? | The `method.Invoke()` call executes the delegate on the current executing thread. Using the `BeginInvoke(method)` ensures that the delegate is called on the GUI thread.
This is the correct way of avoiding code duplication when the same method can be called both from the GUI thread and other threads. | Personally I like this method:
```
private void ExecuteSecure(Action a)
{
if (InvokeRequired)
BeginInvoke(a);
else
a();
}
```
And then you can write one-liners like this:
```
ExecuteSecure(() => this.Enabled = true);
``` | Using C# MethodInvoker.Invoke() for a GUI app... is this good? | [
"",
"c#",
"multithreading",
"c#-2.0",
"invoke",
""
] |
I have a class:
```
public class MyClass
{
public int code { set; get; }
public bool foo()
{
// do some stuff
// ...
code = 100;
return true;
}
public bool bar()
{
// do some stuff
// ...
code = 200;
return true;
}
// more methods ...
// ...
}
```
I would like to reset the value of code to zero at the beginning of each member function call. Of course I can manually set the value to zero at the beginning of each function but I am wondering if it is possible to use attributes for this purpose:
```
[ResetTheCode]
public bool bar()
{
// do some stuff
// ...
code = 200;
return true;
}
```
Something similar to action filters in ASP.NET MVC.
Is this possible? | You could definitely do something like this with an AOP framework (like [PostSharp](http://www.postsharp.org/)) but don't you think that would be quite confusing to anyone unfamiliar with your process?
This is one of those things that even though you can do it doesn't necessarily mean you should. The time and effort taken to type the attribute name above the method cannot possibly be less than the time and effort needed to write the reset code (which should be in its own method as well so you don't copy/paste a magic number everywhere). | Agreed with Kent. In addition, take a look at [PostSharp](http://www.postsharp.org/), which is also a very mature .NET AOP framework. | Execute some specific code before member functions of a class using attributes? | [
"",
"c#",
"asp.net-mvc",
""
] |
I have a very special NHibernate mapping case. The class has a reference to itself.
```
public class MyClass
{
public Guid Id { get; set; }
public MyClass SelfReference { get; set; }
}
```
The data base table has a foreign key field on the primary key of the same table. And event worse, this self reference can be null.
Is that possible to map and how can this be done? | one-to-one can be used to synchronize primary keys and is used rarely, in my experience many-to-one is the most "natural" association for "normal" references:
```
<many-to-one name="SelfReference" class="MyClass" column="SelfReference_FK" />
``` | Seems like you're willing to map a tree:
<http://nhibernate.hibernatingrhinos.com/16/how-to-map-a-tree-in-nhibernate> | How to map a self-reference in NHibernate | [
"",
"c#",
"nhibernate-mapping",
""
] |
Is there a 3rd party add-on/application or some way to perform object map dumping in script debugger for a JavaScript object?
Here is the situation... I have a method being called twice, and during each time something is different. I'm not sure what is different, but something is. So, if I could dump all the properties of window (or at least window.document) into a text editor, I could compare the state between the two calls with a simple file diff. Thoughts? | [Firebug](http://getfirebug.com/) + `console.log(myObjectInstance)` | ```
console.log("my object: %o", myObj)
```
Otherwise you'll end up with a string representation sometimes displaying:
```
[object Object]
```
or some such. | Object Dump JavaScript | [
"",
"javascript",
""
] |
What is the C# & .NET Regex Pattern that I need to use to get "bar" out of this url?
> ```
> http://www.foo.com/bar/123/abc
> ```
In ATL regular expressions, the pattern would have been
> ```
> http://www\.foo\.com/{[a-z]+}/123/abc
> ``` | Here is a solution that breaks the url up into component parts; protocol, site and part. The protocol group is not required so you could give the expression 'www.foo.com/bar/123/abc'. The part group can contain multiple sub groups representing the folders and file under the site.
```
^(?<protocol>.+://)?(?<site>[^/]+)/(?:(?<part>[^/]+)/?)*$
```
You would use the expression as follows to get 'foo'
```
string s = Regex.Match(@"http://www.foo.com/bar/123/abc", @"^(?<protocol>.+://)?(?<site>[^/]+)/(?:(?<part>[^/]+)/?)*$").Groups["part"].Captures[0].Value;
```
The breakdown of the expression results are as follows
protocol: http://
site: www.foo.com
part[0]: bar
part[1]: 123
part[2]: abc | Simply:
#http://www\.foo\.com/([a-z]+)/123/abc#
use parenthesis instead of brackets.
You will need to use a character on the front and the end of the regular expression to make it work too. | C# substring parse using regular expression (ATL >> NET)? | [
"",
"c#",
"regex",
"atl",
""
] |
I have one question concerning Python and the sqlalchemy module. What is the equivalent for `cursor.rowcount` in the sqlalchemy Python? | `ResultProxy` objects have a [`rowcount`](https://docs.sqlalchemy.org/en/13/core/connections.html#sqlalchemy.engine.ResultProxy.rowcount) property as well. | Actually there is **no way** to know this precisely for postgres.
The closes thing is `rowcount`. But
`rowcount` is **not** the number of affected rows. Its the number of matched rows. See what [doc](https://docs.sqlalchemy.org/en/14/core/connections.html#sqlalchemy.engine.BaseCursorResult.rowcount) says
> This attribute returns the number of rows *matched*, which is not necessarily the same as the number of rows that were actually *modified* - an UPDATE statement, for example, may have no net change on a given row if the SET values given are the same as those present in the row already. Such a row would be matched but not modified. On backends that feature both styles, such as MySQL, `rowcount` is configured by default to return the match count in all cases
So for both of the following scenarios `rowcount` will report `1`. Because of `Rows matched: 1`
1. one row changed with `update` statement.
```
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
```
2. same `update` statement is executed.
```
Query OK, 0 row affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0
``` | How to get number of affected rows in sqlalchemy? | [
"",
"python",
"sqlalchemy",
""
] |
I thought I would ask this question to see why many examples and people prefer to use inline databinding in the aspx code vs implementing an OnDataBinding event when using WebForms.
For any **databound control (eg. Repeater, GridView, etc)** I always implement the OnDataBinding method for field level controls if I need to do anything that isn't built in out of the box (eg. I need to do an Eval). Most examples I see have the code right in the aspx page using the inline <%# syntax.
Example of inline ASP.NET code:
```
<asp:Literal ID="litExample" runat="server"
Text='<%# Eval("ExampleField").ToString() %>' />
```
Example of how I prefer to do it:
In the aspx:
```
<asp:Literal ID="litExample" runat="server"
OnDataBinding="litExample_DataBinding" />
```
In the codebehind .cs:
```
protected void litExample_DataBinding(object sender, System.EventArgs e)
{
Literal lit = (Literal)(sender);
lit.Text = string.Format("{1} - {2}",
Eval("ExampleField").ToString(),
Eval("ExampleField2").ToString());
}
```
I personally prefer the codebehind method because it keeps my aspx pages clean and I don't have all this inline code all over the place and the next guy just knows to always look in the .cs files for code changes. The seperation of presentation and code is also maintained better this way as the HTML is place holders only and the codebind is determining what is actually being put in control.
Now these are very basic examples. The field could be a integer that you want to format with leading 0s or a DateTime that needs a specific format etc. It could also take all sort of manipulation and code to get the finally value that should be stored in the 'Text' property at the end.
Where do you draw the line and move it to the codebehind if you are using inline code?
What are the pros and cons for doing it either way?
Does one take more overhead than the other?
**Edit Note:** I am not talking about assigning a value to a control that is just on the page but one that is being databound to because it exists in a repeater template or gridview item template etc... Obviously a literal sitting on a page you can just assign in code.
**Edit Note:** I thought I would gather more response, especially with regards to the overhead. Do most people NOT use the OnDataBinding events? | There's little performance difference between them. A data binding expression is parsed and compiles out to something like
```
control.DataBinding += new EventHandler(ControlDataBinding);
```
and also
```
private void ControlDataBinding(object sender, EventArgs e) {
control.Text = Eval("Field");
}
```
In this case, the OnDataBinding method is not overridden. The base Control.OnDataBinding method is executed, which raises the DataBinding event, causing the above code to execute.
When you override OnDataBinding, you're simply taking over before the base code is run, and get to set the `Text` property yourself (for example).
---
I dislike giving out partial answers, but I'll do it this time because I think it's neat, and it saved me recently:
I said that the data binding expression are parsed. In fact, all of the markup is parsed, code in C#, VB.NET or whatever language is generated, and this is them compiled into a class. When the page is requested, an instance of this class is created, and it begins its life.
You can locate these generated code files on disk *sorry, I don't remember where*. The interesting thing about them is that they still work, as code.
For instance, I recently had some fairly complex Infragistics grids set up, had all the formatting complete, and then found that I needed to be able to set the formatting at rumtime (to get the correct format into exported Excel files). In order to do this, I opened the source file (all grids were in a single user control) and was able to extract the configuration of each grid into a separate group of methods.
I was able to clean them up with ReSharper, extract common code sequences into a base class, and was left with one static method to set up each grid. I was then able to call them both for the initial setup, and for the setup of the dummy grid used for Excel export. | I much prefer the opposite. I prefer to keep my code-behind limited to procedural code, and keep all my declarative code in my Aspx page. In your example above, the literal is absolutely declarative and therefore (by my preference) would not belong in code-behind. Much more robust functionality generally goes in my code-behind, and I don't want my developers to be cluttered by having to sift through a bunch of initialization lines when trying to understand it. | OnDataBinding vs Inline: pros, cons and overhead | [
"",
"c#",
"asp.net",
"coding-style",
"code-behind",
""
] |
I can't seem to see the problem with the example code below. For some reason seems to be ignoring the year and saying the dates are the same, as can be seen in the output below. I must be missing something simple.
01/28/2006
01/16/2007
Tue Apr 01 00:00:00 PDT 2008
Tue Apr 01 00:00:00 PDT 2008
done
```
import java.util.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
class ExampleProgram {
public static void main(String[] args){
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String d1String = "01/28/2006";
String d2String = "01/16/2007";
System.out.println(d1String);
System.out.println(d2String);
Date d1=null;
try {
d1 = df.parse(d1String);
} catch (ParseException e) {
System.out.println(e.getMessage());
}
Date d2=null;
try {
d2 = df.parse(d2String);
} catch (ParseException e) {
System.out.println(e.getMessage());
}
System.out.println(d1);
System.out.println(d2);
System.out.println("done");
}
}
``` | ```
"dd/MM/yyyy"
```
should read:
```
"MM/dd/yyyy"
``` | As Peter mentioned, the meaning of the letters can be found in the documentation here:
<https://docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html>. | java string to datetime conversion issue | [
"",
"java",
"string",
"datetime",
""
] |
There are some attributes in HTML which are "boolean" - browsers treat them as "true" if they are present, regardless of the value. An example of such an attribute is **selected** on the `<option>` tag. Another is **checked** on `<input type="checkbox">`.
If you have a call to `setAttribute()` for such an attribute, there seems to be no value you can set to have the browsers consistently behave as though the attribute is missing.
For example
```
option.setAttribute("selected", false)
```
will still mark the option selected. **null**, empty string or **undefined** don't work either. If anyone knows of a value I can set to achieve my goal, please let me know, but I don't think one exists. (Because of some framework code I use, **not** calling `setAttribute()`, or calling `removeAttribute()` is difficult.)
I'm trying to find an exhaustive list of such attributes to special case them. Here's what I have so far:
* **selected** of `<option>`
* **checked** of `<input>`
* **disabled**, **readonly** of `<input>`, `<select>`, `<option>`, `<optgroup>`, `<button>`, `<textarea>`
* **multiple** of `<select>`
Please help me complete this list - or point me to an existing one. | > (Because of some framework code I use, not calling setAttribute(), or calling removeAttribute() is difficult.)
Then I would submit that the framework code needs fixing, or dumping.
You can't setAttribute to unset an attribute, by design. Any solution you found involving out-of-band values like ‘null’, if it happened to work in any particular browser, would be quite invalid according to the DOM Core standard.
setAttribute() is in any case best avoided in browser (non-XML) HTML contexts. IE pre-8 doesn't know the difference between a DOM attribute and a JavaScript property, which can easily result in many really weird problems. If you're trying to set ‘checked’ as an attribute (which theoretically you should do by setting it to the string "checked"), don't expect IE to co-operate.
The full list of boolean attributes in HTML 4.01 (and hence XHTML 1.0) is (with property names where they differ in case):
```
checked (input type=checkbox/radio)
selected (option)
disabled (input, textarea, button, select, option, optgroup)
readonly (input type=text/password, textarea)
multiple (select,input)
ismap isMap (img, input type=image)
defer (script)
declare (object; never used)
noresize noResize (frame)
nowrap noWrap (td, th; deprecated)
noshade noShade (hr; deprecated)
compact (ul, ol, dl, menu, dir; deprecated)
``` | Try [removeAttribute](https://developer.mozilla.org/en/DOM/element.removeAttribute):
```
option.removeAttribute("selected");
```
EDIT: After reading your comment, read [this](https://developer.mozilla.org/en/DOM/element.setAttribute) about setAttribute. Notably:
> Even though getAttribute() returns null for missing attributes, you should use removeAttribute() instead of elt.setAttribute(attr, null) to remove the attribute. | Boolean HTML Attributes | [
"",
"javascript",
"html",
"dom",
"dhtml",
""
] |
This is in relation to this other SO [question](https://stackoverflow.com/questions/793589/overriding-an-existing-file-in-c) which asks how to overwrite an existing file.
The top answer is this:
```
FileStream file = File.Open("text.txt", FileMode.Create);
```
My answer was this:
```
FileStream fs = System.IO.File.Create(fileName);
```
As of when I wrote this question, the tally was 14-0 in favor of `Open`.
If votes are an indication of good versus bad solutions, this makes me wonder a bit:
> Is there something I'm missing in
> these methods that would make it
> clearly that much better to choose
> `Open` over `Create`? | To me, I know exactly what `File.Open("...", FileMode.Create)` does because I can hover over `FileMode.Create` and it tells me that is will create a new file each time. `File.Create("...")` has no such tool tip that indicates that it will do this. | There only one place I know you could look for an answer to this one: [Reflector](http://www.red-gate.com/products/reflector/)
And it turns out both call `new FileStream(...` with a full set of arguments! | Why is File.Open so much better than File.Create for overwriting an existing file? | [
"",
"c#",
"file",
""
] |
I am doing some text processing on a unix system. I have access to the command line on this machine and it has Python, Perl and the default text processing progams installed, awk etc.
I have a text file that looks like below:
```
2029754527851451717
2029754527851451717
2029754527851451717
2029754527851451717
2029754527851451717
2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009
2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009
2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009
2895635937120524206
2895635937120524206
2895635937120524206
2895635937120524206
2895635937120524206
2895635937120524206
5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009
```
It is basically 3 rows: ID ID Date
I am looking to remove all the lines that do not have 2 ID's and a Date. So the finising results will be like this:
```
2029754527851451717 1232453488239 Tue Mar 3 10:47:44 2009
2029754527851451717 1232453488302 Tue Mar 3 10:47:44 2009
2029754527851451717 1232453488365 Tue Mar 3 10:47:44 2009
5622983575622325494 1232453323986 Thu Feb 12 15:57:49 2009
```
How would you guys suggest doing this? In total the text file is around 30,000 lines long.
Cheers
Eef | With `awk`:
```
awk 'NF > 2' input_file > output_file
``` | ```
grep ':' filename
``` | Remove lines from file | [
"",
"python",
"perl",
"text",
"awk",
"text-processing",
""
] |
So what I'm trying to do is replace a string "keyword" with
`"<b>keyword</b>"`
in a larger string.
Example:
myString = "HI there. You should higher that person for the job. Hi hi."
keyword = "hi"
result I would want would be:
`result = "<b>HI</b> there. You should higher that person for the job.`
`<b>Hi</b> <b>hi</b>."`
I will not know what the keyword until the user types the keyword
and won't know the corpus (myString) until the query is run.
I found a solution that works most of the time, but has some false positives,
`namely it would return "<b>hi<b/>gher"`which is not what I want. Also note that I
am trying to preserve the case of the original text, and the matching should take
place irrespective of case. so if the keyword is "hi" it should replace
`HI with <b>HI</b> and hi with <b>hi</b>.`
The closest I have come is using a slightly derived version of this:
<http://code.activestate.com/recipes/576715/>
but I still could not figure out how to do a second pass of the string to fix all of the false positives mentioned above.
Or using the NLTK's WordPunctTokenizer (which simplifies some things like punctuation)
but I'm not sure how I would put the sentences back together given it does not
have a reverse function and I want to keep the original punctuation of myString. Essential, doing a concatenation of all the tokens does not return the original
string. For example I would not want to replace "7 - 7" with "7-7" when regrouping the tokens into its original text if the original text had "7 - 7".
Hope that was clear enough. Seems like a simple problem, but its a turned out a little more difficult then I thought. | This ok?
```
>>> import re
>>> myString = "HI there. You should higher that person for the job. Hi hi."
>>> keyword = "hi"
>>> search = re.compile(r'\b(%s)\b' % keyword, re.I)
>>> search.sub('<b>\\1</b>', myString)
'<b>HI</b> there. You should higher that person for the job. <b>Hi</b> <b>hi</b>.'
```
The key to the whole thing is using [word boundaries](http://docs.python.org/library/re.html), [groups](http://docs.python.org/library/re.html#regular-expression-syntax) and the [re.I flag](http://docs.python.org/library/re.html#re.I). | You should be able to do this very easily with `re.sub` using the word boundary assertion `\b`, which only matches at a word boundary:
```
import re
def SurroundWith(text, keyword, before, after):
regex = re.compile(r'\b%s\b' % keyword, re.IGNORECASE)
return regex.sub(r'%s\0%s' % (before, after), text)
```
Then you get:
```
>>> SurroundWith('HI there. You should hire that person for the job. '
... 'Hi hi.', 'hi', '<b>', '</b>')
'<b>HI</b> there. You should hire that person for the job. <b>Hi</b> <b>hi</b>.'
```
If you have more complicated criteria for what constitutes a "word boundary," you'll have to do something like:
```
def SurroundWith2(text, keyword, before, after):
regex = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % keyword,
re.IGNORECASE)
return regex.sub(r'\1%s\2%s\3' % (before, after), text)
```
You can modify the `[^a-zA-Z0-9]` groups to match anything you consider a "non-word." | Python: Replace string with prefixStringSuffix keeping original case, but ignoring case when searching for match | [
"",
"python",
"regex",
"search",
"replace",
"nltk",
""
] |
Can you store an image in a PHP SESSION ?
I have a multi-step registration process using PHP on my site. On one of the steps, the users can upload their company logo (image).
The last step is to process their credit card.
So before I write any images to the web server and image location to the database, I want to make sure their credit card is valid and process.
As such, is it possible to temporarily store that image data in the SESSION variable?
If not, how else do people temporaily store image data on forms before committing that data? | You can but expect memory usage of your session to increase depending on the size of the images. In order to do so, you must save the file contents into a session variable.
If it is in session data and you have multiple steps after the upload the image will be reloaded (into the session) every page view until the steps are complete.
I would personally recommend against using the session for holding a binary file. Saving the image on disk into a temporary location until the registration is complete. I would only save the path to the temporary file in session. When the transaciton is completed move it to a proper location and do your db inserts.
Also, in essence, session data is stored on disk (or db) anyway so you might as well save the image file once then issue a move command once complete. | I'd save the file to disk, you could even name it using the user's session id. Then there could be some sort of clean up script which is run as a cron job and deletes the images of people who never successfully paid.
If you try and store an image in the session, you're doing it wrong. | PHP - Store Images in SESSION data? | [
"",
"php",
"session",
"image",
""
] |
I tend to think that keeping up-to-date with the latest version is a good thing. That doesn't mean upgrading as soon as the product is released - but within a relatively short timeframe afterwards (3-6 months).
Upgrades can be for application server, .NET Framework, Java SDK, database, third-party components, etc.
I've found that vendors generally provide a reasonably straightforward upgrade path from version to version and upgrading becomes more problematic if the upgrade must skip a few versions (e.g. .NET Framework 1.1 -> 3.5 sp1)
If an application is working well in production without any problems I can understand the desire not to change anything and avoid the overhead of regression testing. However, with more widespread adoption of automated unit testing, if a new version offers significant benefits in terms of performance and/or features is it worth upgrading?
I've found in my experience that products are not usually kept up-to-date and when the particular version of the product is no longer supported the task of upgrading to the latest version tends to be quite time consuming and expensive.
My question is:
Is it a good idea to keep up-to-date with the latest version of major system components such as operating systems, application servers, databases, frameworks, etc?
**Edit**
Currently we have Oracle Application Server 10.1.2.x which is certified to use up to Java SDK 1.4.2. The latest version of Java is now 1.6 (and 1.7 is currently in the works) and Oracle Application Server is up to 10.1.3 (which is certified for SDK 1.5+).
By upgrading to SDK 1.5 (at least), it opens up the possibility for new applications being developed to use existing infrastructure to use more current versions of supporting frameworks such as Hibernate 3.3 or iBATIS 2.3.4 as well as later standards for JSP, JSF, etc.
If these upgrades are not done the new application being developed is limited to using old versions and consequently will add to the time and cost of future upgrades. | I've found empirically that it's usually not worth the hassle to do incremental upgrades of a whole OS on personal linux boxes. After one too many times that yum or apt-get has hosed my system when doing a system wide upgrade, I generally limit myself to upgrading only those packages that I need. Especially for a non-GUi user, I can't remember the last time there was a killer feature in Ubuntu itself rather than (say) R or gcc.
Servers are another matter -- on security patches at least you need to stay cutting edge.
In terms of software, upgrading to a new version immediately doesn't give you as much of a head start as one might think. As you deal with the various breakages introduced by the new version, you'll be going through and clearing the underbrush with a machete, posting answers on Stackoverflow and elsewhere.
Then someone else follows 3 months later and benefits from the path that you and others have cut, all the answers that early adopters have posted online. Your effective lead is (maybe) only 1 month.
(The exception might be for something like IPhone platform or Facebook platform, where dev time is measured in days and first mover advantage is huge.)
IMO with hardware it's probably even more important to wait a while till you get a step function jump. Wait till you get to the equivalent of a 'quarter tank of gas' before upgrading, as the longer you wait the bigger the step function jump for your applications. The very first generation of Intel Macs might have been one of the few times when an early upgrade was warranted, because the jump was so noticeable overnight.
All that said, I think being an early adopter of *concepts* (especially math) is critical (obviously). Software is fine to play around with on your local box, but IMO definitely wait at least 2-3 months after release before bringing it into production. | Upgrade on a test system first. Validate. Wash rinse and repeat. | To upgrade or not to upgrade | [
"",
"java",
".net",
""
] |
I have this string "1.79769313486232E+308" and am trying to convert it to a .NET numeric value (double?) but am getting the below exception. I am using `Convert.ToDouble()`. What is the proper way to do this conversion?
> OverflowException: Value was either too large or too small for a Double | The problem is likely due to the fact that `Double.MaxValue` was converted to a string, and when the string is output, not all the digits are output, instead it is rounded. Parsing this value overflows the double.
Using `Double.TryParse` and subsequently checking equality on the string "1.79769313486232E+308" in case of failure and substituting `Double.MaxValue` should be a quick workaround, if you need to keep the string the way it is.
EDIT: Of course, if you don't need to keep the string the way it is, use the [Round Trip format specifier](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#RFormatString) to produce the string in the first place, as [Jon describes in his answer](https://stackoverflow.com/a/767011/58391). | Unfortunately this value is greater than `double.MaxValue`, hence the exception.
As codekaizen suggests, you could hard-code a test for the string. A better (IMO) alternative if you're the one *producing* the string in the first place is to use the "r" format specifier. Then the string you produce will be "1.7976931348623157E+308" instead, which then parses correctly:
```
string s = double.MaxValue.ToString("r");
double d = double.Parse(s); // No exception
```
Obviously that's no help if you don't have control over the data - but then you should understand you're likely to be losing data already in that case. | Convert "1.79769313486232E+308" to double without OverflowException? | [
"",
"c#",
".net",
"double",
""
] |
Ok - pretty basic scenario, been there before, seemed all so simple - but can't recall enough to work out what's different about the setup at this particular existing codebase.
Winforms App calls Dll which calls Web Service. Reference in the Dll to the Web Service is dynamic. How do I get the URI for the Web Service into a Winforms app.config so I can easily change it for test, dev, live etc.
[Oh just to make it interesting, though I can't see it mattering, the proxy for the web service needs to NOT be regenerated as we have customised it...] | Set the URL directly in your code.
```
YourServiceProxy service = new YourServiceProxy();
service.Url = ConfigurationManager.AppSettings["YourURLKey"];
``` | Can you configure the web service URI dynamically in code? That way you can easily modify the service to point to the desired location.
You can set the Url property of the webservice in code to point to the URI and use Proxy to set the proxy to your custom proxy. | Dynamic Webservice reference from Class Library used in Winforms app (c#) | [
"",
"c#",
"web-services",
""
] |
I am trying to extend the Bitmap class so that I can apply my own effects to an image. When I use this code:
```
namespace ImageEditor
{
public class Effects : System.Drawing.Bitmap
{
public void toBlackAndWhite()
{
System.Drawing.Bitmap image = (Bitmap)this;
AForge.Imaging.Filters.Grayscale filter = new AForge.Imaging.Filters.Grayscale();
this = filter.Apply(this);
}
}
}
```
I get the following error:
```
'ImageEditor.Effects': cannot derive from sealed type 'System.Drawing.Bitmap'
```
So is there a way to get around this or is it simply not possible to extend the class?
Thanks. | You can't derive from Bitmap because it's sealed.
If you want to add a method to the Bitmap class, write an extension method:
```
// Class containing our Bitmap extension methods.
public static class BitmapExtension
{
public static void ToBlackAndWhite(this Bitmap bitmap)
{
...
}
}
```
Then use it like this:
```
Bitmap bitmap = ...;
bitmap.ToBlackAndWhite();
``` | +1 for Judah's answer.
Also, consider returning a new bitmap with the filter applied rather than modifying the original. This will give your app more options in the long run (undo etc) | How can you extend the Bitmap class | [
"",
"c#",
"inheritance",
"bitmap",
""
] |
I've been coding php for a while now and have a pretty firm grip on it, MySQL, well, lets just say I can make it work.
I'd like to make a stats script to track the stats of other websites similar to the obvious statcounter, google analytics, mint, etc.
I, of course, would like to code this properly and I don't see MySQL liking 20,000,000 to 80,000,000 inserts ( 925 inserts per second "roughly\*\*" ) daily.
I've been doing some research and it looks like I should store each visit, "entry", into a csv or some other form of flat file and then import the data I need from it.
Am I on the right track here? I just need a push in the right direction, the direction being a way to inhale 1,000 psuedo "MySQL" inserts per second and the proper way of doing it.
Example Insert: IP, time(), http\_referer, etc.
I need to collect this data for the day, and then at the end of the day, or in certain intervals, update ONE row in the database with, for example, how many extra unique hits we got. I know how to do that of course, just trying to give a visualization since I'm horrible at explaining things.
If anyone can help me, I'm a great coder, I would be more than willing to return the favor. | We tackled this at the place I've been working the last year so over summer. We didn't require much granularity in the information, so what worked very well for us was coalescing data by different time periods. For example, we'd have a single day's worth of real time stats, after that it'd be pushed into some daily sums, and then off into a monthly table.
This obviously has some huge drawbacks, namely a loss of granularity. We considered a lot of different approaches at the time. For example, as you said, CSV or some similar format could potentially serve as a way to handle a month of data at a time. The big problem is inserts however.
Start by setting out some sample schema in terms of EXACTLY what information you need to keep, and in doing so, you'll guide yourself (through revisions) to what will work for you.
Another note for the vast number of inserts: we had potentially talked through the idea of dumping realtime statistics into a little daemon which would serve to store up to an hours worth of data, then non-realtime, inject that into the database before the next hour was up. Just a thought. | For the kind of activity you're looking at, you need to look at the problem from a new point of view: decoupling. That is, you need to figure out how to decouple the data-recording steps so that delays and problems don't propogate back up the line.
You have the right idea in logging hits to a database table, insofar as that guarantees in-order, non-contended access. This is something the database provides. Unfortunately, it comes at a price, one of which is that the database completes the `INSERT` before getting back to you. Thus the recording of the hit is coupled with the invocation of the hit. Any delay in recording the hit will slow the invocation.
MySQL offers a way to decouple that; it's called `INSERT DELAYED`. In effect, you tell the database "insert this row, but I can't stick around while you do it" and the database says "okay, I got your row, I'll insert it when I have a minute". It is conceivable that this reduces locking issues because it lets one thread in MySQL do the insert, not whichever you connect to. Unfortuantely, it only works with MyISAM tables.
Another solution, which is a more general solution to the problem, is to have a logging daemon that accepts your logging information and just en-queues it to wherever it has to go. The trick to making this fast is the en-queueing step. This the sort of solution syslogd would provide. | PHP/MYSQL - Pushing it to the limit? | [
"",
"php",
"mysql",
"database",
""
] |
is there anyway i can have my application tell how much memory the user has and if the application is getting close to taking up a high percentage of that.
also, how do you know how much memory the machine gives to OS, video cards, etc . .
for example, if you have 4gb of memory, how much actual memory is given to applications, can you configure this. | > is there anyway i can have my application tell how much memory the user has and if the application is getting close to taking up a high percentage of that.
Yes, it's possible (see some of the other answers), but it's going to be very unlikely that your application really needs to care. What is it that you're doing where you think you need to be this sensitive to memory pressure?
> also, how do you know how much memory the machine gives to OS, video cards, etc . .
Again, this **should** be possible using WMI calls, but the bigger question is why do you need to do this?
> for example, if you have 4gb of memory, how much actual memory is given to applications, can you configure this.
No, this isn't a configurable value. When a .NET application starts up the operating system allocates a block of memory for it to use. This is handled by the OS and there is no way to configure the algorithms used to determine the amount of memory to allocate. Likewise, there is no way to configure how much of that memory the .NET runtime uses for the managed heap, stack, large object heap, etc. | I think I read the question a little differently, so hopefully this response isn't too off topic!
You can get a good overview of how much memory your application is consuming by using Windows Task Manager, or even better, Sysinternals [Process Monitor](https://technet.microsoft.com/en-us/sysinternals/bb896645.aspx). This is a quick way to review your processes at their peaks to see how they are behaving.
Out of the box, an x86 process will only be able to address 2GB of RAM. This means any single process on your machine can only consume up to 2GB. In reality, your likely to be able to consume only 1.5-1.8 before getting out of memory exceptions.
How much RAM your copy of Windows can actually address will depend on the Windows version and cpu architecture.
Using your example of 4GB RAM, the OS is going to give your applications up to 2GB of RAM to play in (which all processes share) and it will reserve 2GB for itself.
Depending on the operating system your running, you can tweak this, using the /3GB switch in the boot.ini, will adjust that ratio to 3GB for applications and 1GB for the OS. This has some impact to the OS, so I'd review that impact first and see if you can live with tradeoff (YMMV).
For a single application to be able to address greater than /3GB, your going to need to set a particular bit in the PE image header. This [question/answer](https://stackoverflow.com/questions/586826/imagefilelargeaddressaware-and-3gb-os-switch) has good info on this subject already.
The game changes under x64 architecture. :)
Some good reference information:
[Memory Limits for Windows Releases](http://msdn2.microsoft.com/en-us/library/aa366778.aspx)
[Virtual Address Space](http://msdn2.microsoft.com/en-us/library/aa366912(VS.85).aspx) | winforms application memory usage | [
"",
"c#",
"winforms",
"memory",
""
] |
Is there a simple way to open a web page within a GUI's JPanel?
If not, how do you open a web page with the computer's default web browser?
I am hoping for something that I can do with under 20 lines of code, and at most would need to create one class. No reason for 20 though, just hoping for little code...
I am planning to open a guide to go with a game. The guide is online and has multiple pages, but the pages link to each other, so I am hoping I only have to call one URL with my code. | Opening a web page with the default web browser is easy:
```
java.awt.Desktop.getDesktop().browse(theURI);
```
Embedding a browser is not so easy. `JEditorPane` has *some* HTML ability (if I remember my limited Swing-knowledge correctly), but it's very limited and not suiteable for a general-purpose browser. | There are two standard ways that I know of:
1. The standard [`JEditorPane`](http://java.sun.com/javase/6/docs/api/javax/swing/JEditorPane.html) component
2. [`Desktop`](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html).[`getDesktop()`](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#getDesktop()).[`browse(URI)`](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#browse(java.net.URI)) to open the user's default browser (Java 6 or later)
Soon, there will also be a third:
3. The [`JWebPane`](http://blogs.oracle.com/thejavatutorials/entry/html_component) component, which apparently has not yet been released
`JEditorPane` is very bare-bones; it doesn't handle CSS or JavaScript, and you even have to handle hyperlinks yourself. But you can embed it into your application more seamlessly than launching FireFox would be.
Here's a sample of how to use hyperlinks (assuming your documents don't use frames):
```
// ... initialize myEditorPane
myEditorPane.setEditable(false); // to allow it to generate HyperlinkEvents
myEditorPane.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
myEditorPane.setToolTipText(e.getDescription());
} else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
myEditorPane.setToolTipText(null);
} else if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
myEditorPane.setPage(e.getURL());
} catch (IOException ex) {
// handle error
ex.printStackTrace();
}
}
}
});
``` | How do you open web pages in Java? | [
"",
"java",
"web",
"jframe",
""
] |
I have a COM API foo, the IDL looks like:
```
foo([in] unsigned long ulSize, [in, size_is(ulSize)] unsigned char* pData)
```
when I consume this function with `foo(0,NULL);`
I get an error - NULL argument passed. Is there a way to workaround this? | Don't use char\* in COM APIs -- use BSTR instead. Then pass an empty string.
```
foo([in] unsigned long ulSize, [in] BSTR pData)
...
foo(1, _bstr_t(""));
``` | Have you tried passing an empty string?
```
unsigned char Data = 0;
foo(0,&Data);
``` | COM API - could not pass "NULL" for a pointer argument | [
"",
"c++",
"winapi",
"com",
"midl",
""
] |
How to **exclude** certain file type when getting files from a directory?
I tried
```
var files = Directory.GetFiles(jobDir);
```
But it seems that this function can only choose the file types you want to include, not exclude. | You should filter these files yourself, you can write something like this:
```
var files = Directory.GetFiles(jobDir).Where(name => !name.EndsWith(".xml"));
``` | > I know, this a old request, but about me it's always important.
if you want exlude a list of file extension: (based on <https://stackoverflow.com/a/19961761/1970301>)
```
var exts = new[] { ".mp3", ".jpg" };
public IEnumerable<string> FilterFiles(string path, params string[] exts) {
return
Directory
.GetFiles(path)
.Where(file => !exts.Any(x => file.EndsWith(x, StringComparison.OrdinalIgnoreCase)));
}
``` | Exclude certain file extensions when getting files from a directory | [
"",
"c#",
"file",
"directory",
""
] |
What is the smallest way to store a UUID that is human readable and widely database compatible?
I am thinking a char array of some sort using hex values? | As common approach, i think that encoding the binary data (16 bytes) as Base64 could be what you want. | Use [Base-85](http://en.wikipedia.org/wiki/Base-85) encoding to store the UUID as 20 US-ASCII characters. | What is the smallest way to store a UUID that is human readable? | [
"",
"sql",
"database",
"language-agnostic",
"guid",
"uuid",
""
] |
I am currently developing a webapp based on c# that calls some webservices. I have imported three different WSDLs from the provider into my WebApplication3 project (references -> add web reference). In the class viewer they appear as:
WebApplication3.com.provider.webservices1
WebApplication3.com.provider.webservices2
WebApplication3.Properties
Apparently the first and second WSDL have repeated functions (is that the correct name?)
If I add to my Default.aspx.cs the following using:
using WebApplication3.com.sabre.webservices1;
using WebApplication3.com.sabre.webservices2;
using WebApplication3.Properties;
and then try using:
MessageHeader msgHeader = new MessageHeader();
in my WebApplication3 namespace, I get the error
"Ambiguous reference between WebApplication3.com.provider.webservices1 and
WebApplication3.com.provider.webservices2"
I guess this is because it is declared in both WSDL? How can I fix this so I can use it?
Thanks, and sorry if the question is stupid! | try referencing MessageHeader by using its full namespace.
eg.
```
WebApplication3.com.provider.webservices1.MessageHeader msgHeader = new
WebApplication3.com.provider.webservices1.MessageHeader()
```
for brevity you can try
```
using MessageHeader = WebApplication3.com.provider.webservices1.MessageHeader
```
which would let you use
```
MessageHeader msgHeader = new MessageHeader()
```
where MessageHeader is from the webservices1 namespace | It would seem as though you have imported the same WSDL twice -- or at least some of the types used by both are the same. You may be able to disambiguate between the two same-named types not importing both web reference namespaces or by using a namespace alias.
Could you post the actual code snippet and also indicate the URLs that you imported using "Add Web Reference"? Also, what version of Visual Studio are you using and what version of the .Net Framework are you targeting?
**EDIT -- Follow-up based on the information Peter provided in the comment**
I Examined both the URLs you posted, and just wanted to provide a little background. In deed the reason you first saw the error is that both WSDL imports specify the use of the same type, namely *MessageHeader*. Examining the top of each WSDL file:
<http://webservices.sabre.com/wsdl/sabreXML1.0.00/usg/SessionCreateRQ.wsdl>
```
<definitions targetNamespace="https://webservices.sabre.com/websvc">
<types>
<xsd:schema>
<xsd:import namespace="http://www.opentravel.org/OTA/2002/11" schemaLocation="SessionCreateRQRS.xsd"/>
<xsd:import namespace="http://www.ebxml.org/namespaces/messageHeader" schemaLocation="msg-header-2_0.xsd"/>
...
```
<http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirAvailLLS1.1.1RQ.wsdl>
```
<definitions targetNamespace="https://webservices.sabre.com/websvc">
<types>
<xsd:schema>
<xsd:import namespace="http://webservices.sabre.com/sabreXML/2003/07" schemaLocation="OTA_AirAvailLLS1.1.1RQRS.xsd"/>
<xsd:import namespace="http://www.ebxml.org/namespaces/messageHeader" schemaLocation="msg-header-2_0.xsd"/>
...
```
The last line in each WSDL file shows the reason for your type name collision -- the same XSD file is imported by each WSDL file, obviously because both use the same type. When you create a web reference to each WSDL file, Visual Studio examines the WSDL and generates a class that matches the imported *msg-header-2\_0.xsd* schema.
Unfortunately, Visual Studio can't tell that the schema in each separate WSDSL reference is really the same type, and so it dutifully imports each and generates a separate class for each. Although each of the classes generated share the same name, each is defined within it's own unique namespace that correlates to each of the WSDL files.
So, this is why the solution you accepted for your question works -- either specifying the full name of *one* the types works or using an alias to *one* of the types within *one* of the specific namespace.
Another solution would be to fix the two web references to share a single MessageHeader type. This could be done manually, however, you'd have to redo the manual edit each time you refreshed the web service reference, so I wouldn't recommend it. Also, it's probably a better idea to use the proper *MessageHeader* type defined for with each service, despite the fact that they're the same. So, I would create two *using* aliases if you assuming you were going to call both services from the same source file:
```
using MessageHeader1 = WebApplication3.com.sabre.webservices1.MessageHeader;
using MessageHeader2 = WebApplication3.com.sabre.webservices2.MessageHeader;
```
I would use MessageHeader1 with whatever service you referenced under the namespace *WebApplication3.com.sabre.webservices1* and likewise, MessageHeader2 with the other.
Good luck! | Resolve Type Ambiguity When Referencing More Than One Webservice in C# | [
"",
"c#",
".net",
"web-services",
""
] |
When using the wpf elements of my application, everything styles to the operating system, but when I use an OpenDialog or a MessageBox, it renders the older Windows 9X way. Is there an easier way I can do an Application.EnableVisualStyles() equivalent call to make the message boxes and dialogs look the same as the rest of the application? | This blog post may be worth a look:
[Why does the OpenFileDialog in WPF look so “1999” and how can I fix it?](http://learnwpf.com/post/2007/01/05/Why-does-the-OpenFileDialog-in-WPF-look-so-e2809c1999e2809d-and-how-can-I-fix-it.aspx) | You need to add a manifest to your assembly. You can do this via Add New Item-->General-->Application Manifest file.
Then add the following somewhere inside the asmv1 tag in the manifest file:
```
<dependency>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Windows.Common-Controls" version="6.0.0.0" type="win32" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />
</dependentAssembly>
</dependency>
``` | How to enable visual styles in WPF for common dialogs? | [
"",
"c#",
"wpf",
"dialog",
"styles",
""
] |
All reservations about unsecuring your SecureString by creating a System.String out of it **aside**, how can it be done?
How can I convert an ordinary System.Security.SecureString to System.String?
I'm sure many of you who are familiar with SecureString are going to respond that one should never transform a SecureString to an ordinary .NET string because it removes all security protections. **I know**. But right now my program does everything with ordinary strings anyway, and I'm trying to enhance its security and although I'm going to be using an API that returns a SecureString to me I am *not* trying to use that to increase my security.
I'm aware of Marshal.SecureStringToBSTR, but I don't know how to take that BSTR and make a System.String out of it.
For those who may demand to know why I would ever want to do this, well, I'm taking a password from a user and submitting it as an html form POST to log the user into a web site. So... this really has to be done with managed, unencrypted buffers. If I could even get access to the unmanaged, unencrypted buffer I imagine I could do byte-by-byte stream writing on the network stream and hope that that keeps the password secure the whole way. I'm hoping for an answer to at least one of these scenarios. | Use the [`System.Runtime.InteropServices.Marshal`](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.aspx) class:
```
String SecureStringToString(SecureString value) {
IntPtr valuePtr = IntPtr.Zero;
try {
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
return Marshal.PtrToStringUni(valuePtr);
} finally {
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}
```
If you want to avoid creating a managed string object, you can access the raw data using [`Marshal.ReadInt16(IntPtr, Int32)`](https://msdn.microsoft.com/en-us/library/a0zbzkx2.aspx):
```
void HandleSecureString(SecureString value) {
IntPtr valuePtr = IntPtr.Zero;
try {
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
for (int i=0; i < value.Length; i++) {
short unicodeChar = Marshal.ReadInt16(valuePtr, i*2);
// handle unicodeChar
}
} finally {
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}
``` | Obviously you know how this defeats the whole purpose of a SecureString, but I'll restate it anyway.
If you want a one-liner, try this: (.NET 4 and above only)
```
string password = new System.Net.NetworkCredential(string.Empty, securePassword).Password;
```
Where securePassword is a SecureString. | How to convert SecureString to System.String? | [
"",
"c#",
".net",
"security",
"encryption",
""
] |
I'm trying to split a file with a list comprehension using code similar to:
```
lines = [x for x in re.split(r"\n+", file.read()) if not re.match(r"com", x)]
```
However, the lines list always has an empty string as the last element. Does anyone know a way to avoid this (excluding the cludge of putting a pop() afterwards)? | Put the regular expression hammer away :-)
1. You can iterate over a file directly; `readlines()` is almost obsolete these days.
2. Read about [`str.strip()`](http://docs.python.org/library/stdtypes.html#str.strip) (and its friends, `lstrip()` and `rstrip()`).
3. Don't use `file` as a variable name. It's bad form, because `file` is a [built-in function](http://docs.python.org/library/functions.html#file).
You can write your code as:
```
lines = []
f = open(filename)
for line in f:
if not line.startswith('com'):
lines.append(line.strip())
```
If you are still getting blank lines in there, you can add in a test:
```
lines = []
f = open(filename)
for line in f:
if line.strip() and not line.startswith('com'):
lines.append(line.strip())
```
If you really want it in one line:
```
lines = [line.strip() for line in open(filename) if line.strip() and not line.startswith('com')]
```
Finally, if you're on python 2.6, look at the [with statement](http://effbot.org/zone/python-with-statement.htm) to improve things a little more. | lines = file.readlines()
**edit:**
or if you didnt want blank lines in there, you can do
lines = filter(lambda a:(a!='\n'), file.readlines())
**edit^2:**
to remove trailing newines, you can do
lines = [re.sub('\n','',line) for line in filter(lambda a:(a!='\n'), file.readlines())] | Spliting a file into lines in Python using re.split | [
"",
"python",
"regex",
"list-comprehension",
""
] |
I'm currently creating a right-click context menu by instantiating a new `JMenu` on right click and setting its location to that of the mouse's position... Is there a better way? | You are probably manually calling `setVisible(true)` on the menu. That can cause some nasty buggy behavior in the menu.
The `show(Component, int x, int x)` method handles all of the things you need to happen, (Highlighting things on mouseover and closing the popup when necessary) where using `setVisible(true)` just shows the menu without adding any additional behavior.
To make a right click popup menu simply create a [`JPopupMenu`](http://java.sun.com/javase/6/docs/api/javax/swing/JPopupMenu.html).
```
class PopUpDemo extends JPopupMenu {
JMenuItem anItem;
public PopUpDemo() {
anItem = new JMenuItem("Click Me!");
add(anItem);
}
}
```
Then, all you need to do is add a custom [`MouseListener`](http://java.sun.com/javase/6/docs/api/java/awt/event/MouseListener.html) to the components you would like the menu to popup for.
```
class PopClickListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger())
doPop(e);
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger())
doPop(e);
}
private void doPop(MouseEvent e) {
PopUpDemo menu = new PopUpDemo();
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
// Then on your component(s)
component.addMouseListener(new PopClickListener());
```
Of course, the tutorials have a [slightly more in-depth](http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html#popup) explanation.
**Note:** If you notice that the popup menu is appearing way off from where the user clicked, try using the `e.getXOnScreen()` and `e.getYOnScreen()` methods for the x and y coordinates. | This question is a bit old - as are the answers (and the tutorial as well)
The current api for setting a popupMenu in Swing is
```
myComponent.setComponentPopupMenu(myPopupMenu);
```
This way it will be shown automagically, both for mouse and keyboard triggers (the latter depends on LAF). Plus, it supports re-using the same popup across a container's children. To enable that feature:
```
myChild.setInheritsPopupMenu(true);
``` | How do I create a right click context menu in Java Swing? | [
"",
"java",
"swing",
"contextmenu",
"jpopupmenu",
""
] |
how do i highlight the selected item (in my case, a custom user control) in a flowlayoutpanel | FlowLayoutPanel is purely for layout - it has no concept of a "selected item". You might be able to add some logic to your UserControl which changes its colour when it receives focus (and changes back when it loses focus) but that would be independent of the layout control that's hosting it. | I created a Bindable FlowLayoutPanel that included setting the selected index (with highlighting depending on the selected control. I posted it over on the [code review](https://codereview.stackexchange.com/questions/8816/binding-flowlayoutpanel) site. Check it out and let me know if that works for you. | highlight selected item in flowlayoutpanel | [
"",
"c#",
"winforms",
"flowlayoutpanel",
""
] |
say i have a table
```
Id int
Region int
Name nvarchar
select * from table1 where region = 1 and name = 'test'
select * from table1 where name = 'test' and region = 1
```
will there be a difference in performance?
assume no indexes
is it the same with LINQ? | Because your qualifiers are, in essence, actually the same (it doesn't matter what order the where clauses are put in), then no, there's no difference between those.
As for LINQ, you will need to know what query LINQ to SQL actually emits (you can use a SQL Profiler to find out). Sometimes the query will be the simplest query you can think of, sometimes it will be a convoluted variety of such without you realizing it, because of things like dependencies on FKs or other such constraints. LINQ also wouldn't use an \* for select.
The only real way to know is to find out the SQL Server Query Execution plan of both queries. To read more on the topic, go here:
[SQL Server Query Execution Plan Analysis](http://www.sql-server-performance.com/tips/query_execution_plan_analysis_p1.aspx) | Should it? No. SQL is a relational algebra and the DBMS should optimize irrespective of order within the statement.
Does it? Possibly. Some DBMS' may store data in a certain order (e.g., maintain a key of some sort) despite what they've been told. But, and here's the crux: you cannot rely on it.
You may need to switch DBMS' at some point in the future. Even a later version of the *same* DBMS may change its behavior. The only thing you should be relying on is what's in the SQL standard.
Regarding the query given: with no indexes or primary key on the two fields in question, you should assume that you'll need a full table scan for both cases. Hence they should run at the same speed. | Does the way you write sql queries affect performance? | [
"",
"sql",
"linq",
""
] |
I have code that looks essentially like this:
```
std::map<int, int> map1, map2;
BOOST_FOREACH(int i, map1)
{
// do steps 1-5 here...
}
BOOST_FOREACH(int i, map2)
{
// do steps 1-5 (identical to above) here...
}
```
Is there any way to concatenate the maps to eliminate the duplicate code in the second loop? Or a way to extend BOOST\_FOREACH to iterate over two different maps in one go? Obviously I don't want to increase the time complexity of the program (otherwise I could just create a new map and insert into it map1 and map2). I have a feeling I am missing something rudimentary here. | You could define a function:
```
typedef std::map<int, int> IntMap;
void doStuffWithInt(IntMap::value_type &i)
{
// steps 1 to 5
}
BOOST_FOREACH(IntMap::value_type &i, map1)
doStuffWithInt(i);
BOOST_FOREACH(IntMap::value_type &i, map2)
doStuffWithInt(i);
```
Although in that case it might be even simpler to use `std::for_each`:
```
for_each(map1.begin(), map1.end(), doStuffWithInt);
for_each(map2.begin(), map2.end(), doStuffWithInt);
``` | The idea here is to write a special type of iterators to virtually merge two containers, as far as BOOST\_FOREACH is concerned. Note that i am not creating a new container out of the two existing ones. I am simply jumping from the first container's end() to the second container's begin() iterator.
I did not try and write the actual merged\_iterator class, but although it might a bit long to write, it's not technically difficult. I am actually surprised not to have found something like that using google. I did not look for long, though !
```
template<typename Container>
boost::iterator_range<
merged_iterator<Container::iterator>
>
concat_containers( Container& c1, Container& c2 )
{
typedef merged_iterator<typename Container::iterator> MergedIterator;
typedef boost::iterator_range<MergedIterator> IteratorRange;
return IteratorRange(
MergeIterator( c1.begin(), c1.end(), c2.begin(), c2.end() ),
MergeIterator( c2.end(), c1.end(), c2.begin(), c2.end() ) );
}
// Now use a bit of magic to define merged_iterator<...>
// And you'll be able to write
BOOST_FOREACH( std::pair<int, int> i, concat_containers( map1, map2 ) )
{
// Do whatever you want here
}
``` | How to use BOOST_FOREACH with two std::maps? | [
"",
"c++",
"stl",
"boost",
"foreach",
"maps",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.