Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a REST webservice that listens to POST requests and grabs hold of an XML payload from the client and stores it initially as an InputStream i.e. *on the Representation object you can call getStream()*.
I want to utilise the XML held in the InputStream and I am begining to think it would be wise to persist it, so I can interrogate the data multiple times - as once you read through it, the object becomes null. So I thought about converting the InputStream to a string. This is not a good idea as DocumentBuilder.parse() from javax.xml.parsers library will only allow you to pass:
* InputStreams
* Files
* URLs
* SAX InputSources
not strings.
What should I really be doing here with InputStreams in relation to parsing XML out of it?
Bearing in mind I will want to re-interrogate that XML in future processes by the code. | If you have an InputStream, and want to use it as an XML document, then why aren't you simply parsing it and passing around the Document object? If you want to persist this object, then use a serializers to write it back out as text.
As I noted in my comment to Tom Hawtin, encoding is very important when dealing with XML. Rather than write a long posting here that may miss your specific situation, here's an [article](http://www.kdgregory.com/index.php?page=xml.parsing) that I wrote.
Edit: actually, since my article doesn't specifically talk about web services, I should dive into it a little here. There are two places where the content encoding can be specified: in the XML prologue, or in the *Content-Type* response header. According to the XML spec, the former is the one that you want to use, and it's what the parser will use. In most cases, that doesn't matter: a webservice set up by a person who doesn't know the spec will typically use a text/xml without a character set specification (which is incorrect but probably not going to cause harm). If they do things correctly, they'll specify application/xml, with utf-8 encoding. However, you should verify what you're getting, so that you don't end up with some strange encoding that the parser can't handle. | Generally, when we're talking persistence, we're talking about writing it to disk or other media. There's a performance hit there, and you have to think about disk space concerns. You'll want to weigh that against the value of having that XML around for the long term.
If you're just talking about holding it in memory (which sounds like what you're asking), then you could allocate a byte array, and read the whole thing into the byte array. The you can use ByteArrayInputStream to read and re-read that stream.
The cost with that is two-fold. First, you're holding a copy in memory, and you need to weigh that against your scalability requirements. Second, parsing XML is somewhat expensive, so it's best to parse it once only, if possible, and save the result in an object.
Edit:
To allocate and read the byte array, you can often (but not always) rely on InputStream's available() method to tell you how much to allocate. and wrap the InputStream with a DataInputStream so that you can call readFully() to suck the whole thing into the byte array with one call.
Edit again:
Read Steen's comment below. He's right that it's a bad idea to use available() in this case. | Best way to use an InputStream regarding persistance and XML | [
"",
"java",
"xml",
"web-services",
"inputstream",
""
] |
see above... | ```
select *
from Table1
inner join
Table2
on Table1.ColumnName = Table2.ColumnName
```
Simple really. | Use an Alias for the table names is the shortest.
```
SELECT a.*, b.*
FROM table1 as 'a'
INNER JOIN table2 as 'b'
ON a.col1 = b.col1
```
You can also specify the full table names.
```
SELECT table1.*, table2.*
FROM table1
INNER JOIN table2
ON table1.col1 = table2.col1
``` | How do I join two tables ON a column, that has the same name in both tables? | [
"",
"sql",
""
] |
Earlier today I asked wether it would be a good idea to develop websites using C#. Most of the answers pointed towards .NET and ASP. Currently I develop with PHP. I've dabbled with Python and RoR but I always come back to PHP. This is the first time I've looked at .NET and ASP. A bucket load of Google searches later I'm not really seeing much support for ASP online but then it all seems a bit Biased towards PHP/Apache/MySQL.
It looks like there's a fair amount of .NET and ASP folk around here so I figured it's worth a shot asking for their input in attempt to try and address the balance in my own head. It can't all be bad.
What advantages are there to .NET and ASP over PHP? | Used:
> asp.net vs php site:stackoverflow.com
in Google search and got:
[ASP.NET vs. PHP](https://stackoverflow.com/questions/304948/aspnet-vs-php)
[The use of PHP vs ASP.net](https://stackoverflow.com/questions/543458/the-use-of-php-vs-asp-net-closed)
[PHP MVC (symfony/Zend) vs ASP MVC vs Spring MVC vs Ruby on Rails?](https://stackoverflow.com/questions/253785/php-mvc-symfony-zend-vs-asp-mvc-vs-spring-mvc-vs-ruby-on-rails)
[Career with PHP or with ASP.NET?](https://stackoverflow.com/questions/558124/career-with-php-or-with-asp-net) | I'd say it depends on your background and how much money you have to throw around too. ASP.net has some great features but you may not even need them depending on your project. The tools are expensive, the hosting is expensive.
PHP is great because you get a lot for free, but there are trade offs.
Personally I like .NET better because thats what I started off with, I feel like I can do more with less, but thats a personal preference. I'm sure some vet php developers feel the exact same way too. | .NET & ASP vs PHP | [
"",
"php",
"asp.net",
""
] |
How do I keep my C# form that, lets say is in a for-loop, from locking up? Do I call Application.DoEvents(); before the loop or after? From what I've heard using the DoEvents method will keep my app from locking. | You should not use Application.DoEvents() in order to keep your application responsive.
Calling this method will allow any waiting windows messages to be dispatched. This means if a user clicks on a button (or performs any other user interaction) that action will be processed. This can therefore cause reentrancy. If they press the same button as the one that caused the loop you are processing you will end up having the routine called again before you have finished!
Instead you should use a [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) thread to perform the long process and then once the action is completed perform whatever additional actions are required. For example, once a button is pressed you would start the worker thread and then disable you button so it cannot be pressed again. Once the worker thread completes you would enable the button again. | There are a few ways, this (DoEvents) just forces the message pump to process messages. Some people put a Thread.Sleep at the end of a loop (always inside the loop though) in a thread. What exactly are you doing in your thread, because there might be a better way to accomplish your goal overall? | Application.DoEvents(); | [
"",
"c#",
"multithreading",
""
] |
I'm concerned that the web hosting that I'm paying for is not configured correctly. ASP.NET Web Sites which compile and run correctly on my local machine don't work once they're deployed.
The issue I'm dealing with is a compilation error: CS0246, "Type or namespace could not be found (Are you missing a 'using' directive or assembly reference?)
My Web Site contains the following files and folders:
```
websitedemo/Default.aspx
websitedemo/Default.aspx.cs
websitedemo/App_Code/HelloClass.cs
```
The compilation error occurs if I attempt to use any code contained in my App Code folder.
I've included the entire /websitedemo/ folder in this archive if it helps troubleshoot the error: <http://kivin.ca/websitedemo/source.zip>
I've left the folder in debug mode. The compilation error screen may be viewed at <http://kivin.ca/websitedemo/>
Best regards.
-- update:
If it helps troubleshoot this error, I've got the behaviour that occurs when I attempt to deploy an ASP.NET WebApplication instead of Website.
In the case that my aspx file includes a @Page direct like this:
`<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="myproj._Default" Debug="true" %>`
The compilation error I get is: 'Parser Error Message: Could not load type 'myproj.\_Default'.'
The webapps are being deployed via ftp using Build -> Publish -> [X] Replace matching files, [X] Only files needed to run this app. [X] Include App\_Data folder. | I'd like to thank everyone for their support. It's most appreciated. I've been in contact with a specialist at my web hosting company and they've advised me that this isn't a code or server configuration error, but just a missed step in my control panel.
Setting my website working directory as a virtual dir resolved the issue.
Thanks to the stack overflow community and the outstanding support people at Softsys Hosting. | If you build your site locally and upload the resulting dll (that will contain HelloClass) to the bin directory, I bet it will work. | How do I resolve "Type or namespace could not be found" compilation error? | [
"",
"c#",
"asp.net",
"web",
""
] |
I am starting to learn Qt4 and Python, following along some tutorial i found on the interwebs. I have the following two files:
lcdrange.py:
```
from PyQt4 import QtGui, QtCore
class LCDRange(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
lcd = QtGui.QLCDNumber(2)
self.slider = QtGui.QSlider()
self.slider.setRange(0,99)
self.slider.setValue(0)
self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'),
lcd, QtCore.SLOT('display(int)'))
self.connect(self.slider, QtCore.SIGNAL('valueChanged(int)'),
self, QtCore.SIGNAL('valueChanged(int)'))
layout = QtGui.QVBoxLayout()
layout.addWidget(lcd)
layout.addWidget(self.slider)
self.setLayout(layout)
def value(self):
self.slider.value()
def setValue(self,value):
self.slider.setValue(value)
```
main.py:
```
import sys
from PyQt4 import QtGui, QtCore
from lcdrange import LCDRange
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
quit = QtGui.QPushButton('Quit')
quit.setFont(QtGui.QFont('Times', 18, QtGui.QFont.Bold))
self.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()'))
grid = QtGui.QGridLayout()
previousRange = None
for row in range(0,3):
for column in range(0,3):
lcdRange = LCDRange()
grid.addWidget(lcdRange, row, column)
if not previousRange == None:
self.connect(lcdRange, QtCore.SIGNAL('valueChanged(int)'),
previousRange, QtCore.SLOT('setValue(int)'))
previousRange = lcdRange
layout = QtGui.QVBoxLayout()
layout.addWidget(quit)
layout.addLayout(grid)
self.setLayout(layout)
app = QtGui.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
```
When i run this i get the following errors:
```
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
Object::connect: No such slot LCDRange::setValue(int)
```
I've read that PyQt slots are nothing more than methods, which i have defined, so what am i doing wrong?
I am also learning Qt4 with Ruby which is where this code originates from, i translated it from Ruby to Python. In the Ruby version the LCDRange class is defined as this:
```
class LCDRange < Qt::Widget
signals 'valueChanged(int)'
slots 'setValue(int)'
def initialize(parent = nil)
...
```
So my guess was that i have to somehow declare the existence of the custom slot? | Try this:
```
self.connect(lcdRange, QtCore.SIGNAL('valueChanged'), previousRange.setValue)
```
# What's the difference?
[The PyQt documentation](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#signal-and-slot-support) has a section about SIGNALS/SLOTS in PyQt, they work a little differently.
## SIGNAL
`SIGNAL('valueChanged')` is something called a [short-circuit signal](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#short-circuit-signals). They work only for Python-to-Python methods, but they are faster and easier to implement.
## SLOT
If you have a python slot, you can specify it just by tipping the method: `previousRange.setValue`. This works for all methods accessible by Python.
If your slots should be accessible like C++ Qt slots, as you tried in your code, you have to use a special syntax. You can find information about [pyqtSignature decorator](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/new_style_signals_slots.html#the-pyqtslot-decorator) on the PyQt website. | you forgot to put
```
@Qt.pyqtSlot()
```
above method you are using as slot.
For example your code should look like this
```
@Qt.pyqtSlot('const QPoint&')
def setValue(self,value):
self.slider.setValue(value)
```
Here is one good page about pyqt slot decorator:
[click :-)](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#the-qtcore-pyqtslot-decorator)
Bye | PyQt: No such slot | [
"",
"python",
"ruby",
"qt4",
"pyqt",
""
] |
I am writing a webapplication which will have widgets like iGoogle does (but with different information ;)). Since there will be different colomns I would love to hear your ideas on how to call the modules in the code. I want to define in the database what widgets are enabled and in what column they are and in what order they should appear. I am working with PHP and the Zend Framework. Is there any good practice to add the widgets?
I was thinking of doing it like this:
You save the widgets name and there would be a folder with widgets in them and with require\_once I would include the file and execute a default command like:
```
echo ExampleWidgetClass::run();
``` | Your approach sounds reasonable: insist on a well-defined interface for each widget, and then invoke that method (or those methods) for each registered widget. Some things to keep in mind:
* abstraction: do the widgets know where they are on the page, or how big their window is?
* security: are the widgets written by 3rd parties? do you trust them? does their output need to be escaped or sanitized?
* backend: some widgets may need to make backend calls to get data. consider how they request backend calls be made in a batch before the page is rendered. dispatching multiple backend requests (such as sql queries) simultaneously can yield better page performance than querying sequentially. | Depending on what you are trying to achieve for your users, you may also want to consider external widget specifications like W3C Widgets (Apache Wookie) or OpenSocial Gadgets (Apache Shindig) | Widgets on a webapplication | [
"",
"php",
"zend-framework",
"widget",
""
] |
I was looking at using a lamba expression to allow events to be wired up in a strongly typed manner, but with a listener in the middle, e.g. given the following classes
```
class Producer
{
public event EventHandler MyEvent;
}
class Consumer
{
public void MyHandler(object sender, EventArgs e) { /* ... */ }
}
class Listener
{
public static void WireUp<TProducer, TConsumer>(
Expression<Action<TProducer, TConsumer>> expr) { /* ... */ }
}
```
An event would be wired up as:
```
Listener.WireUp<Producer, Consumer>((p, c) => p.MyEvent += c.MyHandler);
```
However this gives a compiler error:
> CS0832: An expression tree may not contain an assignment operator
Now at first this seems reasonable, particularly after [reading the explanation about why expression trees cannot contain assignments](http://msdn.microsoft.com/en-us/library/bb384223.aspx). However, in spite of the C# syntax, the `+=` is not an assignment, it is a call to the `Producer::add_MyEvent` method, as we can see from the CIL that is produced if we just wire the event up normally:
```
L_0001: newobj instance void LambdaEvents.Producer::.ctor()
L_0007: newobj instance void LambdaEvents.Consumer::.ctor()
L_000f: ldftn instance void LambdaEvents.Consumer::MyHandler(object, class [mscorlib]System.EventArgs)
L_0015: newobj instance void [mscorlib]System.EventHandler::.ctor(object, native int)
L_001a: callvirt instance void LambdaEvents.Producer::add_MyEvent(class [mscorlib]System.EventHandler)
```
So it looks to me like this is a compiler bug as it's complaining about assignments not being allowed, but there is no assignment taking place, just a method call. Or am I missing something...?
**Edit:**
Please note that the question is "Is this behaviour a compiler bug?". Sorry if I wasn't clear about what I was asking.
**Edit 2**
After reading Inferis' answer, where he says "at that point the += is considered to be assignment" this does make some sense, because at this point the compiler arguably doesn't know that it's going to be turned into CIL.
However I am not permitted to write the explicit method call form:
```
Listener.WireUp<Producer, Consumer>(
(p, c) => p.add_MyEvent(new EventHandler(c.MyHandler)));
```
Gives:
> CS0571: 'Producer.MyEvent.add': cannot explicitly call operator or accessor
So, I guess the question comes down to what `+=` actually means in the context of C# events. Does it mean "call the add method for this event" or does it mean "add to this event in an as-yet undefined manner". If it's the former then this appears to me to be a compiler bug, whereas if it's the latter then it's somewhat unintuitive but arguably not a bug. Thoughts? | In the spec, section 7.16.3, the += and -= operators are called "Event assignment" which certainly makes it sound like an assignment operator. The very fact that it's within section 7.16 ("Assignment operators") is a pretty big hint :) From that point of view, the compiler error makes sense.
However, I agree that it *is* overly restrictive as it's perfectly possible for an expression tree to represent the functionality given by the lambda expression.
I *suspect* the language designers went for the "slightly more restrictive but more consistent in operator description" approach, at the expense of situations like this, I'm afraid. | += is an assignment, no matter what it does (e.g. add an event). From the parser point of view, it is still an assignment.
Did you try
```
Listener.WireUp<Producer, Consumer>((p, c) => { p.MyEvent += c.MyHandler; } );
``` | Events in lambda expressions - C# compiler bug? | [
"",
"c#",
"compiler-construction",
"lambda",
"compiler-errors",
""
] |
Look at this simple function
```
def prime_factors(n):
for i in range(2,n):
if n % i == 0:
return i, prime_factors(n / i)
return n
```
Here's the result of `prime_factors(120)`
```
(2, (2, (2, (3, 5))))
```
Instead of nested tuples, I want it to return one flat tuple or list.
```
(2, 2, 2, 3, 5)
```
Is there a simple way to do that? | ```
def prime_factors(n):
for i in range(2,n):
if n % i == 0:
return [i] + prime_factors(n / i)
return [n]
``` | ```
def prime_factors(n):
for i in range(2,n):
if n % i == 0:
yield i
for p in prime_factors(n / i):
yield p
return
yield n
```
Example:
```
>>> tuple(prime_factors(100))
(2, 2, 5, 5)
``` | How can I make this Python recursive function return a flat list? | [
"",
"python",
"recursion",
""
] |
I trying to incorporate a simple error logging into my existing app, at the moment it reports errors just using `cout` so I was hoping to keep a similar interface using the `<<` operator. However I want it to log the line and function the error occurred, but I don't want to have to type `__LINE__, __FUNCTION__` every time I need to log. Does anyone know a trick I can use to allow the `__LINE__` macro to be used inside another function, reporting the calling line instead? Hope that makes sense.
```
class myLogClass {
uint8_t level;
public:
bool operator<<( const char * input );
};
bool myLogClass::operator<<( const char * input ) {
logItInSQL( input );
return true;
}
```
Instead of this every time
```
myLogClass << "Line No: " << __LINE__
<< " Function: " << __FUNCTION__
<< " Error: " << "This is my error to be logged";
```
I would like to just be able to do:
```
myLogClass << "This is my error to be logged";
bool myLogClass::operator<<( const char * input ) {
logItInSQL( " Line No: __LINE__" );
logItInSQL( " Function: __FUNCTION__" );
logItInSQL( " Error: " + input );
return true;
}
``` | ```
myLogClass << "Line No: " << __LINE__ ...
```
With your `operator <<` chaining will not work since it returns a `bool`.
```
bool myLogClass::operator << (const char * input)
```
It is customary to define stream insertion as follows:
```
std::ostream& myLogClass::operator << (std::ostream& o, const char * input) {
// do something
return o;
}
```
Do this:
```
#define log(o, s) o << "Line No: " << __LINE__ << \
" Function: " << __FUNCTION__ << \
" Error: " << s // note I leave ; out
```
Additionally, you can wrap the macro in a `do-while` loop:
```
#define log(o, s) do { o << "Line No: " << __LINE__ << \
" Function: " << __FUNCTION__ << \
" Error: " << s; \
} while(0) // here, I leave ; out
```
Then you can happily write:
```
myLogClass myLogger; // do this
// use it
log(myLogger, "This is my error to be logged"); // note the ;
``` | In ANSI C (which should also work in C++ I assume), you can do that using variadic functions and preprocessor macros. See example below:
```
#include <stdio.h>
#include <stdarg.h>
#define MAXMSIZE 256
#define MyDebug(...) MyInternalDebug(__FILE__,__FUNCTION__,__LINE__,__VA_ARGS__)
void MyInternalDebug( char *file, char *function, const int line, const char *format, ... )
{
char message[MAXMSIZE];
// Variable argument list (VA)
va_list ap;
// Initialize VA
// args : Name of the last named parameter in the function definition.
// The arguments extracted by subsequent calls to va_arg are those after 'args'.
va_start(ap, format);
// Composes a string with the same text that would be printed if 'format' was used on printf,
// but using the elements in the variable argument list identified by 'ap' instead of
// additional function arguments and storing the resulting content as a C string in the buffer pointed by 'message'.
// * The state of arg is likely to be altered by the call.
vsprintf(message, format, ap);
// Custom print function
printf("%s\t%s\t%d\t%s\n",file, function, line, message);
// Finzalize use of VA
va_end(ap);
}
int main ()
{
MyInternalDebug(__FILE__, __FUNCTION__, __LINE__, "An error occured with message = '%s'", "Stack Overflow");
MyDebug("Another error occured with code = %d", 666);
return 0;
}
``` | Error Logging C++ Preprocessor Macros __LINE__, __FUNCTION__ | [
"",
"c++",
"logging",
"c-preprocessor",
""
] |
This is the HTML I have:
```
p_tags = '''<p class="foo-body">
<font class="test-proof">Full name</font> Foobar<br />
<font class="test-proof">Born</font> July 7, 1923, foo, bar<br />
<font class="test-proof">Current age</font> 27 years 226 days<br />
<font class="test-proof">Major teams</font> <span style="white-space: nowrap">Japan,</span> <span style="white-space: nowrap">Jakarta,</span> <span style="white-space: nowrap">bazz,</span> <span style="white-space: nowrap">foo,</span> <span style="white-space: nowrap">foobazz</span><br />
<font class="test-proof">Also</font> bar<br />
<font class="test-proof">foo style</font> hand <br />
<font class="test-proof">bar style</font> ball<br />
<font class="test-proof">foo position</font> bak<br />
<br class="bar" />
</p>'''
```
This is my Python code, using Beautiful Soup:
```
def get_info(p_tags):
"""Returns brief information."""
head_list = []
detail_list = []
# This works fine
for head in p_tags.findAll('font', 'test-proof'):
head_list.append(head.contents[0])
# Some problem with this?
for index in xrange(2, 30, 4):
detail_list.append(p_tags.contents[index])
return dict([(l, detail_list[head_list.index(l)]) for l in head_list])
```
I get the proper `head_list` from the HTML but the `detail_list` is not working.
```
head_list = [u'Full name',
u'Born',
u'Current age',
u'Major teams',
u'Also',
u'foo style',
u'bar style',
u'foo position']
```
I wanted something like this
```
{
'Full name': 'Foobar',
'Born': 'July 7, 1923, foo, bar',
'Current age': '78 years 226 days',
'Major teams': 'Japan, Jakarta, bazz, foo, foobazz',
'Also': 'bar',
'foo style': 'hand',
'bar style': 'ball',
'foo position': 'bak'
}
```
Any help would be appreciable. Thanks in advance. | Sorry for the unnecessarily complex code, I badly need a big dose of caffeine ;)
```
import re
str = """<p class="foo-body">
<font class="test-proof">Full name</font> Foobar<br />
<font class="test-proof">Born</font> July 7, 1923, foo, bar<br />
<font class="test-proof">Current age</font> 27 years 226 days<br />
<font class="test-proof">Major teams</font> <span style="white-space: nowrap">Japan,</span> <span style="white-space: nowrap">Jakarta,</span> <span style="white-space: nowrap">bazz,</span> <span style="white-space: nowrap">foo,</span> <span style="white-space: nowrap">foobazz</span><br />
<font class="test-proof">Also</font> bar<br />
<font class="test-proof">foo style</font> hand <br />
<font class="test-proof">bar style</font> ball<br />
<font class="test-proof">foo position</font> bak<br />
<br class="bar" />
</p>"""
R_EXTRACT_DATA = re.compile("<font\s[^>]*>[\s]*(.*?)[\s]*</font>[\s]*(.*?)[\s]*<br />", re.IGNORECASE)
R_STRIP_TAGS = re.compile("<span\s[^>]*>|</span>", re.IGNORECASE)
def strip_tags(str):
"""Strip un-necessary <span> tags
"""
return R_STRIP_TAGS.sub("", str)
def get_info(str):
"""Extract useful info from the given string
"""
data = R_EXTRACT_DATA.findall(str)
data_dict = {}
for x in [(x[0], strip_tags(x[1])) for x in data]:
data_dict[x[0]] = x[1]
return data_dict
print get_info(str)
``` | The issue is that your HTML is not very well thought out -- you have a "mixed content model" where your labels and your data are interleaved. Your labels are wrapped in `<font>` Tags, but your data is in NavigableString nodes.
You need to iterate over the contents of `p_tag`. There will be two kinds of nodes: `Tag` nodes (which have your `<font>` tags) and `NavigableString` nodes which have the other bits of text.
```
from beautifulsoup import *
label_value_pairs = []
for n in p_tag.contents:
if isinstance(n,Tag) and tag == "font"
label= n.string
elif isinstance(n, NavigableString):
value= n.string
label_value_pairs.append( label, value )
else:
# Generally tag == "br"
pass
print dict( label_value_pairs )
```
Something approximately like that. | How do i extract my required data from HTML file? | [
"",
"python",
"screen-scraping",
"beautifulsoup",
""
] |
I am trying to make a form with some dynamic behavior. Specifically, I have my inputs in divs, and I would like to make it so when the user clicks anywhere in the div, the input is selected. I was using JQuery 1.2.6 and everything worked fine.
However, I upgraded to JQuery 1.3.2 and I am getting some strange behavior. When I click on any of the inputs, I get a delay before it is selected. My Firefox error console gives me several "too much recursion" errors, from within the JQuery library. I tried the page in Internet Explorer 7 and got an error saying "Object doesn't support this property or method".
Am I doing something wrong, or is this a bug in JQuery? Does anyone know a way to fix this behavior, without going back to the old version? I am using Firefox 3.0.7 in case that matters. Here is a simple example I made to illustrate the problem:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>quiz test</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
<div class='question'>Favorite soda?
<div><input type='radio' name='q' value='A' id='a'><label for='a'>Coke</label></div>
<div><input type='radio' name='q' value='B' id='b'><label for='b'>Pepsi</label></div>
</div>
<script type="text/javascript">
$(function() {
$(".question div").click(function() {
$(this).children("input").click();
});
});
</script>
</body></html>
``` | Thank you all. I tried grillix's idea of setting the checked attribute, although I had to fix up the syntax a little bit. Here is what I did:
```
$(this).children("input").attr("checked", true);
```
It works, but I am still curious as to why my previous way stopped working with JQuery 1.3.2. I know about the changes in event bubbling behavior, but why can't I fix that by calling "event.stopPropagation()" or "return false" within my callback? | ```
$(function() {
$(".question div").click(function() {
var radio = $(this).children("input")[0];
radio.checked = !radio.checked;
});
});
``` | "too much recursion" error in JQuery 1.3.2 | [
"",
"javascript",
"jquery",
""
] |
In C++ on Win32:
Suppose I have a DLL with a header file that declares a class. The DLL exports some means of obtaining a pointer/reference to an instance of that class, such as a factory function.
Am I correct in believing that it is not necessary to mark that class as exported using \_\_declspec if one is only going to call virtual or inline functions on its instances?
Conversely, is it necessary to export the class declaration if one wishes to call nonvirtual member functions? | > Am I correct in believing that it is not necessary to mark that class as exported using \_\_declspec if one is only going to call virtual or inline functions on its instances?
Yes,this is correct, and that's what COM do, the DLL only expotys 4 methods, one of them returns to the class factory, which all its members are pure virtual functions.
> Conversely, is it necessary to export the class declaration if one wishes to call statically defined member functions?
No, just export the static member functions. | It's not necessary only if the function/class have all it's definition with in a header file.
It's not dependant on virtuality.
So, if you don't export all your class, it's usable by client code as far as it don't have any public or protected function definition in a cpp file.
You can also declare only specific member functions to be exported instead of the whole class, by using \_\_declspec in the function declaration and not in the class name declaration. | Not necessary to export class with only virtual/inline functions? | [
"",
"c++",
"winapi",
"dll",
""
] |
**UPDATED** - please read further details below original question
I have a select form element with various urls, that I want to open in a new window when selected - to do this I have the following code in the element's onchange event:
```
window.open(this.options[this.selectedIndex].value,'_blank');
```
This works fine. But I also want to submit the form when changing this select element value - I've tried various things, but I can't seem to get it to work.
I have jquery, so if it's easier to achieve via that then that's fine.
*Update - I've just realised there is another issue with the above, because some of the urls are actually used to generate and output pdfs, and these do not work - they open and then immediately close (at least in IE7).*
**UPDATE 07/05/09** - I've now opened a bounty for this question as I really need to come up with a working solution. I did originally get around the issue by displaying links instead of a form select element, but this is no longer feasible.
The reason I need the above is that I have a large number of files that might need to be viewed / printed, too many to reasonably display as a list of links. I need to submit the form to record the fact a particular file has been viewed / printed, then display a log of the file history on the form - I'm comfortable with achieving this side of things, so don't require assistance there, but I thought it would help to place the context.
So, to clarify my requirements - I need a form select element and 'View' button that when clicked will not only launch a file download in a new window (note the above issue I faced when these files were PDFs), but also submit the form that contains the select element. | Here ya go
```
<script type="text/javascript">
$(function() {
$("#selectElement").change(function() {
if ($(this).val()) {
window.open($(this).val(), '_blank');
$("#formElement").submit();
}
});
// just to be sure that it is submitting, remove this code
$("#formElement").submit(function() {
alert('submitting ... ');
});
});
</script>
<form id="formElement" method="get" action="#">
<select id="selectElement">
<option></option>
<option value="http://www.deviantnation.com/">View Site 1</option>
<option value="http://stackoverflow.com/">View Site 2</option>
<option value="http://serverfault.com/">View Site 3</option>
</select>
</form>
``` | **You can use `this.form.submit()` to trigger the form submit:**
```
<script language="javascript">
function myChangeHandler() {
window.open(this.options[this.selectedIndex].value, '_blank');
this.form.submit();
}
</script>
<select onchange="myChangeHandler.apply(this)">
...
</select>
``` | Javascript - form select element open url in new window and submit form | [
"",
"javascript",
"jquery",
"forms",
"select",
"form-submit",
""
] |
Will the array be deallocated and if so, what is a workaround?
```
double * GetArrayFromVector( std::map<std::string, double> m, char ** names, int count )
{
if(!names) return 0;
std::vector<double> vec(m.size());
for (int i=0; i<count; ++i)
{
if(!names[i]) return 0;
std::map<std::string, double>::iterator iter=m.find(name[i]);
if(iter!=m.end())
vec.push_back(iter->second);
else
return 0;
}
return &vec[0];
}
```
Thanks a lot | Divide your function on two.
Make your functions make just one action:
1. fill vector from map.
2. create array from vector.
Don't forget to pass map by const reference.
Main note: caller of the GetArrayFromVector is responsible for memory deallocation.
```
void FillVector( const std::map<std::string, double>& m,
std::vector< double >& v,
char ** names,
int count )
{
.......
}
double* createArray( const std::vector< double >& v )
{
double* result = new double [v.size()];
memcpy( result, &v.front(), v.size() * sizeof( double ) );
return result;
}
// and finally your function
double* GetArrayFromVector( const std::map<std::string, double>& m,
char ** names,
int count )
{
std::vector< double > v;
FillVector( m, v, names, count );
return CreateArray( v );
}
``` | Yes -- it's deallocated as soon as your return from the function, because `vec` is declared on the stack. The `std::vector` destructor takes care of freeing the memory. Since you're returning the address of a deallocated array, you're going to start messing around with deallocated memory, which is a big no-no. At best, you'll crash immediately. At worst, you'll silently succeed with a big gaping security hole.
There are two ways to fix this: (1) return the entire vector by-value, which makes a copy of the entire vector, or (2) return the vector via a reference parameter.
Solution 1:
```
std::vector<double> GetArrayFromVector(...)
{
...
return vec; // make copy of entire vec, probably not a good idea
}
```
Solution 2:
```
void GetArrayFromVector(..., std::vector<double> & vec)
{
// compute result, store it in vec
}
``` | return underlying array from vector | [
"",
"c++",
"stl",
""
] |
I have several forms with many textboxes/comboboxes, and I would like to have the "Save" button disabled while at least one of the fields are invalid. I've been able to setup some custom ValidationRules, like so (textbox example shown):
```
<Binding Path="Name">
<Binding.ValidationRules>
<my:TextFieldNotEmpty/>
</Binding.ValidationRules>
</Binding>
```
My question is: how can I set my form up so that, when even 1 validation rule fails, the "Save" button is not enabled? Is there a standard way of handling a situation (a trigger, perhaps), or is this a place where WPF falls short? | Will this answer your question? [Detecting WPF Validation Errors](https://stackoverflow.com/questions/127477/detecting-wpf-validation-errors) | You might be interested in the **BookLibrary** sample application of the **[WPF Application Framework (WAF)](http://waf.codeplex.com)**. It shows how to use validation in WPF and how to control the Save button when validation errors exists. | What's the best way to go about form validation in WPF (with databinding)? | [
"",
"c#",
".net",
"wpf",
"validation",
"data-binding",
""
] |
How can I bind the count of a list to a label. The following code does't get updated with the list is changed:
```
private IList<string> list = new List<string>();
//...
label1.DataBindings.Add("Text", list.Count, "");
``` | According to Marc Gravell for this problem, he has [suggested to create a facade](http://objectmix.com/csharp/388347-binding-formatstring-rendering-curly-braces-trick-bind-list-t-countproperty.html) that wraps the collection you want to bind to label1.Text
I have tried to implement one (for fun) and was able to get binding to *Count* working.
`CountList<T>` is a facade that wraps a collection to bind to.
Here is the full of the demo.
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
namespace TextBindingTest
{
public partial class Form1 : Form
{
private readonly CountList<string> _List =
new CountList<string>(new List<string> { "a", "b", "c" });
public Form1()
{
InitializeComponent();
BindAll();
}
private void BindAll()
{
var binding = new Binding("Text", _List, "Count", true);
binding.Format += (sender, e) => e.Value = string.Format("{0} items", e.Value);
label1.DataBindings.Add(binding);
}
private void addToList_Click(object sender, EventArgs e)
{
_List.Add("a");
}
private void closeButton_Click(object sender, EventArgs e)
{
Close();
}
}
public class CountList<T> : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void OnPropertyChanged(PropertyChangedEventArgs e)
{
var handler = PropertyChanged;
handler(this, e);
}
private ICollection<T> List { get; set; }
public int Count { get { return List.Count; } }
public CountList(ICollection<T> list)
{
List = list;
}
public void Add(T item)
{
List.Add(item);
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
}
}
}
``` | Bindings listen to the PropertyChanged event of the IPropertyChanged interface. I don't think that List.Count is reported as a PropertyChanged event when it is changed.
What you could do is to implement your custom List or to find a collection that notifies when the Count is changed. | How to bind a list count to a label in WinForms? | [
"",
"c#",
"winforms",
""
] |
I am developing a web page for iPhones and iPod Touch's. I am using the Universal iPhone UI framework. I need to have silding page transitions, but can't seem to get it working. Is there a good javascript framework I could use that would make this easier? I've done a lot of normal web dev with jquery, but it doesn't seem to like the iPhone. | Regardless of what framework you're using, the WebKit CSS trasitions are extensions of CSS and were developed with the iPhone and iPhone web-based apps in mind. You can do some very clever, complex animations with no JavaScript and only a few lines of CSS.
Here's [what Google finds](http://www.google.com/search?client=safari&rls=en-us&q=webkit+css+transitions&ie=UTF-8&oe=UTF-8) on the subject. | Try <http://code.google.com/p/iui/>
It's a nice little JS framework, among other things, that will help you with the transition aspect. Have a flick through the documentation too, as it'll give you quite a few additional options as well. | iphone web page transitions | [
"",
"javascript",
"iphone",
""
] |
Is there a quick, simple way to check if a file is ASCII or binary with PHP? | This only works for PHP>=5.3.0, and isn't 100% reliable, but hey, it's pretty darn close.
```
// return mime type ala mimetype extension
$finfo = finfo_open(FILEINFO_MIME);
//check to see if the mime-type starts with 'text'
return substr(finfo_file($finfo, $filename), 0, 4) == 'text';
```
<http://us.php.net/manual/en/ref.fileinfo.php> | In one of my older PHP projects I use ASCII / Binary compression. When the user uploads their file, they are required to specify if that file is ASCII or Binary. I decided to modify my code to have the server automatically decide what the file mode is, as relying on the user's decision could result in a failed compression. I decided my code has to be absolute, and not use tricks that would potentially cause my program to fail. I quickly whipped up some code, ran some speed tests and then decided to search the internet to see if there is a faster code example to complete this task.
---
Devin's very vague answer relates to the first code I wrote to complete this task. The results were so-so. I found that searching byte for byte was in many cases faster for binary files. If you find a byte larger than 127, the rest of the file could be ignored and the entire file is considered a binary file. That being said, you would have to read every last byte of a file to determine if the file is ASCII. It appears faster for many binary files because a binary byte will likely come earlier than the very last byte of the file, sometimes even the very first byte would be binary.
```
<?php
$filemodes = array(
-2 => 'Unreadable',
-1 => 'Missing',
0 => 'Empty',
1 => 'ASCII',
2 => 'Binary'
);
function filemode($filename) {
if(is_file($filename)) {
if(is_readable($filename)) {
$size = filesize($filename);
if($size === 0)
return 0; // Empty
$handle = fopen($filename, 'rb');
for($i = 0; $i < $size; ++$i) {
$byte = fread($handle, 1);
if(ord($byte) > 127) {
fclose($handle);
return 2; // Binary
}
}
fclose($handle);
return 1; // ASCII
}
else
return -2; // Unreadable
}
else
return -1; // Missing
}
// ==========
$filename = 'e:\test.txt';
$loops = 1;
$x = 0;
$i = 0;
$start = microtime(true);
for($i = 0; $i < $loops; ++$i)
$x = filemode($filename);
$stop = microtime(true);
$duration = $stop - $start;
echo
'Filename: ', $filename, "\n",
'Filemode: ', $filemodes[filemode($filename)], "\n",
'Duration: ', $duration;
```
My processor isn't exactly modern but I found that a 600Kb ASCII file would take about 0.25 seconds to complete. If I were to use this on hundreds or thousands of large files it might take a very long time. I decided to try and speed things up a bit by making my buffer larger than a single byte to read the file as chunks instead of one byte at a time. Using chunks will allow me to process more of the file at once but not load too much into memory. If a file we're testing is huge and we were to load the entire file into memory, it could use up far too much memory and cause the program to fail.
```
<?php
$filemodes = array(
-2 => 'Unreadable',
-1 => 'Missing',
0 => 'Empty',
1 => 'ASCII',
2 => 'Binary'
);
function filemode($filename) {
if(is_file($filename)) {
if(is_readable($filename)) {
$size = filesize($filename);
if($size === 0)
return 0; // Empty
$buffer_size = 256;
$chunks = ceil($size / $buffer_size);
$handle = fopen($filename, 'rb');
for($chunk = 0; $chunk < $chunks; ++$chunk) {
$buffer = fread($handle, $buffer_size);
$buffer_length = strlen($buffer);
for($byte = 0; $byte < $buffer_length; ++$byte) {
if(ord($buffer[$byte]) > 127) {
fclose($handle);
return 2; // Binary
}
}
}
fclose($handle);
return 1; // ASCII
}
else
return -2; // Unreadable
}
else
return -1; // Missing
}
// ==========
$filename = 'e:\test.txt';
$loops = 1;
$x = 0;
$i = 0;
$start = microtime(true);
for($i = 0; $i < $loops; ++$i)
$x = filemode($filename);
$stop = microtime(true);
$duration = $stop - $start;
echo
'Filename: ', $filename, "\n",
'Filemode: ', $filemodes[filemode($filename)], "\n",
'Duration: ', $duration;
```
The difference in speed was fairly significant taking only 0.15 seconds instead of the 0.25 seconds of the previous function, almost a tenth of a second faster to read my 600Kb ASCII file.
---
Now that I have my file in chunks, I thought it would be a good idea to find alternative ways to test my chunks for binary characters. My first thought would be to use a regular expression to find non-ascii characters.
```
<?php
$filemodes = array(
-2 => 'Unreadable',
-1 => 'Missing',
0 => 'Empty',
1 => 'ASCII',
2 => 'Binary'
);
function filemode($filename) {
if(is_file($filename)) {
if(is_readable($filename)) {
$size = filesize($filename);
if($size === 0)
return 0; // Empty
$buffer_size = 256;
$chunks = ceil($size / $buffer_size);
$handle = fopen($filename, 'rb');
for($chunk = 0; $chunk < $chunks; ++$chunk) {
$buffer = fread($handle, $buffer_size);
if(preg_match('/[\x80-\xFF]/', $buffer) === 1) {
fclose($handle);
return 2; // Binary
}
}
fclose($handle);
return 1; // ASCII
}
else
return -2; // Unreadable
}
else
return -1; // Missing
}
// ==========
$filename = 'e:\test.txt';
$loops = 1;
$x = 0;
$i = 0;
$start = microtime(true);
for($i = 0; $i < $loops; ++$i)
$x = filemode($filename);
$stop = microtime(true);
$duration = $stop - $start;
echo
'Filename: ', $filename, "\n",
'Filemode: ', $filemodes[filemode($filename)], "\n",
'Duration: ', $duration;
```
Amazing! 0.02 seconds to consider my 600Kb file an ASCII file and this code appears to be 100% reliable.
---
Now that I have arrived here, I have the opportunity to inspect several other methods deployed by other users.
The most accepted answer today, written by davethegr8 uses the mimetype extension. First, I was required to enable this extension in the php.ini file. Next, I tested this code against an actual ASCII file that has no file extension and a binary file that has no file extension.
Here is how I created my two test files.
```
<?php
$handle = fopen('E:\ASCII', 'wb');
for($i = 0; $i < 128; ++$i) {
fwrite($handle, chr($i));
}
fclose($handle);
$handle = fopen('E:\Binary', 'wb');
for($i = 0; $i < 256; ++$i) {
fwrite($handle, chr($i));
}
fclose($handle);
```
Here is how I tested both files...
```
<?php
$filename = 'E:\ASCII';
$finfo = finfo_open(FILEINFO_MIME);
echo (substr(finfo_file($finfo, $filename), 0, 4) == 'text') ? 'ASCII' : 'Binary';
```
Which outputs:
> Binary
and...
```
<?php
$filename = 'E:\Binary';
$finfo = finfo_open(FILEINFO_MIME);
echo (substr(finfo_file($finfo, $filename), 0, 4) == 'text') ? 'ASCII' : 'Binary';
```
Which outputs:
> Binary
This code shows both my ASCII and binary files to both be binary, which is obviously incorrect, so I had to find what was causing the mimetype to be "text". To me it was obvious, maybe text is just printable ASCII characters. So I limited the range of my ASCII file.
```
<?php
$handle = fopen('E:\ASCII', 'wb');
for($i = 32; $i < 127; ++$i) {
fwrite($handle, chr($i));
}
fclose($handle);
```
And tested it again.
```
<?php
$filename = 'E:\ASCII';
$finfo = finfo_open(FILEINFO_MIME);
echo (substr(finfo_file($finfo, $filename), 0, 4) == 'text') ? 'ASCII' : 'Binary';
```
Which outputs:
> ASCII
If I lower the range, it treats it as binary. If I increase the range, once again, it treats it as binary.
So the most accepted answer does not tell you if your file is ASCII but rather that it contains only readable text or not.
---
Lastly, I need to test the other answer which uses ctype\_print against my files. I decided the easiest way to do this was to use the code I made and supplement in MarcoA's code.
```
<?php
$filemodes = array(
-2 => 'Unreadable',
-1 => 'Missing',
0 => 'Empty',
1 => 'ASCII',
2 => 'Binary'
);
function filemode($filename) {
if(is_file($filename)) {
if(is_readable($filename)) {
$size = filesize($filename);
if($size === 0)
return 0; // Empty
$buffer_size = 256;
$chunks = ceil($size / $buffer_size);
$handle = fopen($filename, 'rb');
for($chunk = 0; $chunk < $chunks; ++$chunk) {
$buffer = fread($handle, $buffer_size);
$buffer = str_ireplace("\t", '', $buffer);
$buffer = str_ireplace("\n", '', $buffer);
$buffer = str_ireplace("\r", '', $buffer);
if(ctype_print($buffer) === false) {
fclose($handle);
return 2; // Binary
}
}
fclose($handle);
return 1; // ASCII
}
else
return -2; // Unreadable
}
else
return -1; // Missing
}
// ==========
$filename = 'e:\test.txt';
$loops = 1;
$x = 0;
$i = 0;
$start = microtime(true);
for($i = 0; $i < $loops; ++$i)
$x = filemode($filename);
$stop = microtime(true);
$duration = $stop - $start;
echo
'Filename: ', $filename, "\n",
'Filemode: ', $filemodes[filemode($filename)], "\n",
'Duration: ', $duration;
```
Ouch! 0.2 seconds to tell me that my 600Kb file is ASCII. My large ASCII file, I know, contains visible ASCII characters only. It does seem to know that my binary files are binary. And my pure ASCII file... Binary!
I decided to read the documentation for [ctype\_print](https://www.php.net/manual/en/function.ctype-print.php) and its return value is defined as:
> Returns TRUE if every character in text will actually create output
> (including blanks). Returns FALSE if text contains control characters
> or characters that do not have any output or control function at all.
This function, like davethegr8's answer only tells you if your text contains printable ASCII characters and does not tell you if your text is actually ASCII or not. That doesn't necessarily mean MacroA is completely wrong, they are just not completely right. str\_ireplace is slow compared to str\_replace, and only replacing those three control characters to test ctype\_print isn't enough to know if the string is ASCII or not. To make this example work for ASCII, we must replace every control character!
```
<?php
$filemodes = array(
-2 => 'Unreadable',
-1 => 'Missing',
0 => 'Empty',
1 => 'ASCII',
2 => 'Binary'
);
function filemode($filename) {
if(is_file($filename)) {
if(is_readable($filename)) {
$size = filesize($filename);
if($size === 0)
return 0; // Empty
$buffer_size = 256;
$chunks = ceil($size / $buffer_size);
$replace = array(
"\x00", "\x01", "\x02", "\x03",
"\x04", "\x05", "\x06", "\x07",
"\x08", "\x09", "\x0A", "\x0B",
"\x0C", "\x0D", "\x0E", "\x0F",
"\x10", "\x11", "\x12", "\x13",
"\x14", "\x15", "\x16", "\x17",
"\x18", "\x19", "\x1A", "\x1B",
"\x1C", "\x1D", "\x1E", "\x1F",
"\x7F"
);
$handle = fopen($filename, 'rb');
for($chunk = 0; $chunk < $chunks; ++$chunk) {
$buffer = fread($handle, $buffer_size);
$buffer = str_replace($replace, '', $buffer);
if(ctype_print($buffer) === false) {
fclose($handle);
return 2; // Binary
}
}
fclose($handle);
return 1; // ASCII
}
else
return -2; // Unreadable
}
else
return -1; // Missing
}
```
This took 0.04 seconds to tell me that my 600Kb file is ASCII.
---
All of this testing I believe hasn't been completely useless as it did give me one more idea. Why not add a printable filemode to my original function! While it does seem to be 0.018 seconds slower on my 600Kb printable ASCII file, here it is.
```
<?php
$filemodes = array(
-2 => 'Unreadable',
-1 => 'Missing',
0 => 'Empty',
1 => 'Printable',
2 => 'ASCII',
3 => 'Binary'
);
function filemode($filename) {
if(is_file($filename)) {
if(is_readable($filename)) {
$size = filesize($filename);
if($size === 0)
return 0; // Empty
$printable = true;
$buffer_size = 256;
$chunks = ceil($size / $buffer_size);
$handle = fopen($filename, 'rb');
for($chunk = 0; $chunk < $chunks; ++$chunk) {
$buffer = fread($handle, $buffer_size);
if(preg_match('/[\x80-\xFF]/', $buffer) === 1) {
fclose($handle);
return 3; // Binary
}
else
if($printable === true)
$printable = ctype_print($buffer);
}
fclose($handle);
return $printable === true ? 1 : 2; // Printable or ASCII
}
else
return -2; // Unreadable
}
else
return -1; // Missing
}
// ==========
$filename = 'e:\test.txt';
$loops = 1;
$x = 0;
$i = 0;
$start = microtime(true);
for($i = 0; $i < $loops; ++$i)
$x = filemode($filename);
$stop = microtime(true);
$duration = $stop - $start;
echo
'Filename: ', $filename, "\n",
'Filemode: ', $filemodes[filemode($filename)], "\n",
'Duration: ', $duration;
```
I also tested ctype\_print against a regular expression and found ctype\_print to be a bit faster.
```
$printable = preg_match('/[^\x20-\x7E]/', $buffer) === 0;
```
---
Here is my final function where finding printable text is optional, as is the buffer size.
```
<?php
const filemodes = array(
-2 => 'Unreadable',
-1 => 'Missing',
0 => 'Empty',
1 => 'Printable',
2 => 'ASCII',
3 => 'Binary'
);
function filemode($filename, $printable = false, $buffer_size = 256) {
if(is_bool($printable) === false || is_int($buffer_size) === false)
return false;
$buffer_size = floor($buffer_size);
if($buffer_size <= 0)
return false;
if(is_file($filename)) {
if(is_readable($filename)) {
$size = filesize($filename);
if($size === 0)
return 0; // Empty
if($buffer_size > $size)
$buffer_size = $size;
$chunks = ceil($size / $buffer_size);
$handle = fopen($filename, 'rb');
for($chunk = 0; $chunk < $chunks; ++$chunk) {
$buffer = fread($handle, $buffer_size);
if(preg_match('/[\x80-\xFF]/', $buffer) === 1) {
fclose($handle);
return 3; // Binary
}
else
if($printable === true)
$printable = ctype_print($buffer);
}
fclose($handle);
return $printable === true ? 1 : 2; // Printable or ASCII
}
else
return -2; // Unreadable
}
else
return -1; // Missing
}
// ==========
$filename = 'e:\test.txt';
echo
'Filename: ', $filename, "\n",
'Filemode: ', filemodes[filemode($filename, true)], "\n";
``` | How to Check if File is ASCII or Binary in PHP | [
"",
"php",
""
] |
I have an interface defined like so:
```
public interface IRipper
{
IRipperHost Host { get; set; }
void Rip(FileStream stream);
event RipperEventHandler OnStart;
event RipperEventHandler OnComplete;
event RipperEventHandler OnProgressChanged;
}
public delegate void RipperEventHandler(object sender, RipperEventArgs e);
```
and a base class that implements that interface
```
public class RipperBase : IRipper
{
public void Rip(FileStream stream)
{
throw new System.NotImplementedException();
}
public event RipperEventHandler PostRipEvent;
event RipperEventHandler IRipper.OnComplete
{
add
{
if (PostRipEvent != null)
{
lock (PostRipEvent)
{
PostRipEvent += value;
}
}
else
{
PostRipEvent = value;
}
}
remove
{
if (PostRipEvent != null)
{
lock (PostRipEvent)
{
PostRipEvent -= value;
}
}
}
}
... and so on
}
```
My question is how would ***you*** inherit from RipperBase and override the BaseClass Rip method. in reality that function should be abstract - but i don't know how to do that with interfaces.
Also how can i call the base classes event handler from the class derived from RipperBase? I tried this
```
RipperEventHandler handler = PreRipEvent;
if (handler != null)
{
handler(this, new RipperEventArgs { Message = "Started Ripping file to CSV!" });
}
handler = RipProgEvent;
```
this but I'm getting the "event can only appear on the left hand side of += or -=." error
any help would be greatly appreciated! I'm trying to make this as scalable as possible. | I would do it like this:
```
public abstract class RipperBase : IRipper
{
public void Rip( Filestream fs )
{
RipCore (fs);
OnCompleted();
}
protected abstract void RipCore(Filestream fs);
public event EventHandler<RipperEventArgs> Completed;
protected void OnCompleted
{
if( Completed != null )
{
// TODO: make this Threadsafe.
Completed (this, new RipperEventArgs( ... ) );
}
}
}
```
I've declared the class as abstract, since I presume that you cannot instantiate objects from RipperBase ?
Classes that inherit from RipperBase have to override the RipCore method, and implement the correct functionality.
Rip is the method that calls the RipCore method, and it also raises the Completed eventhandler. (Maybe you do not want to do this, i dunno).
You can also make sure that the Rip method calls the RipCore method on another thread if you want.
For the events, I create a protected method in the base class that can be used to raise the events. If you want to raise the event in a subclass, you just call this method. | declare the method in the base class as virtual, like:
```
public virtual void Rip(FileStream stream)
{
throw new System.NotImplementedException();
}
```
and in the specific class:
```
public override void Rip(FileStream stream){}
```
For the event, do this on the base:
```
protected void FireASpecificEvent(SomeClass someArguments)
{//fire event normally
}
``` | Inheritance & Events | [
"",
"c#",
"oop",
""
] |
How do you convert a double into the nearest int? | Use `Math.round()`, possibly in conjunction with `MidpointRounding.AwayFromZero`
eg:
```
Math.Round(1.2) ==> 1
Math.Round(1.5) ==> 2
Math.Round(2.5) ==> 2
Math.Round(2.5, MidpointRounding.AwayFromZero) ==> 3
``` | ```
double d = 1.234;
int i = Convert.ToInt32(d);
```
[Reference](http://msdn.microsoft.com/en-us/library/ffdk7eyz.aspx)
Handles rounding like so:
> rounded to the nearest 32-bit signed integer. If value is halfway
> between two whole numbers, the even number is returned; that is, 4.5
> is converted to 4, and 5.5 is converted to 6. | How might I convert a double to the nearest integer value? | [
"",
"c#",
"rounding",
""
] |
I have this in my base class:
```
protected abstract XmlDocument CreateRequestXML();
```
I try to override this in my derived class:
```
protected override XmlDocument CreateRequestXML(int somevalue)
{
...rest of code
}
```
I know this is an easy question but because I've introduced a param is that the issue? The thing is, some of the derived classes may or may not have params in its implementation. | When you override a method, with the exception of the word override in place of virtual or abstract, it must have the exact same signature as the original method.
What you've done here is create a new unrelated method. It is not possible to introduce a parameter and still override. | If some of the derived classes need paramters and some do not, you need to have two overloaded versions of the method. Then each derived class can override the one it needs.
```
class Foo {
protected abstract XmlDocument CreateRequestXML(int somevalue);
protected abstract XmlDocument CreateRequestXML();
};
class Bar : public Foo {
protected override XmlDocument CreateRequestXML(int somevalue) { ... };
protected override XmlDocument CreateRequestXML()
{ CreateRequestXML(defaultInt); }
};
```
This of course introduces a problem of the user calling the wrong one. If there is no acceptable default for the extra paramter, you may have to throw an exception in the derived class if the wrong version is called. | How to override a Base Class method and add a parameter | [
"",
"c#",
"architecture",
""
] |
Whats the shortest way to assert that an attribute is applied to method in c#?
I'm using nunit-2.5
:) | ```
MethodInfo mi = typeof(MyType).GetMethod("methodname");
Assert.IsFalse (Attribute.IsDefined (mi, typeof(MyAttributeClass)));
``` | I'm not sure of the assert method that nunit uses, but you can simply use this boolean expression for the parameter that is passed to it (assuming you are able to use LINQ:
```
methodInfo.GetCustomAttributes(attributeType, true).Any()
```
If the attribute is applied, then it will return true.
If you want to make a generic version (and not use typeof) you can use a generic method to do this for you:
```
static bool IsAttributeAppliedToMethodInfo<T>(this MethodInfo methodInfo)
where T : Attribute
{
// If the attribute exists, then return true.
return methodInfo.GetCustomAttributes(typeof(T), true).Any();
}
```
And then call it in your assert method like so:
```
<assert method>(methodInfo.IsAttributeAppliedToMethodInfo<MyAttribute>());
```
To do this with an expression, you can define the following extension method first:
```
public static MethodInfo
AssertAttributeAppliedToMethod<TExpression, TAttribute>
(this Expression<T> expression) where TAttribute : Attribute
{
// Get the method info in the expression of T.
MethodInfo mi = (expression.Body as MethodCallExpression).Method;
Assert.That(mi, Has.Attribute(typeof(TAttribute)));
}
```
And then call it in code like this:
```
(() => Console.WriteLine("Hello nurse")).
AssertAttributeAppliedToMethod<MyAttribute>();
```
Note that it doesn't matter what the parameters that are passed to the method are, as the method is never called, it simply needs the expression. | Whats the shortest way to assert that an attribute is applied to method in c#? | [
"",
"c#",
"unit-testing",
"reflection",
"nunit-2.5",
""
] |
I am curious about prevalent methodologies.
I found myself doing both of these things interchangeably:
*Note in all cases the object is allocated locally.*
```
std::string GetDescription ()
{
std::string desc;
/* Create a description */
return desc;
}
void GetResult (map<int, double> & resultMap)
{
/*Fill map result map with values*/
}
map<int, double> GetResult2(map<int, double> & resultMap)
{
map<int, double> & resultMap
/* Fill map result map with values */
return resultMap;
}
```
What is the preferred way to do this? | It greatly depends on the task at hand. I would go for the first approach for functions that create new values while using the second approach for functions that change the parameters. As mentioned by others, in some cases other restrictions (cost of creation / assignment) can affect the decision.
The first definition is clearly stating that it will create a new object out of nothing and will return it. That is, the same definition is stating the semantics of the call.
The second and third definitions require the caller to create an object *before* calling the function. This can be a hassle to the user as she cannot just ignore the return value (or use it as an unnamed temporal to feed another function, see snippet 1), and can be limited in cases (i.e. cannot reassign a reference from an already created object, see snippet 2).
It is not clear from the function definition what is the use of the parameter inside the function. Will the behavior of the function differ depending on the passed object? It is not clear from the function definition.
The third type is, I believe, the worst option. Not only it forces the caller to create a named variable to pass to the function but also makes a copy to return (unless it was a typo and you are returning a [possibly const] reference)
At any rate, other considerations can unbalance the advantage of clear semantics that the first approach provides. In some cases performance, or other limitations like objects that cannot be copied (see snippet 3)
```
// snippet 1
// user code to the different approaches
class X {};
X f1();
void f2( X& );
X f3( X& );
void g( X const & );
void test1()
{
g( f1() ); // valid code
}
void test2()
{
X x; // must create instance before
f2( x ); // then call the function
g( x );
}
void test3()
{
X x; // must create instance before
g( f3( x ) );
}
// snippet 2
class Y {};
class X
{
public:
X( Y & y ) : y_( y ) {}
private:
Y & y_;
};
X f1();
void f2( X & );
X f3( X & );
void test1()
{
X x = f1();
}
void test2or3()
{
Y y;
X x( y ); // user must create with a reference
f2( x ); // f2 cannot change the reference inside x to another instance
}
// snippet 3
class X
{
private:
X( X const & );
X& operator= ( X const & );
};
X f1(); // Returned object cannot be used
void f2( X & );
X f3( X & );
void test1()
{
X x = f1(); // compilation error
}
void test2()
{
X x;
f2( x );
}
void test3()
{
X x;
X y = f3( x ); // compilation error
}
``` | Either return it by value or manipulate it as an out parameter that is passed in. Don't return anything allocated on the stack via a reference unless you like crashes and undefined behavior.
EDIT: It really is a matter of style. I prefer values for value types and out parameters for non-value types. Although if I'm really in the mood to abstract things I use a specialized interface, something in the spirit of an `ostream`. | How do you usually return an instance of a user-defined type allocated on the local stack | [
"",
"c++",
""
] |
In a managed wrapper over a native library, I have to accomplish certain operations which to the user of the high level objects should be considered atomic and consistent. However, the underlying operations in native code are atomic and consistent individually, but not as a whole.
```
// Simplistic look at the AddRange operation
void AddRange(IEnumerable<ChildType> range)
{
foreach (var value in range)
{
this.NativeAdd(value);
}
}
// Simplistic look at the Delete operation
void Delete(ParentType value)
{
foreach (var child in value.Children)
{
this.NativeDelete(child);
}
this.NativeDelete(value);
}
```
All of the Native operations fail with a common exception type if the Native code relates there has been an error:
```
void NativeDelete(ChildType child)
{
StatusCode status = StatusCode.NoError;
NativeMethods.DeleteChild(this.id, child.Id, out status);
if (status != StatusCode.NoError)
{
throw new LibraryException(this, child, status);
}
}
```
In the high-level AddRange and Delete routines I run into the situation where some of either the native Add or Delete calls have completed, but an error occurs in one of them and the rest do not complete.
**UPDATE:** The actual file on disk, to a user, will not look any different if they added 7 items and it failed on the 7th item, or if they added 6 items successfully. The only time the error is recorded is during runtime. Therefore, if the user is not made aware of the possibility of an inconsistent state, they may not be able to decide if the underlying file is valid.
Should I:
1. Let the LibraryException through and provide documentation to the user that the ParentType or ChildType object may be in an inconsistent state
2. Wrap the LibraryException in an InconsistentStateException containing information about which objects may be in an inconsistent state
3. Catch the LibraryException and attempt to "hand" rollback the changes made, before rethrowing the exception for the user (not a fan of this)
4. Something else? | If I understand your update correctly, all the caller can do is pass the information on to the end user, who has to decide whether to accept the state, or to roll back.
In that case, (2): provide all information so the caller can pass the information to the user, or a log file, or some statistics without a lot of work.
(1) would be ok if there is no informational difference to (2), e.g. knowing which item failed is irrelevant.
(3) is pointless if you can't expect fix it most of the time, and dangerous if there is the slightest chance you make it worse.
Depending on the file size you might be able to make the change quasi-atomic by working on a copy. At least, the user would probably expect an easy way to roll back to the last save. | 3 just isn't possible without a true two-phase commit support (i.e. a transaction manager). Rolling back by hand is just going to lead you to more of an inconsistent state if an error occurs there.
I think 2 is redundant. If you call a method on the parent type (which is where these methods exposed) and you have an exception that occurs when you throw that exception, the assumption is that the state on the object is corrupted (with the exception of a few exceptions). Generally, when that occurs, you can't do much with the object except throw it away and use a new one with a consistent state.
That leaves 1, to document it. While you might give a lot of structured information in 2, if the object is in an inconsistent state, you *really* don't want to try and fix that state, as you run a greater risk of screwing it up more. | Alerting Library Users to an Inconsistent State | [
"",
"c#",
".net",
""
] |
I need to be able to set up a background hotkey event for a WPF application. (by background I mean that the application in question might not necessary be in focus).
I know that with WinForms the proper way of doing it would be to import user32.dll, and use RegisterHotKey, and the catch the appropriate WM\_POST message. I'm convinced that there has to be a better solution with WPF, then using user32.dll, but I have been unable to find anything. Any suggestions? Thanks | I don't think WPF has any built in support for hotkeys, at least I couldn't find any and I used RegisterHotKey directly. | This has an excellent example (see 5.2 "Registering the System Hotkey"):
<http://blog.280z28.org/archives/2007/03/15/>
It uses the [Managed Windows API](http://mwinapi.sourceforge.net/), which is a great wrapper around a lot of the legacy api calls. | Proper way of creating a background hotkey with WPF C#? (preferably without using legacy code) | [
"",
"c#",
"wpf",
"hotkeys",
""
] |
Our Python CMS stores some date values in a generic "attribute" table's *varchar* column. Some of these dates are later moved into a table with an actual *date* column. If the CMS user entered an invalid date, it doesn't get caught until the migration, when the query fails with an "Invalid string date" error.
How can I use Python to make sure that all dates put into our CMS are valid Oracle string date representations? | > How can I use Python to make sure that all dates put into our CMS are valid Oracle string date representations?
I'd change the approach a bit. Have Python parse the original date input as forgivingly as possible, then output the date in a known-good representation.
[dateutil](http://labix.org/python-dateutil)'s liberal parser may be a good place to start:
```
import dateutil.parser
d= dateutil.parser.parse('1/2/2003')
d.strftime('%d-%b-%y')
```
I'm not sure '%d-%b-%y' is actually still the right date format for Oracle, but it'll probably be something similar, ideally with four-digit years and no reliance on month names. (Trap: %b is locale-dependent so may return unwanted month names on a non-English OS.) Perhaps “strftime('%Y-%m-%d')” followed by “TO\_DATE(..., 'YYYY-MM-DD')” at the Oracle end is needed? | The format of a date string that Oracle recognizes as a date is a configurable property of the database and as such it's considered bad form to rely on implicit conversions of strings to dates.
Typically Oracle dates format to 'DD-MON-YYYY' but you can't always rely on it being set that way.
Personally I would have the CMS write to this "attribute" table in a standard format like 'YYYY-MM-DD', and then whichever job moves that to a DATE column can explicitly cast the value with to\_date( value, 'YYYY-MM-DD' ) and you won't have any problems. | Validating Oracle dates in Python | [
"",
"python",
"oracle",
"validation",
""
] |
Ok, I'm having issues with the linker on my current project (This is a continuation of another question, ish)
Basically, the linker gives an undefined reference in dynamiclib.so for:
```
std::basic_ostream<char, std::char_traits<char> >& SparseImplementationLib::operator<< <double, double, SparseImplementationLib::DefaultPtr<double, double> >(std::basic_ostream<char, std::char_traits<char> >&, SparseImplementationLib::AbstractSparseNode<double, double, SparseImplementationLib::DefaultPtr<double, double> > const&)
```
And I can only find:
```
std::ostream& SparseImplementationLib::operator<< <double, double, SparseImplementationLib::DefaultPtr<double, double> >(std::ostream&, SparseImplementationLib::AbstractSparseNode<double, double, SparseImplementationLib::DefaultPtr<double, double> > const&)
```
within the file.
Thing is, they're the same methods, really (basic\_ostream and ostream are interchangable?)
If I add the first method in manually to the namespace it moans about it being already defined at compile time.
Does anyone know what on earth might be going on here?
Cheers, Ed
NB this is with MPICXX and CCMAKE | Ok, I managed to fix this this morning after about 10 hours hacking away last night.
Turns out that it compiles if you make the definitions of the function inline, and make sure it has options for the function with both all the template arguments and just non-defaulted arguments! | It sounds like you're not linking dynamiclib.so to the SparseImplementationLib correctly. Do you have a linker flag similar to -lSparseImplementationLib in your makefile? | Linker problem, doesn't find an existing method? | [
"",
"c++",
"linker",
""
] |
I have a zip file which contains the following directory structure:
```
dir1\dir2\dir3a
dir1\dir2\dir3b
```
I'm trying to unzip it and maintain the directory structure however I get the error:
```
IOError: [Errno 2] No such file or directory: 'C:\\\projects\\\testFolder\\\subdir\\\unzip.exe'
```
where testFolder is dir1 above and subdir is dir2.
Is there a quick way of unzipping the file and maintaining the directory structure? | The extract and extractall methods are great if you're on Python 2.6. I have to use Python 2.5 for now, so I just need to create the directories if they don't exist. You can get a listing of directories with the `namelist()` method. The directories will always end with a forward slash (even on Windows) e.g.,
```
import os, zipfile
z = zipfile.ZipFile('myfile.zip')
for f in z.namelist():
if f.endswith('/'):
os.makedirs(f)
```
You probably don't want to do it *exactly* like that (i.e., you'd probably want to extract the contents of the zip file as you iterate over the namelist), but you get the idea. | **Don't** trust extract() or extractall().
These methods blindly extract files to the paths given in their filenames. But ZIP filenames can be anything at all, including dangerous strings like “x/../../../etc/passwd”. Extract such files and you could have just compromised your entire server.
Maybe this should be considered a reportable security hole in Python's zipfile module, but any number of zip-dearchivers have exhibited the exact same behaviour in the past. To unarchive a ZIP file with folder structure safely you need in-depth checking of each file path. | Unzipping directory structure with python | [
"",
"python",
"unzip",
""
] |
I need to delete a directory that contains read-only files. Which approach is better:
* Using `DirectoryInfo.Delete()`, or,
* `ManagementObject.InvokeMethod("Delete")`?
With `DirectoryInfo.Delete()`, I have to manually turn off the read-only attribute for each file, but `ManagementObject.InvokeMethod("Delete")` doesn't appear to need to. Is there any situation where one is more preferable to the other?
Sample code (test.txt is read only).
### First way:
```
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\David\Desktop\");
dir.CreateSubdirectory("Test");
DirectoryInfo test = new DirectoryInfo(@"C:\Users\David\Desktop\Test\");
File.Copy(@"C:\Users\David\Desktop\test.txt", @"C:\Users\David\Desktop\Test\test.txt");
File.SetAttributes(@"C:\Users\David\Desktop\Test\test.txt", FileAttributes.Archive);
test.Delete(true);
```
### Second way:
```
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\David\Desktop\");
dir.CreateSubdirectory("Test");
DirectoryInfo test = new DirectoryInfo(@"C:\Users\David\Desktop\Test\");
File.Copy(@"C:\Users\David\Desktop\test.txt", @"C:\Users\David\Desktop\Test\test.txt");
string folder = @"C:\Users\David\Desktop\Test";
string dirObject = "Win32_Directory.Name='" + folder + "'";
using (ManagementObject managementObject = new ManagementObject(dirObject))
{
managementObject.Get();
ManagementBaseObject outParams = managementObject.InvokeMethod("Delete", null,
null);
// ReturnValue should be 0, else failure
if (Convert.ToInt32(outParams.Properties["ReturnValue"].Value) != 0)
{
}
}
``` | Here is an extension method which sets `Attributes` to `Normal` recursively, then deletes the items:
```
public static void DeleteReadOnly(this FileSystemInfo fileSystemInfo)
{
var directoryInfo = fileSystemInfo as DirectoryInfo;
if (directoryInfo != null)
{
foreach (FileSystemInfo childInfo in directoryInfo.GetFileSystemInfos())
{
childInfo.DeleteReadOnly();
}
}
fileSystemInfo.Attributes = FileAttributes.Normal;
fileSystemInfo.Delete();
}
``` | Simplest way of avoiding recursive calls is by utilising the `AllDirectories` option when getting `FileSystemInfo`s, like so:
```
public static void ForceDeleteDirectory(string path)
{
var directory = new DirectoryInfo(path) { Attributes = FileAttributes.Normal };
foreach (var info in directory.GetFileSystemInfos("*", SearchOption.AllDirectories))
{
info.Attributes = FileAttributes.Normal;
}
directory.Delete(true);
}
``` | How do I delete a directory with read-only files in C#? | [
"",
"c#",
"directory",
"readonly",
"delete-directory",
""
] |
In Python, functions like str(), int(), float(), etc. are generally used to perform type conversions. However, these require you to know at development time what type you want to convert to. A subproblem of some Python code I'm trying to write is as follows:
Given two variables, `foo` and `bar`, find the type of `foo`. (It is not known at development time, as this is generic code.) Then, attempt to convert `bar` to whatever type `foo` is. If this cannot be done, throw an exception.
For example, let's say you call the function that does this `conv`. Its signature would look like
```
def conv(foo, bar) :
# Do stuff.
```
It would be called something like:
```
result = conv(3.14, "2.718") # result is now 2.718, as a float.
``` | Use `foo.__class__` to get the type of `foo`. Then call it to convert bar to the type of foo:
```
def conv(foo, bar) :
return foo.__class__(bar)
```
Of course, this only works if the type of `foo` has a constructor that knows how to convert bar. | that would be best:
```
type(foo)(bar)
``` | Python Reflection and Type Conversion | [
"",
"python",
"reflection",
"type-conversion",
"introspection",
"python-datamodel",
""
] |
I have 2 separate classes:
* AreaProperties
* FieldProperties
1 AreaProperties can map to 1 FieldProperties. Without changing the design, I want a method to return a `List<>` of these objects
What generic collection in C# would be suitable?
I understand I can send 2 Lists and the function would look like:
```
public List<AreaProperties> Save(ref List<FieldProperties>)
{
..code
}
```
**EDIT:
Dror Helper's solution sounds good. However, I recently found out that there is no 1:1 between FieldProperties and AreaProperties.
How would I now handle this. I still want to go with a custom class that has an object of FieldProperties and AreaProperties but how would I handle the 1 to many scenario?** | You can create a class/struct that has two members - AreaProperties & FieldProperties and return a list of that class
```
class Pair<T1, T2>
{
T1 t1;
T2 t2;
}
List<Pair<AreaProperties, FieldProperties>> Save(){ ...}
```
Or use System.Collections.Generic.KeyValuePair instead (per Patrick suggestion below)
```
List<KeyValuePair<AreaProperties, FieldProperties>> Save(){ ... }
```
This way you keep the 1..1 relation as well.
**Edit:**
In case you need 1..n relation I think you want to return
List>> instead this way you have a list of Field Properties for each AreaProperties you get back and you still keep the relation between them. | You could return a `List<KeyValuePair<AreaProperties, FieldProperties>>` | Which generic collection to use? | [
"",
"c#",
".net",
"asp.net",
"generics",
"collections",
""
] |
I wrote some JavaScript to allow editing a list of items within an HTML form, including adding and removing items. Got it working in Firefox. When trying it in Internet Explorer, I found that any added items were not being submitted with the form.
Long story short... lots of simplification, debugging, figured out what line is triggering IE to ignore the new form input. So the behavior problem is solved.
But now I must ask: Why? Is this an IE bug?
Here is the simplified code:
```
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function add() {
div = document.getElementById("mylist");
// *** Adding text here works perfectly fine. ***
div.innerHTML += " ";
e = document.createElement("input");
e.setAttribute("type", "text");
e.setAttribute("name", "field3");
e.setAttribute("value", "--NEWVALUE--");
div.appendChild(e);
// *** Adding text here works perfectly fine in Firefox, but for
// Internet Explorer it causes field3 to not be submitted. ***
//div.innerHTML += " ";
}
</script>
</head>
<body>
<form action="" method="get">
<div id="mylist">
<input type="text" name="field1" value="value1" />
<input type="text" name="field2" value="value2" />
</div>
<a href="javascript:" onclick="add()" />Add</a>
<input type="submit" value="Submit" />
</form>
</body>
</html>
```
To try it out, do the obvious: load in IE, click Add, click Submit, look what's in the address bar. If you uncomment the last line in `add()`, IE will suddenly stop reporting `field3`. It works fine either way in Firefox.
Any ideas? A curious mind wants to know. (And how would I add text there if needed, in a portable fashion, so IE is happy?) | > Is this an IE bug?
Seems so. When you create an <input> element through DOM methods, IE doesn't quite pick up the ‘name’ attribute. It's sort-of-there in that the element does submit, but if you try to get an ‘innerHTML’ representation of the element it mysteriously vanishes. This doesn't happen if you create the element by writing directly to innerHTML.
Also if you use DOM Level 0 form navigation methods, like ‘myform.elements.x.value’, access through the ‘elements’ array may not work (similarly the direct ‘myform.x’ access some people misguidedly use). In any case these days you might prefer getElementById().
So *either* use innerHTML *or* use DOM methods; best not to mix them when creating form fields.
This is [documented (see ‘Remarks’)](http://msdn.microsoft.com/en-us/library/ms534184(VS.85).aspx) and finally fixed in IE8.
In any case, never do:
> div.innerHTML+= '...';
This is only syntactical sugar for:
> div.innerHTML= div.innerHTML+'...';
In other words it has to serialise the entire child HTML content of the element, then do the string concatenation, then re-parse the new string back into the element, throwing away all the original content. That means you lose anything that can't be serialised: as well as IE's bogus half-created ‘name’ attributes that also means any JavaScript event handlers, DOM Listeners or other custom properties you have attached to each child element. Also, the unnecessary serialise/parse cycle is slow. | IE is very picky about changing some built-in properties at runtime. For example, the name of an input element cannot be changed while set.
Two things I would try if I were you:
1. Instead of using `setAttribute()`, try setting the `name`, `type` and `value` properties explicitly:
`e.name = "text";`
2. If this doesn't work, you may have to include all these attributes into the `document.createElement()` call:
`var e = document.createElement("<input type='text' name='field'>");`
this may actually throw an exception in some browsers. So the best cross browser way to go would be:
.
```
var e;
try {
e = document.createElement("<input type='text' name='field'>");
} catch (ex) {
e = document.createElement("input");
e.type = 'text';
e.name = 'field';
}
e.value = 'value';
``` | IE is not submitting dynamically added form elements | [
"",
"javascript",
"internet-explorer",
"webforms",
"dhtml",
""
] |
If I have the following enum:
```
public enum ReturnValue{
Success = 0,
FailReason1 = 1,
FailReason2 = 2
//Etc...
}
```
Can I avoid casting when I return, like this:
```
public static int main(string[] args){
return (int)ReturnValue.Success;
}
```
If not, why isn't an enum value treated as an int by default? | enums are supposed to be type safe. I think they didn't make them implicitly castable to discourage other uses. Although the framework allows you to assign a constant value to them, you should reconsider your intent. If you primarily use the enum for storing constant values, consider using a static class:
```
public static class ReturnValue
{
public const int Success = 0;
public const int FailReason1 = 1;
public const int FailReason2 = 2;
//Etc...
}
```
That lets you do this.
```
public static int main(string[] args){
return ReturnValue.Success;
}
```
**EDIT**
When you *do* want to provide values to an enum is when you want to combine them. See the below example:
```
[Flags] // indicates bitwise operations occur on this enum
public enum DaysOfWeek : byte // byte type to limit size
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
Weekend = Sunday | Saturday,
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}
```
This enum can then be consumed by using bitwise math. See the below example for some applications.
```
public static class DaysOfWeekEvaluator
{
public static bool IsWeekends(DaysOfWeek days)
{
return (days & DaysOfWeek.Weekend) == DaysOfWeek.Weekend;
}
public static bool IsAllWeekdays(DaysOfWeek days)
{
return (days & DaysOfWeek.Weekdays) == DaysOfWeek.Weekdays;
}
public static bool HasWeekdays(DaysOfWeek days)
{
return ((int) (days & DaysOfWeek.Weekdays)) > 0;
}
public static bool HasWeekendDays(DaysOfWeek days)
{
return ((int) (days & DaysOfWeek.Weekend)) > 0;
}
}
``` | There is no implicit cast because the enum does not have to use int as the underlying type. If your enum used a uint as the underlying type, for instance, there is no implicit cast from uint to int. | Can I avoid casting an enum value when I try to use or return it? | [
"",
"c#",
".net",
"enums",
"casting",
"return-value",
""
] |
I would like to unit test a method on a class I have made, but this method requires another method to be called first. Example:
```
// This would work
MyClass myClass1 = new MyClass(mockDevice);
myClass1.Run(myDatastructure);
myClass1.Stop();
// This would throw an InvalidOperationException
MyClass myClass2 = new MyClass(mockDevice);
myClass2.Stop();
```
`Run` is starting an operation on a hardware device, and `Stop` is of course trying to stop that operation (sending a reset-command and starting a timeout-timer).
Anyway I would like to test various post-conditions of calling `Stop`, but I would like NOT to have to call `Run`, because I am testing `Stop` - not `Run`! I would like something like this:
```
MyClass myClass = new MyClass(mockDevice);
myClass.Stop();
Assert.IsTrue(mockDevice.ResetCalled);
```
So far I only see one possible solution, and that is to create a `TestableMyClass` that inherits from `MyClass`, that makes it possible to set the right internal state of the `MyClass` instance before calling `Stop`. The problem with this solution is that I have to change my `MyClass`-implementation to have protected members instead of private members, and I *don't* like the idea of having to change the implementation in order to test it!
Should I use this solution, is there an error in my design, or is there a smarter way of doing this? | As far as I see it, you are already testing `Stop` in the two ways in which it can be used (with and without a running operation). As long as the `mockDevice` is doing its job, it seem to me that you're testing it reasonably. Ideally you should be able to verify the commands sent to the device etc (which most mock frameworks will make simple). | In this situation, personally, I would have two tests for this:
1. Test without Run() being called first. I would test if it really throws the exception. I would also test if the post conditions are what I expect them to be.
2. Test with Run() being called first. I would test only the post conditions, that I expect.
Those are the only two important uses of the method that have different behaviors - therefor I would test them both.
EDIT:
I understand, why you don't want to call run, before stop - you think that if run fails, the test, that is supposed to only test stop method will most likely fail as well.
However, I would assume, that you also have test for the run method. This means, that when the tests, that test the behavior of run method pass - stop method tests must pass as well. If the run method tests fail, then the results of run method tests are undefined - they may or may not fail.
So, I'd say, don't be afraid to call other dependent methods in your tests, but make sure you test those dependent methods in separate tests. | Unit testing dependent methods | [
"",
"c#",
"unit-testing",
""
] |
We are always taught to make sure we use a *break* in switch statements to avoid fall-through.
The Java compiler warns about these situations to help us not make trivial (but drastic) errors.
I have, however, used case fall-through as a feature (we don't have to get into it here, but it provides a very elegant solution).
However the compiler spits out massive amounts of warnings that may obscure warnings that I need to know about. I know how I can change the compiler to ignore ALL fall-through warnings, but I would like to implement this on a method-by-method basis to avoid missing a place where I did not intend for fall-through to happen.
Any Ideas? | If you really, really must do this, and you are sure you are not making a mistake, check out the [@SuppressWarnings annotation](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/SuppressWarnings.html). I suppose in your case you need
```
@SuppressWarnings("fallthrough")
``` | Is the annotation `@SuppressWarnings` ([javadoc](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/SuppressWarnings.html)) what you are looking for?
For example:
```
@SuppressWarnings("unchecked")
public void someMethod(...) {
...
}
``` | How to suppress Java compiler warnings for specific functions | [
"",
"java",
"compiler-construction",
"warnings",
"compiler-warnings",
"suppress-warnings",
""
] |
Is it possible to use the users windows authentication (setting in iis) for database connections in PHP?
This is possible in the .NET world through a technique called "impersonation". Does this also exist in the PHP/IIS world?
**EDIT**: The Database I am using is MS SQL Server 2005. | If you can authenticate the PHP application with Keberos, you can use kerberos Delegation to pass the credentials to the secondary server.
[Ken Schaefer](http://www.adopenstatic.com/cs/blogs/ken/) has a whole series of blogs on Kerberos, including [this article](http://www.adopenstatic.com/cs/blogs/ken/archive/2007/01/27/1282.aspx) on delegation. | Impersonation through Kerberos is the most secure answer, as well as the simplest to administrate. Having separate 'synthetic' users when accessing resources like databases means you basically bypass all possibilities for database authorization, get duplicate points of access administration, and that you get zero traceability at the database level (you just see that MySyntheticUser tried to access something, not who was behind it).
Having said this, I should warn you that Microsoft's Kerberos isn't always as straightforward as you would expect. We've had significant trouble getting it to work between pure .NET solutions, IIS, SQL Server 2005, AD domains and Internet Explorer. Most of it was down to getting trust configured exactly right. Also, while I'm not a PHP developer myself, I find [some indications](http://mailman.mit.edu/pipermail/kerberos/2006-December/010915.html) that you may have trouble accessing Kerberos library functionality. Find out what support you can get for [SSPI](http://en.wikipedia.org/wiki/Security_Support_Provider_Interface). Also, your PHP process must have the necessary permissions to impersonate users, which I believe can be administered through IIS.
I would not necessarily expect all of this to be straightforward or easy, particularly as Microsoft has few incitaments to support non-Microsoft languages and platforms. | Can Windows Authentication be used with PHP on IIS for ODBC connections? | [
"",
"php",
"sql-server-2005",
"iis",
"authentication",
"odbc",
""
] |
I have a situation where I require to consult different objects in PHP via different methods to find some data.
The question regards more about formatting the code than an actual programming issue. What I am trying to do is not using several `if`'s to gather this data like:
```
$data = obj->getData();
if (!isset($data)) $data = othObj->getThisData();
if (!isset($data)) $data = anothObj->getTheData();
if (!isset($data)) $data = anothOne->getAData();
...
process($data)
```
I was wondering what are the best practices in this case, if there is a better way using another procedures, like `foreach` or `switch/case`.
Thanks! | You can make an array of the possible objects you want to try, then run a loop. Might be more maintainable. This code can be modified to include parameters and use call\_user\_func\_array instead.
```
$dataCallback = array(
array($othObj, 'getData'),
array($othObj, 'getThisData'),
array($anothObj, 'getTheData'),
array($anothOne, 'getAData'),
);
for($i = 0, $t = count($dataCallback); !isset($data) && $i < $t; $i++) {
$callback = $dataCallback[$i];
$data = call_user_func($callback);
}
if (isset($data))
process($data);
else
//no valid data returned at all ...
``` | I'd probably group the objects to ask for data into an array:
```
$objArray = array($obj, $othObj, $anothObj, ... );
```
Then run through a while loop until I had data:
```
$i = 0;
do {
$data = $objArray[$i]->getData();
$i++;
} while(!isset($data) && $i < count($objArray));
``` | Switching methods for a single result | [
"",
"php",
"code-formatting",
""
] |
I am planning to use NHibernate for my next project with mapping through FluentNHibernate.
I have a database already, so I have to generate C# classes for entities mapped to database tables.
What tool would you recommend (if there is any?) for automatic C# class generation for NH from MS SQL database?
Thanks for sharing. | [NConstruct Lite](http://www.nconstruct.com/App/NConstructLite.aspx?PageId=12) will generate the classes and the hbm mapping files for free even though it does not support fluent NHibernate, nor does it make use of some of the new C# 3.0 features. | Don't.
The whole point of object-relational mapping is to... well... map.
If you generate the classes from the database you may as well be using typed datasets.
Think about what you would want your classes to look like in the object world and then use NHibernate to map that to your database schema. | Database tables to C# entity classes - generator for FluentNHibernate? | [
"",
"c#",
"nhibernate",
""
] |
Folks,
For the n-th time in a row, i'm hitting the same old problem again. It's about "how do I map OOP structures to database tables in a painless way."
Here's a scenario: I have several types of "actors" in my system - workers, employers, contacts. They have certain pieces of functionality in common; other pieces are vastly different. The entities that all actors deal with are "communications", "notes" (admins like to leave notes on customers), and a few more. There are tons of types of other entities that each actor type deals with, while the others don't.
Currently, my database schema includes tables for:
Actors:
* worker
* employer
* contact
Entities:
* communication
* notes
* etc.
Association tables between entities and actors:
* worker-communication-assn
* employer-communication-assn
* worker-notes-assn
* etc, you get the drill.
This feels like a "code smell" to me. Whenever a customer changes their role (i.e. promoted from "contact" to "employer"), a bunch of crazy scripts need to be run. Yuck... On the other hand, if i was operating in a purely OOP-driven world, this would be much easier - have a base class for all entities with common properties, and be done with it...
In the DB world, that option seems theoretically possible, but sounds very messy... I.e. if I understand this right, I'd have a new base\_actor table, and each other actor would have a base\_actor\_id, and then the associations would be between base\_actor and the entities... But then, how do I do reverse-association queries? I.e. "show me all communications with just actors of type worker"?
Any advice? Any general thoughts on the subject of "mapping OOP structures to relational DB"? | Here's a solution I came up with about 10 years ago. The system that uses this design is still running, so it worked well enough to survive longer than most of my code. ;) Today I may use one of the ORM packages that Scott mentions, but there's really no huge problems just using SQL directly.
1. Model all of your inheritance relations as joins between tables. Each table in your system will hold the attributes of a specific class.
2. Use a synthetic object id (oid) as your primary key for all objects. A sequence generator or autoincrement column is necessary to generate oid values.
3. All inherited classes must use the same oid type as their parent. Define the oid as a foreign key with cascaded delete. The parent table gets the autoincrement oid column and the children get plain oid columns.
4. Queries on final classes are made on the corresponding table. You can either join all the parent class tables into the query or just lazy load the attributes you need. If your inheritance hierarchy is deep and you have many classes, an ORM package can really simplify your code. My system had less than 50 classes with a maximum inheritance depth of 3.
5. Queries across child classes (i.e. queries on a parent class) can either lazy load the child attributes on a per-instance basis, or you can repeat the query for each child class joined with base classes. Lazy loading child attributes based on a parent class query requires you know the type of the object. You may have enough information in the parent classes already, but if not you'll need to add type information. Again, this is where an ORM package can help.
Virtual classes without member attributes can be skipped in the table structure, but you won't be able to query based on those classes.
Here's what "show me all communications with just actors of type worker" looks like.
```
select * from comm c, worker w where c.actor=w.oid;
```
If you have sub-classes of communication, and you want to immediately load all the child class attributes (perhaps your system does not allow partial construction), the easiest solution is to eager join on all the possible classes.
```
select * from comm c, worker w, missive m where c.actor=w.oid and c.oid=m.oid;
select * from comm c, worker w, shoutout s where c.actor=w.oid and c.oid=s.oid;
```
One last thing. Make sure you have a good database and correct indexes. Performance can be a serious problem if you database can't optimize these joins. | > .. It's about "how do I map OOP structures to database tables in a painless way."
You don't.
Object oriented and relational algebra are two fundamentally different paradigms. You can't transition between them without a subjective interpretation. This is called an impedance mismatch, and has been dubbed the [The Vietnam of Computer Science](https://web.archive.org/web/20180122225838/http://blogs.tedneward.com/post/the-vietnam-of-computer-science/). | Object-oriented-like structures in relational databases | [
"",
"php",
"mysql",
"database",
"oop",
""
] |
I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses that are preceeded by "From:" and a few wildcard characters, and ending with ">" (because the emails are set up as From [name]<[email]>).
Here's the code now:
```
import re #allows program to use regular expressions
foundemail = []
#this is an empty list
mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
#do not currently know exact meaning of this expression but assuming
#it means something like "[stuff]@[stuff][stuff1-4 letters]"
# "line" is a variable is set to a single line read from the file
# ("text.txt"):
for line in open("text.txt"):
foundemail.extend(mailsrch.findall(line))
# this extends the previously named list via the "mailsrch" variable
#which was named before
print foundemail
``` | If your goal is actually to extract email addresses from text, you should use a library built for that purpose. Regular expressions are not well suited to match arbitrary email addresses.
But if you're doing this as an exercise to understand regular expressions better, I'd take the approach of expanding the expression you're using to include the extra text you want to match. So first, let me explain what that regex does:
```
[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}
```
* `[\w\-]` matches any "word" character (letter, number, or underscore), *or* a hyphen
* `[\w\-\.]+` matches (any word character *or* hyphen *or* period) one or more times
* `@` matches a literal '@'
* `[\w\-]` matches any word character *or* hyphen
* `[\w\-\.]+` matches (any word character *or* hyphen *or* period) one or more times
* `[a-zA-Z]{1,4}` matches 1, 2, 3, or 4 lowercase or uppercase letters
So this matches a sequence of a "word" that may contain hyphens or periods but doesn't start with a period, followed by an `@` sign, followed by another "word" (same sense as before) that ends with a letter.
Now, to modify this for your purposes, let's add regex parts to match "From", the name, and the angle brackets:
```
From: [\w\s]+?<([\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4})>
```
* `From:` matches the literal text "From: "
* `[\w\s]+?` matches one or more consecutive word characters *or* space characters. The question mark makes the match non-greedy, so it will match as few characters as possible while still allowing the whole regular expression to match (in this case, it's probably not necessary, but it does make the match more efficient since the thing that comes immediately afterwards is not a word character or space character).
* `<` matches a literal less-than sign (opening angle bracket)
* The same regular expression you had before is now surrounded by parentheses. This makes it a *capturing group*, so you can call `m.group(1)` to get the text matched by that part of the regex.
* `>` matches a literal greater-than sign
Since the regex now uses capturing groups, your code will need to change a little as well:
```
import re
foundemail = []
mailsrch = re.compile(r'From: [\w\s]+?<([\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4})>')
for line in open("text.txt"):
foundemail.extend([m.group(1) for m in mailsrch.finditer(line)])
print foundemail
```
The code `[m.group(1) for m in mailsrch.finditer(line)]` produces a list out of the first capturing group (remember, that was the part in parentheses) from each match found by the regular expression. | Try this out:
```
>>> from email.utils import parseaddr
>>> parseaddr('From: vg@m.com')
('', 'vg@m.com')
>>> parseaddr('From: Van Gale <vg@m.com>')
('Van Gale', 'vg@m.com')
>>> parseaddr(' From: Van Gale <vg@m.com> ')
('Van Gale', 'vg@m.com')
>>> parseaddr('blah abdf From: Van Gale <vg@m.com> and this')
('Van Gale', 'vg@m.com')
```
Unfortunately it only finds the first email in each line because it's expecting header lines, but maybe that's ok? | Parsing "From" addresses from email text | [
"",
"python",
"string",
"email",
"parsing",
"text",
""
] |
I've got a wrapper class which encapsulates a piece of information that needs to be transmitted as a byte array.
In that way, the class encapsulates the necessary header (with fields like DATA\_LENGTH or MESSAGE\_TYPE) into the corresponding byte positions. For that I want to define positions and length in constants, for example:
```
HEADER_DATA_LENGTH_IX = 0;
HEADER_DATA_LENGTH_LENGTH = 2;
```
which means DATA\_LENGTH starts at 0 and takes two bytes.
but so far I'm struggling with making them constants or static readonly fields. Const cannot be protected, therefore I won't be able to derive a new class and change the constants if a use them, on the other way I might declare new constants in the derived class and the use them.
What will be your approach? | If you want to change the value of these params in a derived class, you can make them [readonly](http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx) and change them in the constructor of the derived class
I wouldn't make them [const](http://msdn.microsoft.com/en-us/library/e6w8fe1b.aspx) anyhow, because they're not... | The basic difference is when the variable is initialized. 'readonly' is set at initialization, or in the contructor, while 'const' is set at compile time.
I think the big decision is if you want to inherit the class and override the value. If you do, go readonly. Otherwise I don't think it really matters.
readonly C#ref: <http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx>
const C# ref: <http://msdn.microsoft.com/en-us/library/e6w8fe1b.aspx> | Const vs protected static readonly | [
"",
"c#",
".net",
""
] |
I'm trying to handle a bunch of files, and I need to alter then to remove extraneous information in the filenames; notably, I'm trying to remove text inside parentheses. For example:
```
filename = "Example_file_(extra_descriptor).ext"
```
and I want to regex a whole bunch of files where the parenthetical expression might be in the middle or at the end, and of variable length.
What would the regex look like? Perl or Python syntax would be preferred. | ```
s/\([^)]*\)//
```
So in Python, you'd do:
```
re.sub(r'\([^)]*\)', '', filename)
``` | The pattern that matches substrings in parentheses *having no other `(` and `)` characters in between* (like `(xyz 123)` in `Text (abc(xyz 123)`) is
```
\([^()]*\)
```
**Details**:
* `\(` - an opening round bracket (note that in POSIX BRE, `(` should be used, see `sed` example below)
* `[^()]*` - zero or more (due to the `*` [Kleene star quantifier](http://www.regular-expressions.info/repeat.html)) characters *other than* those defined in the [*negated character class*/*POSIX bracket expression*](http://www.regular-expressions.info/charclass.html#negated), that is, any chars other than `(` and `)`
* `\)` - a closing round bracket (no escaping in POSIX BRE allowed)
Removing code snippets:
* **JavaScript**: `string.replace(/\([^()]*\)/g, '')`
* **PHP**: `preg_replace('~\([^()]*\)~', '', $string)`
* **Perl**: `$s =~ s/\([^()]*\)//g`
* **Python**: `re.sub(r'\([^()]*\)', '', s)`
* **C#**: `Regex.Replace(str, @"\([^()]*\)", string.Empty)`
* **VB.NET**: `Regex.Replace(str, "\([^()]*\)", "")`
* **Java**: `s.replaceAll("\\([^()]*\\)", "")`
* **Ruby**: `s.gsub(/\([^()]*\)/, '')`
* **R**: `gsub("\\([^()]*\\)", "", x)`
* **Lua**: `string.gsub(s, "%([^()]*%)", "")`
* **sed**: `sed 's/([^()]*)//g'`
* **Tcl**: `regsub -all {\([^()]*\)} $s "" result`
* **C++ `std::regex`**: `std::regex_replace(s, std::regex(R"(\([^()]*\))"), "")`
* **Objective-C**:
`NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\([^()]*\\)" options:NSRegularExpressionCaseInsensitive error:&error]; NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];`
* **Swift**: `s.replacingOccurrences(of: "\\([^()]*\\)", with: "", options: [.regularExpression])`
* **Google BigQuery**: `REGEXP_REPLACE(col, "\\([^()]*\\)" , "")` | How can I remove text within parentheses with a regex? | [
"",
"python",
"regex",
"perl",
""
] |
I am looking for any resources that gives examples of Best Practices, Design patterns and the SOLID principles using Python. | Some overlap in these
[Intermediate and Advanced Software Carpentry in Python](https://web.archive.org/web/20180504173504/http://ivory.idyll.org/articles/advanced-swc/)
[Code Like a Pythonista: Idiomatic Python](https://web.archive.org/web/20180411011411/http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html)
[Python Idioms and Efficiency](https://web.archive.org/web/20120118192448/http://jaynes.colorado.edu/PythonIdioms.html)
[Google Developers Day US - Python Design Patterns](http://www.youtube.com/watch?v=0vJJlVBVTFg)
Another resource is by example at the [Python Recipes](https://github.com/ActiveState/code). A good number do not follow best practices but you can find some patterns in there that are useful | Type
```
>>> import this
```
in a Python console.
Although this is usually treated as a (fine!) joke, it contains a couple of valid python-specific axioms. | python design patterns | [
"",
"python",
"design-patterns",
""
] |
I have a vb.net function that creates several Stored Procedures based on parameters being passed into the function.
I want to move this vb.Net into a single SQL file (for maintenance reasons) but I am not sure how I can re-create it in SQL without creating 7 separate stored procedures.
I create a total of 20 Stored Procedures and I don't really want to create this many in a SQL file as maintenance will be a nightmare. I am wondering if there is a solution similar to how I have done it VB.Net below:
```
Private Sub CreateStoredProcedures()
CreateSP("SummaryNone", "YEAR([sale].[DateTime])")
CreateSP("SummaryUser", "[sale].[User]")
CreateSP("Summarysale", "[sale].[sale]")
CreateSP("SummaryBatch", "[sale].[Batch]")
CreateSP("SummaryDay", "dbo.FormatDateTime([sale].[DateTime], 'yyyy-mm-dd')")
CreateSP("SummaryMonth", "dbo.FormatDateTime(dbo.DateSerial(YEAR([sale].[DateTime]), MONTH([sale].[DateTime]), 1), 'yyyy-mm-dd')")
CreateSP("SummaryYear", "Year([sale].[DateTime])")
Return
End Sub
Private Sub CreateSP(ByVal vName As String, ByVal vGroup As String)
Dim CommandText As String = _
"CREATE PROCEDURE " & vName _
& " @StartDate varchar(50)," _
& " @EndDate varchar(50)" _
& " AS " _
& " SELECT " & vGroup & " AS GroupField," _
& " Sum([Project].[NumProject]) AS TotalProject," _
& " Sum([Project].[Title]) AS SumTitle," _
& " Sum([Project].[Duration]) AS SumDuration," _
& " Sum([Project].[Info]) AS SumInfo," _
& " Sum([Customer].[NumCustomer]) AS TotalNumCustomer," _
& " Sum([Orders].[NumOrders]) AS TotalNumOrders," _
& " Sum([OrderInspection].[NumInspects]) AS TotalNumInspects," _
& " Sum([OrderInspection].[NumFails]) AS TotalNumFails," _
& " Sum([CustomerInspection].[NumInspects]) AS TotalNumCustomerInspectionInspects," _
& " Sum([CustomerInspection].[NumFails]) AS TotalNumCustomerInspectionFails," _
& " Sum([Measurements].[NumMeasurements]) AS TotalNumMeasurementss" _
& " FROM ((((((sale LEFT JOIN Project ON [sale].[saleId]=[Project].[saleId])" _
& " LEFT JOIN Customer ON [Project].[PrintId]=[Customer].[PrintId])" _
& " LEFT JOIN Orders ON [Project].[PrintId]=[Orders].[PrintId])" _
& " LEFT JOIN OrderInspection ON [Project].[PrintId]=[OrderInspection].[PrintId])" _
& " LEFT JOIN CustomerInspection ON [Project].[PrintId]=[CustomerInspection].[PrintId])" _
& " LEFT JOIN Measurements ON [Project].[PrintId]=[Measurements].[PrintId])" _
& " WHERE [sale].[DateTime] BETWEEN dbo.FormatDateTime((@StartDate), 'yyyy-mm-dd')" _
& " AND dbo.FormatDateTime((@Enddate),'yyyy-mm-dd')" _
& " GROUP BY " & vGroup & "" _
& " ORDER BY " & vGroup & ";"
SqlExecuteNonQuery(CommandText)
return
End Sub
```
I look forward to your comments and replies.
Thanks | You could store a template in a text file as an embedded resource in your .NET DLL. Have some placeholders for your dynamic bits. Which would make your current solution a lot more maintainable. Then you load the stream from the DLL and keep your current implementation.
Editing the text file is easier than that big chunk of SQL which is embedded in your C# file.
You will probably get a performance hit if you move this to a single proc, you may be happy with it but keep in mind that the proc will also have some maintenance issues. We usually like to avoid dynamic SQL in stored procs. And a 7 way IF branch is a maintenance nightmare. | I would recommend that you create a single stored procedure that you call.
Then use dynamic SQL to build the appropriate select statement to be used within the single stored procedure.
Make sense? | How to create several stored procedure using SQL | [
"",
"sql",
"sql-server",
"vb.net",
"sql-server-2005",
"t-sql",
""
] |
I've a few lines of code within a project, that I can't see the value of...
```
buffer[i] = (currentByte & 0x7F) | (currentByte & 0x80);
```
It reads the filebuffer from a file, stored as bytes, and then transfers then to buffer[i] as shown, but I can't understand what the overall purpose is, any ideas?
Thanks | As the other answers already stated, `(currentByte & 0x7F) | (currentByte & 0x80)` is equivalent to `(currentByte & 0xFF)`. The JLS3 [15.22.1](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.22) says this is promoted to an `int`:
> When both operands of an operator &,
> ^, or | are of a type that is
> convertible (§5.1.8) to a primitive
> integral type, binary numeric
> promotion is first performed on the
> operands (§5.6.2). The type of the
> bitwise operator expression is the
> promoted type of the operands.
because JLS3 [5.6.2](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#170983) says that when `currentByte` has type `byte` and `0x7F` is an `int` (and this is the case), then both operands are promoted to `int`.
Therefore, `buffer` will be an array of element type `int` or wider.
Now, by performing `& 0xFF` on an `int`, we effectively map the original `byte` range -128..127 into the unsigned range 0..255, an operation often used by `java.io` streams for example.
You can see this in action in the following code snippet. Note that to understand what is happening here, you have to know that Java stores integral types, except `char`, as [2's complement](http://en.wikipedia.org/wiki/Two%27s_complement) values.
```
byte b = -123;
int r = b;
System.out.println(r + "= " + Integer.toBinaryString(r));
int r2 = b & 0xFF;
System.out.println(r2 + "= " + Integer.toBinaryString(r2));
```
Finally, for a real-world example, check out the Javadoc and implementation of the `read` method of `java.io.ByteArrayInputStream`:
```
/**
* Reads the next byte of data from this input stream. The value
* byte is returned as an <code>int</code> in the range
* <code>0</code> to <code>255</code>. If no byte is available
* because the end of the stream has been reached, the value
* <code>-1</code> is returned.
*/
public synchronized int read() {
return (pos < count) ? (buf[pos++] & 0xff) : -1;
}
``` | ```
(currentByte & 0x7F) | (currentByte & 0x80)
```
is equivalent to
```
currentByte & (0x7F | 0x80)
```
which equals
```
currentByte & 0xFF
```
which is exactly the same as
```
currentByte
```
Edit: I only looked at the right side of the assignment, and I still think the equivalance is true.
However, it seems like the code wants to cast the signed byte to a larger type while interpreting the byte as unsigned.
Is there an easier way to cast signed-byte to unsigned in java? | Bitwise AND, Bitwise Inclusive OR question, in Java | [
"",
"java",
"bit-manipulation",
"byte",
"operator-keyword",
""
] |
Anyone out there know how to make your .net windows form app sticky/snappy like Winamp so it snaps to the edges of the screen?
The target framework would be .NET 2.0 Windows Form written in C#, using VS08. I am looking to add this functionality to a custom user control, but I figured more people would benefit from having it described for the application and its main form.
Thank you. | This worked pretty well, works on multiple monitors, observes the taskbar:
```
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private const int SnapDist = 100;
private bool DoSnap(int pos, int edge) {
int delta = pos - edge;
return delta > 0 && delta <= SnapDist;
}
protected override void OnResizeEnd(EventArgs e) {
base.OnResizeEnd(e);
Screen scn = Screen.FromPoint(this.Location);
if (DoSnap(this.Left, scn.WorkingArea.Left)) this.Left= scn.WorkingArea.Left;
if (DoSnap(this.Top, scn.WorkingArea.Top)) this.Top = scn.WorkingArea.Top;
if (DoSnap(scn.WorkingArea.Right, this.Right)) this.Left = scn.WorkingArea.Right - this.Width;
if (DoSnap(scn.WorkingArea.Bottom, this.Bottom)) this.Top = scn.WorkingArea.Bottom - this.Height;
}
}
``` | The accepted answer only snaps the window after finishing the drag, whereas I wanted the form to continuously snap to the screen edges while dragging. Here's my solution, loosely based off the [Paint.NET source code](https://github.com/rivy/OpenPDN/blob/cca476b0df2a2f70996e6b9486ec45327631568c/src/FloatingToolForm.cs):
```
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Whatever
{
/// <summary>
/// Managed equivalent of the Win32 <code>RECT</code> structure.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct LtrbRectangle
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public LtrbRectangle(int left, int top, int right, int bottom)
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
public Rectangle ToRectangle()
{
return Rectangle.FromLTRB(Left, Top, Right, Bottom);
}
public static LtrbRectangle FromRectangle(Rectangle rect)
{
return new LtrbRectangle(rect.X, rect.Y, rect.X + rect.Width, rect.Y + rect.Height);
}
public override string ToString()
{
return "{Left=" + Left + ",Top=" + Top + ",Right=" + Right + ",Bottom=" + Bottom + "}";
}
}
/// <summary>
/// A form that "snaps" to screen edges when moving.
/// </summary>
public class AnchoredForm : Form
{
private const int WmEnterSizeMove = 0x0231;
private const int WmMoving = 0x0216;
private const int WmSize = 0x0005;
private SnapLocation _snapAnchor;
private int _dragOffsetX;
private int _dragOffsetY;
/// <summary>
/// Flags specifying which edges to anchor the form at.
/// </summary>
[Flags]
public enum SnapLocation
{
None = 0,
Left = 1 << 0,
Top = 1 << 1,
Right = 1 << 2,
Bottom = 1 << 3,
All = Left | Top | Right | Bottom
}
/// <summary>
/// How far from the screen edge to anchor the form.
/// </summary>
[Browsable(true)]
[DefaultValue(10)]
[Description("The distance from the screen edge to anchor the form.")]
public virtual int AnchorDistance { get; set; } = 10;
/// <summary>
/// Gets or sets how close the form must be to the
/// anchor point to snap to it. A higher value gives
/// a more noticable "snap" effect.
/// </summary>
[Browsable(true)]
[DefaultValue(20)]
[Description("The maximum form snapping distance.")]
public virtual int SnapDistance { get; set; } = 20;
/// <summary>
/// Re-snaps the control to its current anchor points.
/// This can be useful for re-positioning the form after
/// the screen resolution changes.
/// </summary>
public void ReSnap()
{
SnapTo(_snapAnchor);
}
/// <summary>
/// Forces the control to snap to the specified edges.
/// </summary>
/// <param name="anchor">The screen edges to snap to.</param>
public void SnapTo(SnapLocation anchor)
{
Screen currentScreen = Screen.FromPoint(Location);
Rectangle workingArea = currentScreen.WorkingArea;
if ((anchor & SnapLocation.Left) != 0)
{
Left = workingArea.Left + AnchorDistance;
}
else if ((anchor & SnapLocation.Right) != 0)
{
Left = workingArea.Right - AnchorDistance - Width;
}
if ((anchor & SnapLocation.Top) != 0)
{
Top = workingArea.Top + AnchorDistance;
}
else if ((anchor & SnapLocation.Bottom) != 0)
{
Top = workingArea.Bottom - AnchorDistance - Height;
}
_snapAnchor = anchor;
}
private bool InSnapRange(int a, int b)
{
return Math.Abs(a - b) < SnapDistance;
}
private SnapLocation FindSnap(ref Rectangle effectiveBounds)
{
Screen currentScreen = Screen.FromPoint(effectiveBounds.Location);
Rectangle workingArea = currentScreen.WorkingArea;
SnapLocation anchor = SnapLocation.None;
if (InSnapRange(effectiveBounds.Left, workingArea.Left + AnchorDistance))
{
effectiveBounds.X = workingArea.Left + AnchorDistance;
anchor |= SnapLocation.Left;
}
else if (InSnapRange(effectiveBounds.Right, workingArea.Right - AnchorDistance))
{
effectiveBounds.X = workingArea.Right - AnchorDistance - effectiveBounds.Width;
anchor |= SnapLocation.Right;
}
if (InSnapRange(effectiveBounds.Top, workingArea.Top + AnchorDistance))
{
effectiveBounds.Y = workingArea.Top + AnchorDistance;
anchor |= SnapLocation.Top;
}
else if (InSnapRange(effectiveBounds.Bottom, workingArea.Bottom - AnchorDistance))
{
effectiveBounds.Y = workingArea.Bottom - AnchorDistance - effectiveBounds.Height;
anchor |= SnapLocation.Bottom;
}
return anchor;
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WmEnterSizeMove:
case WmSize:
// Need to handle window size changed as well when
// un-maximizing the form by dragging the title bar.
_dragOffsetX = Cursor.Position.X - Left;
_dragOffsetY = Cursor.Position.Y - Top;
break;
case WmMoving:
LtrbRectangle boundsLtrb = Marshal.PtrToStructure<LtrbRectangle>(m.LParam);
Rectangle bounds = boundsLtrb.ToRectangle();
// This is where the window _would_ be located if snapping
// had not occurred. This prevents the cursor from sliding
// off the title bar if the snap distance is too large.
Rectangle effectiveBounds = new Rectangle(
Cursor.Position.X - _dragOffsetX,
Cursor.Position.Y - _dragOffsetY,
bounds.Width,
bounds.Height);
_snapAnchor = FindSnap(ref effectiveBounds);
LtrbRectangle newLtrb = LtrbRectangle.FromRectangle(effectiveBounds);
Marshal.StructureToPtr(newLtrb, m.LParam, false);
m.Result = new IntPtr(1);
break;
}
base.WndProc(ref m);
}
}
}
```
And here's what it looks like:
[](https://i.stack.imgur.com/2BPFH.gif) | How to make my Windows Form app snap to screen edges? | [
"",
"c#",
"windows",
"winforms",
".net-2.0",
""
] |
Is there a standard c# class that defines a notional Left, Right, Top and Bottom?
Should I just use my own?
```
enum controlAlignment
{
left = 1,
top,
right,
bottom,
none = 0
}
``` | Perhaps System.Windows.Forms.AnchorStyles or System.Windows.Forms.DockStyles could do the job. | A quick search revealed that the following Framework Enumerations already have these members (some have other additional members) :
* AnchorStyles - System.Windows.Forms
* Border3DSide - System.Windows.Forms
* DockStyle - System.Windows.Forms
* Edges - System.Windows.Forms.VisualStyles
* TabAlignment - System.Windows.Forms
* ToolStripStatusLabelBorderSides - System.Windows.Forms
* VerticalAlignment - System.Windows.Forms.VisualStyles | C# standard class (enumeration?) for Top, Bottom, Left, Right | [
"",
"c#",
""
] |
I know how to map a list to a string:
```
foostring = ",".join( map(str, list_of_ids) )
```
And I know that I can use the following to get that string into an IN clause:
```
cursor.execute("DELETE FROM foo.bar WHERE baz IN ('%s')" % (foostring))
```
How can I accomplish the same thing *safely* (avoiding [SQL injection](https://SQL%20injection)) using a MySQL database?
In the above example, because foostring is not passed as an argument to execute, it is vulnerable. I also have to quote and escape outside of the MySQL library.
(There is a [related Stack Overflow question](https://stackoverflow.com/questions/315672/automagically-expanding-a-python-list-with-formatted-output), but the answers listed there either do not work for MySQL database or are vulnerable to SQL injection.) | Use the `list_of_ids` directly:
```
format_strings = ','.join(['%s'] * len(list_of_ids))
cursor.execute("DELETE FROM foo.bar WHERE baz IN (%s)" % format_strings,
tuple(list_of_ids))
```
That way you avoid having to quote yourself, and avoid all kinds of [SQL injection](https://en.wikipedia.org/wiki/SQL_injection).
Note that the data (`list_of_ids`) is going directly to MySQL's driver, as a parameter (not in the query text) so there isn't any injection. You can leave any characters you want in the string; there isn't any need to remove or quote characters. | [The accepted answer](https://stackoverflow.com/questions/589284/imploding-a-list-for-use-in-a-python-mysql-in-clause/589416#589416) gets messy when we have a lot of the parameters or if we want to use named parameters.
After some trials,
```
ids = [5, 3, ...] # List of ids
cursor.execute('''
SELECT
...
WHERE
id IN %(ids)s
AND created_at > %(start_dt)s
''', {
'ids': tuple(ids), 'start_dt': '2019-10-31 00:00:00'
})
```
It was kested with Python 2.7 and pymysql 0.7.11. | Imploding a list for use in a Python MySQL IN clause | [
"",
"python",
"mysql",
""
] |
I am using Tomcat to compress my HTML content like this:
```
<Connector port="8080" maxHttpHeaderSize="8192"
maxProcessors="150" maxThreads="150" minSpareThreads="25"
maxSpareThreads="75" enableLookups="false" redirectPort="8443"
acceptCount="150" connectionTimeout="20000" disableUploadTimeout="true"
compression="on" compressionMinSize="128" noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html"
URIEncoding="UTF-8" />
```
In the HTTP header (as observed via YSlow), however, I am not seeing
```
Content-Encoding: gzip
```
resulting in a poor YSlow score.
All I see is
```
HeadersPost
Response Headers
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-US
Content-Length: 5251
Date: Sat, 14 Feb 2009 23:33:51 GMT
```
I am running an apache mod\_jk Tomcat configuration.
How do I compress HTML content with Tomcat, and also have it add "Content-Encoding: gzip" in the header? | Have a look at [<http://sourceforge.net/projects/pjl-comp-filter/>](http://sourceforge.net/projects/pjl-comp-filter/).
Other custom solutions may have memory leaks.
Also, if you are using mod\_jk then you are certainly not using the 8080 connector (which supports compression) for those requests. | Tomcat will be doing the compression. However because you are using `mod_jk` I guess you are getting you requests via Apache on port 80 rather than tomcat on port `8080`. As an experiment try getting your page via port 8080 and then checking `yslow` you should see the correct headers.
I think what is happening is that apache is unzipping the content that it is getting from tomcat via `mod_jk` and then passing the deflated content on to the browser.
If you wish to use `mod_jk` then you will need to set up your compression on Apache rather than Tomcat. | Tomcat Compression Does Not Add a Content-Encoding: gzip in the Header | [
"",
"java",
"tomcat",
"gzip",
"yslow",
""
] |
I have a database table. It has several hundred entries and each entry is timestamped. I'm looking to only output each day and not have it duplicate any days.
Data:
2009-02-04 06:20:27
2009-02-04 06:20:27
2009-02-05 06:20:27
2009-02-07 06:20:27
2009-02-07 06:20:27
2009-02-07 06:20:27
Output should only be (time is irrelevant):
2009-02-04 06:20:27
2009-02-05 06:20:27
2009-02-07 06:20:27
What is the best way to accomplish this? Should I really be cycling through each row and comparing one from another? Just doesn't seem efficient. Any ideas/tips? | You would want to do this on the database level using the mysql DISTINCT keyword:
```
SELECT DISTINCT date
FROM table
```
This will make it so if there are duplicate dates, only one is returned. Read more about it [here](http://www.webdevelopersnotes.com/tutorials/sql/online_mysql_guide_the_distinct_keyword.php3). | can't you just select for a "DISTINCT" timestamp in your query?
Or if the times vary on each day (not sure from your example) you can convert the timestamp column to just a date of the fly using the mysql DATE function. Keep in mind this may prevent use of an index if it's used on that column.
eg.
```
SELECT DISTINCT DATE(timestamp_column) FROM table
```
This will remove the time part of the timestamp. | Best way to calculate dates from results? | [
"",
"php",
"mysql",
"sorting",
"timestamp",
"date",
""
] |
I'm looking for things that might trigger the following PHP warning:
> PHP Warning: Cannot modify header
> information - headers already sent in
> Unknown on line 0 | Turned out that it was the line
```
ob_start("ob_gzhandler");
```
that caused the warning. This has been [reported and fixed in 2001](http://bugs.php.net/bug.php?id=9031), it seems, but for some reason it keeps coming back. | I think whats happening is one of the built in php functions is outputting something. I've seen this with a couple of the IMAP functions where they out put just a " " (space character) and it screws things up.
You can thry tracking it down using Xdebug or the Zend debugger, but i f you have neither
try wrapping output buffering around some of the functions you think may be cause it.
```
ob_start();
callYourFunction();
ob_end_clean();
```
Do this one function at a time and when the error goes away you'll know which function is cause you the problem, then you can either file a bug report or just leave it in as a hack. But at least then you know what function is cause the issue.
**Edit: The fact that is says your output is occurring on line 0 means that it's a C level function doing the output, not any code that's been written using PHP.** | PHP warning: headers already sent in Unknown | [
"",
"php",
"error-reporting",
""
] |
I have been asked to test a library provided by a 3rd party. The library is known to be accurate to *n* significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:
```
def nearlyequal(a, b, sigfig=5):
```
The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to **sigfig** significant-figures when written in decimal.
Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:
```
assert nearlyequal(1, 1, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(-1e-9, 1e-9, 5)
assert nearlyequal(1e9, 1e9 + 1 , 5)
assert not nearlyequal(1e4, 1e4 + 1, 5)
assert nearlyequal(0.0, 1e-15, 5)
assert not nearlyequal(0.0, 1e-4, 6)
```
Additional notes:
1. Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.
2. Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.
3. Speed... I've got to compare a lot of numbers so the faster the better.
4. I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project. | There is a function `assert_approx_equal` in `numpy.testing` (source [here)](https://github.com/numpy/numpy/blob/1225aef37298ec82048d0828f6cb7e0be8ed58cc/numpy/testing/utils.py#L513) which may be a good starting point.
```
def assert_approx_equal(actual, desired, significant=7, err_msg='', verbose=True):
"""
Raise an assertion if two items are not equal up to significant digits.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
comparisons.
Given two numbers, check that they are approximately equal.
Approximately equal is defined as the number of significant digits
that agree.
``` | As of Python 3.5, the standard way to do this (using the standard library) is with the [`math.isclose`](https://docs.python.org/3/library/math.html#math.isclose) function.
It has the following signature:
```
isclose(a, b, rel_tol=1e-9, abs_tol=0.0)
```
An example of usage with absolute error tolerance:
```
from math import isclose
a = 1.0
b = 1.00000001
assert isclose(a, b, abs_tol=1e-8)
```
If you want it with precision of ***n*** significant digits, simply replace the last line with:
```
assert isclose(a, b, abs_tol=10**-n)
``` | Function to determine if two numbers are nearly equal when rounded to n significant decimal digits | [
"",
"python",
"math",
"floating-point",
"numpy",
""
] |
I am looking for a Python library which does Bayesian Spam Filtering. I looked at SpamBayes and OpenBayes, but both seem to be unmaintained (I might be wrong).
Can anyone suggest a good Python (or Clojure, Common Lisp, even Ruby) library which implements Bayesian Spam Filtering?
Thanks in advance.
**Clarification**: I am actually looking for a *Bayesian Spam Classifier* and not necessarily a spam filter. I just want to train it using some data and later tell me whether some given data is spam. Sorry for any confusion. | Do you want spam filtering or Bayesian classification?
For Bayesian classification there are a number of Python modules. I was just recently reviewing [Orange](http://www.ailab.si/orange/) which looks very impressive. R has a number of Bayesian modules. You can use [Rpy](http://rpy.sourceforge.net/) to hook into R. | Try [Reverend](http://bazaar.launchpad.net/~divmod-dev/divmod.org/trunk/files/head:/Reverend/). It's a spam filtering module. | Bayesian spam filtering library for Python | [
"",
"python",
"spam-prevention",
"bayesian",
"bayesian-networks",
""
] |
```
File "C:\Python25\lib\SocketServer.py", line 330, in __init__
self.server_bind()
File "C:\Python25\lib\BaseHTTPServer.py", line 101, in server_bind
SocketServer.TCPServer.server_bind(self)
File "C:\Python25\lib\SocketServer.py", line 341, in server_bind
self.socket.bind(self.server_address)
File "<string>", line 1, in bind
socket.error: (10013, 'Permission denied')
```
I tried to start up the Google App Engine development server and received this error the first time I tried to run it. Any ideas? I'm new to python. | It might be possible that you are trying to run on a port the current user account does not have permission to bind to. This could be port 80 or something. Try increasing the portnumber or use a user with sufficient privileges.
Hope this helps | > I wonder why the error is not "Port
> already in use". I kind of know the
> answer but I should not need to use SO
> to know it. :) – Oscar Reyes May 13 at
> 19:09
The port is not in use, (in UNIX) you need to be superuser to listen on any port < 1024. | What causes Python socket error? | [
"",
"python",
"sockets",
"permissions",
""
] |
**Question:**
* What is the **difference** between:
+ `vector<string>` and `vector<char *>`?
* How would I pass a value of data type: `string` to a function, that specifically accepts:
+ `const char *`?
For **instance**:
```
vector<string> args(argv, argv + argc);
vector<string>::iterator i;
void foo (const char *); //*i
```
* I understand using `vector<char *>`: I'll have to copy the data, as well as the pointer
### Edit:
Thanks for input! | This really has nothing to do with vectors specifically.
A `char*` is a pointer, which may or may not point to valid string data.
A [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string) is a string class, encapsulating all the required data that makes up a string, along with allocation and deallocation functionality.
If you store `std::string`'s in a vector, or anywhere else, then everything will *just work*.
If you store char pointers, you have to do all the hard work of allocating and freeing memory, and ensuring the pointers only ever point to meaningful string data, and determine the length of the strings and so on.
And since `char*`'s are expected by a lot of C API's as well as part of the C++ standard library, the `string` class has the `c_str()` function which returns a `char*`. | To pass a `string` to something expecting `const char *`, use the `string`'s `c_str()` member, which returns a null-terminated string:
```
string s = "foobar";
int n = strlen( s.c_str() );
``` | vector<string> or vector<char *>? | [
"",
"c++",
"string",
"visual-studio-2008",
"pointers",
"char",
""
] |
I am currently trying to modify a Javascript function that "slides in" a <div>. The script as it is requires you to define the height of the div, so it is mostly useless in dynamically filled <div>s. I found some text on the clientHeight property in javascript, but it would appear that it doesn't support <div>s with display set to none (which is the method used to slide the div in). That makes sense, as the height of that div in the client window is nothing.
Basically I was wondering what other methods you all know of, or if there's a way to get around the clientHeight = 0 when display: none.
Thanks!
Oh, and here's the function I'm using:
```
function getDivHeight(objName) {
return boxHeight = document.getElementById(objName).clientHeight;
}
``` | A simple solution is to set it's visibility to "hidden" and it's display to "block" and measure it. However, some modern browsers will manage to update the page layout during this short time and you will get a nasty flicker. The easiest way to overcome this is to place the element in an absolutely positioned container with overflow set to "hidden". | I've had luck cloning the element, moving it offscreen, then displaying it to get the client height:
```
var original = document.getElementById(some_id);
var new_item = original.cloneNode(true);
document.body.appendChild(new_item); // item already hidden, so it won't show yet.
// you may wish to validate it is hidden first
new_item.style.position = "absolute";
new_item.style.left = "-1000px";
new_item.style.display = "block";
var height = new_item.clientHeight;
```
**EDIT:** Looking through the jQuery code, they do exactly what Tsvetomir Tsonev suggests. jQuery temporarily sets the style to "display: block; position: absolute; visibility: none", and then measures the height, swapping the properties back after the measurement.
So, it looks like you're stuck with having to do something hackish, whether it's cloning the node or risking having it flicker in some browsers... I like Tsvetomir's suggestion better than my initial hack as it, at least, doesn't involve cloning a node into the DOM that you don't need. Either way, the element must not be set to "display: none" in order to measure it's height. Isn't the DOM wonderful? :-)
**EDIT 2:** Also worth noting that, after jQuery gathers the height, it adds allowances for padding, margin and border sizes, so you may need to as well. | Javascript clientHeight and alternatives | [
"",
"javascript",
"html",
"css",
""
] |
I have a aspx page that looks something like this:
```
<tr id="Row1">
<td>Some label</td>
<td>Some complex control</td>
</tr>
<tr id="Row2">
<td>Some label</td>
<td>Some complex control</td>
</tr>
<tr id="Row3">
<td>Some label</td>
<td>Some complex control</td>
</tr>
```
As soon as the page is loaded, I would want to reorder these rows based on the user's previously selected order (stored in a database)
How would I use JQuery/JS to accomplish this?
EDIT:
I have run into a performance issue with the appendTo code. It takes 400ms for a table of 10 rows which is really unacceptable. Can anyone help me tweak it for performance?
```
function RearrangeTable(csvOrder, tableId)
{
var arrCSVOrder = csvOrder.split(',');
//No need to rearrange if array length is 1
if (arrCSVOrder.length > 1)
{
for (var i = 0; i < arrCSVOrder.length; i++)
{
$('#' + tableId).find('[fieldname = ' + arrCSVOrder[i] + ']').eq(0).parents('tr').eq(0).appendTo('#' + tableId);
}
}
}
``` | Just do something like this:
Say you have table like so:
```
<table id='table'>
<tr id='row1'><td> .... </td></tr>
<tr id='row2'><td> .... </td></tr>
<tr id='row3'><td> .... </td></tr>
<tr id='row4'><td> .... </td></tr>
</table>
```
And an array with the new order like this:
```
NewOrder[1] = 3;
NewOrder[2] = 4;
NewOrder[3] = 2;
```
Then, do some something like this (not tested, so you may need to tweak the code, but this is the idea):
```
for ( i=1; i<=NewOrder.length; i++ ) {
$('#row'+i).appendTo( '#table' );
}
```
This way, they are moved to the end of the table in order.
So you will have 3 moved to the end, then 4 behind it, then 2 behind that, etc. After they have **ALL** been appended to the end of the table, the first one will become the first row, and the rest will be in the correct order behind it.
**Edit:**
Make the table style='display:none;' and then do $('#table').show(); at startup.
**Edit Again:**
You could do a div around the entire body content, like
```
<body>
<div id='everything' style='display:none;'>
....
</div>
</body>
```
So that the entire page will be hidden (just blank white) for the fraction of a second it takes to load and order the table.
Then you would use:
```
$(function(){
$('#everything').show();
}
```
To show the entire page all at once as soon as the DOM is ready. It will take a fraction of a second longer for the page to load, but it will all load at once, so there won't be any flash of missing tables, etc. As long as EVERYTHING is in #everything, it will just look like the page loaded - should be transparent to the viewer. | Try the jQuery [tablesorter plugin](http://tablesorter.com/docs/).
When the document loads you can sort the table by specifying the column index to sort on (and it allows sorting by multiple columns):
```
$(document).ready(function()
{
$("#myTable").tablesorter( {sortList: [[0,0], [1,0]]} );
}
);
``` | JQuery/Javascript Reordering rows | [
"",
"javascript",
"jquery",
""
] |
[A previous question](https://stackoverflow.com/questions/69738/c-how-to-get-fprintf-results-as-a-stdstring-w-o-sprintf#69911) showed a nice way of printing to a string. The answer involved va\_copy:
```
std::string format (const char *fmt, ...);
{
va_list ap;
va_start (ap, fmt);
std::string buf = vformat (fmt, ap);
va_end (ap);
return buf;
}
std::string vformat (const char *fmt, va_list ap)
{
// Allocate a buffer on the stack that's big enough for us almost
// all the time.
s ize_t size = 1024;
char buf[size];
// Try to vsnprintf into our buffer.
va_list apcopy;
va_copy (apcopy, ap);
int needed = vsnprintf (&buf[0], size, fmt, ap);
if (needed <= size) {
// It fit fine the first time, we're done.
return std::string (&buf[0]);
} else {
// vsnprintf reported that it wanted to write more characters
// than we allotted. So do a malloc of the right size and try again.
// This doesn't happen very often if we chose our initial size
// well.
std::vector <char> buf;
size = needed;
buf.resize (size);
needed = vsnprintf (&buf[0], size, fmt, apcopy);
return std::string (&buf[0]);
}
```
}
The problem I'm having is that the above code doesn't port to Visual C++ because it doesn't provide va\_copy (or even \_\_va\_copy). So, does anyone know how to safely port the above code? Presumably, I need to do a va\_copy copy because vsnprintf destructively modifies the passed va\_list. | You should be able to get away with just doing a regular assignment:
```
va_list apcopy = ap;
```
It's technically non-portable and undefined behavior, but it will work with most compilers and architectures. In the x86 calling convention, `va_list`s are just pointers into the stack and are safe to copy. | For Windows, you can simply define va\_copy yourself:
```
#define va_copy(dest, src) (dest = src)
``` | va_copy -- porting to visual C++? | [
"",
"c++",
"c",
"visual-studio-2008",
"visual-c++",
""
] |
Assuming the following data:
```
Column1 (data type: varchar(50))
--------
11.6
-1
1,000
10"
Non-Numeric String
```
I have a query, which is pulling data from this column and would like to determine if the value is a number, then return it as such in my query. So I am doing the following
```
SELECT CASE
WHEN IsNumeric(Replace(Column1, '"', '')) = 1 THEN Replace(Column1, '"', '')
ELSE 0
END AS NumericValue
```
SQL is reporting back:
> Conversion failed when converting the varchar value '11.6' to data type int.
Why? I have also tried to force cast this:
```
SELECT CASE
WHEN IsNumeric(Replace(Column1, '"', '')) = 1 THEN cast(Replace(Column1, '"', '') AS float)
ELSE 0
END AS NumericValue
```
And I got:
> Error converting data type varchar to float. | You need to replace comma with a period:
```
CAST(REPLACE(column, ',', '.') AS FLOAT)
```
`SQL Server` outputs decimal separator defined with locale, but does not unterstand anything but a period in `CAST`s to numeric types. | First convert the string to money, then covert it to any other numeric format since money type gives a true numeric string always. You will never see an error then.
Try the following in your query, and you'll know what I am talking about. Both will return 2345.5656. The Money datatype is rounded to 4 decimal places, and hence the casting causes rounding to 4 decimal places.
```
SELECT CAST('2,345.56556' as money), CAST('$2,345.56556' as money)
```
Cast( cast('2,344' as money) as float) will work perfectly or
cast( cast('2,344' as money) as decimal(7,2)) will also work.
Even cast(CAST('$2,345.56556' as money) as int ) will work perfectly rounding it to nearest integer. | SQL IsNumeric Returns True but SQL Reports 'Conversion Failed' | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have an ASP.NET WebForms application that has a feature that requires the user to provide data in multiple steps. This is currently implemented using multiple pages. So, the user visits step1.aspx, provides some information, and then is redirected to step2.aspx to provider additional information.
The objects that are manipulated as part of this process are stored in a generic List<> object. I'm currently storing this List<> in a Session variable so that the state of the objects is maintained between pages. Once the process is complete the data is sent to a web service api exposed by another application. I don't want to maintain the state of this data in a database between posts, preferring to keep it in memory until it gets submitted to the web service.
I'm in the process of extracting this logic out of the web application into it's own class library so we can use the same library from a windows application.
What are the best practices for maintaining this data between posts after extracting the business logic to a self-contained class library? | If you want to have the library responsible for managing it's own state you could use a IoC pattern and inject a class which will handle the state for the data. So for example imagine you have:
```
class MyWizardLogic
{
public void DoStep1()
{
}
}
```
Now we can define a new interface call it a StateProvider because it provides state:
```
interface IStateProvider
{
List<WizState> CurrentState{get;set;}
}
```
Now what you need to do is to tell the MyWizardLogic to use IStateProvider there are lots of choices if you want to use a DI framework but lets keep this simple. You can create a SessionStateProvider class which will store the List to session. And you could create a second WinFormsStateProvider class which will store the List in a static variable or some other appropiate place.
I would create these class in their respective projects. These class shouldn't be part of the BL library.
Now you can modify your DoStep1() method to take a parameter of IStateProvider. This will let your web or winform app specify which IStateProvider to use. Additionally you could set it via a property or in the constructor. I prefer using a constructor typically.
Now your all set for your client to control the BL dependancies. This should also help make testing easier. For example you could write a mock state provider which validates that it is being called correctly. | With ASP.NET, you have a few options. You could store it in session state, but that quickly becomes a problem because of multiple browser windows in the same session.
That leaves passing the data input on one page from page to page.
You could encode the data in the query string and append it to the URL, but depending on the size of the data, that could get pretty long and unwieldy.
That leaves posting the data. You can start with the first form and have it post to the second form. The second form encodes the data from the first form in a hidden field, and then passes it's data and the hidden field data to the next form, etc, etc.
Then, on the page after the last form (that processes everything) you have all of your data for the separate steps. | Maintain List<> state across page boundaries in ASP.Net | [
"",
"c#",
"asp.net",
""
] |
I have a program that gets a string from a method.
I want to know how to insert a string value to that string at certain positions.
For example:
```
mystring = "column1 in('a','b')column2 in('c','d')column3 in('e','f')";
```
Here, how would I insert the string value " and " after every occurance of the character ')' in `mystring`?
PS. If possible, also include how not to insert it right at the end. | You could accomplish this with replace..
```
string mystring = "column1 in('a','b')column2 in('c','d')column3 in('e','f')";
mystring = mystring.Replace(")", ") and ").TrimEnd(" and".ToCharArray());
```
Resulting In:
```
"column1 in('a','b') and column2 in('c','d') and column3 in('e','f')"
``` | Probably the simplest:
```
mystring = mystring.Replace(")", ") and ");
mystring = mystring.Substring(0, mystring.Length - " and ".Length);
``` | How to insert a value in a string at certain positions c# | [
"",
"c#",
"string",
""
] |
I love the Beautiful Soup scraping library in Python. It just works. Is there a close equivalent in Ruby? | This page from [Ruby Toolbox](https://www.ruby-toolbox.com/categories/html_parsing) includes a chart of the relative popularity of various parsers. | [Nokogiri](https://nokogiri.org/) is another HTML/XML parser. It's faster than hpricot according to [these benchmarks](http://gist.github.com/18533). Nokogiri uses libxml2 and is a drop in replacement for hpricot. It also has css3 selector support which is pretty nice.
Edit: There's a new benchmark comparing nokogiri, libxml-ruby, hpricot and rexml [here](http://www.rubyinside.com/ruby-xml-performance-benchmarks-1641.html).
[Ruby Toolbox](http://www.ruby-toolbox.com/) has a category on HTML parsers [here](http://www.ruby-toolbox.com/categories/html_parsing.html). | What's the nearest equivalent of Beautiful Soup for Ruby? | [
"",
"python",
"ruby",
"beautifulsoup",
""
] |
I'm trying to forward my IDE, Netbeans, over ssh to the Xming server on my Windows Desktop. I'm able to get Netbeans to launch and run, but the fonts look terrible because they aren't being anti-aliased. I've uploaded a screenshot [here](http://www.compucatedsolutions.com/~jmc/badnetbeans.jpg).
If I launch Netbeans from Gnome on the linux box itself, the fonts look fine, so it must be a problem with Xming or the Windows font rendering. Does anyone have any ideas about how to get Xming to display the fonts anti-aliased?
**Update:**
I just setup a font server on the host, but the fonts still appear pixelated on the client side. | I ended up setting some of the netbeans command line options in the launcher script to force anti aliasing and force subpixel font rendering. This fixed the issue.
**Update: Added Steps**
I set the netbeans\_default\_options under /etc/netbeans.conf to read:
```
netbeans\_default\_options="-J-client -J-Xss2m -J-Xms32m -J-XX:PermSize=32m -J-XX:MaxPermSize=200m -J-Xverify:none -J-Dapple.laf.useScreenMenuBar=true -J-Dawt.useSystemAAFontSettings=lcd"
``` | Java is a bit weird on Linux as to how it decides whether to anti-alias or not.
It seems to detect if KDE or GNOME are running, and if not, decides not to bother.
If you want another solution, try making sure that "gnome-settings-daemon" is running before launching netbeans. | Netbeans Forwarded over X11 Font Problem | [
"",
"java",
"netbeans",
"fonts",
"x11",
"xming",
""
] |
> **Possible Duplicate:**
> [Way to have compiled python files in a separate folder?](https://stackoverflow.com/questions/471928/way-to-have-compiled-python-files-in-a-separate-folder)
When python compiles modules to bytecode, it produces .pyc files from your .py files.
My question is, is it possible to have these .pyc files written to a different directory than where the module resides?
For example, I have a large directory of modules. Rather than having it littered with .pyc files, I would like to keep my source code in the directory and have a subdirectory like "bytecode" where all of the .pyc are stored.
Is this possible? | This is answered in "[Way to have compiled python files in a seperate folder?](https://stackoverflow.com/questions/471928/way-to-have-compiled-python-files-in-a-seperate-folder)"
Short answer: **No** – unless you're running Python 3.2 or later – see [here](https://stackoverflow.com/a/16476434/66851).
To clarify: Before 3.2, you *can* compile bytecode and put it elsewhere as per Brian R. Bondy's suggestion, but unless you actually run it from there (and not from the folder you want to keep pristine) Python will still output bytecode where the .py files are. | Check the [py\_compile module](http://docs.python.org/library/py_compile.html#module-py_compile), and in particular:
```
py_compile.compile(file[, cfile[, dfile[, doraise]]])
```
The cfile is the parameter you are interested in.
From the link above:
> ...The byte-code is written to cfile,
> which defaults to file + 'c'... | Can compiled bytecode files (.pyc) get generated in different directory? | [
"",
"python",
"bytecode",
""
] |
I'm trying to use a std::vector<>::const\_iterator and I get an 'access violation' crash. It looks like the std::vector code is crashing when it uses its own internal `First_` and `Last_` pointers. Presumably this is a known bug. I'm hoping someone can point me to the correct workaround. It's probably relevant that the crashing function is called from an external library?
```
const Thing const* AClass::findThing (const std::string& label) const
{
//ThingList_.begin() blows up at run time. Compiles fine.
for (std::vector<Thing*>::const_iterator it = ThingList_.begin(); it != ThingList_.end(); ++it) {
//Irrelevant.
}
return 0;
}
```
Simply calling `ThingList_.size()` also crashes.
This is sp6, if it matters. | If you're passing C++ objects across external library boundaries, you must ensure that all libraries are using the same runtime library (in particular, the same heap allocator). In practice, this means that all libraries must be linked to the DLL version of MSVCRT. | It's almost certainly a bug in your code and not std::vector. This code is used by way too many projects to have such an easy to repro bug.
What's likely happening is that the ThnigList\_ variable has been corrupted in some way. Was the underlying array accessed directly and/or modified? | VC++ 6.0 vector access violation crash. Known bug? | [
"",
"c++",
"visual-c++-6",
""
] |
I have a class with a static method that looks roughly like:
```
class X {
static float getFloat(MyBase& obj) {
return obj.value(); // MyBase::value() is virtual
}
};
```
I'm calling it with an instance of MyDerived which subclasses MyBase:
```
MyDerived d;
float f = X::getFloat(d);
```
If I link the obj file containing X into my executable, everything works as expected. If I'm expecting to get 3.14, I get it.
If I create a .lib that contains the X.obj file and link in the .lib, it breaks. When I call getFloat(), it's returning **-1.#IND00**. Is this some type of sentinel value that should tell me what's wrong here?
Is anything different when you link in a lib rather than an obj directly?
I don't get any compiler warnings or errors.
**Edit:**
I'm using Visual Studio 2005 on Windows XP Pro SP3. To make sure I wasn't linking old files, I cloned the value() method into a new value2() method and called that instead. The behavior was the same.
**Edit #2:**
So, if I trace into the call with my debugger, I'm finding that it isn't going into my value() method at all. Instead it's going into a different (unrelated) method. This makes me think my vtable is corrupted. I think the behavior I'm seeing must be a side effect of some other problem.
---
**Solved!** (thanks to Vlad)
It turns out I was violating the one definition rule (ODR) although it wasn't evident from the code I posted. [This](http://blogs.msdn.com/vcblog/archive/2007/05/17/diagnosing-hidden-odr-violations-in-visual-c-and-fixing-lnk2022.aspx) is a great article from the Visual C++ guys that explains the problem and one way to track it down. The */d1reportSingleClassLayout* compiler flag is a fantastic learning tool.
When I dumped out the my class layout for MyBase and MyDerived in the two different projects, I found differences between the calling code and the library code. It turns out I had some *#ifdef* blocks in my header files and the corresponding *#define* statement was in the precompiled header for the main project but not in the subproject (the library). Have I mentioned how evil I think preprocessor macros are?
Anyway, I'm only posting this stuff because it might be helpful to somebody else. [This question](https://stackoverflow.com/questions/302446/how-can-one-inspect-a-vtable-in-visual-c) was also very helpful to me. | This problem will occur when the lib and the executable have been be compiled with **different definitions of the `MyDerived` class** (i.e. different versions of the `.h`/`.hh`/`.hpp` file that declares `MyDerived`. Completely clean and rebuild your projects. Barring this, different compiler options *could* be responsible, though it is somewhat unlikely.
If the problem persists after rebuilding everything from scratch, then nail it by instantiating a dummy `MyDerived` object inside `getFloat`, in the library. Use the debugger to compare the `vtable` of the dummy `MyDerived` (instantiated in the library) and the `vtable` of the `MyDerived` object reference passed as parameter (instantiated in the executable.) Something should spring to eye right away. | Since a lib is just a container, if you are linking the same .obj file in both cases then as Brian says they shouldn't (can't?) be a difference.
One thing to watch is if you changed the definition of MyBase you obviously need to recompile both the library and the code using it. For example, if you added a new virtual method to MyBase before the value method, then that would mess up the library since the v-table offset of value would be different. | Problem calling a function when it is in a .lib | [
"",
"c++",
"virtual",
""
] |
### Duplicate
> [Regex for variable declaration and initialization in c#](https://stackoverflow.com/questions/585853/regex-for-variable-declaration-and-initialization-in-c)
I was looking for a Regular Expression to parse CSV values, and I came across this Regular Expression
```
[^,]+
```
Which does my work by splitting the words on every occurance of a ",". What i want to know is say I have the string
> value\_name v1,v2,v3,v4,...
Now I want a regular expression to find me the words v1,v2,v3,v4..
I tried ->
```
^value_name\s+([^,]+)*
```
But it didn't work for me. Can you tell me what I am doing wrong? I remember working on regular expressions and their statemachine implementation. Doesn't it work in the same way.
If a string starts with Value\_name followed by one or more whitespaces. Go to Next State. In That State read a word until a "," comes. Then do it again! And each word will be grouped!
Am i wrong in understanding it? | You could use a Regex similar to those proposed:
```
(?:^value_name\s+)?([^,]+)(?:\s*,\s*)?
```
* The first group is non-capturing and would match the start of the line and the `value_name`.
To ensure that the Regex is still valid over all matches, we make that group optional by using the `'?'` modified (meaning *match at most once*).
* The second group is capturing and would match your `vXX` data.
* The third group is non-capturing and would match the `,`, and any whitespace before and after it.
Again, we make it optional by using the `'?'` modifier, otherwise the last `'vXX'` group would not match unless we ended the string with a final `','`.
In you trials, the Regex wouldn't match multiple times: you have to remember that if you want a Regex to match multiple occurrences in a strings, the whole Regex needs to match *every single occurrence* in the string, so you have to build your Regex not only to match the start of the string `'value_name'`, but also match every occurrence of `'vXX'` in it.
In C#, you could list all matches and groups using code like this:
```
Regex r = new Regex(@"(?:^value_name\s+)?([^,]+)(?:\s*,\s*)?");
Match m = r.Match(subjectString);
while (m.Success) {
for (int i = 1; i < m.Groups.Count; i++) {
Group g = m.Groups[i];
if (g.Success) {
// matched text: g.Value
// match start: g.Index
// match length: g.Length
}
}
m = m.NextMatch();
}
``` | I would expect it only to get v1 in the group, because the first comma is "blocking" it from grabbing the rest of the fields. How you handle this is going to depend on the methods you use on the regular expression, but it may make sense to make two passes, first grab all the fields seperated by commas and then break things up on spaces. Perhaps `^value_name\s+(?:([^,]+),?)*` instead. | Extending [^,]+, Regular Expression in C# | [
"",
"c#",
"regex",
"csv",
""
] |
**Update: My current question is how can I get my code to read to the EOF starting from the beginning with each new search phrase.**
This is an assignment I am doing and currently stuck on. Mind you this is a beginner's programming class using Python.
```
jargon = open("jargonFile.txt","r")
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
result = jargon.readline().find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
searchPhrase = raw_input("Enter the search phrase: ")
jargon.close()
```
The assignment is to take a user's searchPhrase and find it in a file (jargonFile.txt) and then have it print the result (which is the line it occured and the character occurence). I will be using a counter to find the line number of the occurence but I will implement this later. For now my question is the error I am getting. I cann't find a way for it to search the entire file.
Sample run:
```
Enter the search phrase: dog
16
Enter the search phrase: hack
Cannot find this term.
Enter the search phrase:
```
"dog" is found in the first line however it is also found in other lines of the jargonFile (multiple times as a string) but it is only showing the first occurence in the first line. The string hack is found numerous times in the jargonFile but my code is setup to only search the first line. How may I go about solving this problem?
If this is not clear enough I can post up the assignment if need be. | Hmm, I don't know anything at all about Python, but it looks to me like you are not iterating through all the lines of the file for the search string entered.
Typically, you need to do something like this:
```
enter search string
open file
if file has data
start loop
get next line of file
search the line for your string and do something
Exit loop if line was end of file
```
So for your code:
```
jargon = open("jargonFile.txt","r")
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
<<if file has data?>>
<<while>>
result = jargon.readline().find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
<<result is not end of file>>
searchPhrase = raw_input("Enter the search phrase: ")
jargon.close()
```
Cool, did a little research on the page DNS provided and Python happens to have the "with" keyword. Example:
```
with open("hello.txt") as f:
for line in f:
print line
```
So another form of your code could be:
```
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
with open("jargonFile.txt") as f:
for line in f:
result = line.find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
searchPhrase = raw_input("Enter the search phrase: ")
```
Note that "with" automatically closes the file when you're done. | First you open the file and read it into a string with readline(). Later on you try to readline() from the string you obtained in the first step.
You need to take care what object (thing) you're handling: open() gave you a file "jargon", readline on jargon gave you the string "jargonFile".
So jargonFile.readline does not make sense anymore
Update as answer to comment:
Okay, now that the str error problem is solved think about the program structure:
```
big loop
enter a search term
open file
inner loop
read a line
print result if string found
close file
```
You'd need to change your program so it follows that descripiton
Update II:
SD, if you want to avoid reopening the file you'd still need two loops, but this time one loop reads the file into memory, when that's done the second loop asks for the search term. So you would structure it like
```
create empty list
open file
read loop:
read a line from the file
append the file to the list
close file
query loop:
ask the user for input
for each line in the array:
print result if string found
```
For extra points from your professor add some comments to your solution that mention both possible solutions and say why you choose the one you did. Hint: In this case it is a classic tradeoff between execution time (memory is fast) and memory usage (what if your jargon file contains 100 million entries ... ok, you'd use something more complicated than a flat file in that case, bu you can't load it in memory either.)
Oh and one more hint to the second solution: Python supports tuples ("a","b","c") and lists ["a","b","c"]. You want to use the latter one, because list can be modified (a tuple can't.)
```
myList = ["Hello", "SD"]
myList.append("How are you?")
foreach line in myList:
print line
```
==>
```
Hello
SD
How are you?
```
Okay that last example contains all the new stuff (define list, append to list, loop over list) for the second solution of your program. Have fun putting it all together. | AttributeError: 'str' object has no attribute 'readline' | [
"",
"python",
"file",
"readline",
""
] |
Its been YEARS since I did any PHP.
I am working in .NET but supposed to be teaming up with some PHP people. I'd really like to get up to speed a little in whats changed in the language and the IDE tools - but I really don't have the time nor energy to learn anything. I probably won't have to write any PHP, but I want to.
I'm looking therefore for some kind of videos [like these .NET ones](http://www.asp.net/learn/mvc-videos/video-422.aspx) where you get to see the IDE, the basic way of working etc. etc. I'm not looking for someone using notepad - I want something where I can see how real expert PHP programmers work. | the thing is that with PHP there is no single "the IDE" and "the way". there is a multitude of tools, frameworks, libraries, extensions, IDEs, plugins, etc.
my favourite IDE for PHP is **Aptana** and the nice thing about Aptana is that there is Aptana.tv: **<http://www.aptana.tv/>** which has very nice video-casts about all aspects of the IDE...
the Video **PHPEditorPart1** is quite close to what you're asking for. | Only thing I can suggest is the CodeIgniter how-to videos [here](http://codeigniter.com/tutorials/). It should give you a general idea how the architecture of a typical PHP app is layed out and how a coder goes about creating it.
Whatever you do, do NOT search for PHP on Youtube. | Where can I find videos of someone (who knows what they're doing) writing PHP? | [
"",
"php",
"video",
""
] |
I want to use the mail() function from my localhost. I have WAMP installed and a Gmail account. I know that the SMTP for Gmail is smtp.gmail.com and the port is 465 ([more info from gmail](http://mail.google.com/support/bin/answer.py?answer=78799)).
What I need to configure in WAMP so I can use the mail() function?
Thanks!! | Gmail servers use SMTP Authentication under SSL or TLS. I think that there is no way to use the `mail()` function under that circumstances, so you might want to check these alternatives:
* [PEAR::Mail](http://pear.php.net/package/Mail)
* [phpMailer](http://sourceforge.net/projects/phpmailer/)
* [Nette\Mail](https://github.com/nette/mail)
They all support SMTP auth under SSL.
You'll need to enable the `php_openssl` extension in your php.ini.
Additional Resources:
* [How to Send Email from a PHP Script Using SMTP Authentication](http://email.about.com/od/emailprogrammingtips/qt/et073006.htm) (using `PEAR::Mail`)
* [Send email using PHP with Gmail](http://deepakssn.blogspot.com/2006/06/gmail-php-send-email-using-php-with.html) (using *phpMailer*)
* [Mailing](https://doc.nette.org/en/2.3/mailing) using `Nette\Mail` | I've answered that here: [(WAMP/XAMP) send Mail using SMTP localhost](https://stackoverflow.com/questions/16830673/wamp-xamp-send-mail-using-smtp-localhost) (works not only GMAIL, but for others too). | How to configure WAMP (localhost) to send email using Gmail? | [
"",
"php",
"gmail",
"localhost",
"wamp",
""
] |
Playing around with creating a NetBeans plugin but I am making very little progress since the process of installing the module fails. What I am doing is right-clicking on the and choosing the 'Install/Reload in Development IDE' option and it fails with the following exception:
```
Enabling StandardModule:org.willcodejavaforfood.com jarFile: /Users/Erik/NetBeansProjects/module2/build/cluster/modules/org-willcodejavaforfood-com.jar...
java.io.IOException: Cannot enable StandardModule:org.willcodejavaforfood jarFile: /Users/Erik/NetBeansProjects/module2/build/cluster/modules/org-willcodejavaforfood.jar; problems: [Java > 1.6]
at org.netbeans.core.startup.ModuleSystem.deployTestModule(ModuleSystem.java:358)
at org.netbeans.core.startup.TestModuleDeployer.deployTestModule(TestModuleDeployer.java:68)
at org.netbeans.modules.apisupport.ant.InstallModuleTask.execute(InstallModuleTask.java:77)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
at sun.reflect.GeneratedMethodAccessor176.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:357)
at org.apache.tools.ant.Target.performTasks(Target.java:385)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)
at org.apache.tools.ant.Project.executeTarget(Project.java:1306)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
at org.apache.tools.ant.Project.executeTargets(Project.java:1189)
at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:273)
at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:499)
at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:151)
```
Using NetBeans 6.5 and running Java 1.6 on Mac OS X 10.5.6 | Apperently this is a NetBeans issue for Mac OS X...
[Answer from netbeans forums](http://forums.netbeans.org/viewtopic.php?p=26822#26822) | If you make a new NetBeans module project and simply run that does it work? (trying to narrow the issue down, and eliminating anything but the absolute basics is a good place to start) | Fail to install my NetBeans plugin | [
"",
"java",
"netbeans",
"netbeans-plugins",
""
] |
I am looking for a way to check on the life of a PHP session, and return the number of seconds a session has been "alive".
Is there a PHP function that I am missing out on? | I think there are two options neither are great but here they are.
1) If you have access to the file system you can check the creation timestamp on the session file.
2) Store the creation time in the session e.g.
```
session_start();
if( ! isset($_SESSION['generated'])) {
$_SESSION['generated'] = time();
}
``` | You could store the time when the session has been initialized and return that value:
```
session_start();
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
}
```
And for retrieving that information from an arbitrary session:
```
function getSessionLifetime($sid)
{
$oldSid = session_id();
if ($oldSid) {
session_write_close();
}
session_id($sid);
session_start();
if (!isset($_SESSION['CREATED'])) {
return false;
}
$created = $_SESSION['CREATED'];
session_write_close();
if ($oldSid) {
session_id($oldSid);
session_start();
}
return time() - $created;
}
``` | PHP: return life of current session | [
"",
"php",
"session",
""
] |
I have some strings in Java (originally from an Excel sheet) that I presume are in Windows 1252 codepage. I want them converted to Javas own unicode format. The Excel file was parsed using the JXL package, in case that matter.
I will clarify: apparently the strings gotten from the Excel file look pretty much like it already is some kind of unicode.
```
WorkbookSettings ws = new WorkbookSettings();
ws.setCharacterSet(someInteger);
Workbook workbook = Workbook.getWorkbook(new File(filename), ws);
Sheet s = workbook.getSheet(sheet);
row = s.getRow(4);
String contents = row[0].getContents();
```
This is where contents seems to contain something unicode, the åäö are multibyte characters, while the ASCII ones are normal single byte characters. It is most definitely not Latin1. If I print the "contents" string with printLn and redirect it to a hello.txt file, I find that the letter "ö" is represented with two bytes, C3 B6 in hex. (195 and 179 in decimal.)
[edit]
I have tried the suggestions with different codepages etc given below, tried converting from Cp1252 etc. There was some kind of conversion, because I would get some other kind of gibberish instead. As reference I always printed an "ö" string hand coded into the source code, to verify that there was not something wrong with my terminal or typefaces or anything. The manually typed "ö" always worked.
[edit]
I also tried WorkBookSettings as suggested in the comments, but I looked in the code for JXL and characterSet seems to be ignored by parsing code. I think the parsing code just looks at whatever encoding the XLS file is supposed to be in. | WorkbookSettings ws = new WorkbookSettings();
ws.setEncoding("CP1250");
Worked for me. | If none of the answer above solve the problem, the trick might be done like this:
```
String myOutput = new String (myInput, "UTF-8");
```
This should **decode** the incoming string, whatever its format. | Convert from Codepage 1252 (Windows) to Java, in Java | [
"",
"java",
"windows",
"unicode",
"codepages",
""
] |
Usually, if you need to set a style attribute in JavaScript, you say something like:
```
element.style.attribute = "value";
```
There are slight variations but usually the attribute name is a similar, albeit camelcased, version of the HTML attribute name.
The problem for me is that the float attribute doesn't work. Float is a keyword in JavaScript and so style.float makes all the JavaScript for the page break. I looked in MSDN, and it said to use styleFloat like so:
```
element.style.styleFloat = "value";
```
That only works in IE. Firefox, Safari, Chrome, Opera - none of them seem to have an answer. Where am I going wrong? There has to be a simple answer to this. | Use cssFloat as in...
```
element.style.cssFloat = "value";
```
That works in everything *except* IE 8 and older, but you can always detect the browser and switch, or just set them both. Unfortuantely, there is no way to set just one style value to work in all browsers.
So to summarize, everyone you need to set the float, just say:
```
element.style.styleFloat = "value";
element.style.cssFloat = "value";
```
That *should* work everywhere. | better:
```
element.style.styleFloat = element.style.cssFloat = "value";
``` | Is there a cross browser way of setting style.float in Javascript? | [
"",
"javascript",
""
] |
I was contemplating switching to Linux for C++ development, coming from a Windows environment. Is this a bad idea? My workplace uses Windows and Visual Studio for our projects (some C# and java too, but right now I'm only developing in C++). If they decide to put me on a C# project, would development still possible (mono?)? What are the difficulties in this sort of transition?
Would I have a problem working on their projects and vice versa? I read somewhere that there'd be problems with precompiled headers and such (we do use them), and encodings (tabs/spaces, line endings, etc)..
If it's not too hard to do this switch, how do I get started? IDE? vim+make?
Thanks.
By the way, we make MOSTLY windows software..
---
EDIT: Thanks guys, I guess that makes sense.. | That's a bad idea. I can see at least two reasons :
* Develop on the same OS you write software for
* Visual Studio rocks | Stick with Windows if you're developing for C++ and C#.
The Visual Studio debugger is absolutely brilliant, and it seems that most of the Linux IDEs aren't comparable (except Eclipse for Java stuff).
Also, the chances are that you'll be using a different compiler if you're on Linux, and that can cause *really* weird bugs. | Switching to Linux for Windows development, bad idea? | [
"",
"c++",
"windows",
"linux",
"cross-platform",
"development-environment",
""
] |
I am a systems guy and currently doing a part time web development project so am pretty new to it. I am trying to write a http client for www.portapower.com.
It will for certain items which are posted on the website and if they match a particular requirement it will print a message.
While trying to access this page:
<http://www.portapower.com/getbainfo.php?fclasscode=1&code=CB1831B.40H&fbrand=QUNFUg==>
The website redirects me to a default register page:
<http://www.portapower.com/defaregit.php>
Here is a snippet of what I coded:
```
CookieContainer myContainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://www.portapower.com/" + urlpart);
request.Credentials = new NetworkCredential("****", "******");
request.CookieContainer = myContainer;
request.PreAuthenticate = true;
request.Method = "POST";
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
Console.WriteLine(response.StatusCode);
Stream resStream = response.GetResponseStream();
Console.WriteLine(resStream.ToString());
```
I do have the username and password and it works fine when used from a browser. Please tell me if this a correct way to access a authenticated page. | It depends on how the website is authenticating users. If they are using basic authentication or Windows authentication, then you can set the [`Credentials` property](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.credentials.aspx) of the [`HttpWebRequest` class](http://msdn.microsoft.com/en-us/library/8y7x3zz2.aspx) to the username/password/domain information and it should work.
However, it sounds like you have to enter the username/password on the site, which means you are going to have to login to the site first. Looking at the main page, this is what I find in the `<form>` element that handles login:
```
<form name="formlogin" method="post" action="./defalogin.php" >
<input name="emtext" type="text" id="emtext" size="12">
<input name="pstext" type="password" id="pstext" size="12">
<input type="submit" name="Submit" value="Logn in"
onClick="return logincheck()" >
</form>
```
I've included only the relevant portions.
Given this, you have to go to the `./defalogin.php` page first with the `HttpWebRequest` and POST the `emtext` and `pstext` values. Also, make sure you set the [`CookieContainer` property](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.cookiecontainer.aspx) to an instance of [`CookieContainer`](http://msdn.microsoft.com/en-us/library/system.net.cookiecontainer.aspx). When that call to POST returns, it's more than likely going to be populated with a cookie which you will have to send back to the site. Just keep setting the `CookieContainer` property on any subsequent `HttpWebRequest` instances to that `CookieContainer` to make sure the cookies are passed around.
Then you would go to the page indicated in the link.
Of concern is also the `logincheck` javascript function, but looking at the script sources, it does nothing of note. | The credentials that you are passing is for windows authentication. You need to submit post data with data that mimics the submission of a form then captrue the session cookie set in the response ans use that cookie for future requests
Take a look at this answer which has the code to do this:
[Login to the page with HttpWebRequest](https://stackoverflow.com/questions/450380/login-to-the-page-with-httpwebrequest/595318#595318) | HttpWebRequest and forms authentication in C# | [
"",
"c#",
"httpwebrequest",
"forms-authentication",
""
] |
This has some lengthy background before the actual question, however, it bears some explaining to hopefully weed out some red herrings.
Our application, developed in Microsoft Visual C++ (2005), uses a 3rd party library (whose source code we luckily happen to have) to export a compressed file used in another 3rd party application. The library is responsible for creating the exported file, managing the data and compression, and generally handling all errors. Recently, we began getting feedback that on certain machines, our application would crash during writes to the file. Based on some initial exploration, we were able to determine the following:
* The crashes happened on a variety of hardware setups and Operating Systems (although our customers are restricted to XP / 2000)
* The crashes would always happen on the same set of data; however they would not occur on all sets of data
* For a set of data that caused a crash, the crash is not reproducible on all machines, even with similar characteristics, i.e., operating system, amount of RAM, etc.
* The bug would only manifest itself when the application was run in the installation directory - **not** when built from Visual Studio, run in debug mode, or even run in other directories that the user had access to
* The issue occurs whether the file is being constructed on a local or a mapped drive
Upon investigating the problem, we found the issue to be in the following block of code (slightly modified to remove some macros):
```
while (size>0) {
do {
nbytes = _write(file->fd, buf, size);
} while (-1==nbytes && EINTR==errno);
if (-1==nbytes) /* error */
throw("file write failed")
assert(nbytes>0);
assert((size_t)nbytes<=size);
size -= (size_t)nbytes;
addr += (haddr_t)nbytes;
buf = (const char*)buf + nbytes;
}
```
Specifically, the \_write is returning error code 22, or EINVAL. According to [MSDN](http://msdn.microsoft.com/en-us/library/1570wh78(VS.80).aspx), \_write returning EINVAL implies that the buffer (buf in this case) is a null pointer. Some simple checks however around this function verified that this was not the case in any calls made to it.
We do, however, call this method with some very large sets of data - upwards of 250MB in a single call, depending on the input data. When we imposed an artificial limit on the amount of data that went to this method, we appear to have resolved the issue. This, however, smacks of a code fix for a problem that is machine dependent / permissions dependent / dependent on the phase of the moon. So now the questions:
1. Is anyone aware of a limit on the amount of data \_write can handle in a single call? Or - barring \_write - any file I/O command support by Visual C++?
2. Since this does not occur on all machines - or even on every call that is a sufficient size (one call with 250 MB will work, another call will not) - is anyone aware of user, machine, group policy settings, or folder permissions that would affect this?
**UPDATE:**
A few other points, from the posts so far:
* We do handle the cases where the large buffer allocation fails. For performance reasons in the 3rd party application that reads the file we're creating, we want to write all the data out in one big block (although given this error, it may not be possible)
* We have checked the initial value of size in the routine above, and it is the same as the size of the buffer that was allocated. Also, when the EINVAL error code is raised, size is equal to 0, and buf is not a null pointer - which makes me think that this isn't the cause of the problem.
**Another Update:**
An example of a failure is below with some handy printfs in the code sample above.
```
while (size>0) {
if (NULL == buf)
{
printf("Buffer is null\n");
}
do {
nbytes = _write(file->fd, buf, size);
} while (-1==nbytes && EINTR==errno);
if (-1==nbytes) /* error */
{
if (NULL == buf)
{
printf("Buffer is null post write\n");
}
printf("Error number: %d\n", errno);
printf("Buffer address: %d\n", &buf);
printf("Size: %d\n", size);
throw("file write failed")
}
assert(nbytes>0);
assert((size_t)nbytes<=size);
size -= (size_t)nbytes;
addr += (haddr_t)nbytes;
buf = (const char*)buf + nbytes;
}
```
On a failure, this will print out:
```
Error number: 22
Buffer address: 1194824
Size: 89702400
```
Note that no bytes were successfully written and that the buffer has a valid address (and no NULL pointer checks were triggered, pre or post \_write)
**LAST UPDATE**
Unfortunately, we were overcome by events and were not able to conclusively solve this. We were able to find some interesting (and maybe even disturbing) facts.
1. The errors only occurred on machines with slower write times on their hard disks. Two PCs, with the exact same hardware specs, but with different RAID configurations (RAID 0 versus RAID 1) would have different results. The RAID 0 would process the data correctly; the RAID 1 would fail. Similarly, older PCs with slower hard drives would also fail; newers PCs with faster hard drives - but similar processors / memory - would work.
2. The write size mattered. When we limited the amount of data passed to \_write to be 64 MB, all but one file succeeded. When we limited it to 32 MB, all the files succeeded. We took a performance hit in the library we were using - which was a limitation of that library and independent of \_write or the problem we were seeing - but it was our only "software" fix.
Unfortunately, I never got a good answer (and we were about to call Microsoft on this, but we had to get business to sign off on the expense of a tech support call) as to why the EINVAL was being returned in the first place. It isn't - from what we were able to find - documented anywhere in the C library API.
If anyone does find a good answer for this, please post it on here and I'll mark it as the answer. I'd love to get a conclusion for this saga, even if it no longer directly applies to me. | We had a very similar problem which we managed to reproduce quite easily. We first compiled the following program:
```
#include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{ int len = 70000000;
int handle= creat(argv[1], S_IWRITE | S_IREAD);
setmode (handle, _O_BINARY);
void *buf = malloc(len);
int byteswritten = write(handle, buf, len);
if (byteswritten == len)
printf("Write successful.\n");
else
printf("Write failed.\n");
close(handle);
return 0;
}
```
Now, let's say you are working on the computer mycomputer and that C:\inbox maps to a shared folder \\mycomputer\inbox. Then the observe the following effect:
```
C:\>a.exe C:\inbox\x
Write successful.
C:\>a.exe \\mycomputer\inbox\x
Write failed.
```
Note that if len is changed to 60000000, there is no problem...
Based on this web page [support.microsoft.com/kb/899149](http://support.microsoft.com/kb/899149), we think it is a "limitation of the operating system" (the same effect has been observed with fwrite). Our work around is to try to cut the write in 63 MB pieces if it fails. This problem has apparently been corrected on Windows Vista.
I hope this helps!
Simon | Did you look at the implementation of `_write()` in the CRT (C runtime) source that was installed with Visual Studio (`C:\Program Files\Microsoft Visual Studio 8\VC\crt\src\write.c`)?
There are at least two conditions that cause `_write()` to set `errno` to `EINVAL`:
1. `buffer` is NULL, as you mentioned.
2. `count` parameter is odd when the file is opened in text mode in UTF-16 format (or UTF-8? the comments don't match the code). Is this a text or binary file? If it's text, does it have a byte order mark?
3. Perhaps another function that `_write()` calls also sets `errno` to `EINVAL`?
If you can reliably reproduce this problem, you should be able to narrow down the source of the error by putting breakpoints in the parts of the CRT source that set the error code. It also appears that the debug version of the CRT is capable of asserting when the error occurs, but it might require [tweaking some options](http://msdn.microsoft.com/en-us/library/1y71x448.aspx) (I haven't tried it). | Machine dependent _write failures with EINVAL error code | [
"",
"c++",
"c",
"debugging",
"visual-c++",
""
] |
Does anyone have a `T_PAAMAYIM_NEKUDOTAYIM`? | It’s the double colon operator [`::`](http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php) (see [list of parser tokens](http://docs.php.net/manual/en/tokens.php)). | It's [Hebrew](https://en.wikipedia.org/wiki/Hebrew_language) for "double colon". | PHP expects T_PAAMAYIM_NEKUDOTAYIM? | [
"",
"php",
"runtime-error",
"syntax-error",
"error-code",
""
] |
Why does the onclick handler below trigger an "elem.parentNode is not a function" error?
```
<html>
<head>
<script type="text/javascript">
function getParent(elem) {
var parent = elem.parentNode();
}
</script>
</head>
<body>
<div style="border: solid black 2px">
<span onclick="getParent(this)">hello</span>
</div>
</body>
</html>
``` | Your problem is that parentNode is not a function. Try removing the `()`. | parentNode is a property, not a function.
```
var parent = element.parentNode;
``` | Why can't my onclick handler find its parent node? | [
"",
"javascript",
"html",
""
] |
If I have a string like this:
```
FOO[BAR]
```
I need a generic way to get the "BAR" string out of the string so that no matter what string is between the square brackets it would be able to get the string.
e.g.
```
FOO[DOG] = DOG
FOO[CAT] = CAT
``` | You should be able to use non-greedy quantifiers, specifically \*?. You're going to probably want the following:
```
Pattern MY_PATTERN = Pattern.compile("\\[(.*?)\\]");
```
This will give you a pattern that will match your string and put the text within the square brackets in the first group. Have a look at the [Pattern API Documentation](http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html) for more information.
To extract the string, you could use something like the following:
```
Matcher m = MY_PATTERN.matcher("FOO[BAR]");
while (m.find()) {
String s = m.group(1);
// s now contains "BAR"
}
``` | the non-regex way:
```
String input = "FOO[BAR]", extracted;
extracted = input.substring(input.indexOf("["),input.indexOf("]"));
```
alternatively, for slightly better performance/memory usage (thanks Hosam):
```
String input = "FOO[BAR]", extracted;
extracted = input.substring(input.indexOf('['),input.lastIndexOf(']'));
``` | Using Java to find substring of a bigger string using Regular Expression | [
"",
"java",
"regex",
"string",
""
] |
I have some old java code for a REST service that uses a separate thread for every incoming request. I.e. the main loop would loop on socket.accept() and hand off the socket to a Runnable which then would start up its own background thread and invoke run on itself. This worked admiringly well for a while until recently i noticed that the lag of accept to processing the request would get unacceptable under high load. When i say admiringly well, i mean that it was handling 100-200 requests a second without significant CPU usage. The performance only degraded when other daemons were adding load as well and then only once load exceeded 5. When the machine was under high load (5-8) from a combination of other processes, the time from accept to processing would get ridiculously high (500ms to 3000ms) while the actual processing stayed sub-10ms. This is all on dual-core centos 5 systems.
Having been used to Threadpools on .NET, i assumed that thread creation was the culprit and i thought i'd apply the same pattern in java. Now my Runnable is executed with ThreadPool.Executor (and the pool uses and ArrayBlockingQueue). Again, it works great under most scenarios unless the machine load gets high, then the time from creating the runnable until run() is invoked exhibits about the same ridiculous timing. But worse, the system load nearly doubled (10-16) with the threadpool logic in place. So now i get the same latency problems with double the load.
My suspicion is that the lock contention of the queue is worse than the previous new thread start-up cost that had no locks. Can anyone share their experience of new thread vs. threadpool. And if my suspicion is correct, anyone have an alternative approach to dealing with a threadpool without lock contention?
I'd be tempted to just make the whole system single-threaded since i don't know how much my threading helps and IO doesn't seem to be an issue, but I do get some requests that are long-lived that would then block everything.
thanks,
arne
UPDATE: I switched over to `Executors.newFixedThreadPool(100);` and while it maintained the same processing capacity, load pretty much immediately doubled and running it for 12 hours showed load staying consistently at 2x. I guess in my case a new thread per request is cheaper. | With the configuration of:
```
new ThreadPoolExecutor(10, 100, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(100))
```
Then once 10 threads are concurrently processing requests, further requests are added to the queue, unless it reaches 100 requests in the queue, at which time it will start creating new threads, unless there are already 100 threads, when the processing of the command will be rejected.
The section of the [javadocs of `ThreadPoolExecutor`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html) (copied below) may be worth another read.
Based on them, and your apparent willingness to have 100 threads running, and your desire to accept all requests, processing them eventually.. I'd recommend trying variations like:
```
new ThreadPoolExecutor(100, 100, 0, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>())
```
Which, incidentally, is what you'd get from `Executors.newFixedThreadPool(100);`
---
> ## Queuing
>
> Any BlockingQueue may be used to transfer and hold submitted tasks. The use of this queue interacts with pool sizing:
>
> * If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing.
> * If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.
> * If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected.
>
> There are three general strategies for queuing:
>
> 1. Direct handoffs. A good default choice for a work queue is a SynchronousQueue that hands off tasks to threads without otherwise holding them. Here, an attempt to queue a task will fail if no threads are immediately available to run it, so a new thread will be constructed. This policy avoids lockups when handling sets of requests that might have internal dependencies. Direct handoffs generally require unbounded maximumPoolSizes to avoid rejection of new submitted tasks. This in turn admits the possibility of unbounded thread growth when commands continue to arrive on average faster than they can be processed.
> 2. Unbounded queues. Using an unbounded queue (for example a LinkedBlockingQueue without a predefined capacity) will cause new tasks to wait in the queue when all corePoolSize threads are busy. Thus, no more than corePoolSize threads will ever be created. (And the value of the maximumPoolSize therefore doesn't have any effect.) This may be appropriate when each task is completely independent of others, so tasks cannot affect each others execution; for example, in a web page server. While this style of queuing can be useful in smoothing out transient bursts of requests, it admits the possibility of unbounded work queue growth when commands continue to arrive on average faster than they can be processed.
> 3. Bounded queues. A bounded queue (for example, an ArrayBlockingQueue) helps prevent resource exhaustion when used with finite maximumPoolSizes, but can be more difficult to tune and control. Queue sizes and maximum pool sizes may be traded off for each other: Using large queues and small pools minimizes CPU usage, OS resources, and context-switching overhead, but can lead to artificially low throughput. If tasks frequently block (for example if they are I/O bound), a system may be able to schedule time for more threads than you otherwise allow. Use of small queues generally requires larger pool sizes, which keeps CPUs busier but may encounter unacceptable scheduling overhead, which also decreases throughput. | measurement, measurement, measurement! Where is it spending the time? What has to happen when you create your Runnable? Does the Runnable have anything that could be blocking or delaying in the instantiation? What's happening during that delay?
I'm actually a big believer in thinking things through in general, but this sort of case, with unexpected behavior like this, just has to have some measurements.
What is the runtime environment, JVM version, and architecture? | Java Threadpool vs. new Thread in high request scenario | [
"",
"java",
"sockets",
"threadpool",
""
] |
I have written a server/client application using sockets in C# for .NET 3.5. I'm interested in porting the client part to some kind of mobile device and am pondering the best way. The client is actually an underlying library and a GUI depending heavily on touch interface capabilities.
As I see it I have a few options:
1. Just get an EEE PC and run it on, that's kind of portable but I loose the touch part
2. Rebuild the library for mobile platforms and make a new, reduced, GUI app
3. Start a web server and make some kind of web interface to run on iPhones and what not
What would be the best route? What problems can I run into in my alternatives above? I'd really prefer alternative 1 or 2 over 3 because of how the server is currently done and the fact that I know nothing about webservers or ASP.NET. Oh and I'd like to stay with the environment I'm alredy in, that is .NET, so no Ruby on Rails suggestions please. (Not saying Ruby is bad or anything, I just don't know it and don't have the time to learn). | I'd go for option 2 then. It wont take you too long (hopefully) to port the libraries over to the Compact Framework, and providing it's just sockets, etc, you're dealing with then I'm sure the CF will handle it fine.
**EDIT:** The only problems you'll have with option 2 is if you use any .Net functions that are not in the CF. If that is the case, you'll usually be able to find it within OpenNETCF.
You will need to create a new GUI, but providing you've coded your libraries well, it should just be a case of assigning methods/events where applicable on your device.
I'd say though that option 3 is the best option - it expands your customer base dramatically, especially with the growing number of WM and iPhone users. | I would opt for Option 2.
Most of the members of the [TcpClient Class](http://msdn.microsoft.com/en-au/library/system.net.sockets.tcpclient.aspx) class in System.Net.Sockets namespace are implemented in the .Net Compact Framework.
I would be interested to understand what your requirements are in selecting a mobile device. There are a lot of differences between a Windows Mobile Smartphone and EEE PC. | Porting a .NET 3.5 application to a portable device | [
"",
"c#",
".net",
"mobile",
"webserver",
"porting",
""
] |
Is there a succinct way to represent a bounded numeric value in .NET 3.5?
By this I mean a value such as a percentage (0 - 100) probability (0 - 1) or stock level (0 or above).
I would want a `ArgumentOutOfRangeException` (or equivalent) to be thrown if an out-of-range assignment was attempted. I would also want static `MaxValue` and `MinValue` properties to be available.
It was suggested in a [comment to another SO question](https://stackoverflow.com/questions/575977/choosing-between-immutable-objects-and-structs-for-value-objects/576014#576014) that this was a good use of a `struct`. | I don't think there is a built-in way like the Ada ["range" keyword](http://en.wikibooks.org/wiki/Ada_Programming/Types/range), but you could easily create a type like RestrictedRange<T> that had a min and max value along with the current value:
```
public class RestrictedRange<T> where T : IComparable
{
private T _Value;
public T MinValue { get; private set; }
public T MaxValue { get; private set; }
public RestrictedRange(T minValue, T maxValue)
: this(minValue, maxValue, minValue)
{
}
public RestrictedRange(T minValue, T maxValue, T value)
{
if (minValue.CompareTo(maxValue) > 0)
{
throw new ArgumentOutOfRangeException("minValue");
}
this.MinValue = minValue;
this.MaxValue = maxValue;
this.Value = value;
}
public T Value
{
get
{
return _Value;
}
set
{
if ((0 < MinValue.CompareTo(value)) || (MaxValue.CompareTo(value) < 0))
{
throw new ArgumentOutOfRangeException("value");
}
_Value = value;
}
}
public static implicit operator T(RestrictedRange<T> value)
{
return value.Value;
}
public override string ToString()
{
return MinValue + " <= " + Value + " <= " + MaxValue;
}
}
```
Since there is an implicit conversion to automatically get the value, this will work:
```
var adultAge = new RestrictedRange<int>(18, 130, 21);
adultAge.Value++;
int currentAge = adultAge; // = 22
```
In addition, you can do things like this
```
var stockLevel = new RestrictedRange<int>(0, 1000)
var percentage = new RestrictedRange<double>(0.0, 1.0);
``` | This is, in fact, the type of thing used as an example of 'places to use a struct' in the MS Press study guide for the 70-526 exam. A small group of data (< 16 bytes), with value semantics, is best designed as a struct, not a class. | Representing a percentage, probability, or stock level | [
"",
"c#",
".net",
"data-structures",
""
] |
My program, alas, has a memory leak somewhere, but I'll be damned if I know what it is.
Its job is to read in a bunch of ~2MB files, do some parsing and string replacement, then output them in various formats. Naturally, this means a lot of strings, and so doing memory tracing shows that I have a lot of strings, which is exactly what I'd expect. The structure of the program is a series of classes (each in their own thread, because I'm an *idiot*) that acts on an object that represents each file in memory. (Each object has an input queue that uses a lock on both ends. While this means I get to run this simple processing in parallel, it also means I have multiple 2MB objects sitting in memory.) Each object's structure is defined by a schema object.
My processing classes raise events when they've done their processing and pass a reference to the large object that holds all my strings to add it to the next processing object's queue. Replacing the event with a function call to add to the queue does not stop the leak. One of the output formats requires me to use an unmanaged object. Implementing Dispose() on the class does not stop the leak. I've replaced all the references to the schema object with an index name. No dice. I got no idea what's causing it, and no idea where to look. The memory trace doesn't help because all I see are a bunch of strings being created, and I don't see where the references are sticking in memory.
We're pretty much going to give up and roll back at this point, but I have a pathological need to know exactly how I messed this up. I know Stack Overflow can't exactly comb my code, but what strategies can you suggest for tracking this leak down? I'm probably going to do this in my own time, so any approach is viable. | One technique I would try is to systematically reduce the amount of code you need to demonstrate the problem without making the problem go away. This is informally known as "divide and conquer" and is a powerful debugging technique. Once you have a *small* example that demonstrates the same problem, it will be much easier for you to understand. Perhaps the memory problem will become clearer at that point. | There is only one person who can help you. That person's name is [Tess Ferrandez](http://blogs.msdn.com/tess/). (hushed silence)
But seriously. read her blog (the first article is pretty pertinent). Seeing how she debugs this stuff will give you a lot of deep insight into knowing what's going on with your problem. | Strategies For Tracking Down Memory Leaks When You've Done Everything Wrong | [
"",
"c#",
"memory-leaks",
""
] |
i've created an rss feed in php using the below code. i've double checked all the variables (i.e. username and password) and they are correct. mysql is set up correctly as well. i'm just getting a blank page when i try to view this locally on my computer using mamp. any help would be appreciated.. does this code look correct, and is there something else i should be using to view this other than mamp?
```
<? header('Content-type: text/xml'); ?>
<?php
$dbhost = "localhost"; // almost always localhost.
$dbname = "links"; // Database Name
$dbuser = "root"; // Database Username
$dbpass = "password"; // Databse Password
$connect = mysql_connect("$dbhost","$dbuser","$dbpass");// Connecting to Database
mysql_select_db($dbname) or die (mysql_error()); // Selecting Database
?>
<rss version="2.0">
<channel>
<title> </title>
<description> </description>
<link></link>
<?
$sql = "SELECT * FROM news limit 5";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
?>
<item>
<title><?=$row['title']; ?></title>
<author><?=$row['author']; ?></author>
<link>http://MYSITE.com/news.php?id=<?=$row['id']; ?></link>
</item>
<?
}
?>
</channel>
</rss>
``` | A couple things to try:
1. Check the logs.
2. Move the call to `header()` to the top, before output.
3. Remove the `<blockquote>` tags.
4. Add a processing instruction (`<?xml version="1.0"?>`) at the top, before the `<rss>` element.
5. Change the `content-type` header from `text/xml` to `application/xml`. | When I copy this code and change around the MySQL settings to use a database that actually exists for my setup of MAMP, this works fine for me, with 0 items since the table doesn't exist in the DB. In other words, it seems like something is wrong with your MAMP setup, not your code. Are you absolutely sure that your MySQL server is running and you have the right information for connecting to it? | creating an rss feed in php (viewing in mamp) | [
"",
"php",
"rss",
"mamp",
""
] |
Is it OK to pass to function a reference to the value of map element, and to modify it there?
```
foo(string & s)
{
s = "xyz";
}
map<int, string> m;
m[1] = "abc";
foo(m[1]); // <-- Is it ok? Will m[1] be "xyz" after this call?
```
Thank you. | The answer is Yes.
(operator [] returns a [reference](http://www.cplusplus.com/reference/stl/map/operator[].html)) | Yes, we can.
And it also works with `std::vectors` (and since it looks like you're using numeric keys, you may consider using them instead). | Reference to value of STL map element? | [
"",
"c++",
"stl",
"dictionary",
""
] |
In PHP, it's pretty easy:
```
is_numeric(23);//true
is_numeric("23");//true
is_numeric(23.5);//true
is_numeric(true);//false
```
But how do I do this in Javascript?
I could use a regular expression, but is there a function for this? | What about:
```
function isNumber(n){
return typeof(n) != "boolean" && !isNaN(n);
}
```
The [isNaN](http://www.w3schools.com/jsref/jsref_isNaN.asp) built-in function is used to check if a value is **not** a number.
**Update:** Christoph is right, in JavaScript Boolean types are convertible to Number, returning the 1 for true and 0 for false, so if you evaluate `1 + true` the result will be 2.
Considering this behavior I've updated the function to prevent converting boolean values to its numeric representation. | I don't think any of the suggestions till now actually work. Eg
```
!isNaN(parseFloat(foo))
```
doesn't because `parseFloat()` ignores trailing non-numeric characters.
To work around this, you could compare the returned value to the one returned by a cast via `Number()` (or equivalently by using unary `+`, but I prefer explicit casting):
```
parseFloat(foo) === Number(foo)
```
This will still work if both functions return `NaN` because `NaN !== NaN` is `true`.
Another possibility would be to first cast to string, then to number and then check for `NaN`, ie
```
!isNaN(Number(String(foo)))
```
or equivalently, but less readable (but most likely faster)
```
!isNaN(+('' + foo))
```
If you want to exclude infinity values, use `isFinite()` instead of `!isNaN()`, ie
```
isFinite(Number(String(foo)))
```
The explicit cast via `Number()` is actually unnecessary, because `isNan()` and `isFinite()` cast to number implicitly - that's the reason why `!isNaN()` doesn't work!
In my opinion, the most appropriate solution therefore would be
```
isFinite(String(foo))
```
---
As Matthew pointed out, the second approach does not handle strings that only contain whitespace correctly.
It's not hard to fix - use the code from Matthew's comment or
```
isFinite(String(foo).trim() || NaN)
```
You'll have to decide if that's still nicer than comparing the results of `parseFloat()` and `Number()`. | Check if a variable contains a numerical value in Javascript? | [
"",
"javascript",
""
] |
Once in a while my shared hosting environment gets compromised because, well, I failed to keep the portfolio of my installed apps patched up.
Last week, it was because of an old and unused installation of a PHP application called Help Center Live.
The result was that every single PHP file on the server (and I have several Wordpresses, Joomlas, SilverStripe installations) had code added that pulled cloaked links from other sites and included them in my page. Other people report their sites banned from Google after this kind of attack - luckily I seem to have caught it early enough. I only noticed it when browswing to one of the sites from my phone - the page had the links included on the Mobile browser.
I found many attack attempts like this one in the log:
62.149.18.193 - -
[06/Feb/2009:14:52:45 +0000]
"GET /support/module.php?module=
HelpCenter//include/main.php?config
[search\_disp]=true&include\_dir=
<http://www.portlandonnuri.com/>
2008\_web//technote7/data/photo/
id2.txt???
HTTP/1.1" 200 26 "-" "libwww-perl/5.814"
I immediately removed this application, and wrote a script that removed the offending PHP code from every source file. I also found that the script had created HTML files containing links for other infected sites to include. I removed them as well. Now I am concerned that the attacker may have left something else that I missed - a PHP file somewhere that will give him permanent access. The file dates were all modified in the attack, and I could not find any other files that were changed during the time in question. Is there something obvious that I have missed, in order to make sure there are no backdoors on my server?
Edit: I also search for text files containing attack code, like the one shown in the log file snippet above. I did not find any.
Another edit:
If you happen to come across this post because you are finding yourself in the same situation, maybe this will help you. I used this to back up all my PHP source files before manipulating them:
```
find . -name *.php -exec tar -uvf ~/www/allphp.tar {} \;
```
and this to undo the changes that the attacker had made:
```
find . -name *.php -exec sed -i '/<?php \/\*\*\/eval(base64_decode(/d' {} \;
```
Not rocket science, but not trivial either for the occasional Linux/Unix user like myself :-).
Another edit:
I cannot audit every line of code on the server, but I can search for suspicious data.
I searched for all occurences of "eval" and "base64" and did not find anything that did not look legit.
I then ran a grep for ".ru" (since the perpetrators seems to come from there) and, lo and behold, found something called a c99 shell, which I swiftly removed.
Final edit:
I found out how the c99 shell was uploaded - through a hole in the Coppermine Photo Gallery.
```
97.74.118.95 - - [03/Feb/2009:00:31:37 +0000] "POST
/pics/picEditor.php?img_dir=http://xakforum.altnet.ru/tmp_upload/files
/c99shell.txt&CURRENT_PIC[filename]=/1.php HTTP/1.1" 404 - "-" "-"
97.74.118.95 - - [03/Feb/2009:00:32:24 +0000] "
GET /pics/albums/1.php HTTP/1.1" 200 25352 "-" "-"
```
The IP address, btw, is a Godaddy hosted IP. | After your system has been comprised you really have only two options: audit every line of every application or reinstall everything. Since it sounds like these are all open-source or commercial programs you're probably better to re-install them all. There really isn't a better way to ensure you don't have a back-door in one of them now.
A security expert would likely recommend that you completely reinstall the OS too because you can't be certain that some code wasn't slipped into a place that will affect the OS, however if your permissions where setup correctly this may be overkill. | 1.) Keep a repository of the files you are using for these apps (e.g. SVN or similar)
2.) Keep up-to-date as best as possible with each apps security updates (most have an RSS feed)
3.) Backup your DB's regularly
If/when the !@#$ hits the fan you can start over with a fresh copy of the DB and redeploy the code from SVN. | PHP Injection Attack - how to best clean up the mess? | [
"",
"php",
"code-injection",
""
] |
In C# to use a TcpClient or generally to connect to a socket how can I first check if a certain port is free on my machine?
*more info:*
This is the code I use:
```
TcpClient c;
//I want to check here if port is free.
c = new TcpClient(ip, port);
``` | Since you're using a `TcpClient`, that means you're checking open TCP ports. There are lots of good objects available in the [System.Net.NetworkInformation](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.aspx) namespace.
Use the `IPGlobalProperties` object to get to an array of `TcpConnectionInformation` objects, which you can then interrogate about endpoint IP and port.
---
```
int port = 456; //<--- This is your value
bool isAvailable = true;
// Evaluate current system tcp connections. This is the same information provided
// by the netstat command line application, just in .Net strongly-typed object
// form. We will look through the list, and if our port we would like to use
// in our TcpClient is occupied, we will set isAvailable to false.
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
{
if (tcpi.LocalEndPoint.Port==port)
{
isAvailable = false;
break;
}
}
// At this point, if isAvailable is true, we can proceed accordingly.
``` | You're on the wrong end of the Intertube. It is the server that can have only one particular port open. Some code:
```
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
try {
TcpListener tcpListener = new TcpListener(ipAddress, 666);
tcpListener.Start();
}
catch (SocketException ex) {
MessageBox.Show(ex.Message, "kaboom");
}
```
Fails with:
> Only one usage of each socket address (protocol/network address/port) is normally permitted. | In C#, how to check if a TCP port is available? | [
"",
"c#",
".net",
"tcp",
"tcpclient",
""
] |
Hey everyone, I'm working on a widget for Apple's Dashboard and I've run into a problem while trying to get data from my server using jquery's ajax function. Here's my javascript code:
```
$.getJSON("http://example.com/getData.php?act=data",function(json) {
$("#devMessage").html(json.message)
if(json.version != version) {
$("#latestVersion").css("color","red")
}
$("#latestVersion").html(json.version)
})
```
And the server responds with this json:
```
{"message":"Hello World","version":"1.0"}
```
For some reason though, when I run this the fields on the widget don't change. From debugging, I've learned that the widget doesn't even make the request to the server, so it makes me think that Apple has some kind of external URL block in place. I know this can't be true though, because many widgets phone home to check for updates.
Does anyone have any ideas as to what could be wrong?
EDIT: Also, this code works perfectly fine in Safari.
---
As requested by Luca, here's the PHP and Javascript code that's running right now:
PHP:
```
echo $_GET["callback"].'({"message":"Hello World","version":"1.0"});';
```
Javascript:
```
function showBack(event)
{
var front = document.getElementById("front");
var back = document.getElementById("back");
if (window.widget) {
widget.prepareForTransition("ToBack");
}
front.style.display = "none";
back.style.display = "block";
stopTime();
if (window.widget) {
setTimeout('widget.performTransition();', 0);
}
$.getJSON('http://nakedsteve.com/data/the-button.php?callback=?',function(json) {
$("#devMessage").html(json.message)
if(json.version != version) {
$("#latestVersion").css("color","red")
}
$("#latestVersion").html(json.version)
})
}
``` | In Dashcode click **Widget Attributes** then **Allow Network Access** make sure that option is checked. I've built something that simply refused to work, and this was the solution. | Cross-domain Ajax requests ( Using the XMLHttpRequest / ActiveX object ) are not allowed in the current standard, as per the [W3C spec](http://www.w3.org/TR/XMLHttpRequest/):
> This specification does not include
> the following features which are being
> considered for a future version of
> this specification:
>
> * Cross-site XMLHttpRequest;
However there's 1 technique of doing *ajax* requests cross-domain, [JSONP](http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/), by including a script tag on the page, and with a little server configuration.
jQuery supports [this](http://docs.jquery.com/Ajax/jQuery.getJSON), but instead of responding on your server with this
```
{"message":"Hello World","version":"1.0"}
```
you'll want to respond with this:
```
myCallback({"message":"Hello World","version":"1.0"});
```
**myCallback** must be the value in the "callback" parameter you passed in the $.getJSON() function. So if I was using PHP, this would work:
```
echo $_GET["callback"].'({"message":"Hello World","version":"1.0"});';
``` | Dashboard Cross-domain AJAX with jquery | [
"",
"javascript",
"jquery",
"ajax",
"widget",
"dashboard",
""
] |
Sending email is easy with commons-email, and with spring it is even easier. What about receiving incoming email? Are there easy to use APIs that allow to bounce emails, process attachments, etc. | [SubEthaSMTP Mail Server](http://code.google.com/p/subethasmtp/) allows you to create your own SMTP Server for receiving emails. | [James](http://james.apache.org) is probably your best bet, but email handling is extremely complex, requiring not only configuration of your MTA (the James server), but also DNS. In the past, I've found it easier to initiate my handlers via hooks from non-Java MTA's like postfix. And procmail might also be useful to you. For a Java MTA though, James rocks. | What is the easiest way for a Java application to receive incoming email? | [
"",
"java",
"smtp",
"email",
"smtpd",
""
] |
I'm trying to load a few modules via hooking into the `AppDomain.AssemblyResolve` and `AppDomain.ReflectionOnlyAssemblyResolve` events. While I got the former to work, I fail miserably on the latter. I've boiled my problem down to this little program:
```
public static class AssemblyLoader
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve +=
ReflectionOnlyAssemblyResolve;
// fails with FileNotFoundException
Assembly.ReflectionOnlyLoad("Foo");
}
public static Assembly ReflectionOnlyAssemblyResolve(object sender,
ResolveEventArgs args)
{
Trace.TraceInformation(
"Failed resolving Assembly {0} for reflection", args.Name);
return null;
}
}
```
Running this program fails with a `FileNotFoundException` when trying to `Assembly.ReflectionOnlyLoad`, but it doesn't call the ReflectionOnlyAssemblyResolve handler. I'm pretty stumped there.
Does anybody have an idea what could be the root cause of this and how to get this to work?
Thanks! | It would appear that the ReflectionOnlyAssemblyResolve event is only used to resolve dependencies, not top-level assemblies, as indicated here:
<http://codeidol.com/csharp/net-framework/Assemblies,-Loading,-and-Deployment/Assembly-Loading/>
And here:
<http://blogs.msdn.com/junfeng/archive/2004/08/24/219691.aspx> | Expanding on casperOne's answer.
If you want to intercept direct Assembly Resolve events you need to hook into the AppDomain.AssemblyResolve event. This is a global hook though so it alone won't fit your scenario. However if your application is single threaded you could a short term hookup in order to intercept specific resolve events.
```
static void LoadWithIntercept(string assemblyName) {
var domain = AppDomain.CurrentDomain;
domain.AssemblyResolve += MyInterceptMethod;
try {
Assembly.ReflectionOnlyLoad(assemblyName);
} finally {
domain.AssemblyResolve -= MyInterceptMethod;
}
}
private static Assembly MyInterceptMethod(object sender, ResolveEventArgs e) {
// do custom code here
}
``` | Why is ReflectionOnlyAssemblyResolve not executed when trying to Assembly.ReflectionOnlyLoad? | [
"",
"c#",
".net",
"assemblies",
"clr",
"assembly.reflectiononly",
""
] |
I couldn't get this to work in Silverlight, so I created two test projects. One simple WPF project and one simple Silverlight project that both do only one thing: set a public static readonly variable in code, and use it in a completely bare bones XAML. In WPF, works without a hitch. In Silverlight, I get the following compiler warning and runtime error:
**Warning 2 The tag 'Static' does not exist in XML namespace '<http://schemas.microsoft.com/winfx/2006/xaml>'...**
and
**Invalid attribute value {x:Static SilverlightApplication3:Page.Test} for property Text. [Line: 7 Position: 25]**
I'm assuming this is not supported in Silverlight 2, or am I just missing something really simple? Here's the full code for both just in case it's the latter:
```
public partial class Window1 : Window
{
public static readonly string Test = "test";
public Window1()
{
InitializeComponent();
}
}
<Window x:Class="WpfApplication4.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:WpfApplication4="clr-namespace:WpfApplication4">
<Grid>
<TextBlock Text="{x:Static WpfApplication4:Window1.Test}" />
</Grid>
</Window>
```
and here's the SL version:
```
public partial class Page : UserControl
{
public static readonly string Test = "test";
public Page()
{
InitializeComponent();
}
}
<UserControl x:Class="SilverlightApplication3.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:SilverlightApplication3="clr-namespace:SilverlightApplication3"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="{x:Static SilverlightApplication3:Page.Test}" />
</Grid>
</UserControl>
``` | Unfortunately, it looks like Silverlight doesn't support binding to static properties: [What is the {x:Static sdfsdf} equivalent?](https://silverlight.net/forums/t/69176.aspx) | Unfortunately Silverlight has many limits with respect to functionality and you just found one of them. StaticMarkupExpression is not supported by SL2. You also can't define it by yourself.
e.g. guy from ms: <http://blogs.msdn.com/edmaia/archive/2008/11/23/animating-objects-visibility-in-silverlight.aspx>
The trick may be to use an object like
```
class Helper{
public string Value {get{return Page.Test;}}
// implement INotifyPropertyChange if you want updates
}
```
And then
```
<Grid.Resources>
<somexmlns:Helper x:Key="Helper"/>
</Grid.Resources>
<TextBlock Text="{Binding Value, Source={StaticResource Helper}}"/>
``` | Using static objects in XAML that were created in code in Silverlight | [
"",
"c#",
".net",
"wpf",
"silverlight",
"xaml",
""
] |
I've been tasked with creating a tool that can diff and merge the configuration files for my company's product. The configurations are stored as either XML or URL-encoded strings. I'm looking for a library, preferably open source with a license compatible with commercial software, that can do these diffs. Our app is written in C++, so C++ libraries would be best, but I'm willing to look at libraries that are C#-specific since I can write a wrapper that exposes it to C++ via COM. Three-way diffs would be ideal, but two-way is acceptable. If it has an understanding of XML, that would also be a plus (since XML nodes can be reordered without changing the document, etc). Any library suggestions? Should I even consider writing my own diff tools in the hopes of giving it semantic knowledge of our formats?
Thanks to [this similar question](https://stackoverflow.com/questions/479654/java-library-for-free-text-diff), I've already discovered [this google library](http://code.google.com/p/google-diff-match-patch/), which seems really great, but I'm still looking for other options. It also seems to be able to output the diffs in HTML format (using the `<ins>` and `<del>` tags that I didn't know existed before I discovered it), which could be really handy, but it seems to be a unified diff only. I'm going to need to display the results in a web browser, and probably have to build an interface for doing the merges in the browser as well. I don't expect a library to be able to help with these tasks, but it must produce output in a format that is amenable to me building this on top of it. I'm currently envisioning something along the lines of TortoiseMerge (side-by-side diffs, not unified), except browser-based. Any tips/tricks/design ideas on how to present this would be appreciated too. | For diffing the XML I would propose that you normalize it first: sort all the elements in alphabetic order, then generate a stream of tokens/xml that represents the original document but is independent of the original formatting. After running the diff, parse the result to get a tree containing what was added / removed. | Subversion comes with `libsvn_diff` and `libsvn_delta` licensed under Apache Software License. | library for doing diffs | [
"",
"c++",
"diff",
""
] |
I have a manytomany relationship between publication and pathology. Each publication can have many pathologies. When a publication appears in the admin template, I need to be able to see the many pathologies associated with that publication. Here is the model statement:
```
class Pathology(models.Model):
pathology = models.CharField(max_length=100)
def __unicode__(self):
return self.pathology
class Meta:
ordering = ["pathology"]
class Publication(models.Model):
pubtitle = models.TextField()
pathology = models.ManyToManyField(Pathology)
def __unicode__(self):
return self.pubtitle
class Meta:
ordering = ["pubtitle"]
```
Here is the admin.py. I have tried variations of the following, but always
get an error saying either publication or pathology doesn't have a foreign key
associated.
```
from myprograms.cpssite.models import Pathology
class PathologyAdmin(admin.ModelAdmin):
# ...
list_display = ('pathology', 'id')
admin.site.register(Pathology, PathologyAdmin)
class PathologyInline(admin.TabularInline):
#...
model = Pathology
extra = 3
class PublicationAdmin(admin.ModelAdmin):
# ...
ordering = ('pubtitle', 'year')
inlines = [PathologyInline]
admin.site.register(Publication,PublicationAdmin)
```
Thanks for any help. | I realize now that Django is great for the administration (data entry) of a website, simple searching and template inheritance, but Django and Python are not very good for complex web applications, where data is moved back and forth between a database and an html template. I have decided to combine Django and PHP, hopefully, applying the strengths of both. Thanks for you help! | Unless you are using a intermediate table as documented here <http://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models>, I don't think you need to create an Inline class. Try removing the line `includes=[PathologyInline]` and see what happens. | admin template for manytomany | [
"",
"python",
"django",
"django-admin",
"many-to-many",
""
] |
I have two sites.
The first site requires users to log in. An authentication token then will be passed to the second site when the users navigate from the first to the second. So the users can't just grab the url of the second sites and login to it.
What is the best encryption/ authentication algorithm that I can use for the this authentication purpose? | Typical PK scheme. On site1 encrypt auth info with site1's private key, and site2's public key. On site2 decrytp using site2's private key, and site1's public key.
Functions of interest:
* [`openssl_private_encrypt()`](http://www.php.net/manual/en/function.openssl-private-encrypt.php)
* [`openssl_private_decrypt()`](http://www.php.net/manual/en/function.openssl-private-decrypt.php)
* [`openssl_public_encrypt()`](http://www.php.net/manual/en/function.openssl-public-encrypt.php)
* [`openssl_public_decrypt()`](http://www.php.net/manual/en/function.openssl-public-decrypt.php) | Be sure to have a look at the [OpenID](http://openid.net/) protocol, it does what you want. | Best Encryption algorithm (PHP) to authenticate users from other sites | [
"",
"php",
"authentication",
""
] |
I am trying to prevent user controls from having and <% ... %> on them. I have sub-classed PageParserFilter in an attempt to use the ProcessCodeConstruct() method to detect when a code block is being parsed and cause an error. Using the debugger I was able to see that the other methods of my overriden PageParserFilter are being called as intended, but ProcessCodeConstruct is not. Any idea when ProcessCodeConstruct is being called? If not, is there another way to accomplish what I'm trying to do? | It turns out that ProcessCodeConstruct is only called when the page is first compiled. We got it to work as intended. | Why are you trying to limit the functionality of User Controls? I for one find it convient to use <%,,,%> in script blocks to get the client id. Just curious whats your reasoning. | C#: PageParserFilter and ProcessCodeConstruct | [
"",
"c#",
""
] |
Let's say you have a \*SQL\* buffer already open in Emacs that is connected to a specific server and database. Now, your intention is to connect to a different server and database while keeping your other SQL buffer process active.
How exactly can you create a new \*SQL\* buffer process without killing your original SQL buffer? Can this be done? Is there a way to instead change your connection info for the existing buffer? | Running:
```
M-x sql-rename-buffer
```
On a connected `*SQL*` buffer will rename the current buffer after the current connection. So:
```
*SQL*
```
Becomes:
```
*SQL user/database*
```
You can then do:
```
M-x sql-mysql
```
Or whatever your flavor of DB is to create another SQL buffer. | As a slight simplification, you can just do:
```
(add-hook 'sql-interactive-mode-hook 'sql-rename-buffer)
```
(I.e., you don't need the `lambda`). | Can you create a new SQL buffer in Emacs if one already exists? | [
"",
"sql",
"emacs",
"sql-mode",
""
] |
After doing a bit of processing, I want to set a cookie value to user input and then redirect them to a new page. However, the cookie is not getting set. If I comment out the redirect, then the cookie is set successfully. I assume this is a header issue of some sort. What is the best workaround for this situation?
```
if($form_submitted) {
...
setcookie('type_id', $new_type_id, time() + 60*60*24*30);
header("Location: $url");
exit;
}
```
Note that setcookie returns `true` in either case and I get no errors/warnings/notices.
**EDIT:** I am using Unix/Apache/MySQL/PHP | If you have human-readable urls or subfolders (like [www.domain.com/path1/path2/](http://www.domain.com/path1/path2/)), then you must set cookie path to / to work for all paths, not just current one.
```
if($form_submitted) {
...
setcookie('type_id', $new_type_id, time() + 60*60*24*30, '/');
header("Location: $url");
exit;
}
```
From PHP manual:
> The path on the server in which the
> cookie will be available on. If set to
> '/', the cookie will be available
> within the entire domain . If set to
> '/foo/', the cookie will only be
> available within the /foo/ directory
> and all sub-directories such as
> /foo/bar/ of domain . The default
> value is the current directory that
> the cookie is being set in. | How are you testing if the cookie is set? Cookies are available on the *next* page after they are set.
> Common Pitfalls:
>
> Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print\_r($\_COOKIE);. | How can I set a cookie and then redirect in PHP? | [
"",
"php",
"cookies",
"http-headers",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.