Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I have already posted something similar [here](https://stackoverflow.com/questions/118051/c-grid-binding-not-update) but I would like to ask the question more general over here.
Have you try to serialize an object that implement INotifyPropertyChanged and to get it back from serialization and to bind it to a DataGridView? When I do it, I have no refresh from the value that change (I need to minimize the windows and open it back).
Do you have any trick?
|
Use the `DataContractSerializer` and create a method for OnDeserialized
```
[OnDeserialized]
private void OnDeserialized(StreamingContext c) {}
```
This will let you raise the PropertyChanged event when deserialization is complete
|
The trick of having it's own [Event and binding it after serialization](https://stackoverflow.com/questions/118051/c-grid-binding-not-update#118438) works but is not elegant because require an other event that I would not like to have...
|
C# serialization and event for data binding are lost
|
[
"",
"c#",
"data-binding",
"serialization",
""
] |
I have a string which contain tags in the form `< tag >`. Is there an easy way for me to programmatically replace instances of these tags with special ascii characters? e.g. replace a tag like `"< tab >"` with the ascii equivelent of `'/t'`?
|
```
string s = "...<tab>...";
s = s.Replace("<tab>", "\t");
```
|
```
using System.Text.RegularExpressions;
Regex.Replace(s, "TAB", "\t");//s is your string and TAB is a tab.
```
|
C# string manipulation search and replace
|
[
"",
"c#",
"regex",
"string",
""
] |
What are the best practices for using Java's `@Override` annotation and why?
It seems like it would be overkill to mark every single overridden method with the `@Override` annotation. Are there certain programming situations that call for using the `@Override` and others that should never use the `@Override`?
|
Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.
Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like `@Implements`), but it's better than nothing.
|
I think it is most useful as a compile-time reminder that the intention of the method is to override a parent method. As an example:
```
protected boolean displaySensitiveInformation() {
return false;
}
```
You will often see something like the above method that overrides a method in the base class. This is an important implementation detail of this class -- we don't want sensitive information to be displayed.
Suppose this method is changed in the parent class to
```
protected boolean displaySensitiveInformation(Context context) {
return true;
}
```
This change will not cause any compile time errors or warnings - but it completely changes the intended behavior of the subclass.
To answer your question: you should use the @Override annotation if the lack of a method with the same signature in a superclass is indicative of a bug.
|
When do you use Java's @Override annotation and why?
|
[
"",
"java",
"annotations",
""
] |
I have a static library written in C++ and I have a structure describing data format, i.e.
```
struct Format{
long fmtId;
long dataChunkSize;
long headerSize;
Format(long, long, long);
bool operator==(Format const & other) const;
};
```
Some of data formats are widely used, like `{fmtId=0, dataChunkSize=128, headerSize=0}` and `{fmtId=0, dataChunkSize=256, headerSize=0}`
Some data structure classes receive format in constructor. I'd like to have some sort of shortcuts for those widely used formats, like a couple of global `Format` members `gFmt128, gFmt256` that I can pass by reference. I instantiate them in a .cpp file like
`Format gFmt128(0, 128, 0);`
and in .h there is
`extern Format gFmt128;`
also, I declare `Format const & Format::Fmt128(){return gFmt128;}` and try to use it in the main module.
But if I try and do it in the main module that uses the lib, the linker complains about unresolved external `gFmt128`.
How can I make my library 'export' those global vars, so I can use them from other modules?
|
Don't use the static keyword on global declarations. [Here is an article explain the visibility of variables with/without static](http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx). The static gives globals internal linkage, that is, only visible in the translation unit they are declared in.
|
Are they defined in .cpp file as well? Roughly, it should look like:
```
struct Format
{
[...]
static Format gFmt128;
};
// Format.cpp
Format Format::gFmt128 = { 0, 128, 0 }
```
|
Export variable from C++ static library
|
[
"",
"c++",
"export",
""
] |
I want to build an executable to distribute to people without python installed on their machines.
Is there an add-on to Eclipse that allows this? I couldn't find one.
If not, do you have a builder that you recommend that would make it easy to go to my python project directory created in Eclipse, and bundle it all up?
Thanks,
Mark
|
[See](https://stackoverflow.com/questions/2933/an-executable-python-app) [these](https://stackoverflow.com/questions/106725/how-to-bundle-a-python-application-including-dependencies-for-windows) [questions](https://stackoverflow.com/questions/116657/how-do-you-create-an-osx-applicationdmg-from-a-python-package)
|
It's not eclipse, but ActiveState's [ActivePython FAQ](http://docs.activestate.com/activepython/2.5/faq/windows/index.html#where-is-freeze-for-windows) mentions the freeze utility, which sounds like it might be close to what you're asking for.
|
Is there an Eclipse add-on to build a python executable for distribution?
|
[
"",
"python",
"eclipse",
"bytecode",
""
] |
This came up in [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python), but I can't see good documentation or examples that explain how the feature works.
|
`Ellipsis`, or `...` is not a hidden feature, it's just a constant. It's quite different to, say, javascript ES6 where it's a part of the language syntax. No builtin class or Python language constuct makes use of it.
So the syntax for it depends entirely on you, or someone else, having written code to understand it.
Numpy uses it, as stated in the [documentation](https://web.archive.org/web/20150709134943/http://wiki.scipy.org:80/Numpy_Example_List_With_Doc#head-490d781b49b68b300eedaef32369fae7d58627fb). Some examples [here](https://web.archive.org/web/20150802020005/http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-864862d3f2bb4c32f04260fac61eb4ef34788c4c).
In your own class, you'd use it like this:
```
>>> class TestEllipsis(object):
... def __getitem__(self, item):
... if item is Ellipsis:
... return "Returning all items"
... else:
... return "return %r items" % item
...
>>> x = TestEllipsis()
>>> print x[2]
return 2 items
>>> print x[...]
Returning all items
```
Of course, there is the [python documentation](https://docs.python.org/3/library/constants.html#Ellipsis "Ellipsis"), and [language reference](https://docs.python.org/3/reference/expressions.html#grammar-token-slicing). But those aren't very helpful.
|
The ellipsis is used in numpy to slice higher-dimensional data structures.
It's designed to mean *at this point, insert as many full slices (`:`) to extend the multi-dimensional slice to all dimensions*.
**Example**:
```
>>> from numpy import arange
>>> a = arange(16).reshape(2,2,2,2)
```
Now, you have a 4-dimensional matrix of order 2x2x2x2. To select all first elements in the 4th dimension, you can use the ellipsis notation
```
>>> a[..., 0].flatten()
array([ 0, 2, 4, 6, 8, 10, 12, 14])
```
which is equivalent to
```
>>> a[:,:,:,0].flatten()
array([ 0, 2, 4, 6, 8, 10, 12, 14])
```
In your own implementations, you're free to ignore the contract mentioned above and use it for whatever you see fit.
|
How do you use the ellipsis slicing syntax in Python?
|
[
"",
"python",
"numpy",
"subclass",
"slice",
"ellipsis",
""
] |
When a class field is accessed via a getter method by multiple threads, how do you maintain thread safety? Is the synchronized keyword sufficient?
Is this safe:
```
public class SomeClass {
private int val;
public synchronized int getVal() {
return val;
}
private void setVal(int val) {
this.val = val;
}
}
```
or does the setter introduce further complications?
|
If you use 'synchronized' on the setter here too, this code is threadsafe. However it may not be sufficiently granular; if you have 20 getters and setters and they're all synchronized, you may be creating a synchronization bottleneck.
In this specific instance, with a single int variable, then eliminating the 'synchronized' and marking the int field 'volatile' will also ensure visibility (each thread will see the latest value of 'val' when calling the getter) but it may not be synchronized enough for your needs. For example, expecting
```
int old = someThing.getVal();
if (old == 1) {
someThing.setVal(2);
}
```
to set val to 2 if and only if it's already 1 is incorrect. For this you need an external lock, or some atomic compare-and-set method.
I strongly suggest you read *Java Concurrency In Practice* by Brian Goetz *et al*, it has the best coverage of Java's concurrency constructs.
|
In addition to [Cowan's comment](https://stackoverflow.com/questions/118371/how-do-you-ensure-multiple-threads-can-safely-access-a-class-field#118388), you could do the following for a compare and store:
```
synchronized(someThing) {
int old = someThing.getVal();
if (old == 1) {
someThing.setVal(2);
}
}
```
This works because the lock defined via a synchronized method is implicitly the same as the object's lock ([see java language spec](http://java.sun.com/docs/books/jls/third_edition/html/statements.html#255769)).
|
How do you ensure multiple threads can safely access a class field?
|
[
"",
"java",
"multithreading",
"synchronized",
""
] |
I'm trying to write a query that will pull back the two most recent rows from the Bill table where the Estimated flag is true. The catch is that these need to be consecutive bills.
To put it shortly, I need to enter a row in another table if a Bill has been estimated for the last two bill cycles.
I'd like to do this without a cursor, if possible, since I am working with a sizable amount of data and this has to run fairly often.
**Edit**
There is an AUTOINCREMENT(1,1) column on the table. Without giving away too much of the table structure, the table is essentially of the structure:
```
CREATE TABLE Bills (
BillId INT AUTOINCREMENT(1,1,) PRIMARY KEY,
Estimated BIT NOT NULL,
InvoiceDate DATETIME NOT NULL
)
```
So you might have a set of results like:
```
BillId AccountId Estimated InvoiceDate
-------------------- -------------------- --------- -----------------------
1111196 1234567 1 2008-09-03 00:00:00.000
1111195 1234567 0 2008-08-06 00:00:00.000
1111194 1234567 0 2008-07-03 00:00:00.000
1111193 1234567 0 2008-06-04 00:00:00.000
1111192 1234567 1 2008-05-05 00:00:00.000
1111191 1234567 0 2008-04-04 00:00:00.000
1111190 1234567 1 2008-03-05 00:00:00.000
1111189 1234567 0 2008-02-05 00:00:00.000
1111188 1234567 1 2008-01-07 00:00:00.000
1111187 1234567 1 2007-12-04 00:00:00.000
1111186 1234567 0 2007-11-01 00:00:00.000
1111185 1234567 0 2007-10-01 00:00:00.000
1111184 1234567 1 2007-08-30 00:00:00.000
1111183 1234567 0 2007-08-01 00:00:00.000
1111182 1234567 1 2007-07-02 00:00:00.000
1111181 1234567 0 2007-06-01 00:00:00.000
1111180 1234567 1 2007-05-02 00:00:00.000
1111179 1234567 0 2007-03-30 00:00:00.000
1111178 1234567 1 2007-03-02 00:00:00.000
1111177 1234567 0 2007-02-01 00:00:00.000
1111176 1234567 1 2007-01-03 00:00:00.000
1111175 1234567 0 2006-11-29 00:00:00.000
```
In this case, only records 1111188 and 1111187 would be consecutive.
|
Assuming the rows have sequential IDs, something like this may be what you're looking for:
```
select top 1 *
from
Bills b1
inner join Bills b2 on b1.id = b2.id - 1
where
b1.IsEstimate = 1 and b2.IsEstimate = 1
order by
b1.BillDate desc
```
|
```
select top 2 *
from bills
where estimated = 1
order by billdate desc
```
|
Find two consecutive rows
|
[
"",
"sql",
"sql-server",
"database",
""
] |
Does anyone know how to solve this java error?
```
java.io.IOException: Invalid keystore format
```
I get it when I try and access the certificate store from the Java option in control panels. It's stopping me from loading applets that require elevated privileges.
[Error Image](http://img72.imageshack.us/my.php?image=javaerrorxq7.jpg)
|
I was able to reproduce the error by mangling the trusted.certs file at directory
`C:\Documents and Settings\CDay\Application Data\Sun\Java\Deployment\security`.
Deleting the file fixed the problem.
|
Do not include special characters in organization name and unit
|
Java: Invalid Keystore format Error
|
[
"",
"java",
"keystore",
""
] |
In a destructor, is there a way to determine if an exception is currently being processed?
|
You can use std::uncaught\_exception(), but it might not do what you think it does: see [GoTW#47](http://www.gotw.ca/gotw/047.htm "GoTW#47") for more information.
|
As Luc said, you can use std::uncaught\_exception(). But why do you want to know? In any case, [destructors should never throw exceptions](http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.3)!
|
Is there a way to determine if an exception is occurring?
|
[
"",
"c++",
"exception",
"destructor",
""
] |
In my work I deal mostly with C# code nowadays, with a sprinkle of java from time to time. What I absolutely love about Eclipse (and I know people using it daily love it even more) is a sophisticated code formatter, able to mould code into any coding standard one might imagine. Is there such a tool for C#? Visual Studio code formatting (Crtl+K, Crtl+D) is subpar and StyleCop only checks the source without fixing it.
My dream tool would run from console (for easy inclusion in automated builds or pre-commit hooks and for execution on Linux + Mono), have text-file based configuration easy to store in a project repository and a graphical rule editor with preview - just like the Eclipse Code Formatter does.
|
For Visual Studio, take a look at [ReSharper](http://www.jetbrains.com/resharper). It's an awesome tool and a definite must-have. Versions after 4.0 have the code formatting and clean-up feature that you are looking for. There's also [plugin integration with StyleCop](http://stylecopforresharper.codeplex.com/), including formatting settings file.
You'll probably want [Agent Smith plugin](https://resharper-plugins.jetbrains.com/packages/ReSharper.AgentSmith/) as well, for spell-checking the identifiers and comments. ReSharper supports per-solution formatting setting files, which can be checked into version control system and shared by the whole team. The keyboard shortcut for code cleanup is `Ctrl` + `E`, `C`.
In 'vanilla' Visual Studio, the current file can be automatically formatted with `Ctrl` + `K`, `Ctrl` + `D`, and `Ctrl` + `K`, `Ctrl` + `F` formats the selected text.
As for a runs-everywhere command line tool to be used with commit hooks, try [NArrange](http://www.narrange.net/). It's free, can process whole directories at once and runs on Mono as well as on Microsoft .NET.
Some people also use the [Artistic Style](http://astyle.sourceforge.net/) command line tool, although it requires Perl and works better with C/C++ code than with C#.
|
The [.NET Foundation](https://en.wikipedia.org/wiki/.NET_Foundation) just released their code formatting tool on GitHub
<https://github.com/dotnet/codeformatter>
It uses the [Roslyn](https://en.wikipedia.org/wiki/.NET_Compiler_Platform) compiler services to parse project documents and convert them to their expected formatting conventions. They're applying this to some of the very old [CLR](https://en.wikipedia.org/wiki/Common_Language_Runtime) code in order to make all the projects consistent.
|
Is there an automatic code formatter for C#?
|
[
"",
"c#",
"formatting",
"build-automation",
""
] |
I thought I heard that [py2exe](http://www.py2exe.org/) was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?
Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.
|
[PyInstaller](http://www.pyinstaller.org/) will create a single .exe file with no dependencies; use the `--onefile` option. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see [minty's answer](https://stackoverflow.com/questions/112698/py2exe-generate-single-executable-file#113014))
I use the version of PyInstaller from svn, since the latest release (1.3) is somewhat outdated. It's been working really well for an app which depends on PyQt, PyQwt, numpy, scipy and a few more.
|
The way to do this using py2exe is to use the bundle\_files option in your setup.py file. For a single file you will want to set `bundle_files` to 1, `compressed` to True, and set the zipfile option to None. That way it creates one compressed file for easy distribution.
Here is a more complete description of the bundle\_file option quoted directly from the [py2exe site](http://www.py2exe.org/index.cgi/SingleFileExecutable?highlight=(file)|(single))\*
> Using "bundle\_files" and "zipfile"
>
> An easier (and better) way to create
> single-file executables is to set
> bundle\_files to 1 or 2, and to set
> zipfile to None. This approach does
> not require extracting files to a
> temporary location, which provides
> much faster program startup.
>
> Valid values for bundle\_files are:
>
> * 3 (default) don't bundle
> * 2 bundle everything but the Python interpreter
> * 1 bundle everything, including the Python interpreter
>
> If zipfile is set to None, the files will be bundle
> within the executable instead of library.zip.
Here is a sample setup.py:
```
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1, 'compressed': True}},
windows = [{'script': "single.py"}],
zipfile = None,
)
```
|
py2exe - generate single executable file
|
[
"",
"python",
"packaging",
"py2exe",
""
] |
I have a huge file, where I have to insert certain characters at a specific location. What is the easiest way to do that in C# without rewriting the whole file again.
|
Filesystems do not support "inserting" data in the middle of a file. If you really have a need for a file that can be written to in a sorted kind of way, I suggest you look into using an embedded database.
You might want to take a look at [SQLite](http://sqlite.org/) or [BerkeleyDB](http://www.oracle.com/technology/products/berkeley-db/index.html).
Then again, you might be working with a text file or a legacy binary file. In that case your only option is to rewrite the file, at least from the insertion point up to the end.
I would look at the [FileStream](http://msdn.microsoft.com/en-us/library/system.io.filestream(VS.80).aspx) class to do random I/O in C#.
|
You will probably need to rewrite the file from the point you insert the changes to the end. You might be best always writing to the end of the file and use tools such as sort and grep to get the data out in the desired order. I am assuming you are talking about a text file here, not a binary file.
|
How to insert characters to a file using C#
|
[
"",
"c#",
".net",
"file",
"random-access",
""
] |
I have a given certificate installed on my server. That certificate has valid dates, and seems perfectly valid in the Windows certificates MMC snap-in.
However, when I try to read the certificate, in order to use it in an HttpRequest, I can't find it. Here is the code used:
```
X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly); X509Certificate2Collection col =
store.Certificates.Find(X509FindType.FindBySerialNumber, "xxx", true);
```
`xxx` is the serial number; the argument `true` means "only valid certificates". The returned collection is empty.
The strange thing is that if I pass `false`, indicating invalid certificates are acceptable, the collection contains one element—the certificate with the specified serial number.
In conclusion: the certificate appears valid, but the `Find` method treats it as invalid! Why?
|
Try verifying the certificate chain using the [X509Chain](http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509chain.aspx) class. This can tell you exactly why the certificate isn't considered valid.
As erickson suggested, your X509Store may not have the trusted certificate from the CA in the chain. If you used OpenSSL or another tool to generate your own self-signed CA, you need to add the public certificate for that CA to the X509Store.
|
Is the issuer's certificate present in the X509Store? A certificate is only valid if it's signed by someone you trust.
Is this a certificate from a real CA, or one that you signed yourself? Certificate signing tools often used by developers, like OpenSSL, don't add some important extensions by default.
|
Why is this X.509 certificate considered invalid?
|
[
"",
"c#",
"ssl",
"certificate",
"x509",
""
] |
Is it possible to call a COM API from Java (specifically the HP/Mercury Quality Center OTA API)? If so, what's the best way?
Is something like JACOB appropriate?
Code fragments would be helpful for the basics :-)
|
jacob : yes, <http://sourceforge.net/projects/jacob-project/> is an active project that will suite your purpose pretty well.
you can see multiple examples : <http://jacob-project.wiki.sourceforge.net/Event+Callbacks>
but if you want something that is more tested and are willing to pay money, then go for <http://www.nevaobject.com/_docs/_java2com/java2com.htm>.
|
after a comparison of all the above, none was totally satisfactory.
the most complete solution is in
<https://github.com/java-native-access/jna>
now.
It supports,
* getting interface to a running COM object
* starting a new COM object and returning its interface
* calling COM methods and returning results
* optional separate COM thread handling
* ComEventCallbacks
* RunninObjectTable queries
* lowlevel COM use
* util / high level java proxy abstraction
E.g.
```
MsWordApp comObj = this.factory.createObject(MsWordApp.class);
Documents documents = comObj.getDocuments();
_Document myDocument = documents.Add();
String path = new File(".").getAbsolutePath();
myDocument.SaveAs(path + "\\abcdefg", WdSaveFormat.wdFormatPDF);
comObj.Quit();
```
|
Is it possible to call a COM API from Java?
|
[
"",
"java",
"api",
"com",
"hp-quality-center",
""
] |
After a bind a method to an event of a Tkinter element is there a way to get the method back?
```
>>> root = Tkinter.Tk()
>>> frame = Tkinter.Frame(root, width=100, height=100)
>>> frame.bind('<Button-1>', lambda e: pprint('Click')) # function needed
>>> frame.pack()
>>> bound_event_method = frame.???
```
|
The associated call to do that for the tk C API would be [Get\_GetCommandInfo](http://linux.about.com/library/cmd/blcmdl3_Tcl_GetCommandInfo.htm) which
> places information about the command
> in the Tcl\_CmdInfo structure pointed
> to by infoPtr
However this function is not used anywhere in [\_tkinter.c](http://svn.python.org/projects/python/trunk/Modules/_tkinter.c) which is the binding for tk used by python trough [Tkinter.py](http://svn.python.org/projects/python/trunk/Lib/lib-tk/Tkinter.py).
Therefore it is impossible to get the bound function out of tkinter. You need to remember that function yourself.
|
The standard way to do this in Tcl/Tk is trivial: you use the same bind command but without the final argument.
```
bind .b <Button-1> doSomething
puts "the function is [bind .b <Button-1>]"
=> the function is doSomething
```
You can do something similar with Tkinter but the results are, unfortunately, not quite as usable:
```
e1.bind("<Button-1>",doSomething)
e1.bind("<Button-1>")
=> 'if {"[-1208974516doSomething %# %b %f %h %k %s %t %w %x %y %A %E %K %N %W %T %X %Y %D]" == "break"} break\n'
```
Obviously, Tkinter is doing a lot of juggling below the covers. One solution would be to write a little helper procedure that remembers this for you:
```
def bindWidget(widget,event,func=None):
'''Set or retrieve the binding for an event on a widget'''
if not widget.__dict__.has_key("bindings"): widget.bindings=dict()
if func:
widget.bind(event,func)
widget.bindings[event] = func
else:
return(widget.bindings.setdefault(event,None))
```
You would use it like this:
```
e1=Entry()
print "before, binding for <Button-1>: %s" % bindWidget(e1,"<Button-1>")
bindWidget(e1,"<Button-1>",doSomething)
print " after, binding for <Button-1>: %s" % bindWidget(e1,"<Button-1>")
```
When I run the above code I get:
```
before, binding for <Button-1>: None
after, binding for <Button-1>: <function doSomething at 0xb7f2e79c>
```
As a final caveat, I don't use Tkinter much so I'm not sure what the ramifications are of dynamically adding an attribute to a widget instance. It seems to be harmless, but if not you can always create a global dictionary to keep track of the bindings.
|
Get Bound Event Handler in Tkinter
|
[
"",
"python",
"user-interface",
"events",
"tkinter",
""
] |
Whenever I indent `HTML` in `PHP` mode, `emacs (22.1.1, basic install on Redaht Linux over Putty-SSH)` pops up a frame and tells me to get `MUMODE` or `somesuch` extra add-on. I installed `PHP` Mode without a big hassle, but I don't know how to get this multi-mode rolling.
---
I'd like to know 2 things
```
How to install and configure multi-mode
How to disable pop-ups in Emacs
```
|
If you're running emacs 22, you should just be able to run:
```
M-x nxhtml-mumamo
```
when editing an html document. You might want to add it to your auto-mode-alist to get it to automatically load for html docs. See here for more info:
<http://www.emacswiki.org/cgi-bin/wiki/MuMaMo>
<http://www.emacswiki.org/cgi-bin/wiki/PhpMode>
|
web-mode.el is available on <http://web-mode.org>
This major mode is designed to edit html php templates (with JS and CSS)
Add those two lines in your `.emacs`
```
(require 'web-mode)
(add-to-list 'auto-mode-alist '("\\.phtml$" . web-mode))
```
|
How do I enable multimode emacs to program PHP without messing up my indents?
|
[
"",
"php",
"emacs",
""
] |
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port.
I know that TcpClient will assign a new client side port when I open a connection to a given server.
Is there a simple way to find the next open TCP port in .NET?
I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
|
Here is what I was looking for:
```
static int FreeTcpPort()
{
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
```
|
Use a port number of 0. The TCP stack will allocate the next free one.
|
Find the next TCP port in .NET
|
[
"",
"c#",
".net",
"wcf",
"networking",
"tcp",
""
] |
I have a simple unordered list that I want to show and hide on click using the jQuery slideUp and slideDown effect. Everything seems to work fine, however in IE6 the list will slide up, flicker for a split second, and then disappear.
Does anyone know of a fix for this?
Thanks!
|
Apologies for the extra comment (I can't upvote or comment on Pavel's answer), but adding a DOCTYPE fixed this issue for me, and the slideUp/Down/Toggle effects now work correctly in IE7.
See [A List Apart](http://www.alistapart.com/articles/doctype/) for more information on DOCTYPES, or you can try specifying the fairly lenient 4/Transitional:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
```
|
Just let IE6 flicker. I don't think it's worth it to invest time in a dying browser when your base functionality works well enough. If you're worried about flickering for accessibility reasons, just sniff for IE6 and replace the animation with a generic show() and hide() instead. I recommend avoiding complicated code for edge cases that don't matter.
|
How do you fix the flickering that occurs when you use slideToggle in jQuery?
|
[
"",
"javascript",
"jquery",
""
] |
I've got a sections table, and an items table.
The problem is each item may be in one or more sections, so a simple 'section\_id' for each item won't work, and sql doesn't have a way to store arrays where I can do say "WHERE 5 in section\_ids"...
I've considered storing the list of ids as a comma separated string, the problem is I see no way to then check if an item is in a given section from the sql query. The only option I see here is to select the entire table, and parse the strings in php. Needless to say that with 1000's of items this isn't a good idea.
Is there a better way to 'link' an item with multiple sections, and be able to easily select all items for a given section id?
|
You need an intermediate lookup table:
```
CREATE TABLE item_in_section (item_id int, section_id int)
```
(I'm guessing about your key types, use whatever ones are appropriate).
To find items in a section:
```
SELECT item.* from item, item_in_section WHERE item_in_section.item_id = item.item_id AND item_in_section.section_id = X GROUP BY item_id
```
To find sections an item belongs to
```
SELECT section.* from section, item_in_section WHERE item_in_section.section_id = section.section_id AND item_in_section.item_id = Y GROUP BY section_id
```
|
In order to represent a many-to-many relationship, you need a support table with SectionId and ItemId. Both should be foreign keys to their respective tables and the primary key of this table should be both columns.
From [Wikipedia](http://en.wikipedia.org/wiki/Many-to-many_(data_model)):
> Because most DBMSs only support one-to-many relationships, it is necessary to implement such relationships physically via a third junction table, say, AB with two one-to-many relationships A -> AB and B -> AB. In this case the logical primary key for AB is formed from the two foreign keys (i.e. copies of the primary keys of A and B).
|
Sql design problem - items in multiple sections
|
[
"",
"sql",
"database-design",
""
] |
I need to setup LookAndFeel Files in JDK 1.6.
I have two files:
1. napkinlaf-swingset2.jar
2. napkinlaf.jar
How can I set this up and use it?
I would like a GTK look and feel OR Qt look and feel, Are they available?
|
The class name for Naplin is `net.sourceforge.napkinlaf.NapkinLookAndFeel`. So to set it as default on the command line, use:
```
java -Dswing.defaultlaf=net.sourceforge.napkinlaf.NapkinLookAndFeel
```
To install it add `napkinlaf.jar` to the `lib/ext` direction and the lines:
```
swing.installedlafs=napkin
swing.installedlaf.napkin.name=Napkin
swing.installedlaf.napkin.class=net.sourceforge.napkinlaf.NapkinLookAndFeel
```
to `lib/swing.properties` within your Java installation (you'll probably have to create the file).
See the [Napkin wiki page](http://wiki.java.net/bin/view/Projects/NapkinLAF)
|
This page explains how the work with Look&Feels:
<http://java.sun.com/docs/books/tutorial/uiswing/lookandfeel/plaf.html>
You can do it commandline:
```
java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel MyApp
```
Or in code:
```
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
```
You need to make sure the jars containing the look&feel are on the application classpath. How this works depends on the application. A typical way would be to put it in a lib folder.
Look&Feels that are available by default in the JDK are:
```
com.sun.java.swing.plaf.gtk.GTKLookAndFeel
com.sun.java.swing.plaf.motif.MotifLookAndFeel
com.sun.java.swing.plaf.windows.WindowsLookAndFeel
```
Quioting the link above:
> The GTK+ L&F will only run on UNIX or
> Linux systems with GTK+ 2.2 or later
> installed, while the Windows L&F runs
> only on Windows systems. Like the Java
> (Metal) L&F, the Motif L&F will run on
> any platform.
|
How can I setup LookAndFeel Files in Java?
|
[
"",
"java",
"swing",
"qt",
"gtk",
"look-and-feel",
""
] |
I'm developing a C# assembly which is to be called via COM from a Delphi 7 (iow, native win32, not .net) application.
So far, it seems to work. I've exported a TLB file, imported that into my Delphi project, and I can create my C# object and call its functions.
So that's great, but soon I'm going to **really** want to use Visual Studio to debug the C# code while it's running. Set breakpoints, step through code, all that stuff.
I've tried breaking in the Delphi code after the COM object is created, then looking for a process for VS to attach to, but I can't find one.
Is there a way to set VS2008 up to do this? I'd prefer to just be able to hit f5 and have VS start the Delphi executable, wait for the C# code to be called, and then attach itself to it.. But I could live with manually attaching to a process, I suppose.
Just please don't tell me I have to make do with MessageBox.Show etc.
|
In the VS2008 project properties page, on the Debug tab, there's an option to set a different Start Action.
This can be used to run an external program (e.g. your Delphi app) when you press F5.
|
Place the following in the method you wish to debug:
```
#if DEBUG
if (!System.Diagnostics.Debugger.IsAttached)
Debugger.Launch();
#endif
```
When you want to debug, build a debug version and use that in your application. When this code runs, a dialog pops up asking if you want to attach a debugger.
|
How can I debug a C# COM assembly when it's being called from a native win32 application?
|
[
"",
"c#",
".net",
"windows",
"delphi",
"com",
""
] |
How cheap can MySQL be compared to MS SQL when you have tons of data (and joins/search)? Consider a site like stackoverflow full of Q&As already and after getting dugg.
My ASP.NET sites are currently on SQL Server Express so I don't have any idea how cost compares in the long run. Although after a quick research, I'm starting to envy the savings MySQL folks get.
|
MSSQL Standard Edition (32 or 64 bit) will cost around $5K *per CPU socket*. 64 bit will allow you to use as much RAM as you need. Enterprise Edition is not really necessary for most deployments, so don't worry about the $20K you would need for that license.
MySQL is only free if you forego a lot of the useful tools offered with the licenses, and it's probably (at least as of 2008) going to be a little more work to get it to scale like Sql Server.
In the long run I think you will spend much more on hardware and people than you will on just the licenses. If you need to scale, then you will probably have the cash flow to handle $5K here and there.
|
The performance benefits of MS SQL over MySQL are fairly negligible, especially if you mitigate them with server and client side optimzations like server caching (in RAM), client caching (cache and expires headers) and gzip compression.
|
Scaling cheaply: MySQL and MS SQL
|
[
"",
"sql",
"mysql",
"sql-server",
"scalability",
"scaling",
""
] |
If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process?
Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice?
I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:25; a few of these are part of embedded systems and can't be set up to accept SMTP.
As part of Good Practice, I'd really like to have the library take care of header injection vulnerabilities itself -- so just dumping a string to `popen('/usr/bin/sendmail', 'w')` is a little closer to the metal than I'd like.
If the answer is 'go write a library,' so be it ;-)
|
Header injection isn't a factor in how you send the mail, it's a factor in how you construct the mail. Check the [email](https://docs.python.org/2/library/email.html) package, construct the mail with that, serialise it, and send it to `/usr/sbin/sendmail` using the [subprocess](https://docs.python.org/2/library/subprocess.html) module:
```
import sys
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
msg = MIMEText("Here is the body of my message")
msg["From"] = "me@example.com"
msg["To"] = "you@example.com"
msg["Subject"] = "This is the subject."
p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
# Both Python 2.X and 3.X
p.communicate(msg.as_bytes() if sys.version_info >= (3,0) else msg.as_string())
# Python 2.X
p.communicate(msg.as_string())
# Python 3.X
p.communicate(msg.as_bytes())
```
|
This is a simple python function that uses the unix sendmail to deliver a mail.
```
def sendMail():
sendmail_location = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t" % sendmail_location, "w")
p.write("From: %s\n" % "from@somewhere.com")
p.write("To: %s\n" % "to@somewhereelse.com")
p.write("Subject: thesubject\n")
p.write("\n") # blank line separating headers from body
p.write("body of the mail")
status = p.close()
if status != 0:
print "Sendmail exit status", status
```
|
Sending mail via sendmail from python
|
[
"",
"python",
"email",
"sendmail",
""
] |
I've got the following situation
* A rails application that makes use of rjs / Scriptaculous to offer AJAX functionality
* Lot of nice javascript written using jQuery (for a separate application)
I want to combine the two and use my jQuery based functionality in my Rails application, but I'm worried about jQuery and Scriptaculous clashing (they both define the $() function, etc).
What is my easiest option to bring the two together? Thanks!
|
```
jQuery.noConflict();
```
Then use jQuery instead of $ to refer to jQuery. e.g.,
```
jQuery('div.foo').doSomething()
```
If you need to adapt jQuery code that uses $, you can surround it with this:
```
(function($) {
...your code here...
})(jQuery);
```
|
I believe it's `jQuery.noConflict()`.
You can call it standalone like this:
```
jQuery.noConflict();
jQuery('div').hide();
```
Or you can assign it to another variable of your choosing:
```
var $j = jQuery.noConflict();
$j('div').hide();
```
Or you can keep using jQuery's `$` function inside a block like this:
```
jQuery.noConflict();
// Put all your code in your document ready area
jQuery(document).ready(function($){
// Do jQuery stuff using $
$("div").hide();
});
// Use Prototype with $(...), etc.
$('someid').hide();
```
For more information, see [Using jQuery with Other Libraries](http://docs.jquery.com/Using_jQuery_with_Other_Libraries) in the jQuery documentation.
|
Combining Scriptaculous and jQuery in a Rails application
|
[
"",
"javascript",
"jquery",
"ruby-on-rails",
"ruby",
"scriptaculous",
""
] |
In ASPNET, I grew to love the Application and Cache stores. They're awesome. For the uninitiated, you can just throw your data-logic objects into them, and hey-presto, you only need query the database once for a bit of data.
By far one of the best ASPNET features, IMO.
I've since ditched Windows for Linux, and therefore PHP, Python and Ruby for webdev. I use PHP most because I dev several open source projects, all using PHP.
Needless to say, I've explored what PHP has to offer in terms of caching data-objects. So far I've played with:
1. Serializing to file (a pretty slow/expensive process)
2. Writing the data to file as JSON/XML/plaintext/etc (even slower for read ops)
3. Writing the data to file as pure PHP (the fastest read, but quite a convoluted write op)
I should stress now that I'm looking for a solution that doesn't rely on a third party app (eg memcached) as the apps are installed in all sorts of scenarios, most of which don't have install rights (eg: a cheap shared hosting account).
So back to what I'm doing now, **is persisting to file secure?** `Rule 1` in production server security has always been disable file-writing, but I really don't see any way PHP *could* cache if it couldn't write. Are there any tips and/or tricks to boost the security?
**Is there another persist-to-file method that I'm forgetting?**
**Are there any better methods of caching in "limited" environments?**
|
Serializing is quite safe and commonly used. There is an alternative however, and that is to cache to memory. Check out [memcached](http://pecl.php.net/package/memcache) and [APC](http://www.php.net/manual/en/book.apc.php), they're both free and highly performant. [This article](http://blog.digitalstruct.com/2008/02/27/php-performance-series-caching-techniques/) on different caching techniques in PHP might also be of interest.
|
### Re: Is there another persist-to-file method that I'm forgetting?
It's of limited utility but if you have a particularly beefy database query you could write the serialized object back out to an indexed database table. You'd still have the overhead of a database query, but it would be a simple select as opposed to the beefy query.
### Re: Is persisting to file secure? and cheap shared hosting account)
The sad fact is cheap shared hosting isn't secure. How much do you trust the 100,500, or 1000 other people who have access to your server? For historic and (ironically) security reasons, shared hosting environments have PHP/Apache running as a unprivileged user (with PHP running as an Apache module). The security rational here is if the world facing apache process gets compromised, the exploiters only have access to an unprivileged account that can't screw with important system files.
The bad part is, that means whenever you write to a file using PHP, the owner of that file is the same unprivileged Apache user. This is true for every user on the system, which means anyone has read and write access to the files. The theoretical hackers in the above scenario would also have access to the files.
There's also a persistent bad practice in PHP of giving a directory permissions of 777 to directories and files to enable the unprivileged apache user to write files out, and then leaving the directory or file in that state. That gives **anyone** on the system read/write access.
Finally, you may think obscurity saves you. "There's no way they can know where my secret cache files are", but you'd be wrong. Shared hosting sets up users in the same group, and most default file masks will give your group users read permission on files you create. SSH into your shared hosting account sometime, navigate up a directory, and you can usually start browsing through other users files on the system. This can be used to sniff out writable files.
The solutions aren't pretty. Some hosts will offer a CGI Wrapper that lets you run PHP as a CGI. The benefit here is PHP will run as the owner of the script, which means it will run as you instead of the unprivileged user. Problem averted! New Problem! Traditional CGI is slow as molasses in February.
There is FastCGI, but FastCGI is finicky and requires constant tuning. Not many shared hosts offer it. If you find one that does, chances are they'll have APC enabled, and may even be able to provide a mechanism for memcached.
|
Methods for caching PHP objects to file?
|
[
"",
"php",
"caching",
""
] |
This question comes out of the discussion on [tuples](https://stackoverflow.com/questions/101825/whats-the-best-way-of-using-a-pair-triple-etc-of-values-as-one-value-in-c).
I started thinking about the hash code that a tuple should have.
What if we will accept KeyValuePair class as a tuple? It doesn't override the GetHashCode() method, so probably it won't be aware of the hash codes of it's "children"... So, run-time will call Object.GetHashCode(), which is not aware of the real object structure.
Then we can make two instances of some reference type, which are actually Equal, because of the overloaded GetHashCode() and Equals(). And use them as "children" in tuples to "cheat" the dictionary.
But it doesn't work! Run-time somehow figures out the structure of our tuple and calls the overloaded GetHashCode of our class!
How does it work? What's the analysis made by Object.GetHashCode()?
Can it affect the performance in some bad scenario, when we use some complicated keys? (probably, impossible scenario... but still)
Consider this code as an example:
```
namespace csharp_tricks
{
class Program
{
class MyClass
{
int keyValue;
int someInfo;
public MyClass(int key, int info)
{
keyValue = key;
someInfo = info;
}
public override bool Equals(object obj)
{
MyClass other = obj as MyClass;
if (other == null) return false;
return keyValue.Equals(other.keyValue);
}
public override int GetHashCode()
{
return keyValue.GetHashCode();
}
}
static void Main(string[] args)
{
Dictionary<object, object> dict = new Dictionary<object, object>();
dict.Add(new KeyValuePair<MyClass,object>(new MyClass(1, 1), 1), 1);
//here we get the exception -- an item with the same key was already added
//but how did it figure out the hash code?
dict.Add(new KeyValuePair<MyClass,object>(new MyClass(1, 2), 1), 1);
return;
}
}
}
```
**Update** I think I've found an explanation for this as stated below in my answer. The main outcomes of it are:
* Be careful with your keys and their hash codes :-)
* For complicated dictionary keys you must override Equals() and GetHashCode() correctly.
|
It seems that I have a clue now.
I thought KeyValuePair is a reference type, but it is not, it is a struct. And so it uses ValueType.GetHashCode() method. MSDN for it says: "One or more fields of the derived type is used to calculate the return value".
If you will take a real reference type as a "tuple-provider" you'll cheat the dictionary (or yourself...).
```
using System.Collections.Generic;
namespace csharp_tricks
{
class Program
{
class MyClass
{
int keyValue;
int someInfo;
public MyClass(int key, int info)
{
keyValue = key;
someInfo = info;
}
public override bool Equals(object obj)
{
MyClass other = obj as MyClass;
if (other == null) return false;
return keyValue.Equals(other.keyValue);
}
public override int GetHashCode()
{
return keyValue.GetHashCode();
}
}
class Pair<T, R>
{
public T First { get; set; }
public R Second { get; set; }
}
static void Main(string[] args)
{
var dict = new Dictionary<Pair<int, MyClass>, object>();
dict.Add(new Pair<int, MyClass>() { First = 1, Second = new MyClass(1, 2) }, 1);
//this is a pair of the same values as previous! but... no exception this time...
dict.Add(new Pair<int, MyClass>() { First = 1, Second = new MyClass(1, 3) }, 1);
return;
}
}
}
```
|
Don't override GetHashcode() and Equals() on mutable classes, only override it on immutable classes or structures, else if you modify a object used as key the hash table won't function properly anymore (you won't be able to retrieve the value associated to the key after the key object was modified)
Also hash tables don't use hashcodes to identify objects they use the key objects themselfes as identifiers, it's not required that all keys that are used to add entries in a hash table return different hashcodes, but it is recommended that they do, else performance suffers greatly.
|
How does c# figure out the hash code for an object?
|
[
"",
"c#",
"hash",
"internals",
""
] |
The questions says everything, take this example code:
```
<ul id="css-id">
<li>
<something:CustomControl ID="SomeThingElse" runat="server" />
<something:OtherCustomControl runat="server" />
</li>
</ul>
```
Now if an error gets thrown somewhere inside these controlls (that are located in a master page) they will take down the entire site, how would one catch these exceptions?
|
You can catch all exception not handled elswhere in the Global.asax page / class.
Look at:
```
protected void Application_Error(Object sender, EventArgs e)
```
method.
|
Unfortunately an unhandled exception will always error your site.
YOu can prevent this a few ways though.
* Use the section in your web.config to show a user friendly message
* In your Global.asax - or a Custom Handler - catch your unhandled exception and react accordingly - [like this](http://www.webdude.co.za/archive/2008/09/17/creating-your-own-unhandled-error-logging-module.aspx)
**best solution**
* Make sure you controls don't throw unhandled exceptions!
|
Catching exceptions within .aspx and .ascx pages
|
[
"",
"c#",
".net",
"asp.net",
"exception",
"error-handling",
""
] |
I have a pretty complicated Linq query that I can't seem to get into a LinqDataSsource for use in a GridView:
```
IEnumerable<ticket> tikPart = (
from p in db.comments where
p.submitter == me.id &&
p.ticket.closed == DateTime.Parse("1/1/2001") &&
p.ticket.originating_group != me.sub_unit
select p.ticket
).Distinct();
```
How can I get this into a GridView? Thank you!
|
You can setup your Gridview with no Datasource. Setup the gridview columns, and in codebehind bind that result to the grid view.
|
```
gridview.DataSource = tikPart.ToList();
gridview.DataBind();
```
|
Getting a Linq-toSQL query to show up on a GridView
|
[
"",
"c#",
"linq",
"linq-to-sql",
"gridview",
""
] |
Does anybody use anything else to document their `PHP` code than `PHPDoc?`
Are there any tools that read the same documentation syntax but give richer output?
|
I´ll go for doxygen too.
Here are several reasons :
* compatible with phpdoc tags and other popular ones : it´s interoperable
* works with various programming languages : a better time investment
* there is alternative syntaxes : can choose the commenting style that suit you
* very efficient with advanced formating / tagging / metadata
* there is a GUI that is not linked to any IDE and an eclipse plugin as well
And still free, multiplatform, and open source :-)
It´s easy to learn, but harder that phpdoc because a lot richer.
|
You could try DocBlox; which is intended to be an alternative for phpDocumentor but with support for additional features of which full PHP 5.3 support is one. An additional benefit is that is it quite fast and uses relatively little memory.
You can read more on <http://www.docblox-project.org> or see a demo at <http://demo.docblox-project.org/default>
|
Anything better than PHPDoc out there?
|
[
"",
"php",
"documentation",
"documentation-generation",
"phpdoc",
""
] |
I'm doing some Android development, and I much prefer Visual Studio, but I'll have to use *Eclipse* for this.
Has anyone made a tool which can make *Eclipse* look and behave more like visual studio? I mainly can't stand its **clippyesqe** suggestions on how I should program (Yes, I know I have not yet used that private field! Thanks Eclipse!), or its incredibly lousy **intellisense**.
For example, in eclipse, if I don't type `this` first, its **intellisense** won't realise I want to look for locally scoped members. Also, the TAB to complete VS convention is drilled into my head, and *Eclipse* is ENTER to complete, I could switch everything by hand but that would take hours, and I was hoping someone had some sort of theme or something that has already done it.
|
There are also other choices for Java IDEs. You've obviously found Eclipse, but you also may want to check out [IntelliJ](http://www.jetbrains.com/idea/index.html) and [NetBeans](http://www.netbeans.org/). IntelliJ is not free, but has a 30 day evaluation period and a Visual Studio key map :)
Shop around, find one that you like and start to use it heavily. They are all very good IDEs, and I'm sure once you use one for a while you'll get comfortable with it.
|
Have you tried using the Visual Studio keybindings available in Eclipse Ganymede (3.4)?
(You may want to know that "IntelliSense" is a Visual Studio-term, an probably unknown to anyone without Visual Studio-experience. "Autocompletion" is probably a more widely used term.)
|
Making Eclipse behave like Visual Studio
|
[
"",
"java",
"android",
"eclipse",
"visual-studio",
"ide",
""
] |
I often refactor code first by creating an inner class inside the class I'm working on--When I'm done, I move the entire thing into a new class file. This makes refactoring code into the new class extremely easy because A) I'm only dealing with a single file, and B) I don't create new files until I have a pretty good idea of the name/names (Sometimes it ends up as more than one class).
Is there any way Eclipse can help me with the final move? I should just be able to tell it what package I want the class in, it can figure out the filename from the class name and the directory from the package.
This seems like a trivial refactor and really obvious, but I can't figure out the keystrokes/gestures/whatever to make it happen. I've tried dragging, menus, context menus, and browsing through the keyboard shortcuts.
Anyone know this one?
[edit] These are already "Top Level" classes in this file, not inner classes, and "Move" doesn't seem to want to create a new class for me. This is the hard way that I usually do it--involves going out, creating an empty class, coming back and moving. I would like to do the whole thing in a single step.
|
I'm sorry I gave the wrong answer before. I rechecked, and it didn't do quite want you want. I did find a solution for you though, again, in 3.4.
Highlight the class, do a copy CTRL-C or cut CTRL-X, click on the package you want the class do go into, and do a paste, CTRL-V. Eclipse will auto generate the class for you.
Convert Member Type to Top Level doesn't quite work. Doing that will create a field of the outer class and generate a constructor that takes the outer class as a parameter.
|
In Eclipse 3.6, you can do: Refactor -> Move type to new file
|
Can eclipse extract a second class in class file to its own file
|
[
"",
"java",
"eclipse",
"refactoring",
""
] |
I attempted to open a C#/VB form in designer mode, and instead of the form, I got an ugly error message saying "The path is not of a legal form". This form used to work! What happened?
---
*Thanks to all who have answered. This question is a problem I hit a while back, and I struggled with it for a long time, until I found the answer, which I posted below in order to help other people who might have hit this problem.
Thanks!*
|
I don't know what this error message means, but it seems to be associated with third-party controls on the form. Anyway, the solution is almost as absurd as the problem:
1. Close the designer/error message.
2. Open the form code.
3. Right-click on the form code and select "View Designer".
Presto! The designer opens!
|
Debugging design mode would help. From [here](http://blog.lab49.com/archives/244):
1. List item
2. In visual studio, select the project you want to debug.
3. Right click -> Properties.
4. Select the debugging tab.
5. Change the debug mode to Program.
6. Set the “Start Application” to be your visual studio IDE (C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\IDE\devenv.exe)
7. Set your solution file in the “command line argument field”.
8. Apply -> OK
9. Select the project you want to debug as the startup project.
10. Run.
11. Set a break point in the place you want to start debug (for example, your control constructor)
|
Open .NET form in designer mode - get "The path is not of a legal form"
|
[
"",
"c#",
"vb.net",
"visual-studio",
"winforms",
""
] |
I am using [cxxtest](http://cxxtest.tigris.org/) as the test framework for my C++ classes, and would like to figure out a way to simulate sending data to classes which would normally expect to receive it from standard input. I have several different files which I would like to send to the classes during different tests, so redirection from the command line to the test suite executable is not an option.
Basically, what I would really like to do is find a way to redefine or redirect the 'stdin' handle to some other value that I create inside of my program, and then use fwrite() from these tests so that the corresponding fread() inside of the class pulls the data from within the program, not from the actual standard I/O handles associated with the executable.
Is this even possible? Bonus points for a platform-independent solution, but at a very minimum, I need this to work with Visual Studio 9 under Windows.
|
The appropriate method is to rewrite your classes so that they are testable. They should accept as a parameter the handle, stream or file from which they are supposed to read data - in your test framework, you can then mock in the stream or supply the path to the file containing the test data.
|
You should be able to use freopen() to point stdin to an arbitrary file.
|
How to redirect data to stdin within a single executable?
|
[
"",
"c++",
""
] |
I've seen some people use `EXISTS (SELECT 1 FROM ...)` rather than `EXISTS (SELECT id FROM ...)` as an optimization--rather than looking up and returning a value, SQL Server can simply return the literal it was given.
Is `SELECT(1)` always faster? Would Selecting a value from the table require work that Selecting a literal would avoid?
|
For google's sake, I'll update this question with the same answer as this one ([Subquery using Exists 1 or Exists \*](https://stackoverflow.com/questions/1597442/subquery-using-exists-1-or-exists/)) since (currently) an incorrect answer is marked as accepted. Note the SQL standard actually says that EXISTS via \* is identical to a constant.
No. This has been covered a bazillion times. SQL Server is smart and knows it is being used for an EXISTS, and returns NO DATA to the system.
Quoth Microsoft:
<http://technet.microsoft.com/en-us/library/ms189259.aspx?ppud=4>
> The select list of a subquery
> introduced by EXISTS almost always
> consists of an asterisk (\*). There is
> no reason to list column names because
> you are just testing whether rows that
> meet the conditions specified in the
> subquery exist.
Also, don't believe me? Try running the following:
```
SELECT whatever
FROM yourtable
WHERE EXISTS( SELECT 1/0
FROM someothertable
WHERE a_valid_clause )
```
If it was actually doing something with the SELECT list, it would throw a div by zero error. It doesn't.
EDIT: Note, the SQL Standard actually talks about this.
ANSI SQL 1992 Standard, pg 191 <http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt>
> ```
> 3) Case:
>
> a) If the <select list> "*" is simply contained in a <subquery> that is immediately contained in an <exists predicate>, then the <select list> is equivalent to a <value expression> that is an arbitrary <literal>.
> ```
|
In SQL Server, it does not make a difference whether you use `SELECT 1` or `SELECT *` within `EXISTS`. You are not actually returning the contents of the rows, but that rather the set determined by the `WHERE` clause is not-empty. Try running the query side-by-side with `SET STATISTICS IO ON` and you can prove that the approaches are equivalent. Personally I prefer `SELECT *` within `EXISTS`.
|
SQL Server: Is SELECTing a literal value faster than SELECTing a field?
|
[
"",
"sql",
"sql-server",
""
] |
```
uint color;
bool parsedhex = uint.TryParse(TextBox1.Text, out color);
//where Text is of the form 0xFF0000
if(parsedhex)
//...
```
doesn't work. What am i doing wrong?
|
Try
```
Convert.ToUInt32(hex, 16) //Using ToUInt32 not ToUInt64, as per OP comment
```
|
You can use an overloaded `TryParse()` which adds a NumberStyle parameter to the `TryParse` call which provides parsing of Hexadecimal values. Use `NumberStyles.HexNumber` which allows you to pass the string as a hex number.
**Note**: The problem with `NumberStyles.HexNumber` is that it *doesn't* support parsing values with a prefix (ie. `0x`, `&H`, or `#`), so you have to strip it off before trying to parse the value.
Basically you'd do this:
```
uint color;
var hex = TextBox1.Text;
if (hex.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase) ||
hex.StartsWith("&H", StringComparison.CurrentCultureIgnoreCase))
{
hex = hex.Substring(2);
}
bool parsedSuccessfully = uint.TryParse(hex,
NumberStyles.HexNumber,
CultureInfo.CurrentCulture,
out color);
```
See the documentation for [TryParse(String, NumberStyles, IFormatProvider, Int32)](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0#System_Int32_TryParse_System_String_System_Globalization_NumberStyles_System_IFormatProvider_System_Int32__) for an example of how to use the NumberStyles enumeration.
|
How to parse hex values into a uint?
|
[
"",
"c#",
""
] |
I want to call a few "static" methods of a CPP class defined in a different file but I'm having linking problems. I created a test-case that recreates my problem and the code for it is below.
(I'm completely new to C++, I come from a Java background and I'm a little familiar with C.)
```
// CppClass.cpp
#include <iostream>
#include <pthread.h>
static pthread_t thread;
static pthread_mutex_t mutex;
static pthread_cond_t cond;
static int shutdown;
using namespace std;
class CppClass
{
public:
static void Start()
{
cout << "Testing start function." << endl;
shutdown = 0;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&thread, &attr, run_thread, NULL);
}
static void Stop()
{
pthread_mutex_lock(&mutex);
shutdown = 1;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
static void Join()
{
pthread_join(thread, NULL);
}
private:
static void *run_thread(void *pthread_args)
{
CppClass *obj = new CppClass();
pthread_mutex_lock(&mutex);
while (shutdown == 0)
{
struct timespec ts;
ts.tv_sec = time(NULL) + 3;
pthread_cond_timedwait(&cond, &mutex, &ts);
if (shutdown)
{
break;
}
obj->display();
}
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
pthread_exit(NULL);
return NULL;
}
void display()
{
cout << " Inside display() " << endl;
}
};
// main.cpp
#include <iostream>
/*
* If I remove the comment below and delete the
* the class declaration part, it works.
*/
// #include "CppClass.cpp"
using namespace std;
class CppClass
{
public:
static void Start();
static void Stop();
static void Join();
};
int main()
{
CppClass::Start();
while (1)
{
int quit;
cout << "Do you want to end?: (0 = stay, 1 = quit) ";
cin >> quit;
cout << "Input: " << quit << endl;
if (quit)
{
CppClass::Stop();
cout << "Joining CppClass..." << endl;
CppClass::Join();
break;
}
}
}
```
When I tried to compile, I get the following error:
```
$ g++ -o go main.cpp CppClass.cpp -l pthread
/tmp/cclhBttM.o(.text+0x119): In function `main':
: undefined reference to `CppClass::Start()'
/tmp/cclhBttM.o(.text+0x182): In function `main':
: undefined reference to `CppClass::Stop()'
/tmp/cclhBttM.o(.text+0x1ad): In function `main':
: undefined reference to `CppClass::Join()'
collect2: ld returned 1 exit status
```
But if I remove the class declaration in main.cpp and replace it with #include "CppClass.cpp", it works fine. Basically, I want to put these declarations in a separate .h file and use it. Am I missing something?
Thanks for the help.
|
It's obvious you come from a Java background because you haven't yet grasped the concept of header files. In Java the process of defining something is usually in one piece. You declare and define at the same time. In C/C++ it's a two-step process. **Declaring** something tells the compiler "something exists with this type, but I'll tell you later how it is actually implemented". **Defining** something is giving the compiler the actual implementation part. Header files are used mostly for declarations, .cpp files for definitions.
Header files are there to describe the "API" of classes, but not their actual code. It is possible to include code in the header, that's called header-inlining. You have inlined everything in CppClass.cpp (not good, header-inlining should be the exception), and then you declare your class in main.cpp AGAIN which is a double declaration in C++. The inlining in the class body leads to code reduplication everytime you use a method (this only *sounds* insane. See the [C++ faq section on inlining](http://www.parashift.com/c++-faq-lite/inline-functions.html) for details.)
Including the double declaration in your code gives you a compiler error. Leaving the class code out compiles but gives you a linker error because now you only have the header-like class declaration in main.cpp. The linker sees no code that implements your class methods, that's why the errors appear. Different to Java, the C++ linker will NOT automatically search for object files it wants to use. If you use class XYZ and don't give it object code for XYZ, it will simply fail.
Please have a look at [Wikipedia's header file article](http://en.wikipedia.org/wiki/Header_files) and [Header File Include Patterns](http://www.eventhelix.com/RealtimeMantra/HeaderFileIncludePatterns.htm) (the link is also at the bottom of the Wikipedia article and contains more examples)
In short:
For each class, generate a NewClass.h and NewClass.cpp file.
In the NewClass.h file, write:
```
class NewClass {
public:
NewClass();
int methodA();
int methodB();
}; <- don't forget the semicolon
```
In the NewClass.cpp file, write:
```
#include "NewClass.h"
NewClass::NewClass() {
// constructor goes here
}
int NewClass::methodA() {
// methodA goes here
return 0;
}
int NewClass::methodB() {
// methodB goes here
return 1;
}
```
In main.cpp, write:
```
#include "NewClass.h"
int main() {
NewClass nc;
// do something with nc
}
```
To link it all together, do a
g++ -o NewClassExe NewClass.cpp main.cpp
(just an example with gcc)
|
You're defining the class twice, which I'm pretty sure doesn't work.
Try something like this:
First a header CppClass.h file:
```
// CppClass.h
using namespace std;
class CppClass
{
public:
static void Start();
static void Stop();
static void Join();
private:
void *run_thread(void *pthread_args);
void display();
};
```
Then a CppClass.cpp file implementing it:
```
// CppClass.cpp
#include <iostream>
#include <pthread.h>
#include "CppClass.h"
using namespace std;
void CppClass::Start()
{
/* method body goes here */
}
void CppClass::Stop()
{
/* method body goes here */
}
void CppClass::Join()
{
/* method body goes here */
}
void *CppClass::run_thread(void *pthread_args)
{
/* method body goes here */
}
void CppClass::display() {
/* method body goes here */
}
```
Then your main file:
```
// main.cpp
#include "CppClass.h"
int main()
{
/* main method body here */
}
```
I believe the g++ call would be the same.
Basically, you can't declare the same class twice. You should declare the class in the header file, then declare the implementation in the cpp file. You could also put all the code inline in a *single* declaration of the class in a header file. But declaring it twice like you did won't work.
I hope that made sense...
|
Problem Linking "static" Methods in C++
|
[
"",
"c++",
"linker",
"g++",
""
] |
I've looked for this a few times in the past, to no avail. I would like a simple `php/ajax` web chat interface, that, and this is the critical part, will interface with my `IM client (Pidgin)` ... via Jabber or Aim. `Plugoo` is almost what I want, except it is hosted, and flash based. Flash-based would be OK if not ideal, but hosted isn't.
Note that I don't just need notifications, but I want a user of the website who clicks "live chat" to get a chat interface and my IM client allows me to interact with them.
This is super handy for those of us that want to provide live support to clients who do not use IM.
|
This wouldn't be that hard, if you implement the Oscar protocol that AIM uses. It's not very complex, and that would allow you to build a nice web based AIM client for your website. There may be a 3rd party solution that you could use, but as far as I know, Oscar is pretty trivial.
|
(Disclaimer: I work for [Jabber, Inc.](http://www.jabber.com/), the commercial company behind the product I'm about to pimp.)
[](https://i.stack.imgur.com/tuKFA.png)
(source: [jabber.com](http://www.jabber.com/images/GroupChatAJAXThumb.png))
The [JabberWerx AJAX](http://www.jabber.com/CE/JabberWerxAJAXLibrary) libraries do exactly what you want. You include a reference to a Javascript library, add a div tag where you want the chat to go, and add a couple lines of configuration javascript to hook the two together. There's also a one-to-one mode. User accounts can be created on the fly if you like, as well.
Sorry for the ad, but I think it's exactly what you want.
|
Simple web "live chat" software (LAMP stack) that integrates with Jabber/Aim
|
[
"",
"php",
"ajax",
"chat",
"xmpp",
""
] |
How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call?
|
From the controller you can just return a JsonResult:
```
public ActionResult MyAction()
{
... // Populate myObject
return new JsonResult{ Data = myObject };
}
```
The form of the Ajax call will depend on which library you're using, of course. Using jQuery it would be something like:
```
$.getJSON("/controllerName/MyAction", callbackFunction);
```
where the `callbackFunction` takes a parameter which is the data from the XHR request.
|
Depending on your syntax preferences, the following also works:
```
public ActionResult MyAction()
{
return Json(new {Data = myObject});
}
```
|
JSON and ASP.NET MVC
|
[
"",
"c#",
"asp.net-mvc",
"ajax",
"json",
""
] |
I'm looking for an extremely fast atof() implementation on IA32 optimized for US-en locale, ASCII, and non-scientific notation. The windows multithreaded CRT falls down miserably here as it checks for locale changes on every call to isdigit(). Our current best is derived from the best of perl + tcl's atof implementation, and outperforms msvcrt.dll's atof by an order of magnitude. I want to do better, but am out of ideas. The BCD related x86 instructions seemed promising, but I couldn't get it to outperform the perl/tcl C code. Can any SO'ers dig up a link to the best out there? Non x86 assembly based solutions are also welcome.
Clarifications based upon initial answers:
Inaccuracies of ~2 ulp are fine for this application.
The numbers to be converted will arrive in ascii messages over the network in small batches and our application needs to convert them in the lowest latency possible.
|
What is your accuracy requirement? If you truly need it "correct" (always gets the nearest floating-point value to the decimal specified), it will probably be hard to beat the standard library versions (other than removing locale support, which you've already done), since this requires doing arbitrary precision arithmetic. If you're willing to tolerate an ulp or two of error (and more than that for subnormals), the sort of approach proposed by cruzer's can work and may be faster, but it definitely will not produce <0.5ulp output. You will do better accuracy-wise to compute the integer and fractional parts separately, and compute the fraction at the end (e.g. for 12345.6789, compute it as 12345 + 6789 / 10000.0, rather than 6\*.1 + 7\*.01 + 8\*.001 + 9\*0.0001) since 0.1 is an irrational binary fraction and error will accumulate rapidly as you compute 0.1^n. This also lets you do most of the math with integers instead of floats.
The BCD instructions haven't been implemented in hardware since (IIRC) the 286, and are simply microcoded nowadays. They are unlikely to be particularly high-performance.
|
This implementation I just finished coding runs twice as fast as the built in 'atof' on my desktop. It converts 1024\*1024\*39 number inputs in 2 seconds, compared 4 seconds with my system's standard gnu 'atof'. (Including the setup time and getting memory and all that).
**UPDATE:**
Sorry I have to revoke my twice as fast claim. It's faster if the thing you're converting is already in a string, but if you're passing it hard coded string literals, it's about the same as atof. However I'm going to leave it here, as possibly with some tweaking of the ragel file and state machine, you may be able to generate faster code for specific purposes.
<https://github.com/matiu2/yajp>
The interesting files for you are:
<https://github.com/matiu2/yajp/blob/master/tests/test_number.cpp>
<https://github.com/matiu2/yajp/blob/master/number.hpp>
Also you may be interested in the state machine that does the conversion:
[](https://i.stack.imgur.com/ntLTP.png)
|
Where can I find the world's fastest atof implementation?
|
[
"",
"c++",
"c",
"performance",
"assembly",
"floating-point",
""
] |
I have the following string and I would like to remove `<bpt *>*</bpt>` and `<ept *>*</ept>` (notice the additional tag content inside them that also needs to be removed) without using a XML parser (overhead too large for tiny strings).
```
The big <bpt i="1" x="1" type="bold"><b></bpt>black<ept i="1"></b></ept> <bpt i="2" x="2" type="ulined"><u></bpt>cat<ept i="2"></u></ept> sleeps.
```
Any regex in VB.NET or C# will do.
|
If you just want to remove all the tags from the string, use this (C#):
```
try {
yourstring = Regex.Replace(yourstring, "(<[be]pt[^>]+>.+?</[be]pt>)", "");
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
```
EDIT:
I decided to add on to my solution with a better option. The previous option would not work if there were embedded tags. This new solution should strip all <\*\*pt\*> tags, embedded or not. In addition, this solution uses a back reference to the original [be] match so that the exact matching end tag is found. This solution also creates a reusable Regex object for improved performance so that each iteration does not have to recompile the Regex:
```
bool FoundMatch = false;
try {
Regex regex = new Regex(@"<([be])pt[^>]+>.+?</\1pt>");
while(regex.IsMatch(yourstring) ) {
yourstring = regex.Replace(yourstring, "");
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
```
ADDITIONAL NOTES:
In the comments a user expressed worry that the '.' pattern matcher would be cpu intensive. While this is true in the case of a standalone greedy '.', the use of the non-greedy character '?' causes the regex engine to only look ahead until it finds the first match of the next character in the pattern versus a greedy '.' which requires the engine to look ahead all the way to the end of the string. I use [RegexBuddy](http://www.regexbuddy.com/) as a regex development tool, and it includes a debugger which lets you see the relative performance of different regex patterns. It also auto comments your regexes if desired, so I decided to include those comments here to explain the regex used above:
```
// <([be])pt[^>]+>.+?</\1pt>
//
// Match the character "<" literally «<»
// Match the regular expression below and capture its match into backreference number 1 «([be])»
// Match a single character present in the list "be" «[be]»
// Match the characters "pt" literally «pt»
// Match any character that is not a ">" «[^>]+»
// Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
// Match the character ">" literally «>»
// Match any single character that is not a line break character «.+?»
// Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
// Match the characters "</" literally «</»
// Match the same text as most recently matched by backreference number 1 «\1»
// Match the characters "pt>" literally «pt>»
```
|
I presume you want to drop the tag entirely?
```
(<bpt .*?>.*?</bpt>)|(<ept .*?>.*?</ept>)
```
The ? after the \* makes it non-greedy, so it will try to match as few characters as possible.
One problem you'll have is nested tags. stuff would not see the second because the first matched.
|
Regular expression to remove XML tags and their content
|
[
"",
"c#",
".net",
"xml",
"vb.net",
"regex",
""
] |
Ok, so we have clients and those clients get to customize their web facing page. One option we are giving them is to be able to change the color of a graphic (it's like a framish-looking bar) using one of those hex wheels or whatever.
So, I've thought about it, and I don't know where to start. I am sending comps out this week to my xhtml guy and I want to have the implementation done at least in my mind before I send things out.
Something about System.Drawing sounds about right, but I've never worked with that before and it sounds hella complicated. Does anyone have an idea?
**UPDATE:** The color of an image will be changing. So if I want image 1 to be green, and image 2 to be blue, I go into my admin screen and enter those hex values (probably will give them an interface for it) and then when someone else looks at their page they will see the changes they made. Kind of like customizing a facebook or myspace page (OMFGz soooo Werb 2.0)
|
I'm sort of intuiting that you'll have a black on white bitmap that you use as the base image. The client can then select any other color combination. This may not be exactly your situation, but it should get us started. (The code below is VB -- it's what I know, but converting to C# should be trivial for you.)
```
Imports System.Drawing
Private Function createImage(ByVal srcPath As String, ByVal fg As Color, ByVal bg As Color) As Bitmap
Dim img As New Bitmap(srcPath)
For x As Int16 = 0 To img.Width
For y As Int16 = 0 To img.Height
If img.GetPixel(x, y) = Color.Black Then
img.SetPixel(x, y, fg)
Else
img.SetPixel(x, y, bg)
End If
Next
Next
Return img
End Function
```
And then you can do whatever with the image...
|
What exactly will be changing? Depending on what's changing you may be able to overlay a transparent png on top of an html background color. Just change the background color and the logo color will change. Of course this limits what you can change, but you'd be surprised how much you can get away with.
And yes, the alternative is to paint the image on the web server. [Here's a post on it from hanselman](http://www.hanselman.com/blog/ASPNETFuturesGeneratingDynamicImagesWithHttpHandlersGetsEasier.aspx).
|
Implementing User-Controlled Style Changes in ASP.NET
|
[
"",
"c#",
"asp.net",
"html",
".net-3.5",
""
] |
I need to find the PID of the current running process on a Linux platform (it can be a system dependent solution). Java does not support getting the process ID, and JRuby currently has a bug with the Ruby method, Process.pid.
Is there another way to obtain the PID?
|
If you have [procfs](http://en.wikipedia.org/wiki/Procfs) installed, you can find the process id via the /proc/self symlink, which points to a directory whose name is the pid (there are also files here with other pertinent information, including the PID, but the directory is all you need in this case).
Thus, with Java, you can do:
```
String pid = new File("/proc/self").getCanonicalFile().getName();
```
In JRuby, you can use the same solution:
```
pid = java.io.File.new("/proc/self").canonical_file.name
```
Special thanks to the #stackoverflow channel on free node for helping me solve this! (specifically, [Jerub](https://stackoverflow.com/users/14648/jerub), [gregh](https://stackoverflow.com/users/893/greg-hewgill), and [Topdeck](https://stackoverflow.com/users/1057/harley))
|
Only tested in Linux using Sun JVM. Might not work with other JMX implementations.
```
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
```
|
How do I find my PID in Java or JRuby on Linux?
|
[
"",
"java",
"linux",
"jruby",
"pid",
""
] |
GWT's serializer has limited `java.io.Serializable` support, but for security reasons there is a whitelist of types it supports. The documentation I've found, for example [this FAQ entry](http://www.gwtproject.org/doc/latest/FAQ_Server.html#Does_the_GWT_RPC_system_support_the_use_of_java.io.Serializable) says that any types you want to serialize "must be included in the serialization policy whitelist", and that the list is generated at compile time, but doesn't explain how the compiler decides what goes on the whitelist.
The generated list contains a number of types that are part of the standard library, such as `java.lang.String` and `java.util.HashMap`. I get an error when trying to serialize `java.sql.Date`, which implements the `Serializable` interface, but is not on the whitelist. How can I add this type to the list?
|
Any specific types that you include in your service interface and any types that they reference will be automatically whitelisted, as long as they implement java.io.Serializable, eg:
```
public String getStringForDates(ArrayList<java.util.Date> dates);
```
Will result in ArrayList and Date both being included on the whitelist.
It gets trickier if you try and use java.lang.Object instead of specific types:
```
public Object getObjectForString(String str);
```
Because the compiler doesn't know what to whitelist. In that case if the objects are not referenced anywhere in your service interface, you have to mark them explicitly with the IsSerializable interface, otherwise it won't let you pass them through the RPC mechanism.
|
There's a workaround: define a new `Dummy` class with member fields of all the types that you want to be included in serialization. Then add a method to your RPC interface:
```
Dummy dummy(Dummy d);
```
The implementation is just this:
```
Dummy dummy(Dummy d) { return d; }
```
And the async interface will have this:
```
void dummy(Dummy d, AsyncCallback< Dummy> callback);
```
The GWT compiler will pick this up, and because the `Dummy` class references those types, it will include them in the white list.
Example `Dummy` class:
```
public class Dummy implements IsSerializable {
private java.sql.Date d;
}
```
|
How do I add a type to GWT's Serialization Policy whitelist?
|
[
"",
"java",
"serialization",
"gwt",
"whitelist",
""
] |
So I'm refactoring my code to implement more OOP. I set up a class to hold page attributes.
```
class PageAtrributes
{
private $db_connection;
private $page_title;
public function __construct($db_connection)
{
$this->db_connection = $db_connection;
$this->page_title = '';
}
public function get_page_title()
{
return $this->page_title;
}
public function set_page_title($page_title)
{
$this->page_title = $page_title;
}
}
```
Later on I call the set\_page\_title() function like so
```
function page_properties($objPortal) {
$objPage->set_page_title($myrow['title']);
}
```
When I do I receive the error message:
> Call to a member function set\_page\_title() on a non-object
So what am I missing?
|
It means that `$objPage` is not an instance of an object. Can we see the code you used to initialize the variable?
As you expect a specific object type, you can also make use of [PHPs type-hinting feature*Docs*](http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration) to get the error when your logic is violated:
```
function page_properties(PageAtrributes $objPortal) {
...
$objPage->set_page_title($myrow['title']);
}
```
This function will only accept `PageAtrributes` for the first parameter.
|
There's an easy way to produce this error:
```
$joe = null;
$joe->anything();
```
Will render the error:
> Fatal error: Call to a member function `anything()` on a non-object in /Applications/XAMPP/xamppfiles/htdocs/casMail/dao/server.php on line 23
It would be a lot better if **PHP** would just say,
> Fatal error: Call from Joe is not defined because (a) joe is null or (b) joe does not define `anything()` in on line <##>.
Usually you have build your class so that `$joe` is not defined in the constructor or
|
Call to a member function on a non-object
|
[
"",
"php",
""
] |
In Python there is a really neat function called `zip` which can be used to iterate through two lists at the same time:
```
list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
for v1, v2 in zip(list1, list2):
print v1 + " " + v2
```
The above code should produce the following:
```
1 a
2 b
3 c
```
I wonder if there is a method like it available in .Net? I'm thinking about writing it myself, but there is no point if it's already available.
|
Update: It is built-in in C# 4 as [System.Linq.Enumerable.Zip<TFirst, TSecond, TResult> Method](https://msdn.microsoft.com/en-us/library/vstudio/dd267698(v=vs.110).aspx)
Here is a C# 3 version:
```
IEnumerable<TResult> Zip<TResult,T1,T2>
(IEnumerable<T1> a,
IEnumerable<T2> b,
Func<T1,T2,TResult> combine)
{
using (var f = a.GetEnumerator())
using (var s = b.GetEnumerator())
{
while (f.MoveNext() && s.MoveNext())
yield return combine(f.Current, s.Current);
}
}
```
Dropped the C# 2 version as it was showing its age.
|
As far as I know there is not. I wrote one for myself (as well as a few other useful extensions and put them in a project called [NExtension](http://www.codeplex.com/nextension) on Codeplex.
Apparently the Parallel extensions for .NET have a Zip function.
Here's a simplified version from NExtension (but please check it out for more useful extension methods):
```
public static IEnumerable<TResult> Zip<T1, T2, TResult>(this IEnumerable<T1> source1, IEnumerable<T2> source2, Func<T1, T2, TResult> combine)
{
using (IEnumerator<T1> data1 = source1.GetEnumerator())
using (IEnumerator<T2> data2 = source2.GetEnumerator())
while (data1.MoveNext() && data2.MoveNext())
{
yield return combine(data1.Current, data2.Current);
}
}
```
Usage:
```
int[] list1 = new int[] {1, 2, 3};
string[] list2 = new string[] {"a", "b", "c"};
foreach (var result in list1.Zip(list2, (i, s) => i.ToString() + " " + s))
Console.WriteLine(result);
```
|
Is there a zip-like method in .Net?
|
[
"",
".net",
"python",
"list",
"iteration",
""
] |
I'd like to be able to create a large (say 20,000 x 20,000) pixel bitmap in a C++ MFC application, using a CDC derived class to write to the bitmap. I've tried using memory DCs as described in the MSDN docs, but these appear to be restricted to sizes compatible with the current display driver.
I'm currently using a bitmap print driver to do the job, but it is extremely slow and uses very large amounts of intermediate storage due to spooling GDI information.
The solution I'm looking for should not involve metafiles or spooling, as the model that I am drawing takes many millions of GDI calls to render.
I could use a divide and conquer approach via multiple memory DCs, but it seems like a pretty cumborsome and inelegant technique.
any thoughts?
|
CDC and CBitmap appears to only support device dependant bitmaps, you might have more luck creating your bitmap with [::CreateDIBSection](http://msdn.microsoft.com/en-us/library/ms532292(VS.85).aspx), then attaching a CBitmap to that. The raw GDI interfaces are a little hoary, unfortunately.
You probably won't have much luck with 20,000 x 20,000 at 32 BPP, at least in a 32-bit application, as that comes out at about 1.5 GB of memory, but I got a valid HBITMAP back with 16 bpp:
```
BITMAPINFOHEADER bmi = { sizeof(bmi) };
bmi.biWidth = 20000;
bmi.biHeight = 20000;
bmi.biPlanes = 1;
bmi.biBitCount = 16;
HDC hdc = CreateCompatibleDC(NULL);
BYTE* pbData = 0;
HBITMAP hbm = CreateDIBSection(hdc, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, (void**)&pbData, NULL, 0);
DeleteObject(SelectObject(hdc, hbm));
```
|
This is unusual as I often created a DC based on the screen that will be used for a bitmap image that is much larger than the screen - 3000 pixels plus in some cases - with no problems at all. Do you have some sample code showing this problem in action?
|
How to create a very big bitmap in C++/MFC / GDI
|
[
"",
"c++",
"mfc",
"bitmap",
"gdi",
"cdc",
""
] |
Can anyone point me to a library for 2D game physics, etc for programming gravity, jumping actions, etc for a 2d platform/sidescrolling game ?
Or could you suggest some algorithms for side scroller like mario, sonic etc?
|
It sounds like [Chipmunk](http://chipmunk-physics.net/) might meet your needs.
|
Your best bet is most likely [Box2D](http://www.box2d.org/). It does 2D physics, has tons of options, and is very easy to integrate into an existing project. It does CCD by default for fixed bodies, but any rigid body can be selectively included in the CCD calculation.
|
2d game physics?
|
[
"",
"c++",
"physics",
""
] |
Is there a standard framework (maybe part of Enterprise Library... or .NET itself) that allows you to do common parameter validation in method attributes?
|
[Microsoft Code Contracts](http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx), which are part of .NET Framework since 4.0 CTP and are available for earlier .NET Framework versions as a stand-alone package, allow to specify coding assumptions. This includes specifying pre-conditions which can verify parameters.
An example use for parameter checking would be (copied from [Code Contracts documentation](http://download.microsoft.com/download/C/2/7/C2715F76-F56C-4D37-9231-EF8076B7EC13/userdoc.pdf)):
```
public Rational(int numerator, int denominator)
{
Contract.Requires(denominator ! = 0);
this.numerator = numerator;
this.denominator = denominator;
}
```
The benefit of using Code Contracts is that it is a library which will be part of future .NET Framework releases, so sooner or later you will have one dependency less in your application.
**EDIT:** Just noticed that your specifically asking for a library that uses Attributes for argument checking... that Code Contracts does not. The reason why Code Contracts does not use attributes is listed in their [FAQ](http://research.microsoft.com/en-us/projects/contracts/faq.aspx):
> The advantage of using custom attributes is that they do not impact the code at all. However, the benefits of using method calls far outweigh the seemingly natural first choice of attributes:
>
> **Runtime support:** Without depending on a binary rewriter, contracts expressed with attributes cannot be enforced at runtime. This means that if there are preconditions (or other contracts) that you want enforced at runtime, you need to either duplicate the contracts in the code or else include a binary rewriter in your build process. Contract.RequiresAlways serves both as a declarative contract and as a runtime-checked validation.
>
> **Need for parsing:** Since the values that can be used with custom attributes are limited, conditions end up being encoded as strings. This requires defining a new language that is appropriate for all source languages, requires the strings to be parsed, duplicating all of the functionality the compiler already possesses.
>
> **Lack of IDE support:** Expressed as strings, there is no support for Intellisense, type checking, or refactoring, all of which are available for authoring contracts as code.
|
The Microsoft Enterprise Library has the Microsoft.Practices.EnterpriseLibrary.Validation library/namespace which allows validation using attributes.
|
Is there a standard framework for .NET parameter validation that uses attributes?
|
[
"",
"c#",
".net",
"validation",
"attributes",
"parameters",
""
] |
Right now I'm making an extremely simple website- about 5 pages. Question is if it's overkill and worth the time to integrate some sort of database mapping solution or if it would be better to just use plain old JNDI. I'll have maybe a dozen things I need to read/write from the database. I guess I have a basic understanding of these technologies but it would still take a lot of referring to the documentation. Anyone else faced with the decision before?
EDIT: Sorry, I should've specified JNDI to lookup the DB connection and JDBC to perform the operations.
|
Short answer: It depends on the complexity you want to support.
Long answer:
First of all, ORM ( object relational mapping - database mapping as you call it - ) and JNDI ( Java Naming and Directory Interfaces ) are two different things.
The first as you already know, is used to map the Database tables to classes and objects. The second is to provide a lookup mechanism for resources, they may be DataSources, Ejb, Queues or others.
Maybe your mean "JDBC".
Now as for your question: If it is that simple may be it wouldn't be necessary to implement an ORM. The number tables would be around 5 - 10 at most, and the operations really simple, I guess.
Probably using plain JDBC would be enough.
If you use the DAO pattern you may change it later to support the ORM strategy if needed.
Like this:
Say you have the Employee table
You create the Employee.java with all the fields of the DB by hand ( it should not take too long ) and a EmployeeDaO.java with methods like:
```
+findById( id ): Employee
+insert( Employee )
+update( Employee )
+delete( Employee )
+findAll():List<Employee>
```
And the implementation is quite straight forward:
```
select * from employee where id = ?
insert into employee ( bla, bla, bla ) values ( ? , ? , ? )
update etc. etc
```
When ( and If ) your application becomes too complex you may change the DAO implementation . For instance in the "select" method you change the code to use the ORM object that performs the operation.
```
public Employee selectById( int id ) {
// Commenting out the previous implementation...
// String query = select * from employee where id = ?
// execute( query )
// Using the ORM solution
Session session = getSession();
Employee e = ( Employee ) session.get( Employee.clas, id );
return e;
}
```
This is just an example, in real life you may let the abstact factory create the ORM DAO, but that is offtopic. The point is you may start simple and by using the desing patterns you may change the implementation later if needed.
Of course if you want to learn the technology you may start rigth away with even 1 table.
The choice of one or another ( ORM solution that is ) depend basically on the technology you're using. For instance for JBoss or other opensource products Hibernate is great. It is opensource, there's a lot of resources where to learn from. But if you're using something that already has Toplink ( like the oracle application server ) or if the base is already built on Toplink you should stay with that framework.
By the way, since Oracle bought BEA, they said they're replacing Kodo ( weblogic peresistence framework ) with toplink in the now called "Oracle Weblogic Application Server".
I leave you some resources where you can get more info about this:
---
In this "Patterns of Enterprise Application Architecture" book, Martin Fowler, explains where to use one or another, here is the catalog. Take a look at Data Source Architectural Patterns vs. Object-Relational Behavioral Patterns:
[PEAA Catalog](http://martinfowler.com/eaaCatalog/index.html)
---
DAO ( Data Access Object ) is part of the core J2EE patterns catalog:
[The DAO pattern](http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html)
---
This is a starter tutorial for Hibernate:
[Hibernate](http://hibernate.org/152.html)
---
The official page of Toplink:
[Toplink](http://www.oracle.com/technology/products/ias/toplink/index.html)
---
Finally I "think" the good think of JPA is that you may change providers lately.
Start simple and then evolve.
I hope this helps.
|
It does seem like it would be overkill for a very simple application, especially if you don't have plans to expand on it ever. However, it also seems like it could be worthwhile to use those with this simple application so that you have a better understanding of how they work for next time you have something that could use them.
|
When to use Hibernate/JPA/Toplink?
|
[
"",
"java",
"hibernate",
"orm",
"jpa",
"toplink",
""
] |
Without spending a long time reviewing the boost source code, could someone give me a quick rundown of how boost bind is implemented?
|
I like this piece of the `bind` source:
```
template<class R, class F, class L> class bind_t
{
public:
typedef bind_t this_type;
bind_t(F f, L const & l): f_(f), l_(l) {}
#define BOOST_BIND_RETURN return
#include <boost/bind/bind_template.hpp>
#undef BOOST_BIND_RETURN
};
```
Tells you almost all you need to know, really.
The `bind_template` header expands to a list of inline `operator()` definitions. For example, the simplest:
```
result_type operator()()
{
list0 a;
BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);
}
```
We can see the `BOOST_BIND_RETURN` macro expands to `return` at this point so the line is more like `return l_(type...)`.
The one parameter version is here:
```
template<class A1> result_type operator()(A1 & a1)
{
list1<A1 &> a(a1);
BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);
}
```
It's pretty similar.
The `listN` classes are wrappers for the parameter lists. There is a lot of deep magic going on here that I don't really understand too much though. They have also overloaded `operator()` that calls the mysterious `unwrap` function. Ignoring some compiler specific overloads, it doesn't do a lot:
```
// unwrap
template<class F> inline F & unwrap(F * f, long)
{
return *f;
}
template<class F> inline F & unwrap(reference_wrapper<F> * f, int)
{
return f->get();
}
template<class F> inline F & unwrap(reference_wrapper<F> const * f, int)
{
return f->get();
}
```
The naming convention seems to be: `F` is the type of the function parameter to `bind`. `R` is the return type. `L` tends to be a list of parameter types. There are also a lot of complications because there are no less than nine overloads for different numbers of parameters. Best not to dwell on that too much.
|
By the way, if `bind_t` is collapsed and simplified by including `boost/bind/bind_template.hpp` , it becomes easier to understand like the following :
```
template<class R, class F, class L>
class bind_t
{
public:
typedef bind_t this_type;
bind_t(F f, L const & l): f_(f), l_(l) {}
typedef typename result_traits<R, F>::type result_type;
...
template<class A1>
result_type operator()(A1 & a1)
{
list1<A1 &> a(a1);
return l_(type<result_type>(), f_, a, 0);
}
private:
F f_;
L l_;
};
```
|
How does boost bind work behind the scenes in general?
|
[
"",
"c++",
"boost",
"boost-bind",
""
] |
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms.
Thus splitting the respective string by the space-character is not sufficient anymore.
Example:
```
input : 'foo bar "lorem ipsum" baz'
output: ['foo', 'bar', 'lorem ipsum', 'baz']
```
I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations.
Any help would be greatly appreciated!
|
```
var str = 'foo bar "lorem ipsum" baz';
var results = str.match(/("[^"]+"|[^"\s]+)/g);
```
... returns the array you're looking for.
Note, however:
* Bounding quotes are included, so can be removed with `replace(/^"([^"]+)"$/,"$1")` on the results.
* Spaces between the quotes will stay intact. So, if there are three spaces between `lorem` and `ipsum`, they'll be in the result. You can fix this by running `replace(/\s+/," ")` on the results.
* If there's no closing `"` after `ipsum` (i.e. an incorrectly-quoted phrase) you'll end up with: `['foo', 'bar', 'lorem', 'ipsum', 'baz']`
|
Try this:
```
var input = 'foo bar "lorem ipsum" baz';
var R = /(\w|\s)*\w(?=")|\w+/g;
var output = input.match(R);
output is ["foo", "bar", "lorem ipsum", "baz"]
```
Note there are no extra double quotes around lorem ipsum
Although it assumes the input has the double quotes in the right place:
```
var input2 = 'foo bar lorem ipsum" baz'; var output2 = input2.match(R);
var input3 = 'foo bar "lorem ipsum baz'; var output3 = input3.match(R);
output2 is ["foo bar lorem ipsum", "baz"]
output3 is ["foo", "bar", "lorem", "ipsum", "baz"]
```
And won't handle escaped double quotes (is that a problem?):
```
var input4 = 'foo b\"ar bar\" \"bar "lorem ipsum" baz';
var output4 = input4.match(R);
output4 is ["foo b", "ar bar", "bar", "lorem ipsum", "baz"]
```
|
parsings strings: extracting words and phrases [JavaScript]
|
[
"",
"javascript",
"regex",
"parsing",
""
] |
I need a robust and simple way to remove illegal path and file characters from a simple string. I've used the below code but it doesn't seem to do anything, what am I missing?
```
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";
illegal = illegal.Trim(Path.GetInvalidFileNameChars());
illegal = illegal.Trim(Path.GetInvalidPathChars());
Console.WriteLine(illegal);
Console.ReadLine();
}
}
}
```
|
Try something like this instead;
```
string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalid)
{
illegal = illegal.Replace(c.ToString(), "");
}
```
But I have to agree with the comments, I'd probably try to deal with the source of the illegal paths, rather than try to mangle an illegal path into a legitimate but probably unintended one.
Edit: Or a potentially 'better' solution, using Regex's.
```
string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
illegal = r.Replace(illegal, "");
```
Still, the question begs to be asked, why you're doing this in the first place.
|
The original question asked to "remove illegal characters":
```
public string RemoveInvalidChars(string filename)
{
return string.Concat(filename.Split(Path.GetInvalidFileNameChars()));
}
```
You may instead want to replace them:
```
public string ReplaceInvalidChars(string filename)
{
return string.Join("_", filename.Split(Path.GetInvalidFileNameChars()));
}
```
[This answer was on another thread by Ceres](https://stackoverflow.com/a/12800424/512365), I really like it neat and simple.
|
How to remove illegal characters from path and filenames?
|
[
"",
"c#",
"string",
"path",
"directory",
""
] |
What is the best way to layout a large django project? The tutorials provide simple instructions for setting up apps, models, and views, but there is less information about how apps and projects should be broken down, how much sharing is allowable/necessary between apps in a typical project (obviously that is largely dependent on the project) and how/where general templates should be kept.
Does anyone have examples, suggestions, and *explanations* as to why a certain project layout is better than another? I am particularly interested in the incorporation of large numbers of unit tests (2-5x the size of the actual code base) and string externalization / templates.
|
The major guidelines are similar to any other large code project. Apps should address a single, clearly-defined responsibility. The name "application" is a misnomer; Django apps should be thought of more as reusable components which can be plugged together to create a real application. Tests for each app should be contained within that app. Apps should be decoupled from each other as much as possible, but clearly there will be dependencies, so the goal should be to keep the dependency graph as simple and sane as possible.
I prefer to keep all the templates for a project under a single project-wide templates directory, with a subdirectory for each app (using a template subdirectory for each app is a very strong convention in Django, as it avoids template name collisions between apps). The reason for a single project-wide templates directory is that templates, template inheritance trees, and block names can be quite project-specific, so it's hard to provide "default" app templates that can plug in to any project. There have been some attempts to settle on standard naming conventions for base site-wide templates and the blocks they define, but I haven't seen a standard emerge yet (the way they do things over at [Pinax](http://pinaxproject.com) is probably the closest we have to a standard).
Re "string externalization", if you mean i18n and l10n, Django has strong support for that and standard places where it puts the .po files - check the [docs](http://docs.djangoproject.com/en/dev/topics/i18n/#topics-i18n).
|
I found Zachary's layout quite useful
[Zachary Voase’s Blog » Django Project Conventions, Revisited.](http://zacharyvoase.com/2010/02/03/django-project-conventions/)
|
Project design / FS layout for large django projects
|
[
"",
"python",
"django",
""
] |
I'm getting a warning from ReSharper about a call to a virtual member from my objects constructor.
Why would this be something not to do?
|
When an object written in C# is constructed, what happens is that the initializers run in order from the most derived class to the base class, and then constructors run in order from the base class to the most derived class ([see Eric Lippert's blog for details as to why this is](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two)).
Also in .NET objects do not change type as they are constructed, but start out as the most derived type, with the method table being for the most derived type. This means that virtual method calls always run on the most derived type.
When you combine these two facts you are left with the problem that if you make a virtual method call in a constructor, and it is not the most derived type in its inheritance hierarchy, that it will be called on a class whose constructor has not been run, and therefore may not be in a suitable state to have that method called.
This problem is, of course, mitigated if you mark your class as sealed to ensure that it is the most derived type in the inheritance hierarchy - in which case it is perfectly safe to call the virtual method.
|
In order to answer your question, consider this question: what will the below code print out when the `Child` object is instantiated?
```
class Parent
{
public Parent()
{
DoSomething();
}
protected virtual void DoSomething()
{
}
}
class Child : Parent
{
private string foo;
public Child()
{
foo = "HELLO";
}
protected override void DoSomething()
{
Console.WriteLine(foo.ToLower()); //NullReferenceException!?!
}
}
```
The answer is that in fact a `NullReferenceException` will be thrown, because `foo` is null. **An object's base constructor is called before its own constructor**. By having a `virtual` call in an object's constructor you are introducing the possibility that inheriting objects will execute code before they have been fully initialized.
|
Virtual member call in a constructor
|
[
"",
"c#",
"constructor",
"warnings",
"resharper",
"virtual-functions",
""
] |
Hey, I've been developing an application in the windows console with Java, and want to put it online in all of its console-graphics-glory.
Is there a simple web applet API I can use to port my app over?
I'm just using basic System.out and System.in functionality, but I'm happy to rebuild my I/O wrappers.
I think something along these lines would be a great asset to any beginning Java developers who want to put their work online.
|
Sure, just make into an applet, put a small swing UI on it with a JFrame with two components - one for writing output to, and one for entering inputs from. Embed the applet in the page.
|
I did as [Lars](https://stackoverflow.com/questions/138157/java-console-like-web-app#138206) suggested and wrote my own.
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.awt.Font;
public class Applet extends JFrame {
static final long serialVersionUID = 1;
/** Text area for console output. */
protected JTextArea textArea;
/** Text box for user input. */
protected JTextField textBox;
/** "GO" button, in case they don't know to hit enter. */
protected JButton goButton;
protected PrintStream printStream;
protected BufferedReader bufferedReader;
/**
* This function is called when they hit ENTER or click GO.
*/
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
goButton.setEnabled(false);
SwingUtilities.invokeLater(
new Thread() {
public void run() {
String userInput = textBox.getText();
printStream.println("> "+userInput);
Input.inString = userInput;
textBox.setText("");
goButton.setEnabled(true);
}
}
);
}
};
public void println(final String string) {
SwingUtilities.invokeLater(
new Thread() {
public void run() {
printStream.println(string);
}
}
);
}
public void printmsg(final String string) {
SwingUtilities.invokeLater(
new Thread() {
public void run() {
printStream.print(string);
}
}
);
}
public Applet() throws IOException {
super("My Applet Title");
Container contentPane = getContentPane();
textArea = new JTextArea(30, 60);
JScrollPane jScrollPane = new JScrollPane(textArea);
final JScrollBar jScrollBar = jScrollPane.getVerticalScrollBar();
contentPane.add(BorderLayout.NORTH, jScrollPane);
textArea.setFocusable(false);
textArea.setAutoscrolls(true);
textArea.setFont(new Font("Comic Sans MS", Font.TRUETYPE_FONT, 14));
// TODO This might be overkill
new Thread() {
public void run() {
while(true) {
jScrollBar.setValue(jScrollBar.getMaximum());
try{
Thread.sleep(100);
} catch (Exception e) {}
}
}
}.start();
JPanel panel;
contentPane.add(BorderLayout.CENTER, panel = new JPanel());
panel.add(textBox = new JTextField(55));
textBox.addActionListener(actionListener);
panel.add(goButton = new JButton("GO"));
goButton.addActionListener(actionListener);
pack();
// End of GUI stuff
PipedInputStream inputStream;
PipedOutputStream outputStream;
inputStream = new PipedInputStream();
outputStream = new PipedOutputStream(inputStream);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "ISO8859_1"));
printStream = new PrintStream(outputStream);
new Thread() {
public void run() {
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
textArea.append(line+"\n");
}
} catch (IOException ioException) {
textArea.append("ERROR");
}
}
}.start();
}
}
```
This below code was in a separate class, "Input", which has a static "inString" string.
```
public static String getString() {
inString = "";
// Wait for input
while (inString == "") {
try{
Thread.sleep(100);
} catch (Exception e) {}
}
return inString;
}
```
Through-out the lifespan of the project I will probably maintain this code some more, but at this point - it works :)
|
Java - Console-like web applet
|
[
"",
"java",
"api",
"console",
"applet",
""
] |
I'm new to PHP and I'm confused seeing some examples calling a function with a @ prefix like @mysql\_ping().
What is it for? Googling / searching is not much of a help since @ gets discarded and 'alias' is not good enough keyword.
|
@ suppresses errors, warnings and notices.
You can use it for good purpose if you complement it with a custom [error handler](http://php.net/manual/en/function.set-error-handler.php) or with due check of $php\_errormsg variable so you can handle errors properly.
In my experience, this proper usage is not seen very much and is instead used a lot in the bad way, just to hide errors without acting on them.
More info at <http://www.php.net/manual/en/language.operators.errorcontrol.php>
|
It suppresses the output of error messages.
Contrary to another commentator here, I think that it is good programming practice to use it (especially if you are developing a web app, where the output would be mixed in the html of the output page).
Functions like mysql\_connect return a resource identifier, or FALSE on errors. Use @mysql\_connect(...) and check the return value.
|
PHP alias @ function
|
[
"",
"php",
"operators",
"error-suppression",
""
] |
I want to have my PHP application labeled with the revision number which it uses, but I don't want to use [CruiseControl](http://en.wikipedia.org/wiki/CruiseControl) or update a file and upload it every time. How should I do it?
|
SVN keywords is not a good solution. As others pointed out adding $Revision$ in a file only affects **the specific file**, which may not change for a long time.
Remembering to "edit" a file (by adding or removing a blank line) before every commit is pointless. You could as well just type the revision by hand.
One good way to do it (that I know of) is to have an automated deployment process (which is always a good thing) and using the command svnversion. Here is what I do:
Wherever I need the revision I do an include: `<?php include 'version.php'; ?>`. This "version.php" file only has the revision number. Moreover it is not part of the repository (it set to be ignored). Here is how I create it:
1) On projects where SVN is installed on the server, I also use it for deployment. Getting the latest version to the server I have a script that among other things does the following (it runs on the server):
```
cd /var/www/project
svn update
rm version.php
svnversion > version.php
```
2) On projects where SVN is not installed my deployment script is more complex: it creates the version.php file locally, zips the code, uploads and extracts it
|
Assuming your webroot is a checked-out copy of the subversion tree, you could parse the /.svn/entries file and hook out the revision number (4th line here)...
In PHP:
```
$svn = File('.svn/entries');
$svnrev = $svn[3];
unset($svn);
```
|
How can I get the Subversion revision number in PHP?
|
[
"",
"php",
"svn",
"revision",
""
] |
Why does this javascript return 108 instead of 2008? it gets the day and month correct but not the year?
```
myDate = new Date();
year = myDate.getYear();
```
year = 108?
|
It's a [Y2K](http://en.wikipedia.org/wiki/Y2K) thing, only the years since 1900 are counted.
There are potential compatibility issues now that `getYear()` has been deprecated in favour of `getFullYear()` - from [quirksmode](http://www.quirksmode.org/js/introdate.html):
> To make the matter even more complex, date.getYear() is deprecated nowadays and you should use date.getFullYear(), which, in turn, is not supported by the older browsers. If it works, however, it should always give the full year, ie. 2000 instead of 100.
>
> Your browser gives the following years with these two methods:
```
* The year according to getYear(): 108
* The year according to getFullYear(): 2008
```
There are also implementation differences between Internet Explorer and Firefox, as IE's implementation of `getYear()` was changed to behave like `getFullYear()` - from [IBM](http://www-128.ibm.com/developerworks/web/library/wa-ie2mozgd/):
> Per the ECMAScript specification, getYear returns the year minus 1900, originally meant to return "98" for 1998. getYear was deprecated in ECMAScript Version 3 and replaced with getFullYear().
>
> Internet Explorer changed getYear() to work like getFullYear() and make it Y2k-compliant, while Mozilla kept the standard behavior.
|
Since getFullYear doesn't work in older browsers, you can use something like this:
```
Date.prototype.getRealYear = function()
{
if(this.getFullYear)
return this.getFullYear();
else
return this.getYear() + 1900;
};
```
Javascript prototype can be used to extend existing objects, much like C# extension methods. Now, we can just do this;
```
var myDate = new Date();
myDate.getRealYear();
// Outputs 2008
```
|
Why does Javascript getYear() return a three digit number?
|
[
"",
"javascript",
"date",
""
] |
I believe any programmer who has been dealing with database requests in a gui application has run into some or all of the following problems:
* Your GUI freezes because you call
database layer from within the event
dispatch thread
* When you have multiple windows/panels/jframes where user can start a db request your performance degrades because you don't have any control about the threads your user creates
* User may be able to lock down the application and even the database because he calls any action many times before the first action has been finished
What I'd like to know about: are there any frameworks that handle the requirements of handling an ordered set of long running actions (including but not limited to database calls, i.e. calculations) outside the event dispatch thread?
Note: I know of SwingWorker ;-)
|
Such a thing should be found in Netbeans for example. See RequestProcessor. But in simpler cases this is not required. Last time I need something like thread scheduling and control I simply used new concurrency packages included in J5 (I used J6). With its ExecutorFactory-ies you can simply achieve basic control over tasks. You can also use some queues. [This PDF can help](http://java.cz/dwn/1003/8060_CZJUG_SwingInAction.pdf). The PDF is written in Slovak language but the Single/Multiple task workers are there written in Java ;)
|
Naked Objects facilitate a clean domain model and they also have a GUI 2 DB mapping layer -- <http://www.nakedobjects.org/home/index.shtml>
|
Are there any frameworks for handling database requests in swing applications?
|
[
"",
"java",
"database",
"multithreading",
"swing",
""
] |
I use several referenced tables with integer primary keys. Now I want to change ints to GUIDs leaving all references intact. What is the easiest way to do it?
Thank you!
**Addition**
I do understand the process in general, so I need more detailed advices, for example, how to fill new GUID column. Using default value newid() is correct, but what for already existing rows?
|
* Create a new column for the guid
value in the master table. Use the
uniqueidentifier data type, make it
not null with a newid() default so
all existing rows will be populated.
* Create new uniqueidentifier columns
in the child tables.
* Run update statements to build the guild relationships using the exisitng int relationships to reference the entities.
* Drop the original int columns.
In addition, leave some space in your data/index pages (specify fillfactor < 100) as guids are not sequential like int identity columns are. This means inserts can be anywhere in the data range and will cause page splits if your pages are 100% full.
|
Firstly: Dear God why?!?!?
Secondly, you're going to have to add the GUID column to all your tables first, then populate them based on the int value. Once done you can set the GUIDs to primary/foreign keys then drop the int columns.
To update the value you'd do something like
1. Set the new GUIDs in the primary key table
2. Run this:
.
```
UPDATE foreignTable f
SET f.guidCol = p.guidCol
FROM primaryTable p
WHERE p.intCol = f.intCol
```
|
Moving from ints to GUIDs as primary keys
|
[
"",
"sql",
"sql-server",
"foreign-keys",
"primary-key",
"guid",
""
] |
I've been impressed by the screencasts for Rails that demonstrate the built-in web server, and database to allow development and testing to occur on the local machine. How can I get an instance of Apache to execute a project directory as its DocumentRoot, and maybe serve up the files on port 8080 (or something similar)?
The reason why I'm asking is that I'm going to be trying out CodeIgniter, and I would like to use it for multiple projects. I would rather not clutter up my machine's DocumentRoot with each one. Suggestions on how to do database migrations are also welcome.
---
Thank you for your responses so far. I should clarify that I'm on Mac OS X. It looks like WAMP is Windows-only. Also, XAMPP looks like a great way to install Apache and many other web tools, but I don't see a way of loading up an instance to serve up a project directory. Mac OS X has both Apache and PHP installed - I'm just looking for a way to get it to serve up a project on a non-standard port.
I just found [MAMP Pro](http://www.mamp.info/en/mamp-pro/) which does what I want, but a more minimalist approach would be better if it's possible. Does anyone have a `httpd.conf` file that can be edited and dropped into a project directory?
Also, sorry that I just threw in that database migration question. What I'm hoping to find is something that will enable me to push schema changes onto a live server without losing the existing data. I suspect that this is difficult and highly dependent on environmental factors.
|
Your Mac comes with both an Apache Web Server and a build of PHP. It's one of the big reasons the platform is well loved by web developers.
Since you're using Code Igniter, you'll want PHP 5, which is the default version of PHP shipped with 10.5. If you're on a previous version of the OS hop on over to [entropy.ch](http://www.entropy.ch/home/) and install the provided PHP5 package.
Next, you'll want to turn Apache on. In the sharing preferences panel, turn on personal web sharing. This will start up apache on your local machine.
Next, you'll want to setup some fake development URLs to use for your sites. Long standing tradition was that we'd use the fake TLD .dev for this (ex. stackoverflow.dev). However, `.dev` is now an actual TLD so you probably don't want to do this -- `.localhost` seems like an emerging defacto standard. Edit your /etc/hosts file and add the following lines
```
127.0.0.1 www.example.localhost
127.0.0.1 example.localhost
```
This points the above URLs at your local machine. The last step is configuring apache. Specifically, enabling named virtual hosting, enabling PHP and setting up a few virtual hosts. If you used the entropy PHP package, enabling PHP will already be done. If not, you'll need to edit your http.conf file as described [here](http://foundationphp.com/tutorials/php_leopard.php). Basically, you're uncommenting the lines that will load the PHP module.
Whenever you make a change to your apache config, you'll need to restart apache for the changes to take effect. At a terminal window, type the following command
```
sudo apachectl graceful
```
This will gracefully restart apache. If you've made a syntax error in the config file apache won't restart. You can highlight config problems with
```
sudo apachectl configtest
```
So,with PHP enabled, you'll want to turn on NamedVirtualHosts. This will let apache respond to multiple URLs. Look for the following (or similar) line in your http.conf file and uncomment it.
```
#NameVirtualHost *
```
Finally, you'll need to tell apache where it should look for the files for your new virtual hosts. You can do so by adding the following to your http.conf file. NOTE: I find it's a good best practice to break out config rules like this into a separate file and use the include directive to include your changes. This will stop any automatic updates from wiping out your changes.
```
<VirtualHost *>
DocumentRoot /Users/username/Sites/example.localhost
ServerName example.localhost
ServerAlias www.example.localhost
</VirtualHost>
```
You can specify any folder as the DocumentRoot, but I find it convenient to use your personal Sites folder, as it's already been configured with the correct permissions to include files.
|
Sorry Kyle, I don't have enough cred to respond directly to your comment. But if you want to have each project be served on a different port, try setting up your virtual host config exactly like Kelly's above (minus the DNS stuff) except instead of 80, give each virtual host its own port number, assuming that you've added this port to your `ports.conf` file.
```
NameVirtualHost *
<virtualhost *:80>
DocumentRoot /site1/documentroot
</virtualhost>
<virtualhost *:81>
DocumentRoot /site2/documentroot
</virtualhost>
<virtualhost *:82>
DocumentRoot /site3/documentroot
</virtualhost>
<virtualhost *:83>
DocumentRoot /site4/documentroot
</virtualhost>
```
Hope that helps
|
Set up Apache for local development/testing?
|
[
"",
"php",
"codeigniter",
"apache",
""
] |
I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Oracle, and if possible, what version of Oracle they are running by sending a SQL statement to the datasource.
|
Run this SQL:
```
select * from v$version;
```
And you'll get a result like:
```
BANNER
----------------------------------------------------------------
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production
PL/SQL Release 10.2.0.3.0 - Production
CORE 10.2.0.3.0 Production
TNS for Solaris: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production
```
|
Two methods:
```
select * from v$version;
```
will give you:
```
Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - 64bit Production
PL/SQL Release 11.1.0.6.0 - Production
CORE 11.1.0.6.0 Production
TNS for Solaris: Version 11.1.0.6.0 - Production
NLSRTL Version 11.1.0.6.0 - Production
```
OR [Identifying Your Oracle Database Software Release](https://docs.oracle.com/database/121/ADMIN/dba.htm#ADMIN11032):
```
select * from product_component_version;
```
will give you:
```
PRODUCT VERSION STATUS
NLSRTL 11.1.0.6.0 Production
Oracle Database 11g Enterprise Edition 11.1.0.6.0 64bit Production
PL/SQL 11.1.0.6.0 Production
TNS for Solaris: 11.1.0.6.0 Production
```
|
How can I confirm a database is Oracle & what version it is using SQL?
|
[
"",
"sql",
"oracle",
""
] |
I am trying to use the Google Maps API in a ColdFusion template that is a border type cflayoutarea container. However, the map simply doesn't show up:
```
<cfif isdefined("url.lat")>
<cfset lat="#url.lat#">
<cfset lng="#url.lng#">
</cfif>
<head>
<script src= "http://maps.google.com/maps?file=api&v=2&key=xxxx" type="text/javascript">
function getMap(lat,lng){
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var pt= new GLatLng(lat,lng);
map.setCenter(pt, 18,G_HYBRID_MAP);
map.addOverlay(new GMarker(pt));
}
}
</script>
</head>
<cfoutput>
<body onLoad="getMap(#lat#,#lng#)" onUnload="GUnload()">
Map:<br>
<div id="map_canvas" style="width: 500px; height: 300px"/>
</body>
</cfoutput>"
```
where lat and lng are the co-ordinates in degree.decimal format. I have traced down to the line where GBrowserIsCompatible() somehow never returns TRUE and thus no further action was taken.
If opened separately the template works perfectly but just not when opened as a cflayoutarea container. Anyone has experience in this? Any suggestions is much appreciated.
Lawrence
Using CF 8.01, Dreamweaver 8
---
Tried your suggestion but still doesn't work; the map only shows when the calling code is inline. However, if this container page was called from yet another div the map disappears again.
I suspect this issue is related to the cflayout container; I'll look up the Extjs doc to see if there're any leads to a solution.
|
Success! (sort of...)
Finally got it working, but not in the way Adam suggested:
```
<script src= "http://maps.google.com/maps?file=api&v=2&key=xxxx" type="text/javascript"></script>
<script type="text/javascript">
getMap=function(lat,lng){
if (GBrowserIsCompatible()){
var map = new GMap2(document.getElementById("map_canvas"));
var pt = new GLatLng(lat,lng);
map.setCenter(pt, 18,G_HYBRID_MAP);
map.addOverlay(new GMarker(pt));
}
}
</script>
<cflayout name="testlayout" type="border">
<cflayoutarea name="left" position="left" size="250"/>
<cflayoutarea name="center" position="center">
<!--- sample hard-coded co-ordinates --->
<body onLoad="getMap(22.280161,114.185096)">
Map:<br />
<div id="map_canvas" style="width:500px; height: 300px"/>
</body>
</cflayoutarea>
<!--- <cflayoutarea name="center" position="center" source="map_content.cfm?lat=22.280161&lng=114.185096"/> --->
</cflayout>
```
The whole thing must be contained within the same file or it would not work. My suspicion is that the getElementByID function, as it stands, cannot not reference an element that is outside of its own file. If the div is in another file (as in Adam's exmaple), it results in an undefined map, ie a map object is created but with nothing in it.
So I think this question is now elevated to a different level: how do you reference an element that is inside an ajax container?
|
> So I think this question is now elevated to a different level: how do you reference an element that is inside an ajax container?
It should be possible reference an element loaded via AJAX -- just not until the element is on screen (so not on page load). It looks like getMap() triggers everything. (Is that right?)
Try this: Take exactly what you have as your inline-content for the map tab, and make it the content of map\_content.cfm; **then** instead of using body onload to fire the event, write it inline, after the div is defined:
```
<body>
Map:<br />
<div id="map_canvas" style="width:500px; height: 300px"/>
<script type="text/javascript">
getMap(22.280161,114.185096);
</script>
</body>
```
|
Using Google Maps in ColdFusion
|
[
"",
"javascript",
"google-maps",
"coldfusion",
""
] |
I was writing a database handler class in PHP using the mysqli class and prepared statements. I was attempting to print out the result. It didn't work right off the bat so I decided to do some debugging. I tried to use the `num_rows()` method from the `mysqli_statement` class, but it kept returning 0. I decided to write a small portion of the test code to keep it simpler so I could see what was going wrong. I was then able to return the data I wanted, but the `num_rows()` method still returns 0 even when it is actually selecting and retrieving some data. Here is the code:
```
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno())
{
die('connection failed');
}
$statement = $mysqli->stmt_init();
$query = "SELECT name FROM table WHERE id = '2000'";
if($statement->prepare($query))
{
$statement->execute();
$statement->bind_result($name);
$statement->fetch();
$statement->store_result();
echo $statement->num_rows();
echo $name;
}
else
{
echo 'prepare statement failed';
exit();
}
```
The expected result is:
```
1name
```
And the actual result is:
```
0name
```
Can anyone tell me why this is?
|
I wonder if num\_rows() is reporting relative to the current resultset. Try capturing num\_rows() prior to fetching the data. e.g.
```
if($statement->prepare($query))
{
$statement->execute();
$statement->store_result();
echo $statement->num_rows();
$statement->bind_result($name);
$statement->fetch();
echo $name;
}
```
Does that have any effect?
|
`num_rows` is not a method, it's a property.
|
mysqli_stmt::num_rows() returns the wrong value
|
[
"",
"php",
"mysql",
"mysqli",
""
] |
I have an application that tracks high scores in a game.
I have a **user\_scores** table that maps a user\_id to a score.
I need to return the 5 highest scores, but only 1 high score for any *specific* user.
So if user X has the 5 highest scores on a purely numerical basis, I simply return the highest one and then the next 4 user scores.
I have tried to use:
```
SELECT user_id, score
FROM user_scores
ORDER BY score DESC
GROUP BY user_id
LIMIT 5
```
But it seems that MySQL drops any user\_id with more than 1 score.
|
This should work:
```
SELECT user_id, MAX(score)
FROM user_scores
GROUP BY user_id
ORDER BY MAX(score) DESC
LIMIT 5
```
|
```
SELECT user_id, MAX(score) AS score
FROM user_scores
GROUP BY user_id
ORDER BY score DESC
LIMIT 5
```
Should do the job for you... though don't forget to create indexes...
|
Selecting values grouped to a specific identifer
|
[
"",
"mysql",
"sql",
"database",
""
] |
In what scenarios is it better to use a `struct` vs a `class` in C++?
|
The differences between a `class` and a `struct` in C++ are:
* `struct` members and base classes/structs are `public` by default.
* `class` members and base classes/structs are `private` by default.
Both classes and structs can have a mixture of `public`, `protected` and `private` members, can use inheritance, and can have member functions.
I would recommend you:
* use `struct` for plain-old-data structures without any class-like features;
* use `class` when you make use of features such as `private` or `protected` members, non-default constructors and operators, etc.
|
As everyone else notes there are really only two actual language differences:
* `struct` defaults to public access and `class` defaults to private access.
* When inheriting, `struct` defaults to `public` inheritance and `class` defaults to `private` inheritance. (Ironically, as with so many things in C++, the default is backwards: `public` inheritance is by far the more common choice, but people rarely declare `struct`s just to save on typing the "`public`" keyword.
But the real difference in practice is between a `class`/`struct` that declares a constructor/destructor and one that doesn't. There are certain guarantees to a "plain-old-data" POD type, that no longer apply once you take over the class's construction. To keep this distinction clear, many people deliberately only use `struct`s for POD types, and, if they are going to add any methods at all, use `class`es. The difference between the two fragments below is otherwise meaningless:
```
class X
{
public:
// ...
};
struct X
{
// ...
};
```
(Incidentally, here's a thread with some good explanations about what "POD type" actually means: [What are POD types in C++?](https://stackoverflow.com/questions/146452/what-are-pod-types-in-c))
|
When should you use a class vs a struct in C++?
|
[
"",
"c++",
"oop",
"class",
"struct",
"ooad",
""
] |
Along the lines of my previous [question](https://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat), how can i join a list of strings into a string such that values get quoted cleanly. Something like:
```
['a', 'one "two" three', 'foo, bar', """both"'"""]
```
into:
```
a, 'one "two" three', "foo, bar", "both\"'"
```
I suspect that the csv module will come into play here, but i'm not sure how to get the output I want.
|
Using the `csv` module you can do that way:
```
import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerow(the_list)
```
If you need a string just use `StringIO` instance as a file:
```
f = StringIO.StringIO()
writer = csv.writer(f)
writer.writerow(the_list)
print f.getvalue()
```
The output: `a,"one ""two"" three","foo, bar","both""'"`
`csv` will write in a way it can read back later.
You can fine-tune its output by defining a `dialect`, just set `quotechar`, `escapechar`, etc, as needed:
```
class SomeDialect(csv.excel):
delimiter = ','
quotechar = '"'
escapechar = "\\"
doublequote = False
lineterminator = '\n'
quoting = csv.QUOTE_MINIMAL
f = cStringIO.StringIO()
writer = csv.writer(f, dialect=SomeDialect)
writer.writerow(the_list)
print f.getvalue()
```
The output: `a,one \"two\" three,"foo, bar",both\"'`
The same dialect can be used with csv module to read the string back later to a list.
|
On a related note, Python's [builtin encoders](http://docs.python.org/lib/standard-encodings.html) can also do string escaping:
```
>>> print "that's interesting".encode('string_escape')
that\'s interesting
```
|
How can I join a list into a string (caveat)?
|
[
"",
"python",
"string",
"list",
"csv",
""
] |
In [PostgreSQL](http://en.wikipedia.org/wiki/PostgreSQL), I can do something like this:
```
ALTER SEQUENCE serial RESTART WITH 0;
```
Is there an Oracle equivalent?
|
Here is a good procedure for resetting any sequence to 0 from Oracle guru [Tom Kyte](http://asktom.oracle.com). Great discussion on the pros and cons in the links below too.
```
tkyte@TKYTE901.US.ORACLE.COM>
create or replace
procedure reset_seq( p_seq_name in varchar2 )
is
l_val number;
begin
execute immediate
'select ' || p_seq_name || '.nextval from dual' INTO l_val;
execute immediate
'alter sequence ' || p_seq_name || ' increment by -' || l_val ||
' minvalue 0';
execute immediate
'select ' || p_seq_name || '.nextval from dual' INTO l_val;
execute immediate
'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0';
end;
/
```
From this page: [Dynamic SQL to reset sequence value](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:951269671592)
Another good discussion is also here: [How to reset sequences?](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1119633817597)
|
A true restart is not possible [AFAIK](http://en.wiktionary.org/wiki/AFAIK). (Please correct me if I'm wrong!).
However, if you want to set it to 0, you can just delete and recreate it.
If you want to set it to a specific value, you can set the INCREMENT to a negative value and get the next value.
That is, if your sequence is at 500, you can set it to 100 via
```
ALTER SEQUENCE serial INCREMENT BY -400;
SELECT serial.NEXTVAL FROM dual;
ALTER SEQUENCE serial INCREMENT BY 1;
```
|
How do I reset a sequence in Oracle?
|
[
"",
"sql",
"database",
"oracle",
"sequence",
""
] |
I'm now in search for a Java Text to Speech (TTS) framework. During my investigations I've found several JSAPI1.0-(partially)-compatible frameworks listed on [JSAPI Implementations page](http://java.sun.com/products/java-media/speech/reference/codesamples/index.html), as well as a pair of Java TTS frameworks which do not appear to follow JSAPI spec ([Mary](http://mary.dfki.de/), [Say-It-Now](http://www.say-it-now.com/mainsite.htm)). I've also noted that currently no reference implementation exists for JSAPI.
Brief tests I've done for FreeTTS (first one listed in JSAPI impls page) show that it is far from reading simple and obvious words (examples: ABC, blackboard). Other tests are currently in progress.
And here goes the question (6, actually):
1. Which of the Java-based TTS frameworks have you used?
2. Which ones, by your opinion, are capable of reading the largest wordbase?
3. What about their voice quality?
4. What about their performance?
5. Which non-Java frameworks with Java bindings are there on the scene?
6. Which of them would you recommend?
Thank you in advance for your comments and suggestions.
|
I've actually had pretty good luck with [FreeTTS](http://freetts.sourceforge.net/)
|
Google Translate has a secret tts api:
<https://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hello%20World>
|
Java: Text to Speech engines overview
|
[
"",
"java",
"text-to-speech",
""
] |
How can I detect, using php, if the machine has oracle `(oci8 and/or pdo_oci)` installed?
I'm working on a `PHP` project where some developers, such as myself, have it installed, but there's little need for the themers to have it. How can I write a quick function to use in the code so that my themers are able to work on the look of the site without having it crash on them?
|
if the oci extension isn't installed, then you'll get a fatal error with farside.myopenid.com's answer, you can use function\_exists('oci\_connect') or extension\_loaded('oci8') (or whatever the extension's actually called)
|
The folks here have pieces of the solution, but let's roll it all into one solution.
For just a single instance of an oracle function, testing with `function_exists()` is good enough; but if the code is sprinkled throughout to OCI calls, it's going to be a huge pain in the ass to wrap every one in a `function_exists()` test.
Therefore, I think the simplest solution would be to create a file called *nodatabase.php* that might look something like this:
```
<?php
// nodatabase.php
// explicitly override database functions with empty stubs. Only include this file
// when you want to run the code without an actual database backend. Any database-
// related functions used in the codebase must be included below.
function oci_connect($user, $password, $db = '', $charset='UTF-8', $session_mode=null)
{
}
function oci_execute($statement, $mode=0)
{
}
// and so on...
```
Then, conditionally include this file if a global (say, THEME\_TESTING) is defined just ahead of where the database code is called. Such an include might look like this:
```
// define("THEME_TESTING", true) // uncomment this line to disable database usage
if( defined(THEME_TESTING) )
include('nodatabase.php'); // override oracle API with stub functions for the artists.
```
Now, when you hand the project over to the artists, they simply need to make that one modification and they're good to go.
|
How can I detect, using php, if the machine has oracle (oci8 and/or pdo_oci) installed?
|
[
"",
"php",
"oracle",
""
] |
I have a ASP.NET application running on a remote web server and I just started getting this error. I can't seem to reproduce it in my development environment:
```
Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'.
```
Could this be due to some misconfiguration of .NET Framework or IIS 6?
Update:
I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code. (Note that Set is a class that implements a set of unique objects. It inherits from IEnumerable.) This line:
```
Set<int> set = new Set<int>();
```
Is compiled into this line:
```
Set<int> set = (Set<int>) new ICollection<CalendarModule>();
```
The Calendar class is a totally unrelated class!! Has anyone ever noticed .NET incorrectly compiling code like this before?
|
This was caused by a bug in the aspnet merge tool which incorrectly merged optimized assemblies. It can be solved by either not merging the assemblies or not optimizing them.
|
Are the .NET versions on both systems the same inc. the same service pack?
|
ASP.NET: ICollection Constructor Not Found?
|
[
"",
"c#",
"asp.net",
""
] |
What are the differences in implementing interfaces **implicitly** and **explicitly** in C#?
When should you use implicit and when should you use explicit?
Are there any pros and/or cons to one or the other?
---
Microsoft's official guidelines (from first edition [Framework Design Guidelines](https://rads.stackoverflow.com/amzn/click/com/0321246756)) states that **using explicit implementations are not recommended**, since it gives the code unexpected behaviour.
I think this guideline is very **valid in a pre-IoC-time**, when you don't pass things around as interfaces.
Could anyone touch on that aspect as well?
|
**Implicit** is when you define your interface via a member on your class. **Explicit** is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: `IList.CopyTo` would be implicitly implemented as:
```
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
```
and explicitly as:
```
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
```
The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.
```
MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
```
I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.
I am sure there are more reasons to use/not use explicit that others will post.
See the [**next post**](https://stackoverflow.com/questions/143405/c-interfaces-implicit-and-explicit-implementation#143425) in this thread for excellent reasoning behind each.
|
Implicit definition would be to just add the methods / properties, etc. demanded by the interface directly to the class as public methods.
Explicit definition forces the members to be exposed only when you are working with the interface directly, and not the underlying implementation. This is preferred in most cases.
1. By working directly with the interface, you are not acknowledging,
and coupling your code to the underlying implementation.
2. In the event that you already have, say, a public property Name in
your code and you want to implement an interface that also has a
Name property, doing it explicitly will keep the two separate. Even
if they were doing the same thing I'd still delegate the explicit
call to the Name property. You never know, you may want to change
how Name works for the normal class and how Name, the interface
property works later on.
3. If you implement an interface implicitly then your class now exposes
new behaviours that might only be relevant to a client of the
interface and it means you aren't keeping your classes succinct
enough (my opinion).
|
C# Interfaces. Implicit implementation versus Explicit implementation
|
[
"",
"c#",
".net",
"interface",
""
] |
I have video durations stored in HH:MM:SS format. I'd like to display it as HH hours, MM minutes, SS seconds. It shouldn't display hours if it's less than 1.
What would be the best approach?
|
try using split
```
list($hh,$mm,$ss)= split(':',$duration);
```
|
Something like this?
```
$vals = explode(':', $duration);
if ( $vals[0] == 0 )
$result = $vals[1] . ' minutes, ' . $vals[2] . ' seconds';
else
$result = $vals[0] . 'hours, ' . $vals[1] . ' minutes, ' . $vals[2] . ' seconds';
```
|
How do you convert 00:00:00 to hours, minutes, seconds in PHP?
|
[
"",
"php",
"date",
""
] |
I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO\_SETTINGS\_MODULE environment variable?
If I run the following code:
```
>>> import django.template
>>> from django.template import Template, Context
>>> t = Template('My name is {{ my_name }}.')
```
I get:
```
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
```
|
An addition to what other wrote, if you want to use Django Template on Django > 1.7, you must give your settings.configure(...) call the TEMPLATES variable and call django.setup() like this :
```
from django.conf import settings
settings.configure(TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['.'], # if you want the templates from a file
'APP_DIRS': False, # we have no apps
},
])
import django
django.setup()
```
Then you can load your template like normally, from a string :
```
from django import template
t = template.Template('My name is {{ name }}.')
c = template.Context({'name': 'Rob'})
t.render(c)
```
And if you wrote the DIRS variable in the .configure, from the disk :
```
from django.template.loader import get_template
t = get_template('a.html')
t.render({'name': 5})
```
[Django Error: No DjangoTemplates backend is configured](https://stackoverflow.com/questions/43834226/django-error-no-djangotemplates-backend-is-configured#43834287)
<http://django.readthedocs.io/en/latest/releases/1.7.html#standalone-scripts>
|
The solution is simple. It's actually [well documented](http://docs.djangoproject.com/en/dev/ref/templates/api/#configuring-the-template-system-in-standalone-mode), but not too easy to find. (I had to dig around -- it didn't come up when I tried a few different Google searches.)
The following code works:
```
>>> from django.template import Template, Context
>>> from django.conf import settings
>>> settings.configure()
>>> t = Template('My name is {{ my_name }}.')
>>> c = Context({'my_name': 'Daryl Spitzer'})
>>> t.render(c)
u'My name is Daryl Spitzer.'
```
See the Django documentation (linked above) for a description of some of the settings you may want to define (as keyword arguments to configure).
|
How do I use Django templates without the rest of Django?
|
[
"",
"python",
"django",
"templates",
"django-templates",
"template-engine",
""
] |
I am 90% sure I saw this answer on stackoverflow before, in fact I had never seen the "int?" syntax before seeing it here, but no matter how I search I can't find the previous post, and it's driving me crazy.
It's possible that I've been eating the funny mushrooms by accident, but if I'm not, can someone please point out the previous post if they can find it or re-explain it? My stackoverflow search-fu is apparently too low....
|
int? is shorthand for `Nullable<int>`.
[This](https://stackoverflow.com/questions/110229/how-do-nullable-types-work-in-c) may be the post you were looking for.
|
int? is Nullable.
MSDN: [Using Nullable Types (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/using-nullable-types)
|
What's the difference between 'int?' and 'int' in C#?
|
[
"",
"c#",
"syntax",
"types",
"nullable",
""
] |
Is it possible to throw an exception in a JSP without using scriptlet code?
|
You really shouldn't be doing anything at the JSP layer that explicitly throws exceptions. The reason you don't want to use scriptlets in JSPs is because that puts application logic in your view. Throwing an exception is inherently application logic, so it doesn't belong in your JSP, scriptlet or not.
|
You can throw an exception if you do this:
```
<c:out value="${1/0}" />
```
or something that is similarly "illegal"
Ideally though, since JSPs are associated with the view...you don't want to throw an exception. You want to catch them with `<c:catch>`
|
throw exception from a JSP
|
[
"",
"java",
"exception",
"jsp",
""
] |
I need to randomly fade my background images in and out.
It will be a timed function, like once every 5 seconds.
I need to do it with ASP.NET, Javascript, CSS or all three.
Please help me out here guys. Thank you.
|
Cycle, a jQuery plugin is a very flexible image rotating solution: <http://malsup.com/jquery/cycle/>
|
**This is the Answer:** never mind guys, after making a bit more exact search on Google. I found a good solution.
```
<html>
<head>
<!--
This file retrieved from the JS-Examples archives
http://www.js-examples.com
1000s of free ready to use scripts, tutorials, forums.
Author: Steve S - http://jsmadeeasy.com/
-->
<style>
body
{
/*Remove below line to make bgimage NOT fixed*/
background-attachment:fixed;
background-repeat: no-repeat;
/*Use center center in place of 300 200 to center bg image*/
background-position: 300 200;
}
</style>
<script language="JavaScript1.2">
/* you must supply your own immages */
var bgimages=new Array()
bgimages[0]="http://js-examples.com/images/blue_ball0.gif"
bgimages[1]="http://js-examples.com/images/red_ball0.gif"
bgimages[2]="http://js-examples.com/images/green_ball0.gif"
//preload images
var pathToImg=new Array()
for (i=0;i<bgimages.length;i++)
{
pathToImg[i]=new Image()
pathToImg[i].src=bgimages[i]
}
var inc=-1
function bgSlide()
{
if (inc<bgimages.length-1)
inc++
else
inc=0
document.body.background=pathToImg[inc].src
}
if (document.all||document.getElementById)
window.onload=new Function('setInterval("bgSlide()",3000)')
</script>
</head>
<body>
<BR><center><a href='http://www.js-examples.com'>JS-Examples.com</a></center>
</body>
</html>
```
[Found it here](http://www.js-x.com/page/javascripts__example.html?view=1072).
|
How to rotate and fade background images in and out with javascript/ASP.NET/CSS
|
[
"",
"asp.net",
"javascript",
"css",
"image-manipulation",
""
] |
Okay, so this probably sounds terribly nefarious, but I need such capabilities for my senior project. Essentially I'm tasked with writing something that will cut down outbound spam on a zombified pc through a system of packet interception and evaluation. We have a number of algorithms we'll use on the captured messages, but it's the actual capture -- full on interception rather than just sniffing -- that has me a bit stumped.
The app is being designed for windows, so I can't use IP tables. I could use the winpcap libraries, but I don't want to reinvent the wheel if I don't have to. Ettercap seemed a good option, but a test run on vista using the unofficial binaries resulted in nothing but crashes.
So, any suggestions?
Update: Great suggestions. Ended up scaling back the project a bit, but still received an A. I'm thinking Adam Mintz's answer is probably best, though we used WinPcap and Wireshark for the application.
|
Sounds like you need to write a [Winsock LSP](http://en.wikipedia.org/wiki/Layered_Service_Provider).
> Once in the stack, a Layered Service Provider can intercept and modify inbound and outbound Internet traffic. It allows processing all the TCP/IP traffic taking place between the Internet and the applications that are accessing the Internet.
|
Use Snort, stripped down, if this is a long-term thing. It's built to watch for particular packets flying by, examining payload where needed, recording data and launching alerts.
It's intended for intrusion detection, but it makes a surprisingly good network monitor for particular things over long term use.
|
Best OS App for Outbound SMTP Packet Capture?
|
[
"",
"c++",
"windows",
"smtp",
"packet-capture",
"spam-prevention",
""
] |
I am building a java server that needs to scale. One of the servlets will be serving images stored in Amazon S3.
Recently under load, I ran out of memory in my VM and it was after I added the code to serve the images so I'm pretty sure that streaming larger servlet responses is causing my troubles.
My question is : is there any best practice in how to code a java servlet to stream a large (>200k) response back to a browser when read from a database or other cloud storage?
I've considered writing the file to a local temp drive and then spawning another thread to handle the streaming so that the tomcat servlet thread can be re-used. This seems like it would be io heavy.
Any thoughts would be appreciated. Thanks.
|
When possible, you should not store the entire contents of a file to be served in memory. Instead, aquire an InputStream for the data, and copy the data to the Servlet OutputStream in pieces. For example:
```
ServletOutputStream out = response.getOutputStream();
InputStream in = [ code to get source input stream ];
String mimeType = [ code to get mimetype of data to be served ];
byte[] bytes = new byte[FILEBUFFERSIZE];
int bytesRead;
response.setContentType(mimeType);
while ((bytesRead = in.read(bytes)) != -1) {
out.write(bytes, 0, bytesRead);
}
// do the following in a finally block:
in.close();
out.close();
```
I do agree with toby, you should instead "point them to the S3 url."
As for the OOM exception, are you sure it has to do with serving the image data? Let's say your JVM has 256MB of "extra" memory to use for serving image data. With Google's help, "256MB / 200KB" = 1310. For 2GB "extra" memory (these days a very reasonable amount) over 10,000 simultaneous clients could be supported. Even so, 1300 simultaneous clients is a pretty large number. Is this the type of load you experienced? If not, you may need to look elsewhere for the cause of the OOM exception.
Edit - Regarding:
> In this use case the images can contain sensitive data...
When I read through the S3 documentation a few weeks ago, I noticed that you can generate time-expiring keys that can be attached to S3 URLs. So, you would not have to open up the files on S3 to the public. My understanding of the technique is:
1. Initial HTML page has download links to your webapp
2. User clicks on a download link
3. Your webapp generates an S3 URL that includes a key that expires in, lets say, 5 minutes.
4. Send an HTTP redirect to the client with the URL from step 3.
5. The user downloads the file from S3. This works even if the download takes more than 5 minutes - once a download starts it can continue through completion.
|
Why wouldn't you just point them to the S3 url? Taking an artifact from S3 and then streaming it through your own server to me defeats the purpose of using S3, which is to offload the bandwidth and processing of serving the images to Amazon.
|
Streaming large files in a java servlet
|
[
"",
"java",
"java-io",
""
] |
In effect, if I have a `class c` and instances of `$c1` and `$c2`
which might have different private variable amounts but all their public methods return the same values I would like to be able to check that `$c1 == $c2?`
Does anyone know an easy way to do this?
|
You can also implement a equal($other) function like
```
<?php
class Foo {
public function equals($o) {
return ($o instanceof 'Foo') && $o.firstName()==$this.firstName();
}
}
```
or use foreach to iterate over the public properties (this behaviour might be overwritten) of one object and compare them to the other object's properties.
```
<?php
function equalsInSomeWay($a, $b) {
if ( !($b instanceof $a) ) {
return false;
}
foreach($a as $name=>$value) {
if ( !isset($b->$name) || $b->$name!=$value ) {
return false;
}
}
return true;
}
```
(untested)
or (more or less) the same using the Reflection classes, see <http://php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionobject>
With reflection you might also implement a more duck-typing kind of comparision, if you want to, like "I don't care if it's an instance of or the same class as long as it has the same public methods and they return the 'same' values"
it really depends on how you define "equal".
|
It's difficult to follow exactly what you're after. Your question seems to imply that these public methods don't require arguments, or that if they did they would be the same arguments.
You could probably get quite far using the inbuilt reflection classes.
Pasted below is a quick test I knocked up to compare the returns of all the public methods of two classes and ensure they were they same. You could easily modify it to ignore non matching public methods (i.e. only check for equality on public methods in class2 which exist in class1). Giving a set of arguments to pass in would be trickier - but could be done with an array of methods names / arguments to call against each class.
Anyway, this may have some bits in it which could be of use to you.
```
$class1 = new Class1();
$class2 = new Class2();
$class3 = new Class3();
$class4 = new Class4();
$class5 = new Class5();
echo ClassChecker::samePublicMethods($class1,$class2); //should be true
echo ClassChecker::samePublicMethods($class1,$class3); //should be false - different values
echo ClassChecker::samePublicMethods($class1,$class4); //should be false -- class3 contains extra public methods
echo ClassChecker::samePublicMethods($class1,$class5); //should be true -- class5 contains extra private methods
class ClassChecker {
public static function samePublicMethods($class1, $class2) {
$class1methods = array();
$r = new ReflectionClass($class1);
$methods = $r->getMethods();
foreach($methods as $m) {
if ($m->isPublic()) {
@$result = call_user_method($m->getName(), $class1);
$class1methods[$m->getName()] = $result;
}
}
$r = new ReflectionClass($class2);
$methods = $r->getMethods();
foreach($methods as $m) {
//only comparing public methods
if ($m->isPublic()) {
//public method doesn't match method in class1 so return false
if(!isset($class1methods[$m->getName()])) {
return false;
}
//public method of same name doesn't return same value so return false
@$result = call_user_method($m->getName(), $class2);
if ($class1methods[$m->getName()] !== $result) {
return false;
}
}
}
return true;
}
}
class Class1 {
private $b = 'bbb';
public function one() {
return 999;
}
public function two() {
return "bendy";
}
}
class Class2 {
private $a = 'aaa';
public function one() {
return 999;
}
public function two() {
return "bendy";
}
}
class Class3 {
private $c = 'ccc';
public function one() {
return 222;
}
public function two() {
return "bendy";
}
}
class Class4 {
public function one() {
return 999;
}
public function two() {
return "bendy";
}
public function three() {
return true;
}
}
class Class5 {
public function one() {
return 999;
}
public function two() {
return "bendy";
}
private function three() {
return true;
}
}
```
|
PHP: How do I check if all public methods of two classes return the same values?
|
[
"",
"php",
"oop",
""
] |
Sorry the title isn't more help. I have a database of media-file URLs that came from two sources:
(1) RSS feeds and (2) manual entries.
I want to find the ten most-recently added URLs, but a maximum of one from any feed. To simplify, table '`urls`' has columns `'url, feed_id, timestamp'`.
`feed_id=''` for any URL that was entered manually.
How would I write the query? Remember, I want the ten most-recent urls, but only one from any single `feed_id`.
|
Assuming feed\_id = 0 is the manually entered stuff this does the trick:
```
select p.* from programs p
left join
(
select max(id) id1 from programs
where feed_id <> 0
group by feed_id
order by max(id) desc
limit 10
) t on id1 = id
where id1 is not null or feed_id = 0
order by id desc
limit 10;
```
It works cause the id column is constantly increasing, its also pretty speedy. t is a table alias.
This was my original answer:
```
(
select
feed_id, url, dt
from feeds
where feed_id = ''
order by dt desc
limit 10
)
union
(
select feed_id, min(url), max(dt)
from feeds
where feed_id <> ''
group by feed_id
order by dt desc
limit 10
)
order by dt desc
limit 10
```
|
Assuming this table
```
CREATE TABLE feed (
feed varchar(20) NOT NULL,
add_date datetime NOT NULL,
info varchar(45) NOT NULL,
PRIMARY KEY (feed,add_date);
```
**this query should do what you want**. The inner query selects the last entry by feed and picks the 10 most recent, and then the outer query returns the original records for those entries.
```
select f2.*
from (select feed, max(add_date) max_date
from feed f1
group by feed
order by add_date desc
limit 10) f1
left join feed f2 on f1.feed=f2.feed and f1.max_date=f2.add_date;
```
|
MySQL Query: Select most-recent items with a twist
|
[
"",
"sql",
"mysql",
""
] |
I'm giving a presentation to a Java User's Group on Groovy and I'm going to be doing some coding during the presentation to show some side-by-side Java/Groovy. I really like the GroovyConsole as it's simple and I can resize the text easily.
I'm wondering if there is anything similar for Java? I know I could just use Eclipse but I'd rather have a smaller app to use without having to customize a view. What's the community got?
Screen shot of GroovyConsole:

|
[DrJava](http://www.drjava.org/) is your best bet. It also has an [Eclipse plugin](http://www.drjava.org/eclipse.shtml) to use the interactions pane like GroovyConsole.
|
try beanshell. its a scripting wrapper over java. <http://www.beanshell.org/>
|
Is there a Java Console/Editor similar to the GroovyConsole?
|
[
"",
"java",
"editor",
""
] |
What are some general tips to make sure I don't leak memory in C++ programs? How do I figure out who should free memory that has been dynamically allocated?
|
Instead of managing memory manually, try to use smart pointers where applicable.
Take a look at the [Boost lib](http://www.boost.org/), [TR1](http://en.wikipedia.org/wiki/Technical_Report_1), and [smart pointers](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm).
Also smart pointers are now a part of C++ standard called [C++11](http://en.wikipedia.org/wiki/Smart_pointer).
|
I thoroughly endorse all the advice about RAII and smart pointers, but I'd also like to add a slightly higher-level tip: the easiest memory to manage is the memory you never allocated. Unlike languages like C# and Java, where pretty much everything is a reference, in C++ you should put objects on the stack whenever you can. As I've see several people (including Dr Stroustrup) point out, the main reason why garbage collection has never been popular in C++ is that well-written C++ doesn't produce much garbage in the first place.
Don't write
```
Object* x = new Object;
```
or even
```
shared_ptr<Object> x(new Object);
```
when you can just write
```
Object x;
```
|
General guidelines to avoid memory leaks in C++
|
[
"",
"c++",
"memory",
"memory-management",
"raii",
""
] |
Being a C# developer since version 1.0, F# has captured my free time for the past few weeks. Computers are now sold with 2, 4 .. Cores and multi-threading is not always simple to accomplish.
At the moment I see that F# has great potential for complicated and or heavy workloads.
Do you think that F# will (once RTM) become an important player in the Enterprise Software market?
|
I think regardless of whether F# becomes import for Enterprise Software being able to isolate pure functional portions of code in any language will be key to using the potential of multi-core computers. For instance Microsoft's Parallel Extensions for .NET are great, but there is still a lot of room to make mistakes by parallelizing code that can't execute in parallel. If the code is in the form of a pure functional language or a subset of your language that is purely functional, then you are assured that you can execute it in parallel. The trick is then figuring out the most efficient way to assign the work.
The role that F# plays in this I would say would be more as a catalyst to get people's feet wet and start thinking in a more declarative way.
|
I think F# has great opportunity to make inroads some of the niche areas of enterprise applications such as mathematical modelling (e.g. for banking/trading applications). Removing side effects from functions also leads to great opportunities for parallelism and memoization. Its hard to say if these languages will ever take off for mainstream development is hard to say, but in my opinion the problems are more likely to be human oriented (i.e. lack of skills and high learning curve for people familiar with more typical languages like c#/java/c++) rather than technical.
|
F# and Enterprise Software
|
[
"",
"c#",
"f#",
"functional-programming",
"enterprise",
""
] |
In C++0x I would like to write a function like this:
```
template <typename... Types>
void fun(typename std::tuple<Types...> my_tuple) {
//Put things into the tuple
}
```
I first tried to use a for loop on `int i` and then do:
```
get<i>(my_tuple);
```
And then store some value in the result. However, `get` only works on `constexpr`.
If I could get the variables out of the `tuple` and pass them to a variadic templated function I could recurse through the arguments very easily, but I have no idea how to get the variables out of the tuple without `get`. Any ideas on how to do that? Or does anyone have another way of modifying this `tuple`?
|
Since the "i" in
```
get<i>(tup)
```
needs to be a compile-time constant, template instantiation is used to "iterate" (actually recurse) through the values. Boost tuples have the "length" and "element" meta-functions that can be helpful here -- I assume C++0x has these too.
|
[Boost.Fusion](http://www.boost.org/doc/libs/release/libs/fusion/doc/html/index.html) is worth a look. It can 'iterate' over `std::pair`, `boost::tuple`, some other containers and its own tuple types, although I don't think it supports `std::tuple` yet.
|
In C++, can you have a function that modifies a tuple of variable length?
|
[
"",
"c++",
"tuples",
""
] |
I have tried:
1. Xdebug and Eclipse. Eclipse launches a web browser, but the browser tries to access a non-existent file in Eclipse's .app bundle.
2. Xdebug and NetBeans. It does a little bit better; a browser opens a page in /tmp which says "Launching. Please wait…" but nothing happens beyond that.
3. Xdebug and debugclient, the CLI tool which comes with Xdebug. MacPorts (which I used to install PHP and Xdebug) doesn't seem to install this by itself, and when I try compiling it by hand, I get told "you have strange libedit". Installing libedit via MacPorts doesn't solve that.
4. Zend's debugger (the precise name escapes me right now) and Eclipse. I can't recall what the problem was, as this was some time ago, but it didn't work.
With regards to Xdebug, at least, I'm fairly confident I've installed it correctly. It shows up with both a phpinfo() in a PHP file and a `php -i` in the CLI.
If anyone has managed to get PHP debugging working in some way or other on the Mac, I'd appreciate it if you could share with me how. Littering code with `var_dump($foo);die();` gets old quick. Bonus points if it can be done *without* using some bloatware editor like Eclipse, or that expensive proprietary thing Zend wants to sell me.
My server is connecting to PHP via FastCGI, if that makes a diff.
|
You may want to look into [MacGDBp](http://www.bluestatic.org/software/macgdbp/). It's new, free, and the UI looks great. It utilizes the Xdebug PHP extension as well. You can find instructions in the [help](http://www.bluestatic.org/software/macgdbp/help.php) section, which includes Xdebug configurations, and there's also a nice overview of the app from the guys at Particletree here: [Silence The Echo with MacGDBp](http://particletree.com/notebook/silence-the-echo-with-macgdbp/).
|
Here's how I did it:
1 - Copy the latest version of xdebug.so from <http://aspn.activestate.com/ASPN/Downloads/Komodo/RemoteDebugging> to /usr/libexec.
2 - Add the following to the global php.ini:
```
zend_extension="/usr/libexec/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.remote_autostart=1
```
3 - Restart Apache and run [MacGDBp](http://www.bluestatic.org/software/macgdbp/help.php).
|
PHP debugging on OS X - hopeless?
|
[
"",
"php",
"debugging",
"macos",
""
] |
As a beginner to TDD I am trying to write a test that assumes a property has had its value changed on a PropertyGrid (C#, WinForms, .NET 3.5).
Changing a property on an object in a property grid does not fire the event (fair enough, as it's a UI raised event, so I can see why changing the owned object may be invisible to it).
I also had the same issue with getting an AfterSelect on a TreeView to fire when changing the SelectedNode property.
I could have a function that my unit test can call that simulates the code a UI event would fire, but that would be cluttering up my code, and unless I make it public, I would have to write all my tests in the same project, or even class, of the objects I am testing (again, I see this as clutter). This seems ugly to me, and would suffer from maintainability problems.
Is there a convention to do this sort of UI based unit-testing
|
To unit test your code you will need to mock up an object of the UI interface element. There are many tools you can use to do this, and I can't recommend one over another. There's a good comparison between MoQ and Rhino Mocks here [at Phil Haack's blog](http://haacked.com/archive/2008/03/23/comparing-moq-to-rhino-mocks.aspx) that I've found useful and might be useful to you.
Anothing thing to consider if you're using TDD is creating an interface to your views will assist in the TDD process. There is a design model for this (probably more than one, but this is one I use) called Model View Presenter (now split into Passive View and Supervisor Controller). Following one of these will make your code behind far more testable in the future.
Also, bear in mind that testing the UI itself cannot be done through unit testing. A test automation tool as already suggested in another answer will be appropriate for this, but not for unit testing your code.
|
Microsoft has UI Automation built into the .Net Framework. You may be able to use this to simulate a user utilising your software in the normal way.
There is an MSDN article "[Using UI Automation for Automated Testing](http://msdn.microsoft.com/en-us/library/aa348551.aspx "MSDN - Using UI Automation for Automated Testing") which is a good starting point.
|
Firing UI control events from a Unit Test
|
[
"",
"c#",
"winforms",
"unit-testing",
""
] |
In an attempt to add some parameter validation and correct usage semantics to our application, we are trying to add correct exception handling to our .NET applications.
My question is this: When throwing exceptions in ADO.NET if a particular query returns no data or the data could not be found, what type of exception should I use?
Psuedocode:
(read, don't scrutinize the semantics of the code, I know it won't compile)
```
public DataSet GetData(int identifier)
{
dataAdapter.Command.Text = "Select * from table1 Where ident = " + identifier.toString();
DataSet ds = dataAdapter.Fill(ds);
if (ds.table1.Rows.Count == 0)
throw new Exception("Data not found");
return ds;
}
```
|
The [MSDN guidelines](http://msdn.microsoft.com/en-us/library/ms229021(VS.80).aspx) state:
* Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types.
* Do create and throw custom exceptions if you have an error condition that can be programmatically handled in a different way than any other existing exceptions. Otherwise, throw one of the existing exceptions.
* Do not create and throw new exceptions just to have your team's exception.
There is no hard and fast rule: but if you have a scenario for treating this exception differently, consider creating a custom exception type, such as DataNotFoundException [as suggested by Johan Buret](https://stackoverflow.com/questions/121700/what-exception-should-be-thrown-when-an-adonet-query-cannot-retrieve-the-reques#121809).
Otherwise you might consider throwing one of the existing exception types, such as System.Data.DataException or possibly even System.Collections.Generic.KeyNotFoundException.
|
You really should define your own exception : DataNotFoundException.
You should not use the basic class Exception, since when you will catch it in calling code, you will write something like
```
try
{
int i;
GetData(i);
}
catch(Exception e) //will catch many many exceptions
{
//Handle gracefully the "Data not Found" case;
//Whatever else happens will get caught and ignored
}
```
Where as catching only your DataNotFoundEXception will get only the case you really want to handle.
```
try
{
int i;
GetData(i);
}
catch(DataNotFoundException e)
{
//Handle gracefully the "Data not Found" case;
} //Any other exception will bubble up
```
There is a class aptly named SqlException, when there are troubles with the SQL engine but it's better not overload it with your business logic
|
What Exception should be thrown when an ADO.NET query cannot retrieve the requested data?
|
[
"",
".net",
"sql",
"exception",
"ado.net",
""
] |
The question is a fairly open one. I've been using Stored Procs with MS SQLServer for some time with classic ASP and ASP.net and love them, lots.
I have a small hobby project I'm working on and for various reasons have gone the LAMP route. Any hints/tricks/traps or good starting points to get into using stored procedures with MySQL and PHP5? My version of MySQL supports Stored Procedures.
|
Forget about `mysqli`, it's much harder to use than PDO and should have been already removed. It is true that it introduced huge improvements over mysql, but to achieve the same effect in mysqli sometimes requires enormous effort over PDO i.e. associative `fetchAll`.
Instead, take a look at [PDO](http://www.php.net/manual/en/book.pdo.php), specifically [prepared statements and stored procedures](http://www.php.net/manual/en/pdo.prepared-statements.php).
```
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $value\n";
```
|
@michal kralik - unfortunately there's a bug with the MySQL C API that PDO uses which means that running your code as above with some versions of MySQL results in the error:
> "Syntax error or access violation: 1414 OUT or INOUT argument $parameter\_number for routine $procedure\_name is not a variable or NEW pseudo-variable".
You can see the bug report on [bugs.mysql.com](http://bugs.mysql.com/bug.php?id=11638). It's been fixed for version 5.5.3+ & 6.0.8+.
To workaround the issue, you would need to separate in & out parameters, and use user variables to store the result like this:
```
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(:in_string, @out_string)");
$stmt->bindParam(':in_string', 'hello');
// call the stored procedure
$stmt->execute();
// fetch the output
$outputArray = $this->dbh->query("select @out_string")->fetch(PDO::FETCH_ASSOC);
print "procedure returned " . $outputArray['@out_string'] . "\n";
```
|
Stored Procedures, MySQL and PHP
|
[
"",
"php",
"mysql",
"stored-procedures",
""
] |
Here's my first question at SO.
I have a internal application for my company which I've been recently ask to maintain. The applications is built in PHP and its fairly well coded (OO, DB Abstraction, Smarty) nothing WTF-ish.
The problem is the applications is **very slow**.
How do I go about finding out what's slowing the application down? I've optimized the code to make very few DB queries, so I know that it is the PHP code which is taking a while to execute. I need to get some tools which can help me with this and need to devise a strategy for checking my code.
I can do the checking/strategy work myself, but I need more PHP tools to figure out where my app is crapping up.
Thoughts?
|
I've used [XDebug profiling](http://www.xdebug.org/docs/profiler) recently in a similiar situation. It outputs a full profile report that can be read with many common profiling apps ( Can't give you a list though, I just used the one that came with slackware ).
|
As Juan mentioned, xDebug is excellent. If you're on Windows, [WinCacheGrind](http://sourceforge.net/projects/wincachegrind/) will let you look over the reports.
|
Find out where your PHP code is slowing down (Performance Issue)
|
[
"",
"php",
"mysql",
"performance",
"profiling",
""
] |
If I open an image with `open("image.jpg")`, how can I get the RGB values of a pixel assuming I have the coordinates of the pixel?
Then, how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?
I would prefer if I didn't have to download any additional libraries.
|
It's probably best to use the [Python Image Library](http://www.pythonware.com/products/pil/) to do this which I'm afraid is a separate download.
The easiest way to do what you want is via the [load() method on the Image object](https://web.archive.org/web/20201111195341/http://effbot.org/imagingbook/image.htm#tag-Image.Image.load) which returns a pixel access object which you can manipulate like an array:
```
from PIL import Image
im = Image.open('dead_parrot.jpg') # Can be many different formats.
pix = im.load()
print im.size # Get the width and hight of the image for iterating over
print pix[x,y] # Get the RGBA Value of the a pixel of an image
pix[x,y] = value # Set the RGBA Value of the image (tuple)
im.save('alive_parrot.png') # Save the modified pixels as .png
```
Alternatively, look at [ImageDraw](https://web.archive.org/web/20200726042716/http://effbot.org/imagingbook/imagedraw.htm) which gives a much richer API for creating images.
|
Using [Pillow](http://python-pillow.github.io/) (which works with Python 3.X as well as Python 2.7+), you can do the following:
```
from PIL import Image
im = Image.open('image.jpg', 'r')
width, height = im.size
pixel_values = list(im.getdata())
```
Now you have all pixel values. If it is RGB or another mode can be read by `im.mode`. Then you can get pixel `(x, y)` by:
```
pixel_values[width*y+x]
```
Alternatively, you can use Numpy and reshape the array:
```
>>> pixel_values = numpy.array(pixel_values).reshape((width, height, 3))
>>> x, y = 0, 1
>>> pixel_values[x][y]
[ 18 18 12]
```
A complete, simple to use solution is
```
# Third party modules
import numpy
from PIL import Image
def get_image(image_path):
"""Get a numpy array of an image so that one can access values[x][y]."""
image = Image.open(image_path, "r")
width, height = image.size
pixel_values = list(image.getdata())
if image.mode == "RGB":
channels = 3
elif image.mode == "L":
channels = 1
else:
print("Unknown mode: %s" % image.mode)
return None
pixel_values = numpy.array(pixel_values).reshape((width, height, channels))
return pixel_values
image = get_image("gradient.png")
print(image[0])
print(image.shape)
```
## Smoke testing the code
You might be uncertain about the order of width / height / channel. For this reason I've created this gradient:
[](https://i.stack.imgur.com/H70ww.png)
The image has a width of 100px and a height of 26px. It has a color gradient going from `#ffaa00` (yellow) to `#ffffff` (white). The output is:
```
[[255 172 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 171 5]
[255 171 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 171 5]
[255 172 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 171 5]
[255 172 4]
[255 172 5]
[255 171 5]
[255 171 5]
[255 172 5]]
(100, 26, 3)
```
Things to note:
* The shape is (width, height, channels)
* The `image[0]`, hence the first row, has 26 triples of the same color
|
How to read the RGB value of a given pixel in Python?
|
[
"",
"python",
"graphics",
"rgb",
"pixel",
""
] |
How do I have a Python script that can accept user input and how do I make it read in arguments if run from the command line?
|
To read user input you can try [the `cmd` module](https://docs.python.org/dev/library/cmd.html) for easily creating a mini-command line interpreter (with help texts and autocompletion) and [`raw_input`](https://docs.python.org/2/library/functions.html#raw_input) ([`input`](https://docs.python.org/dev/library/functions.html#input) for Python 3+) for reading a line of text from the user.
```
text = raw_input("prompt") # Python 2
text = input("prompt") # Python 3
```
Command line inputs are in `sys.argv`. Try this in your script:
```
import sys
print (sys.argv)
```
There are two modules for parsing command line options: [~~`optparse`~~](https://docs.python.org/dev/library/optparse.html) (deprecated since Python 2.7, use [`argparse`](https://docs.python.org/dev/library/argparse.html) instead) and [`getopt`](https://docs.python.org/dev/library/getopt.html). If you just want to input files to your script, behold the power of [`fileinput`](https://docs.python.org/dev/library/fileinput.html).
The [Python library reference](https://docs.python.org/dev/library/) is your friend.
|
```
var = raw_input("Please enter something: ")
print "you entered", var
```
Or for Python 3:
```
var = input("Please enter something: ")
print("You entered: " + var)
```
|
User input and command line arguments
|
[
"",
"python",
"input",
"command-line-arguments",
""
] |
I've recently read the Yahoo manifesto [Best Practices for Speeding Up Your Web Site](http://developer.yahoo.com/performance/rules.html#postload). They recommend to put the JavaScript inclusion at the bottom of the HTML code when we can.
But where exactly and when?
Should we put it before closing `</html>` or after ? And above all, when should we still put it in the `<head>` section?
|
There are two possibilities for truly unobtrusive scripts:
* including an external script file via a script tag in the head section
* including an external script file via a script tag at the bottom of the body (before `</body></html>`)
The second one can be faster as the original Yahoo research showed some browsers try to load script files when they hit the script tag and therefore don't load the rest of the page until they have finished. However, if your script has a 'ready' portion which must execute as soon as the DOM is ready you may need to have it in the head. Another issue is layout - if your script is going to change the page layout you want it loaded as early as possible so your page does not spend a long time redrawing itself in front of your users.
If the external script site is on another domain (like external widgets) it may be worth putting it at the bottom to avoid it delaying loading of the page.
And for any performance issues *do your own benchmarks* - what may be true at one time when a study is done might change with your own local setup or changes in browsers.
|
It's never so cut and dry - Yahoo recommends putting the scripts just before the closing `</body>` tag, which will create the illusion that the page loads faster on an empty cache (since the scripts won't block downloading the rest of the document).
However, if you have some code you want to run on page load, it will only start executing after the entire page has loaded. If you put the scripts in the `<head>` tag, they would start executing before - so on a primed cache the page would actually appear to load faster.
Also, the privilege of putting scripts at the bottom of the page is not always available. If you need to include inline scripts in your views that depend on a library or some other JavaScript code being loaded before, you must load those dependencies in the `<head>` tag.
All in all Yahoo's recommendations are interesting but not always applicable and should be considered on a case-by-case basis.
|
Unobtrusive JavaScript: <script> at the top or the bottom of the HTML code?
|
[
"",
"javascript",
"performance",
"optimization",
"coding-style",
""
] |
I have a database with two tables (`Table1` and `Table2`). They both have a common column `[ColumnA]` which is an `nvarchar`.
How can I select this column from both tables and return it as a single column in my result set?
So I'm looking for something like:
```
ColumnA in Table1:
a
b
c
ColumnA in Table2:
d
e
f
Result set should be:
a
b
c
d
e
f
```
|
```
SELECT ColumnA FROM Table1 UNION Select ColumnB FROM Table2 ORDER BY 1
```
Also, if you know the contents of Table1 and Table2 will **NEVER** overlap, you can use UNION ALL in place of UNION instead. Saves a little bit of resources that way.
-- Kevin Fairchild
|
Do you care if you get dups or not?
UNION will be slower than UNION ALL because UNION will filter out dups
|
SQL: Select like column from two tables
|
[
"",
"sql",
""
] |
I am looking for a simple JavaScript example that updates DOM.
Any suggestions?
|
Here is a short pure-javascript example. Assume you have a div with the id "maincontent".
```
var newnode = document.createTextNode('Here is some text.');
document.getElementById('maincontent').appendChild(newnode);
```
Of course, things are a lot easier (especially when you want to do more complicated things) with jQuery.
|
[@Ravi](https://stackoverflow.com/questions/44190?sort=newest#44250)
Here's working example of your code
```
<html>
<head>
<title>Font Detect please</title>
<script src="prototype.js" type="text/javascript"></script>
<script type="text/javascript">
function changeTD()
{
$('Myanmar3').innerHTML = 'False';
}
</script>
</head>
<body>
<table border="1">
<tr><td>Font</td><td>Installed</td></tr>
<tr><td>Myanmar3</td><td id="Myanmar3">True</td></tr>
</table>
<a href="javascript:void(0);" onclick="changeTD();">Click Me</a>
</body>
</html>
```
You'll notice that I added a little link that you have to click to actually make the change. I thought this might make it easier to try out for real.
|
Looking for a simple JavaScript example that updates DOM
|
[
"",
"javascript",
"dom",
""
] |
Any recommended crypto libraries for Java. What I need is the ability to parse X.509 Certificates to extract the information contained in them.
Thanks
|
In Java, java.security.cert.CertificateFactory.
"A certificate factory for X.509 must return certificates that are an instance of java.security.cert.X509Certificate"
|
There's a lot more in most certificates than what's handled by `java.security.cert.X509Certificate`. If you need to parse extension values, check out the [Bouncy Castle Crypto API](http://www.bouncycastle.org/index.html). (C# version is offered too.)
|
x509 certificate parsing libraries for Java
|
[
"",
"java",
"certificate",
"x509",
""
] |
In MySQL, If I have a list of date ranges (range-start and range-end). e.g.
```
10/06/1983 to 14/06/1983
15/07/1983 to 16/07/1983
18/07/1983 to 18/07/1983
```
And I want to check if another date range contains ANY of the ranges already in the list, how would I do that?
e.g.
```
06/06/1983 to 18/06/1983 = IN LIST
10/06/1983 to 11/06/1983 = IN LIST
14/07/1983 to 14/07/1983 = NOT IN LIST
```
|
This is a classical problem, and it's actually easier if you reverse the logic.
Let me give you an example.
I'll post one period of time here, and all the different variations of other periods that overlap in some way.
```
|-------------------| compare to this one
|---------| contained within
|----------| contained within, equal start
|-----------| contained within, equal end
|-------------------| contained within, equal start+end
|------------| not fully contained, overlaps start
|---------------| not fully contained, overlaps end
|-------------------------| overlaps start, bigger
|-----------------------| overlaps end, bigger
|------------------------------| overlaps entire period
```
on the other hand, let me post all those that doesn't overlap:
```
|-------------------| compare to this one
|---| ends before
|---| starts after
```
So if you simple reduce the comparison to:
```
starts after end
ends before start
```
then you'll find all those that doesn't overlap, and then you'll find all the non-matching periods.
For your final NOT IN LIST example, you can see that it matches those two rules.
You will need to decide wether the following periods are IN or OUTSIDE your ranges:
```
|-------------|
|-------| equal end with start of comparison period
|-----| equal start with end of comparison period
```
If your table has columns called range\_end and range\_start, here's some simple SQL to retrieve all the matching rows:
```
SELECT *
FROM periods
WHERE NOT (range_start > @check_period_end
OR range_end < @check_period_start)
```
Note the *NOT* in there. Since the two simple rules finds all the *non-matching* rows, a simple NOT will reverse it to say: *if it's not one of the non-matching rows, it has to be one of the matching ones*.
Applying simple reversal logic here to get rid of the NOT and you'll end up with:
```
SELECT *
FROM periods
WHERE range_start <= @check_period_end
AND range_end >= @check_period_start
```
|
Taking your example range of 06/06/1983 to 18/06/1983 and assuming you have columns called **start** and **end** for your ranges, you could use a clause like this
```
where ('1983-06-06' <= end) and ('1983-06-18' >= start)
```
i.e. check the start of your test range is before the end of the database range, and that the end of your test range is after or on the start of the database range.
|
Comparing date ranges
|
[
"",
"sql",
"mysql",
"date",
""
] |
I've been thinking a lot lately about a music-oriented project I'd like to work on. Kind of like a game... kind of like a studio workstation (FL Studio, Reason).
I guess the best way to describe it would be: like "Guitar Hero", but with no canned tracks. All original music--composed by you, on the fly--but the software would use its knowledge of music theory (as well as some supervised learning algorithms) to make sure that your input gets turned into something that sounds great.
It sounds a little silly, explaining it like that, but there ya go. It's something I think would make an interesting side project.
Anyhow, I'm looking for a Java library for generating the actual audio. Browsing around on sourceforge, there are countless software synths, and I have no idea which to choose.
My top priority is that it should sound incredible... Really rich, layered, textured synths, with gobs of configurable parameters. Emulation of acoustic instruments is not important to me.
My second priority is that it ought to be straightforward to use strictly as a library, with no GUI involved at all. (If there's a synth with really breathtaking output, but it's tightly-coupled with a GUI, then I might consider ripping the audio portion out of the application, but I'd rather start with a nicely contained library).
I know I could send MIDI to a standalone synth, but I think it'd be cool to read the actual synth code and learn a little DSP while I'm at it.
Any suggestions?
Oh yeah, I'm on Windows, so posix-only stuff is a no go.
Thanks!
|
Have you checked out [JFugue](http://www.jfugue.org/)? It's an "open-source Java API for programming music without the complexities of MIDI".
**Additional information:** Found a couple of other resources referenced in the [JFugue documentation (pdf)](http://www.jfugue.org/jfugue-chapter1.pdf):
* [Audio Synthesis Engine Project](http://openjdk.java.net/projects/audio-engine): open source version of Java’s MIDI synthesizer
* [Gervill](https://gervill.dev.java.net): open source software synthesizer created as a proposal for the Audio Synthesis Engine Project
|
Yeah, I noticed JFugue a few years ago. It's on my list of interesting computer/music bookmarks:
<http://delicious.com/BenjiSmith/computermusic>
<http://delicious.com/BenjiSmith/programming.java.libraries.music>
But JFugue is all about the structure of the music itself... the melodies, harmonies, rhythms, etc....
What I'm looking for right now is just the synthesizer. Something like this...
```
Synth s = new Synth();
Instrument i = s.getInstrument("Robot Bass");
i.makeAwesome(true);
```
And then I'll send my events into the MIDI stream (or into whatever control API the synth library provides).
|
Software Synth Library for Java
|
[
"",
"java",
"audio",
""
] |
When asking about [common undefined behavior in C](https://stackoverflow.com/questions/98340/what-are-the-common-undefinedunspecified-behavior-for-c-that-you-run-into), people sometimes refer to the strict aliasing rule.
What are they talking about?
|
A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to `uint32_t`s or `uint16_t`s). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.
So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this:
```
typedef struct Msg
{
unsigned int a;
unsigned int b;
} Msg;
void SendWord(uint32_t);
int main(void)
{
// Get a 32-bit buffer from the system
uint32_t* buff = malloc(sizeof(Msg));
// Alias that buffer through message
Msg* msg = (Msg*)(buff);
// Send a bunch of messages
for (int i = 0; i < 10; ++i)
{
msg->a = i;
msg->b = i+1;
SendWord(buff[0]);
SendWord(buff[1]);
}
}
```
The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a [compatible type](http://en.cppreference.com/w/c/language/type) or one of the other types allowed by C 2011 6.5 paragraph 71 is undefined behavior. Unfortunately, you can still code this way, *maybe* get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code.
(GCC appears somewhat inconsistent in its ability to give aliasing warnings, sometimes giving us a friendly warning and sometimes not.)
To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn't have to think about inserting instructions to refresh the contents of `buff` every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load `buff[0]` and `buff[1]` into CPU registers once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of `buff` could change by any preceding memory stores. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced.
Keep in mind, if you think the example is contrived, this might even happen if you're passing a buffer to another function doing the sending for you, if instead you have.
```
void SendMessage(uint32_t* buff, size_t size32)
{
for (int i = 0; i < size32; ++i)
{
SendWord(buff[i]);
}
}
```
And rewrote our earlier loop to take advantage of this convenient function
```
for (int i = 0; i < 10; ++i)
{
msg->a = i;
msg->b = i+1;
SendMessage(buff, 2);
}
```
The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If `SendMessage` is part of another API that's compiled separately, it probably has instructions to load buff's contents. Then again, maybe you're in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it's just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what's happening under the hood, it's still a violation of the rule so no well defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn't necessarily help.
**So how do I get around this?**
* Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11.
```
union {
Msg msg;
unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)];
};
```
* You can disable strict aliasing in your compiler ([f[no-]strict-aliasing](http://gcc.gnu.org/onlinedocs/gcc-4.6.1/gcc/Optimize-Options.html#index-fstrict_002daliasing-825) in gcc))
* You can use `char*` for aliasing instead of your system's word. The rules allow an exception for `char*` (including `signed char` and `unsigned char`). It's always assumed that `char*` aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars.
**Beginner beware**
This is only one potential minefield when overlaying two types onto each other. You should also learn about [endianness](http://en.wikipedia.org/wiki/Endianness), [word alignment](http://web.archive.org/web/20170708093042/http://www.cs.umd.edu:80/class/sum2003/cmsc311/Notes/Data/aligned.html), and how to deal with alignment issues through [packing structs](http://grok2.com/structure_packing.html) correctly.
## Footnote
1 The types that C 2011 6.5 7 allows an lvalue to access are:
* a type compatible with the effective type of the object,
* a qualified version of a type compatible with the effective type of the object,
* a type that is the signed or unsigned type corresponding to the effective type of the object,
* a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
* an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
* a character type.
|
The best explanation I have found is by Mike Acton, [Understanding Strict Aliasing](http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html). It's focused a little on PS3 development, but that's basically just GCC.
From the article:
> "Strict aliasing is an assumption, made by the C (or C++) compiler, that dereferencing pointers to objects of different types will never refer to the same memory location (i.e. alias each other.)"
So basically if you have an `int*` pointing to some memory containing an `int` and then you point a `float*` to that memory and use it as a `float` you break the rule. If your code does not respect this, then the compiler's optimizer will most likely break your code.
The exception to the rule is a `char*`, which is allowed to point to any type.
|
What is the strict aliasing rule?
|
[
"",
"c++",
"c",
"undefined-behavior",
"strict-aliasing",
"type-punning",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.