Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have created a fairly substantial Java GUI application with many form windows where the settings are locked up in .form files. I am wondering is there any way to convert or refactor these .form files into real Java source code that I can modify?
The GUI was created using Netbeans 6.5. | My understanding is that the ".form" files are only used by the Netbeans GUI builder to keep track of where the GUI components are. When you add components in the design view, Netbeans automatically updates the actual source (.java) files. You *can* actually modify these .java files directly to, say, change the label on a button, but if you do it within Netbeans, it will use the .form files to automatically regenerate the source files, destroying your manual changes.
In my experience, once you make the decision to modify the .java files manually, the .form files become out of sync and you will no longer be able to use the Netbeans GUI builder properly. | kazanaki is right, the java files that are generated can be modified but the resulting .java files are notoriously messy, large and hard to interpret. Also, you cannot change some things (as noted in the comments in the generated .java file) without rendering matisse useless because it expects the file to have things in a certain way. That being said, if you are careful not to step on Matisse's toes you can code away and it will not touch your code which is nice.
Outlaw is right too, if you change anything that is already in Matisse's perview it will be overwritten. Any changes that you make outside of matisse must be outside of any element that is covered by the xml that matisse uses to generate the code.
I have tried this kind of thing before with limited success and eventually just rewrote the interface to avoid these maddening headaches. | Convert Java GUI Builder .form files to Source Code? | [
"",
"java",
"netbeans",
"gui-designer",
"matisse",
""
] |
I'm trying to write some code to convert data from a object type field (come from a DataSet) into it's destination (typed) fields. I'm doing (trying at least) it using
dynamic conversion. It seems to work fine for strings, int, DateTime.
But it doesn't work for unsigned types (ulong, uint). Below there's a simple code that shows what I want to do. If you change the ul var type from ulong to int, it works fine.
Does anybody have a clue?
```
public class console
{
public static void CastIt<T>(object value, out T target)
{
target = (T) value;
}
public static void Main()
{
ulong ul;
string str;
int i;
DateTime dt;
object ul_o = (object) 2;
object str_o = (object) "This is a string";
object i_o = (object)1;
object dt_o = (object) DateTime.Now;
Console.WriteLine("Cast");
CastIt(ul_o, out ul);
CastIt(str_o, out str);
CastIt(i_o, out i);
CastIt(dt_o, out dt);
Console.WriteLine(ul);
Console.WriteLine(str);
Console.WriteLine(i);
Console.WriteLine(dt.ToString());
}
}
``` | As Andrew says, the problem is that you can't unbox from a boxed `int` to `ulong`.
Two options:
1) Box a `ulong` instead:
```
object ul_o = (object) 2UL;
```
or
```
ulong tmp = 2;
object ul_o = tmp;
```
2) Make `CastIt<T>` use `Convert.ChangeType`:
```
public static void CastIt<T>(object value, out T target)
{
target = (T) Convert.ChangeType(value, typeof(T));
}
```
This is a bit smelly, but works with your example code. If you can use the first way in your real code, that would be better. | That's because your ul\_o object is an int, not an unsigned number. When you're in your casting function, you're casting while having the target data in the context of an `object`. Explicit/implicit cast operators (which is what you'd need to be using) only work when you have the object in the context of a type that implements them (since those operators are statically linked at compile time rather than dynamically at runtime).
If this is really what you want to do, instead of just a straight cast, use this:
```
target = (T)Convert.ChangeType(value, typeof(T));
``` | C#: Cast a object to a unsigned number type using Generics | [
"",
"c#",
"generics",
"casting",
"unboxing",
""
] |
I want to query for a list of services running as a specific user on a remote machine and then check the health of each. I'm building a custom console. | To use the ServiceController method I'd check out the solution with impersonation implemented in this previous question: [[.Net 2.0 ServiceController.GetServices()](https://stackoverflow.com/questions/210296/net-2-0-servicecontroller-getservices/212673#212673)](https://stackoverflow.com/questions/210296/net-2-0-servicecontroller-getservices/212673#212673)
FWIW, here's C#/WMI way with explicit host, username, password:
```
using System.Management;
static void EnumServices(string host, string username, string password)
{
string ns = @"root\cimv2";
string query = "select * from Win32_Service";
ConnectionOptions options = new ConnectionOptions();
if (!string.IsNullOrEmpty(username))
{
options.Username = username;
options.Password = password;
}
ManagementScope scope =
new ManagementScope(string.Format(@"\\{0}\{1}", host, ns), options);
scope.Connect();
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, new ObjectQuery(query));
ManagementObjectCollection retObjectCollection = searcher.Get();
foreach (ManagementObject mo in retObjectCollection)
{
Console.WriteLine(mo.GetText(TextFormat.Mof));
}
}
``` | **`ServiceController.GetServices("machineName")`** returns an array of `ServiceController` objects for a particular machine.
This:
```
namespace AtYourService
{
using System;
using System.ServiceProcess;
class Program
{
static void Main(string[] args)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController service in services)
{
Console.WriteLine(
"The {0} service is currently {1}.",
service.DisplayName,
service.Status);
}
Console.Read();
}
}
}
```
produces:
```
The Application Experience service is currently Running.
The Andrea ST Filters Service service is currently Running.
The Application Layer Gateway Service service is currently Stopped.
The Application Information service is currently Running.
etc...
```
Of course, I used the parameterless version to get the services on my machine. | In C# how do i query the list of running services on a windows server? | [
"",
"c#",
"windows",
""
] |
## My scenario is the following:
I am working on a winforms application in C# that has a button inside the main page of a tabcontrol that will generate another tabpage each time that it is clicked. Each new tabpage will contain a layout defined by a user control.
## My Questions are:
1. How can I allow the user to then close one of the tabs that were created dynamically at runtime?
2. How might I go about modifying the tabcontrol itself so that it has a small 'X' in each tab that the user may click on in order to close that particular tab? (Like Firefox has)
3. How can I expose the SelectedIndex property of the tabcontrol to the user control if I want to close the tab with a button inside the user control instead? | I created a derived tab control about one year ago. I am not going to post the source here, because it's about 700 lines long and coded quite messy. Maybe I will find some time to clean the code up and then release it here. For now I will briefly outline the way it is build.
Each tab page has a 'X' icon to the *left* of the title and the tab pages support reordering by drag and drop and moving them between multiple tab control.
I choose the easy way to get the icon on the tab pages. The tab control has the [`TabControl.ImageList`](http://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol.imagelist.aspx) property and a tab page has a [`TabPage.ImageIndex`](http://msdn.microsoft.com/en-us/library/system.windows.forms.tabpage.imageindex.aspx) property. So I just added three icons to a image list - normal, hover, pressed - and process the mouse events.
With [`TabControl.GetTabRect()`](http://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol.gettabrect.aspx) you can test if the mouse is over a specific tab pages and with some math you find if it is over the icon. Then you just need to change the icon depending on the mouse button state and eventually remove the tab page under the mouse if the button was pressed.
The main problem with this solution is, that calculating if the mouse is over the icon requires to know where the icon is painted relative to the tab page and this might change with a new windows version. And the icon is to the left of the title, but that does not look too bad. | I found this code and was very helpful to me:
```
private void tabControl_MouseUp(object sender, MouseEventArgs e)
{
// check if the right mouse button was pressed
if(e.Button == MouseButtons.Right)
{
// iterate through all the tab pages
for(int i = 0; i < tabControl1.TabCount; i++)
{
// get their rectangle area and check if it contains the mouse cursor
Rectangle r = tabControl1.GetTabRect(i);
if (r.Contains(e.Location))
{
// show the context menu here
System.Diagnostics.Debug.WriteLine("TabPressed: " + i);
}
}
}
}
```
[TabControl: How To Capture Mouse Right-Click On Tab](http://social.msdn.microsoft.com/forums/en-US/winforms/thread/e09d081d-a7f5-479d-bd29-44b6d163ebc8) | Customizing a TabControl for the Closing of Individual Tabs | [
"",
"c#",
"winforms",
"user-interface",
"controls",
"tabcontrol",
""
] |
With the type Integer you can do this:
```
int lowest = Integer.MIN_VALUE;
```
What can I do if I use generics?
```
K lowest = <...>;
```
I need this in order to implement something similar to a PriorityQueue.
I have access to a node I want to remove from the queue, but it is not the min.
```
1. I need to make it the min by decreasing the key of that node,
2. And then remove the min.
```
I am stuck on the first step. The only thing I can do is set the key of the node to the current min. Not sure it is enough. | This doesn't make any sense...
Given that you don't know what K is at that point, (i.e. You're implementing it generically... duh!) you can't specify a min/max bound for it.
in a case where K could be a int, long, string OR object, you couldn't sensibly guess to use
Integer.MIN\_VALUE, "" OR NULL.
I guess what you're looking for is a K.MIN\_VALUE\_OF\_EVENTUAL\_TYPE but that doesn't exist. | There is no generic form of `MIN_VALUE` or `MAX_VALUE` for all Comparable types.
Think about a `Time` class that implements comparable. There is no `MAX_VALUE` for Time even though it is Comparable. | Java Generics and Infinity (Comparable) | [
"",
"java",
"generics",
"comparable",
"infinity",
""
] |
In one of my django views I query database using plain sql (not orm) and return results.
```
sql = "select * from foo_bar"
cursor = connection.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
```
I am getting the data fine, but not the column names. How can I get the field names of the result set that is returned? | According to [PEP 249](http://www.python.org/dev/peps/pep-0249/), you can try using `cursor.description`, but this is not entirely reliable. | On the [Django docs](https://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly), there's a pretty simple method provided (which does indeed use `cursor.description`, as Ignacio answered).
```
def dictfetchall(cursor):
"Return all rows from a cursor as a dict"
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
]
``` | How to get field names when running plain sql query in django | [
"",
"python",
"django",
""
] |
What's the cleanest/best way in C# to convert something like 400AMP or 6M to an integer? I won't always know what the suffix is, and I just want whatever it is to go away and leave me with the number. | Okay, here's a long-winded solution which should be reasonably fast. It's similar to Guffa's middle answer, but I've put the conditions inside the body of the loop as I think that's simpler (and allows us to fetch the character just once). It's a matter of personal taste really.
It deliberately *doesn't* limit the number of digits that it matches, because if the string is an integer which overflows Int32, I think I'd rather see an exception than just a large integer :)
Note that this also handles negative numbers, which I don't think any of the other solutions so far do...
```
using System;
class Test
{
static void Main()
{
Console.WriteLine(ParseLeadingInt32("-1234AMP"));
Console.WriteLine(ParseLeadingInt32("+1234AMP"));
Console.WriteLine(ParseLeadingInt32("1234AMP"));
Console.WriteLine(ParseLeadingInt32("-1234"));
Console.WriteLine(ParseLeadingInt32("+1234"));
Console.WriteLine(ParseLeadingInt32("1234"));
}
static int ParseLeadingInt32(string text)
{
// Declared before loop because we need the
// final value
int i;
for (i=0; i < text.Length; i++)
{
char c = text[i];
if (i==0 && (c=='-' || c=='+'))
{
continue;
}
if (char.IsDigit(c))
{
continue;
}
break;
}
return int.Parse(text.Substring(0, i));
}
}
``` | You could use a regular expression:
```
Regex reg = new Regex("[0-9]*");
int result = Convert.ToInt32(reg.Match(input));
``` | How should I convert a number with a text suffix to an integer in c#? | [
"",
"c#",
"string",
""
] |
After a huge MySQL blunder on a production server (my fault, and yes I have learned), I am now looking at creating a dump of the MySQL database before I do a critical operation (about 15 queries to the db, insert/update/selects). I know phpMyAdmin can 'dump' the database to SQL queries, but I think this may be a feature of it, not a feature of MySQL?
So, is there a way to do this using MySQL, and if not (which I suspect), what would be the best way to dump the db to a file on the server on command? Preferably as a tarball of the whole DB in ready to import SQL format.
Thank You! | You are looking for the [mysqldump](http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html) function, I believe:
```
mysqldump my_database > database.dump
``` | MySQL dump will do it, and you can pipe it to gzip so it stores better:
```
mysqldump --opt -Q -h[server] -u[username] -p[password] [dbname] | gzip > [file].sql.gz
```
And to restore you unzip it and:
```
mysql -h[server] -u[username] -p[password] [dbname] < [file].sql
``` | Is it possible using PHP to backup SQL without dependecies? If not, which is the best? | [
"",
"php",
"mysql",
""
] |
I received the following error:
```
[27-Apr-2009 10:26:06] PHP Fatal error: Cannot redeclare alphanumeric() (previously declared in /home/iddoc/public_html/lib/common.php:6) in /home/iddoc/public_html/lib/common.php on line 8
```
Notice this:
```
/home/iddoc/public_html/lib/common.php:6) in
/home/iddoc/public_html/lib/common.php on line 8
```
Here are the offending lines:
```
function alphanumeric($str) {
return strtolower(preg_replace("/[^A-Za-z0-9]/",'',$str));
}
```
Prior to these lines there are only comments. There is no other declaration of that function anywhere else in that file or any other.
Strange, no? | Are you using require\_once() to include common.php everywhere? If you use just require or include, that will cause this issue. | Are you using `require`/`include` to reference the file? This is a common error when including a file twice. PHP doesn't know what to do if it sees two declarations, even if they're from an identical file.
Try using this:
```
include_once('lib/common.php');
``` | What on earth could cause this PHP error? Bug in PHP? | [
"",
"php",
"debugging",
""
] |
Which one is better:
```
public:
const vector<int> & GetPointsVector();
private:
vector<int> PointsVector;
```
Or:
```
public:
int GetCurrentPoint();
void MoveToFirstPoint();
void MoveToNextPoint();
bool IsAtLastPoint();
size_t GetNumberOfPoints();
private:
vector<int> PointsVector;
``` | There is no right answer. The answer will vary with context, of which, at present we have very little.
It depends on the clients of your class. In most situations you would not want a casual inspector to change the object's state, so it is better to a certain degree to return a reference to a `const` object. However, in such a case, I'd also make the function a `const` i.e.
```
/* a design const - this accessor does not change the state */
const vector<int> & GetPointsVector() const;
```
This is also efficient since you are not passing around heavy objects as return values (it is a different question that most compilers do a RVO these days).
If, your client needs to use the vector in algorithms, yes, you'd better provide iterators. But two pairs i.e.
```
typedef vector<int>::iterator _MyItr;
_MyItr begin() const;
_MyItr begin();
_MyItr end() const;
_MyItr end();
```
This would be in keeping with the way the STL is designed. But, be careful in specifying what sort of iterator the client can expect (for example: if the class specification says that the iterators returned are `RandomIterators`, it sets a certain amount of expectation on your implementation). | Both are not. Better return the begin() and end() iterators, or still better a boost::range for the iterator.
```
private:
typedef std::vector<int> PointsContainer;
public:
typedef boost::iterator_range<PointsContainer::const_iterator> PointsRange;
PointsRange getPointsRange() const {
return boost::make_iterator_range(pointsContainer_.begin(), pointsContainer_.end());
}
```
The advantage is that the traversal logic is hidden within the range/iterator
While using, one alternative is to do:
```
int p;
foreach(p, obj.getPointsRange()) {
//...
}
```
otherwise
```
C::PointsRange r = obj.getPointsRange();
for(C::PointsRange::iterator i = r.begin(); i != r.end(); ++i) {
int p = *i;
//...
}
``` | Law of demeter or return the whole vector | [
"",
"c++",
"oop",
"vector",
"law-of-demeter",
""
] |
I know this question [has](https://stackoverflow.com/questions/21078/whats-the-best-string-concatenation-method-using-c) been [done](https://stackoverflow.com/questions/38010/c-string-concatenation-and-string-interning) but I have a slightly different twist to it. Several have pointed out that this is premature optimization, which is entirely true if I were asking for practicality's sake and practicality's sake only. My problem is rooted in a practical problem but I'm still curious nonetheless.
---
I'm creating a bunch of SQL statements to create a script (as in it will be saved to disk) to recreate a database schema (easily many many hundreds of tables, views, etc.). This means my string concatenation is append-only. StringBuilder, according to MSDN, works by keeping an internal buffer (surely a char[]) and **copying string characters** into it and **reallocating** the array as necessary.
However, my code has a lot of repeat strings ("CREATE TABLE [", "GO\n", etc.) which means I can take advantage of them [being interned](https://stackoverflow.com/questions/38010/c-string-concatenation-and-string-interning) but not if I use StringBuilder since they would be copied each time. The only variables are essentially table names and such that already exist as strings in other objects that are already in memory.
So as far as I can tell that after my data is read in and my objects created that hold the schema information then all my string information can be reused by interning, yes?
Assuming that, then wouldn't a List or LinkedList of strings be faster because they retain pointers to interned strings? Then it's only one call to String.Concat() for a single memory allocation of the whole string that is exactly the correct length.
A List would have to reallocate string[] of interned pointers and a linked list would have to create nodes and modify pointers, so they aren't "free" to do but if I'm **concatenating many thousands of interned strings** then they would seem like they would be more efficient.
Now I suppose I could come up with some heuristic on character counts for each SQL statement & count each type and get a rough idea and pre-set my StringBuilder capacity to avoid reallocating its char[] but I would have to overshoot by a fair margin to reduce the probability of reallocating.
So for this case, which would be fastest to get a single concatenated string:
* StringBuilder
* List<string> of interned strings
* LinkedList<string> of interned strings
* StringBuilder with a capacity heuristic
* Something else?
As a **separate question** (I may not always go to disk) to the above: would a single StreamWriter to an output file be faster yet? Alternatively, use a List or LinkedList then write them to a file from the list instead of first concatenating in memory.
**EDIT:**
As requested, [the reference](http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx) (.NET 3.5) to MSDN. It says: *"New data is appended to the end of the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer."* That to me means a char[] that is realloced to make it larger (which requires copying old data to the resized array) then appending. | For your **separate question**, Win32 has a **[WriteFileGather](http://msdn.microsoft.com/en-us/library/aa365749(VS.85).aspx)** function, which could efficiently write a list of (interned) strings to disk - but it would make a notable difference only when being called asynchronously, as the disk write will overshadow all but extremely large concatenations.
For your **main question**: unless you are reaching megabytes of script, or tens of thousands of scripts, don't worry.
You can expect StringBuilder to double the allocation size on each reallocation. That would mean growing a buffer from 256 bytes to 1MB is just 12 reallocations - quite good, given that your initial estimate was 3 orders of magnitude off the target.
Purely as an exercise, some estimates: building a buffer of 1MB will sweep roughly 3 MB memory (1MB source, 1MB target, 1MB due to
copying during realloation).
A linked list implementation will sweep about 2MB, (and that's ignoring the 8 byte / object overhead per string reference). So you are saving 1 MB memory reads/writes, compared to a typical memory bandwidth of 10Gbit/s and 1MB L2 cache.)
Yes, a list implementation is potentially faster, and the difference would matter if your buffers are an order of magnitude larger.
For the much more common case of small strings, the algorithmic gain is negligible, and easily offset by other factors: the StringBuilder code is likely in the code cache already, and a viable target for microoptimizations. Also, using a string internally means no copy at all if the final string fits the initial buffer.
Using a linked list will also bring down the reallocation problem from O(number of characters) to O(number of segments) - your list of string references faces the same problem as a string of characters!
---
So, IMO the implementation of StringBuilder is the right choice, optimized for the common case, and degrades mostly for unexpectedly large target buffers. I'd expect a list implementation to degrade for very many small segments first, which is actually the extreme kind of scenario StringBuilder is trying to optimize for.
Still, it would be interesting to see a comparison of the two ideas, and when the list starts to be faster. | If I were implementing something like this, I would never build a StringBuilder (or any other in memory buffer of your script).
I would just stream it out to your file instead, and make all strings inline.
Here's an example pseudo code (not syntactically correct or anything):
```
FileStream f = new FileStream("yourscript.sql");
foreach (Table t in myTables)
{
f.write("CREATE TABLE [");
f.write(t.ToString());
f.write("]");
....
}
```
Then, you'll never need an in memory representation of your script, with all the copying of strings.
Opinions? | String concatenation in C# with interned strings | [
"",
"c#",
"string",
"performance",
"stringbuilder",
""
] |
I'm kind of new in PHP. For some reason in other types of programming languages like JAVA I have no problem with using setters and getters for every single variable, but when I'm programming in PHP probably because it is so flexible it feels kind of like a waste of time. It feels simpler to just set the class attributes as public most of the time and manipulating them like that. The thing is that when I do it like this I feel like I'm doing something wrong and going against OO principles.
Is it really that wrong not using setters and getters? Why or why not? How do you guys do it most of the time? | The main problem with not using property accessors is that if you find out you ever need to change a field to a property later on – to make it a computed property in a subclass, for instance – you’ll break clients of your API. For a published library, this would be unacceptable; for an internal one, just quite a lot of work fixing things.
For private code or small apps, it could be feasible to just wing it. An IDE (or text editor) will let you generate accessor boilerplate and hide it using code folding. This arguably makes using getters and setters mechanically fairly easy.
Note that some programming languages have features to synthesise the default field+getter+setter – Ruby does it via metaprogramming, C# has auto-implemented properties. And Python sidesteps the issue completely by letting you override attribute access, letting you encapsulate the attribute in the subclass that needs it instead of having to bother with it up front. (This is the approach I like best.) | The point of getters or setters is that you can still add logic to your modifications of the field in one place instead of everyplace you want to modify or retrieve the field. You also gain control at class level what happens with the field. | Is it really that wrong not using setters and getters? | [
"",
"php",
"oop",
""
] |
Anyone know of an SWT widget that can be a text editor with support for syntax highlighting? I'm aware of the StyledText widget but I'm hoping that somebody has already written some libraries so one can just specify the keywords that should be highlighted. | Indeed, the general principle of syntax highlighting [are using the **StyledText** Widget](http://www.eclipse.org/articles/StyledText%201/article1.html).

The [**JavaSourcecodeViewer**](http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/JavaSourcecodeViewer.htm) is a more advanced example.

The **[JavaViewer](http://www.eclipse.org/swt/examples.php)** is even more detailed ([source code](http://dev.eclipse.org/viewsvn/index.cgi/org.eclipse.swt.examples/src/org/eclipse/swt/examples/javaviewer/JavaViewer.java?view=co)). | I'd look into what Eclipse uses in their code editor. Because if any SWT application uses syntax highlighting, its Eclipse. | SWT Syntax highlighting widget | [
"",
"java",
"swt",
""
] |
Hitting `ctrl`+`c` while the `dump` operation is saving data, the interrupt results in the file being corrupted (i.e. only partially written, so it cannot be `load`ed again.
Is there a way to make `dump`, or in general any block of code, uninterruptable?
---
My current workaround looks something like this:
```
try:
file = open(path, 'w')
dump(obj, file)
file.close()
except KeyboardInterrupt:
file.close()
file.open(path,'w')
dump(obj, file)
file.close()
raise
```
It seems silly to restart the operation if it is interrupted, so how can the interrupt be deferred? | Put the function in a thread, and wait for the thread to finish.
Python threads cannot be interrupted except with a special C api.
```
import time
from threading import Thread
def noInterrupt():
for i in xrange(4):
print i
time.sleep(1)
a = Thread(target=noInterrupt)
a.start()
a.join()
print "done"
0
1
2
3
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\test.py", line 11, in <module>
a.join()
File "C:\Python26\lib\threading.py", line 634, in join
self.__block.wait()
File "C:\Python26\lib\threading.py", line 237, in wait
waiter.acquire()
KeyboardInterrupt
```
See how the interrupt was deferred until the thread finished?
Here it is adapted to your use:
```
import time
from threading import Thread
def noInterrupt(path, obj):
try:
file = open(path, 'w')
dump(obj, file)
finally:
file.close()
a = Thread(target=noInterrupt, args=(path,obj))
a.start()
a.join()
``` | The following is a context manager that attaches a signal handler for `SIGINT`. If the context manager's signal handler is called, the signal is delayed by only passing the signal to the original handler when the context manager exits.
```
import signal
import logging
class DelayedKeyboardInterrupt:
def __enter__(self):
self.signal_received = False
self.old_handler = signal.signal(signal.SIGINT, self.handler)
def handler(self, sig, frame):
self.signal_received = (sig, frame)
logging.debug('SIGINT received. Delaying KeyboardInterrupt.')
def __exit__(self, type, value, traceback):
signal.signal(signal.SIGINT, self.old_handler)
if self.signal_received:
self.old_handler(*self.signal_received)
with DelayedKeyboardInterrupt():
# stuff here will not be interrupted by SIGINT
critical_code()
``` | How to prevent a block of code from being interrupted by KeyboardInterrupt in Python? | [
"",
"python",
""
] |
I've been asked to create a financial report, which needs to give a total commission rate between two dates for several 'referrers'. That's the easy part.
The difficult part is that the commission rate varies depending not only on the referrer but **also** on the type of referral **and also** on the number of referrals of that type that have been made by a given referrer.
The tracking of the number of referrals needs to take into account ALL referrals, rather than those in the given date range - in other words, the commission rate is on a sliding scale for each referrer, changing as their total referrals increase. Luckily, there are only a maximum of 3 commission levels for each type of referral.
The referrals are all stored in the same table, 1 row per referral, with a field denoting the referrer and the type of referral. An example to illustrate:
```
ID Type Referrer Date
1 A X 01/12/08
2 A X 15/01/09
3 A X 23/02/09
4 B X 01/12/08
5 B X 15/01/09
6 A Y 01/12/08
7 A Y 15/01/09
8 B Y 15/01/09
9 B Y 23/02/09
```
The commission rates are not stored in the referral table - and indeed may change - instead they are stored in the referrer table, like so:
```
Referrer Comm_A1 Comm_A2 Comm_A3 Comm_B1 Comm_B2 Comm_B3
X 30 20 10 55 45 35
Y 45 35 25 60 40 30
```
Looking at the above referral table as an example, and assuming the commission rate level increased after referral number 1 and 2 (then remained the same), running a commission report for December 2008 to February 2009 would return the following:
**[Edit]** - to clarify the above, the commission rate has three levels for each type and each referrer, with the initial rate Comm\_A1 for the first referral commission, then Comm\_A2 for the second, and Comm\_A3 for all subsequent referrals.
```
Referrer Type_A_Comm Type_A_Ref Type_B_Comm Type_B_Ref
X 60 3 100 2
Y 80 2 100 2
```
Running a commission report for just February 2009 would return:
```
Referrer Type_A_Comm Type_A_Ref Type_B_Comm Type_B_Ref
X 10 1 0 0
Y 0 0 40 1
```
**Edit** the above results have been adjusted from my original question, in terms of the column / row grouping.
I'm quite sure that any solution will involve a sub-query (perhaps for each referral type) and also some kind of aggregate / Sum If - but I'm struggling to come up with a working query.
**[Edit]** I'm not sure about writing an equation of my requirements, but I'll try to list the steps as I see them:
Determine the number of previous referrals for each type and each referrer - that is, irrespective of any date range.
Based on the number of previous referrals, select the appropriate commission level - 0 previous = level 1, 1 previous = level 2, 2 or more previous = level 3
(Note: a referrer with no previous referrals but, say, 3 new referrals, would expect a commission of 1 x level 1, 1 x level 2, 1 x level 3 = total commission)
Filter results according to a date range - so that commission payable for a period of activity may be determined.
Return data with column for referrer, and a column with the total commission for each referral type (and ideally, also a column with a count for each referral type).
Does that help to clarify my requirements? | Assuming that you have a table called `type` that lists your particular referral types, this should work (if not, you could substitute another subselect for getting the distinct types from referral for this purpose).
```
select
r.referrer,
t.type,
(case
when isnull(ref_prior.referrals, 0) < @max1 then
(case
when isnull(ref_prior.referrals, 0) + isnull(ref_period.referrals, 0) < @max1 then isnull(ref_period.referrals, 0)
else @max1 - isnull(ref_prior.referrals, 0)
end)
else 0
end) * (case t.type when 'A' then r.Comm_A1 when 'B' then r.Comm_B1 else null end) +
(case when isnull(ref_prior.referrals, 0) + isnull(ref_period.referrals, 0) > @max1 then
(case
when isnull(ref_prior.referrals, 0) < @max2 then
(case
when isnull(ref_prior.referrals, 0) + isnull(ref_period.referrals, 0) < @max2 then isnull(ref_period.referrals, 0)
else @max2 - isnull(ref_prior.referrals, 0)
end)
else 0
end) -
(case
when isnull(ref_prior.referrals, 0) < @max1 then
(case
when isnull(ref_prior.referrals, 0) + isnull(ref_period.referrals, 0) < @max1 then isnull(ref_period.referrals, 0)
else @max1 - isnull(ref_prior.referrals, 0)
end)
else 0
end)
else 0 end) * (case t.type when 'A' then r.Comm_A2 when 'B' then r.Comm_B2 else null end) +
(case when isnull(ref_prior.referrals, 0) + isnull(ref_period.referrals, 0) > @max2 then
(isnull(ref_period.referrals, 0)) -
(
(case when isnull(ref_prior.referrals, 0) + isnull(ref_period.referrals, 0) > @max1 then
(case
when isnull(ref_prior.referrals, 0) < @max2 then
(case
when isnull(ref_prior.referrals, 0) + isnull(ref_period.referrals, 0) < @max2 then isnull(ref_period.referrals, 0)
else @max2 - isnull(ref_prior.referrals, 0)
end)
else 0
end) -
(case
when isnull(ref_prior.referrals, 0) < @max1 then
(case
when isnull(ref_prior.referrals, 0) + isnull(ref_period.referrals, 0) < @max1 then isnull(ref_period.referrals, 0)
else @max1 - isnull(ref_prior.referrals, 0)
end)
else 0
end)
else 0 end) +
(case
when isnull(ref_prior.referrals, 0) < @max1 then
(case
when isnull(ref_prior.referrals, 0) + isnull(ref_period.referrals, 0) < @max1 then isnull(ref_period.referrals, 0)
else @max1 - isnull(ref_prior.referrals, 0)
end)
else 0
end)
)
else 0 end) * (case t.type when 'A' then r.Comm_A3 when 'B' then r.Comm_B3 else null end) as Total_Commission
from referrer r
join type t on 1 = 1 --intentional cartesian product
left join (select referrer, type, count(1) as referrals from referral where date < @start_date group by referrer, type) ref_prior on ref_prior.referrer = r.referrer and ref_prior.type = t.type
left join (select referrer, type, count(1) as referrals from referral where date between @start_date and @end_date group by referrer, type) ref_period on ref_period.referrer = r.referrer and ref_period.type = t.type
```
This assumes that you have a `@start_date` and `@end_date` variable, and you'll obviously have to supply the logic missing from the case statement to make the proper selection of rates based upon the type and number of referrals from ref\_total.
**Edit**
After reviewing the question, I saw the comment about the sliding scale. This greatly increased the complexity of the query, but it's still doable. The revised query now also depends on the presence of two variables `@max1` and `@max2`, representing the maximum number of sales that can fall into category '1' and category '2' (for testing purposes, I used 1 and 2 respectively, and these produced the expected results). | Adam's answer is far more thorough than I'm going to be but I think trying to write this as a single query might not be the right approach.
Have you thought about creating a stored procedure which creates and then populates a temporary table, step by step.
The temporary table would have the shape of the results set you're looking for. The initial insert creates your basic data set (essentially the number of rows you're looking to return with key identifiers and then anything else you're looking to return which can be easily assembled as part of the same query).
You then have a series of updates to the temporary table assembling each section of the more complex data.
Finally select it all back and drop the temporary table.
The advantages of this are that it allows you to break it down in your mind and assemble it a bit at a time which allows you to more easily find where you've gone wrong. It also means that the more complex bits can be assembled in a couple of stages.
In addition if some poor sod comes along and has to debug the whole thing afterwards it's going to be far easier for him to trace through what's happening where. | MySQL Advanced Query Brainteaser | [
"",
"mysql",
"sql",
""
] |
Let say I have a file that contains a serialized object by BinaryFomatter. Now I want to be able to serialize another object and APPEND this on that existing file.
How can I do it? | First, if what you really need is to store an array of object - put them in a container and serialize the container, as said earlier.
Now, if you really want to store two serialized object in a single file concatenated:
I'm not sure that this is possible "out of the box", but you can do two things.
1. Use, or invent your own semi-tar file format, in which you'll write a small header in the beginning (or end) of the file that describes the content of the file (#'objects, and sizes).
2. Write a C# code to detect the beginning and end of each serialized object yourself. I'm not entirely sure it's possible. [Here](http://primates.ximian.com/~lluis/dist/binary_serialization_format.htm) is a non-official documentation of the serialization format. It contains header, however there's no guarantee that this header won't appear in the file. | This is indeed possible. The code below appends the object.
```
using (var fileStream = new FileStream("C:\file.dat", FileMode.Append))
{
var bFormatter = new BinaryFormatter();
bFormatter.Serialize(fileStream, objectToSerialize);
}
```
The following code de-serializes the objects.
```
var list = new List<ObjectToSerialize>();
using (var fileStream = new FileStream("C:\file.dat", FileMode.Open))
{
var bFormatter = new BinaryFormatter();
while (fileStream.Position != fileStream.Length)
{
list.Add((ObjectToSerialize)bFormatter.Deserialize(fileStream));
}
}
```
Note for this to work the file must only contain the same objects. | How to serialize on to existing file? | [
"",
"c#",
".net",
"serialization",
""
] |
I'm using the Scanner class to take some input from the user through the console. Whenever the user inputs something in the screen and presses enter the input stays on screen for example:
This is the prompt
// User writes command and presses enter
* command
* output of command goes here
//Use writes command3
* command
* output of command goes here
* command3
* output of command3 goes here
Is there anyway I can make the command entered not stay in the console after pressing enter?
For example:
//User writes command
* output of command goes here | Short answer: no, not from directly within Java. Java has very limited control over the console: you can only read and write to it. Whatever is displayed on the console cannot be erased programmatically.
Long answer: in Java, all console operations are handled through input and output streams—`System.in` is an input stream, and `System.out` and `System.err` are output streams. As you can see for yourself, [there is no way to modify an output stream](http://java.sun.com/javase/6/docs/api/java/io/OutputStream.html) in Java—essentially, all an output stream really does is output bytes to some destination (which is one reason why it's called a "stream"—it's one-way).\*
The only workaround I can see is to use a [`Console`](http://java.sun.com/javase/6/docs/api/java/io/Console.html) object (from `System.console()`) instead. Specifically, the `readPassword()` method doesn't echo whatever the user types back to the console. However, there are three problems with this approach. First of all, the `Console` class is only available in Java 1.6. Second, I wouldn't recommend using this for input other than passwords, as it would make entering commands more troublesome than it's supposed to be. And third, it still wouldn't erase the prompt from the screen, which would defeat the purpose of what you're trying to achieve, I'd think.
\* - Technically speaking, `System.out` and `System.err` are both instances of `PrintStream`, but `PrintStream` is pretty much just a flexible version of `OutputStream`—a `PrintStream` is still like a normal output stream in that outputting is a one-way operation. | You will struggle to do this with the standard library.
If you don't want to [do it yourself](http://illegalargumentexception.blogspot.com/2009/04/java-unicode-on-windows-command-line.html), you may be able to do this with a 3rd party library like [JLine](http://jline.sourceforge.net/). | How to make Java console input dissapear after pressing enter | [
"",
"java",
"input",
"console",
""
] |
I want to parse a file everytime a new file is created in a certain directory. For this, I'm trying to use [pyinotify](http://pyinotify.sourceforge.net/) to setup a directory to watch for `IN_CREATE` kernel events, and fire the `parse()` method.
Here is the module:
```
from pyinotify import WatchManager,
ThreadedNotifier, ProcessEvent, IN_CREATE
class Watcher(ProcessEvent):
watchdir = '/tmp/watch'
def __init__(self):
ProcessEvent.__init__(self)
wm = WatchManager()
self.notifier = ThreadedNotifier(wm, self)
wdd = wm.add_watch(self.watchdir, IN_CREATE)
self.notifier.start()
def process_IN_CREATE(self, event):
pfile = self._parse(event.pathname)
print(pfile)
def _parse(self, filename):
f = open(filename)
file = [line.strip() for line in f.readlines()]
f.close()
return file
if __name__ == '__main__':
Watcher()
```
The problem is that the list returned by \_parse is *empty* when triggered by a new file creation event, like so (the file is created in another window while `watcher.py` is running):
```
$ python watcher.py
[]
```
...but strangely enough, it works from an interpreter session when called directly.
```
>>> import watcher
>>> w = watcher.Watcher()
>>> w._parse('/tmp/watch/sample')
['This is a sample file', 'Another line', 'And another...']
```
Why is this happening? The farthest I've come debugging this thing is to know that something is making pyinotify not read the file correctly. But... why? | may be you want to wait till file is closed? | As @SilentGhost mentioned, you may be reading the file before any content has been added to file (i.e. you are getting notified of the file creation not file writes).
Update: The loop.py example with pynotify tarball will dump the sequence of inotify events to the screen. To determine which event you need to trigger on, launch loop.py to monitor /tmp and then perform the file manipulation you want to track. | pyinotify bug with reading file on creation? | [
"",
"python",
"linux",
""
] |
In C++, to print a number in hexadecimal you do this:
```
int num = 10;
std::cout << std::hex << num; // => 'a'
```
I know I can create a manipulator that just adds stuff to the stream like so:
```
std::ostream& windows_feed(std::ostream& out)
{
out << "\r\n";
return out;
}
std::cout << "Hello" << windows_feed; // => "Hello\r\n"
```
However, how can I create a manipulator that, like 'hex', modifies items to come on the stream? As a simple example, how would I create the plusone manipulator here?:
```
int num2 = 1;
std::cout << "1 + 1 = " << plusone << num2; // => "1 + 1 = 2"
// note that the value stored in num2 does not change, just its display above.
std::cout << num2; // => "1"
``` | First, you have to store some state into each stream. You can do that with the function [`iword`](http://en.cppreference.com/w/cpp/io/ios_base/iword) and an index you pass to it, given by [`xalloc`](http://en.cppreference.com/w/cpp/io/ios_base/xalloc):
```
inline int geti() {
static int i = ios_base::xalloc();
return i;
}
ostream& add_one(ostream& os) { os.iword(geti()) = 1; return os; }
ostream& add_none(ostream& os) { os.iword(geti()) = 0; return os; }
```
Having that in place, you can already retrieve some state in all streams. Now, you just have to hook into the respective output operation. Numeric output is done by a facet, because it potentially is locale dependent. So you can do
```
struct my_num_put : num_put<char> {
iter_type
do_put(iter_type s, ios_base& f, char_type fill, long v) const {
return num_put<char>::do_put(s, f, fill, v + f.iword(geti()));
}
iter_type
do_put(iter_type s, ios_base& f, char_type fill, unsigned long v) const {
return num_put<char>::do_put(s, f, fill, v + f.iword(geti()));
}
};
```
Now, you can test the stuff.
```
int main() {
// outputs: 11121011
cout.imbue(locale(locale(),new my_num_put));
cout << add_one << 10 << 11
<< add_none << 10 << 11;
}
```
If you want that only the next number is incremented, just set the word to `0` again after each call to `do_put`. | I totally agree with Neil Butterworth on this one, however in the specific case you are using you could do this totally horrible hack. Do not do this in any production code. It has lots of bugs. For one thing it only works in your one-liner above, it does not change the state of the underlying stream.
```
class plusone_stream : public std::ostream
{
public:
std::ostream operator<<(int i)
{
_out << i+1;
return *this;
}
};
std::ostream& plusone(std::ostream& out)
{
return plusone_stream(out);
}
``` | C++ custom stream manipulator that changes next item on stream | [
"",
"c++",
"stream",
""
] |
The method below is what I want to be done in that thread:
```
public void Startup(int port,string path)
{
Run(path);
CRCCheck2();
CRCCheck1();
InitializeCodeCave((ushort)port);
}
```
I tried what I could find googling,but nothing worked
```
public void Test(int port,string path)
{
Thread t = new Thread(Startup(port,path));
}
public void TestA(int port,string path)
{
Thread t = new Thread(Startup);
t.Start (port,path);
}
```
Both don't compile,how to do that? | The following ways work.
```
// The old way of using ParameterizedThreadStart. This requires a
// method which takes ONE object as the parameter so you need to
// encapsulate the parameters inside one object.
Thread t = new Thread(new ParameterizedThreadStart(StartupA));
t.Start(new MyThreadParams(path, port));
// You can also use an anonymous delegate to do this.
Thread t2 = new Thread(delegate()
{
StartupB(port, path);
});
t2.Start();
// Or lambda expressions if you are using C# 3.0
Thread t3 = new Thread(() => StartupB(port, path));
t3.Start();
```
The Startup methods have following signature for these examples.
```
public void StartupA(object parameters);
public void StartupB(int port, string path);
``` | **Update**
The currently suggested way to start a Task is simply using Task.Run()
```
Task.Run(() => foo());
```
Note that this method is described as the best way to start a task [see here](https://stephencleary.com/book/)
**Previous answer**
I like the Task Factory from System.Threading.Tasks. You can do something like this:
```
Task.Factory.StartNew(() =>
{
// Whatever code you want in your thread
});
```
Note that the task factory gives you additional convenience options like *ContinueWith*:
```
Task.Factory.StartNew(() => {}).ContinueWith((result) =>
{
// Whatever code should be executed after the newly started thread.
});
```
Also note that a task is a slightly different concept than threads. They nicely fit with the async/await keywords, see [here](https://blog.stephencleary.com/2012/02/async-and-await.html). | How to create a thread? | [
"",
"c#",
"multithreading",
""
] |
I have a ASP.NET C# business webapp that is used internally. One issue we are running into as we've grown is that the original design did not account for concurrency checking - so now multiple users are accessing the same data and overwriting other users changes. So my question is - for webapps do people usually use a pessimistic or optimistic concurrency system? What drives the preference to use one over another and what are some of the design considerations to take into account?
I'm currently leaning towards an optimistic concurrency check since it seems more forgiving, but I'm concerned about the potential for multiple changes being made that would be in contradiction to each other.
Thanks! | Optimistic locking.
Pessimistic is harder to implement and will give problems in a web environment. What action will release the lock, closing the browser? Leaving the session to time out? What about if they then do save their changes?
You don't specify which database you are using. MS SQL server has a timestamp datatype. It has nothing to do with time though. It is mearly a number that will get changed each time the row gets updated. You don't have to do anything to make sure it gets changed, you just need to check it. You can achive similar by using a date/time last modified as @KM suggests. But this means you have to remember to change it each time you update the row. If you use datetime you need to use a data type with sufficient precision to ensure that you can't end up with the value not changing when it should. For example, some one saves a row, then someone reads it, then another save happens but leaves the modified date/time unchanged. I would use timestamp unless there was a requirement to track last modified date on records.
To check it you can do as @KM suggests and include it in the update statement where clause. Or you can begin a transaction, check the timestamp, if all is well do the update, then commit the transaction, if not then return a failure code or error.
Holding transactions open (as suggested by @le dorfier) is similar to pessimistic locking, but the amount of data locked may be more than a row. Most RDBM's lock at the page level by default. You will also run into the same issues as with pessimistic locking.
You mention in your question that you are worried about conflicting updates. That is what the locking will prevent surely. Both optimistic or pessimistic will, when properly implemented prevent exactly that. | I agree with the first answer above, we try to use optimistic locking when the chance of collisions is fairly low. This can be easily implemented with a LastModifiedDate column or incrementing a Version column. If you are unsure about frequency of collisions, log occurrences somewhere so you can keep an eye on them. If your records are always in "edit" mode, having separate "view" and "edit" modes could help reduce collisions (assuming you reload data when entering edit mode).
If collisions are still high, pessimistic locking is more difficult to implement in web apps, but definitely possible. We have had good success with "leasing" records (locking with a timeout)... similar to that 2 minute warning you get when you buy tickets on TicketMaster. When a user goes into edit mode, we put a record into the "lock" table with a timeout of N minutes. Other users will see a message if they try to edit a record with an active lock. You could also implement a keep-alive for long forms by renewing the lease on any postback of the page, or even with an ajax timer. There is also no reason why you couldn't back this up with a standard optimistic lock mentioned above.
Many apps will need a combination of both approaches. | Preferred database/webapp concurrency design when multiple users can edit the same data | [
"",
"c#",
"asp.net",
"database-design",
"web-applications",
"concurrency",
""
] |
Hey bloggers out there! I've created Wordpress blog that I am hosting myself, and I'm having the hardest time figuring out the best way to add C# snippets to my blog. What do you all use?
I'm currently using the "SyntaxHighlighter Evolved" plugin, and it works great for the most part - the only problem is that switching back to the Visual Editor removes all of the whitsepace padding. I've tried wrapping the [sourcecode] tags in <pre>'s, but then the formatter doesn't work correctly.
Any help would be much appreciated. I've spent about 10 hours trying to come up with a robust solution, and no luck.
Cheers! | See the [blog post that I wrote](http://ellisweb.net/2008/08/using-syntaxhighlighter-to-format-code-in-wordpress/) on this exact question, which explains how to use [SyntaxHighlighter](http://code.google.com/p/syntaxhighlighter/) and fix TinyMCE so that it doesn't mess up your white space or tags (you can either customize one of the tinymce files in Wordpress, or use a [plugin](http://www.engfers.com/plugins/tinymce-valid-elements/) to do it for you). | Use the WP-Syntax plugin. To use it, you wrap the code with a pre tag with a language attribute. Consolidates the effort. | What's best way to format C# in WordPress? | [
"",
"c#",
"wordpress",
"syntax-highlighting",
""
] |
I have a set of transactions occurring at specific points in time:
```
CREATE TABLE Transactions (
TransactionDate Date NOT NULL,
TransactionValue Integer NOT NULL
)
```
The data might be:
```
INSERT INTO Transactions (TransactionDate, TransactionValue)
VALUES ('1/1/2009', 1)
INSERT INTO Transactions (TransactionDate, TransactionValue)
VALUES ('3/1/2009', 2)
INSERT INTO Transactions (TransactionDate, TransactionValue)
VALUES ('6/1/2009', 3)
```
Assuming that the TransactionValue sets some kind of level, I need to know what the level was between the transactions. I need this in the context of a set of T-SQL queries, so it would be best if I could get a result set like this:
```
Month Value
1/2009 1
2/2009 1
3/2009 2
4/2009 2
5/2009 2
6/2009 3
```
Note how, for each month, we either get the value specified in the transaction, or we get the most recent non-null value.
My problem is that I have little idea how to do this! I'm only an "intermediate" level SQL Developer, and I don't remember ever seeing anything like this before. Naturally, I could create the data I want in a program, or using cursors, but I'd like to know if there's a better, set-oriented way to do this.
I'm using SQL Server 2008, so if any of the new features will help, I'd like to hear about it.
P.S. If anyone can think of a better way to state this question, or even a better subject line, I'd greatly appreciate it. It took me quite a while to decide that "spread", while lame, was the best I could come up with. "Smear" sounded worse. | I'd start by building a Numbers table holding sequential integers from 1 to a million or so. They come in really handy once you get the hang of it.
For example, here is how to get the 1st of every month in 2008:
```
select firstOfMonth = dateadd( month, n - 1, '1/1/2008')
from Numbers
where n <= 12;
```
Now, you can put that together using OUTER APPLY to find the most recent transaction for each date like so:
```
with Dates as (
select firstOfMonth = dateadd( month, n - 1, '1/1/2008')
from Numbers
where n <= 12
)
select d.firstOfMonth, t.TransactionValue
from Dates d
outer apply (
select top 1 TransactionValue
from Transactions
where TransactionDate <= d.firstOfMonth
order by TransactionDate desc
) t;
```
This should give you what you're looking for, but you might have to Google around a little to find the best way to create the Numbers table. | I don't have access to BOL from my phone so this is a rough guide...
First, you need to generate the missing rows for the months you have no data. You can either use a OUTER join to a fixed table or temp table with the timespan you want or from a programmatically created dataset (stored proc or suchlike)
Second, you should look at the new SQL 2008 'analytic' functions, like MAX(value) OVER ( partition clause ) to get the previous value.
(I KNOW Oracle can do this 'cause I needed it to calculate compounded interest calcs between transaction dates - same problem really)
Hope this points you in the right direction...
(Avoid throwing it into a temp table and cursoring over it. Too crude!!!) | How to Determine Values for Missing Months based on Data of Previous Months in T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
"gaps-and-islands",
""
] |
This is going to be very simple I know. I have seen so many different ways of using sql in asp.net with no real standard. What I want to know is how to cleanly select from an sql database in asp.net and retrieve multiple records. For example: select all userids.
```
String sql =
"SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"]
.ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
/*
This is where I need to know how to retrieve the information from the
above command(comm). I am looking for something similiar to php's
mysql_result. I want to access the records kind of like an array or some
other form of retrieving all the data.
Also when the new SqlCommand is called...does that actual run the
SELECT STATEMENT or is there another step.
*/
conn.Close();
``` | I think that this is what you are looking for.
```
String sql = "SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'";
string strCon = System.Web
.Configuration
.WebConfigurationManager
.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader nwReader = comm.ExecuteReader();
while (nwReader.Read())
{
int UserID = (int)nwReader["UserID"];
// Do something with UserID here...
}
nwReader.Close();
conn.Close();
```
I do have to say, though, that the overall approach can use a lot of tuning. First, you could at least start by simplifying access to your ConnectionString. For example, you could add the following to your Global.asax.cs file:
```
using System;
using System.Configuration;
public partial class Global : HttpApplication
{
public static string ConnectionString;
void Application_Start(object sender, EventArgs e)
{
ConnectionString = ConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
}
...
}
```
Now, throughout your code, just access it using:
```
SqlConnection conn = new SqlConnection(Global.ConnectionString);
```
Better yet, create a class in which the "plumbing" is hidden. To run the same query in my code, I'd just enter:
```
using (BSDIQuery qry = new BSDIQuery())
{
SqlDataReader nwReader = qry.Command("SELECT...").ReturnReader();
// If I needed to add a parameter I'd add it above as well: .ParamVal("CurrentUser")
while (nwReader.Read())
{
int UserID = (int)nwReader["UserID"];
// Do something with UserID here...
}
nwReader.Close();
}
```
This is just an example using *my* DAL. However, notice that there is no connection string, no command or connection objects being created or managed, just a "BSDIQuery" (which does lots of different things in addition to that shown). Your approach would differ depending on the tasks that you do most often. | Most of the time, I use this (note that I am also using a connection pooling approach):
```
public DataTable ExecuteQueryTable(string query)
{
return ExecuteQueryTable(query, null);
}
public DataTable ExecuteQueryTable(string query, Dictionary<string, object> parameters)
{
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
if (parameters != null)
{
foreach (string parameter in parameters.Keys)
{
cmd.Parameters.AddWithValue(parameter, parameters[parameter]);
}
}
DataTable tbl = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(tbl);
}
return tbl;
}
}
}
``` | Asp.Net select in Sql | [
"",
"asp.net",
"sql",
"ado",
""
] |
Is it possible to pass functions with arguments to another function in Python?
Say for something like:
```
def perform(function):
return function()
```
But the functions to be passed will have arguments like:
```
action1()
action2(p)
action3(p,r)
``` | Do you mean this?
```
def perform(fun, *args):
fun(*args)
def action1(args):
# something
def action2(args):
# something
perform(action1)
perform(action2, p)
perform(action3, p, r)
``` | This is what lambda is for:
```
def perform(f):
f()
perform(lambda: action1())
perform(lambda: action2(p))
perform(lambda: action3(p, r))
``` | Passing functions with arguments to another function in Python? | [
"",
"python",
"function",
""
] |
I'm trying to SELECT from the dba\_tab\_cols view from within a stored procedure. It's not working and I don't know why.
If I execute the following SQL as a query:
```
SELECT t.data_type FROM dba_tab_cols t
WHERE
t.table_name = 'ACCOUNTTYPE' AND
t.column_name = 'ACCESSEDBY';
```
it works fine. However if I copy it into a stored procedure like so:
```
SELECT t.data_type INTO dataType FROM dba_tab_cols t
WHERE
t.table_name = 'ACCOUNTTYPE' AND
t.column_name = 'ACCESSEDBY';
```
I get the error message "PL/SQL: ORA-00942: table or view does not exist" and the editor highlights dba\_tab\_cols while trying to compile. The same db user is being used in both cases.
dataType is declared as:
dataType varchar2(128);
PL/SQL (Oracle 9)
Anybody know the issue? | It's most likely a priviledges issue. Is the permission to access `dba_tab_columns` via a role or is it a direct select grant to your user? Priviledges granted via Roles aren't available in SPROCS.
A quick look on google suggests using `all_tab_cols` instead and seeing if that table has the required info you need. | To add to Eoin's answer:
> For most people, it comes as a
> surprise that the user cannot select
> the table from within a procedure if
> he has not been granted the select
> right directly (as opposed to through
> the role)
>
> If table user tries to compile this
> procedure, he gets a ORA-00942
> although this table certainly exists
> and he was granted the right to select
> this table. The problem is that
> procedures don't respect roles; only
> directly granted rights are respected.
> So, that means that table owner has to
> regrant the right to select:
<http://www.adp-gmbh.ch/ora/err/ora_00942.html> | Can't select from dba_tab_cols from within stored procedure (PL/SQL) | [
"",
"sql",
"oracle",
"stored-procedures",
"oracle9i",
"ora-00942",
""
] |
I got this error message :
```
java.net.URISyntaxException: Illegal character in query at index 31: http://finance.yahoo.com/q/h?s=^IXIC
```
`My_Url = http://finance.yahoo.com/q/h?s=^IXIC`
When I copied it into a browser address field, it showed the correct page, it's a valid `URL`, but I can't parse it with this: `new URI(My_Url)`
I tried : `My_Url=My_Url.replace("^","\\^")`, but
1. It won't be the url I need
2. It doesn't work either
How to handle this ?
Frank | Use `%` encoding for the `^` character, viz. `http://finance.yahoo.com/q/h?s=%5EIXIC` | You need to encode the URI to replace illegal characters with legal encoded characters. If you first make a URL (so you don't have to do the parsing yourself) and then make a URI using the [five-argument constructor](http://docs.oracle.com/javase/6/docs/api/java/net/URI.html#URI%28java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String%29), then the constructor will do the encoding for you.
```
import java.net.*;
public class Test {
public static void main(String[] args) {
String myURL = "http://finance.yahoo.com/q/h?s=^IXIC";
try {
URL url = new URL(myURL);
String nullFragment = null;
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), nullFragment);
System.out.println("URI " + uri.toString() + " is OK");
} catch (MalformedURLException e) {
System.out.println("URL " + myURL + " is a malformed URL");
} catch (URISyntaxException e) {
System.out.println("URI " + myURL + " is a malformed URL");
}
}
}
``` | How to deal with the URISyntaxException | [
"",
"java",
"uri",
""
] |
I am about to build a UI in Java and I am trying to determine what I should use. I definitely don't want to use vanilla swing.
The one caveat is that it has to be added inside of an existing swing application. I am looking at JavaFX and Groovy Swing Builder. For the former it looks like there is fairly poor support for embedding into swing.
Anyone have another other suggestions? | The groovy guys are working on **Griffon**: <http://groovy.codehaus.org/Griffon>.
I believe it is supposed to model a console type GUI like a web UI.
Another possible answer is **JavaFX**. Here's a link to their hello world app:
<http://javafx.com/docs/gettingstarted/javafx/create-first-javafx-app.jsp> | Have you considered using NetBeans?
<http://www.netbeans.org/features/java/swing.html> | Java User Interface Framework? | [
"",
"java",
"user-interface",
"swing",
"groovy",
"javafx",
""
] |
I have been having some trouble figuring out how exactly I get a process's ram usage. (How much ram it is currently consuming, not how much is reserved, or its max or min)
Lets say I have a process running in the back ground, Java.exe, it is allowed to use 1024mb of ram, how can I tell how much ram it is currently using.
I am starting the process myself, so I have access to the Process object, I would just like a little more clarification on what property is the one for me. | If you are purely interested in physical memory, you probably want [WorkingSet64](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.workingset64.aspx), which gives "the amount of physical memory allocated for the associated process." Understand that this value constantly fluctuates, and the value this call gives you may not be up to date. You may also be interested in [PeakWorkingSet64](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.peakworkingset64.aspx), which gives "the maximum amount of physical memory used by the associated process." | I found this on msdn and it is working
```
System.Diagnostics.Process proc = ...; // assign your process here :-)
int memsize = 0; // memsize in KB
PerformanceCounter PC = new PerformanceCounter();
PC.CategoryName = "Process";
PC.CounterName = "Working Set - Private";
PC.InstanceName = proc.ProcessName;
memsize = Convert.ToInt32(PC.NextValue()) / (int)(1024);
PC.Close();
PC.Dispose();
``` | Getting a process's ram usage | [
"",
"c#",
""
] |
Well, I'm trying to reuse a portion of C# code. It's an abstract class with UDP server, which can be seen here:
<http://clutch-inc.com/blog/?p=4>
I've created a derived class like this:
```
public class TheServer : UDPServer
{
protected override void PacketReceived(UDPPacketBuffer buffer)
{
}
protected override void PacketSent(UDPPacketBuffer buffer, int bytesSent)
{
}
}
```
And in my app I've created an instance of the derived class like this:
```
TheServer serv = new TheServer(20501);
serv.Start();
```
But I've got errors and I don't really understand why. Please help.
1. 'TheProject.TheServer' does not
contain a constructor that takes '1'
arguments
2. 'TheProject.UDPServer.Start()' is
inaccessible due to its protection
level
3. 'TheProject.UDPServer' does
not contain a constructor that takes
'0' arguments | Constructors do not get inherited in C#. You will have to chain them manually:
```
public TheServer(int port)
: base(port)
{
}
```
Also, if Start is protected, you will have to create some sort of public method that calls it:
```
public void StartServer()
{
Start();
}
``` | Your derived class needs to add a one-parameter constructor, and delegate it to the base class:
```
public TheServer(int port) : base(port) {}
```
Also, the `Start` method is protected. You'll need your own:
```
public void StartMe(){base.Start();}
``` | Abstract class, constructors and Co | [
"",
"c#",
"constructor",
"abstract-class",
""
] |
I have a `JTextField` in my *Swing* application that holds the file path of a file selected to be used. Currently I have a `JFileChooser` that is used to populate this value. However, I would like to add the ability for a user to drag-and-drop a file onto this `JTextField` and have it place the file path of that file into the `JTextField` instead of always having using the `JFileChooser`.
How can this be done? | First you should look into [Swing DragDrop support](http://java.sun.com/docs/books/tutorial/uiswing/dnd/intro.html). After that there are few little tricks for different operating systems. Once you've got things going you'll be handling the drop() callback. In this callback you'll want to check the DataFlavor of the Transferable.
For Windows you can just check the [DataFlavor.isFlavorJavaFileListType()](http://java.sun.com/javase/6/docs/api/java/awt/datatransfer/DataFlavor.html#isFlavorJavaFileListType()) and then get your data like this
```
List<File> dropppedFiles = (List<File>)transferable.getTransferData(DataFlavor.javaFileListFlavor)
```
For Linux (and probably Solaris) the DataFlavor is a little trickier. You'll need to make your own DataFlavor and the Transferable type will be different
```
nixFileDataFlavor = new DataFlavor("text/uri-list;class=java.lang.String");
String data = (String)transferable.getTransferData(nixFileDataFlavor);
for(StringTokenizer st = new StringTokenizer(data, "\r\n"); st.hasMoreTokens();)
{
String token = st.nextToken().trim();
if(token.startsWith("#") || token.isEmpty())
{
// comment line, by RFC 2483
continue;
}
try
{
File file = new File(new URI(token))
// store this somewhere
}
catch(...)
{
// do something good
....
}
}
``` | In case you don't want to spend too much time researching this relatively complex subject, and you're on Java 7 or later, here's a quick example of how to accept dropped files with a `JTextArea` as a drop target:
```
JTextArea myPanel = new JTextArea();
myPanel.setDropTarget(new DropTarget() {
public synchronized void drop(DropTargetDropEvent evt) {
try {
evt.acceptDrop(DnDConstants.ACTION_COPY);
List<File> droppedFiles = (List<File>)
evt.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
for (File file : droppedFiles) {
// process files
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
``` | How can I use Drag-and-Drop in Swing to get file path? | [
"",
"java",
"swing",
"drag-and-drop",
""
] |
I have this code;
```
using System;
namespace Rapido
{
class Constants
{
public static const string FrameworkName = "Rapido Framework";
}
}
```
Visual Studio tells me: `The constant 'Rapido.Constants.FrameworkName' cannot be marked static`
How can I make this constant available from other classes without having to create a new instance of it? (ie. directly accessing it via `Rapido.Constants.FrameworkName`) | ```
public static class Constants
{
public const string FrameworkName = "Rapido Framework";
}
``` | A const is already static as it cannot change between instances. | Static Constants in C# | [
"",
"c#",
"string",
"constants",
""
] |
The initialization process of a group of classes that share a common parent can be divided into three parts:
* Common initialization
* Subclass-specific initialization
* Common post-initialization
Currently the first two parts are called from the `__init__` method of each child class, but the final post-initialization part has to be called separately, for example
```
class BaseClass:
def __init__(self):
print 'base __init__'
self.common1()
def common1(self):
print 'common 1'
def finalizeInitialization(self):
print 'finalizeInitialization [common2]'
class Subclass1(BaseClass):
def __init__(self):
BaseClass.__init__(self)
self.specific()
def specific(self):
print 'specific'
if __name__ == '__main__':
s = Subclass1() # Don't forget to finalize the initialization
s.finalizeInitialization() # now the object is fully initialized
```
Is there a way to not to have to call `finalizeInitialization()`? Or one can transfer the call to `finalizeInitialization()` into `Subclass1`'s `__init__` (as in [S.Lott's answer](https://stackoverflow.com/questions/795190/how-to-perform-common-post-initialization-tasks-in-inherited-python-classes/795213#795213)). This makes the life easier, but still one has to remember to complete the initialization, this time inside the "constructor". Either way there is no way to enforce full initialization, which is what I'm looking for. | Version 1 - delegate everything.
```
class Subclass1(BaseClass):
def __init__(self):
super( Subclass1, self ).__init__()
self.specific()
super( Subclass1, self ).finalizeInitialization()
```
Version 2 - delegate just one step
```
class BaseClass:
def __init__(self):
print 'base __init__'
self.common1()
self.specific()
self.finalizeInitialization()
def common1(self):
print 'common 1'
def finalizeInitialization(self):
print 'finalizeInitialization [common2]'
def specific( self ):
# two choices:
# if this is "abstract": raise an exception
# if this is "concrete": pass
``` | You can use metaclasses (and updated to Python3 code):
```
class PostInitCaller(type):
def __call__(cls, *args, **kwargs):
obj = type.__call__(cls, *args, **kwargs)
obj.__post_init__()
return obj
class BaseClass(metaclass=PostInitCaller):
def __init__(self):
print('base __init__')
self.common1()
def common1(self):
print('common 1')
def finalizeInitialization(self):
print('finalizeInitialization [common2]')
def __post_init__(self): # this is called at the end of __init__
self.finalizeInitialization()
class Subclass1(BaseClass):
def __init__(self):
super().__init__()
self.specific()
def specific(self):
print('specific')
s = Subclass1()
```
```
base __init__
common 1
specific
finalizeInitialization [common2]
``` | How to perform common post-initialization tasks in inherited classes? | [
"",
"python",
"inheritance",
"initialization",
""
] |
I'm trying to load a custom `log.properties` file when my application is started.
My properties file is in the same package as my main class, so I assumed that the `-Djava.util.logging.config.file=log.properties` command line parameter should get the properties file loaded.
But the properties are only loaded when i specify a full absolute path to the properties file. Any suggestions how to use a relative path? | Java logging doesn't search your whole hard disk for a file; there are very simple rules how files are looked up. You want Java to see that the two files belong to each other but you didn't say so anywhere. Since Java sees no connection between the properties file and your class other than that they are in the same folder on your disk, it can't find the file.
`-Djava.util.logging.config.file=log.properties` only works if the file `log.properties` is in the current directory of the Java process (which can be pretty random). So you should use an absolute path here.
An alternate solution would be to move the file `logging.properties` into `$JAVA_HOME/lib/` (or edit the file which should be there). In that case, you don't need to set a System property. | You can dynamically load `java.util.logging` properties files from a relative path very easily. This is what I put inside a `static {}` block in my `Main` class. Put your `logging.properties` file in the `default package` and you can access it very easily with the following code.
```
final InputStream inputStream = Main.class.getResourceAsStream("/logging.properties");
try
{
LogManager.getLogManager().readConfiguration(inputStream);
}
catch (final IOException e)
{
Logger.getAnonymousLogger().severe("Could not load default logging.properties file");
Logger.getAnonymousLogger().severe(e.getMessage());
}
``` | Load java.util.logging.config.file for default initialization | [
"",
"java",
"properties",
"java.util.logging",
""
] |
I am currently working on a VB.NET desktop application that uses .mdb (Access) database files on the backend. The .mdb files are opened and edited in the VB.NET app. Once editing is completed, the users will need to import the data into our SQL Server database. This is an easy task, until you try to introduce the dynamic filepath scenario.
I have a fair amount of experience with SSIS but am having some trouble with approaching this. I have created a WinForm that allows the user to browse to the .mdb file of their choice. The .mdb filenames have timestamp/date information in them, to make them unique. (I did not develop this part of the app, I recently began working on this, hence the problems. I would not timestamp an .mdb filename but this is what Im forced to use!).
Anyways, I need to pass the filename and path to my SSIS package, dynamically. I see where you create variables for ConnectionString, etc. But I am really unsure of the details and what type of Data Connection I should use for MS Access (Ole DB, ODBC, or Jet 4.0 for Office?? sheesh there are a lot!!)
I also assume that my data connection's connection string must be dynamic, since the package will use the .mdb file as the SOURCE. But how do you create a dynamic data connection in SSIS for .mdb files?
And how do I pass the filename/path string to my SSIS package?
I am currently prototyping with this code:
```
'Execute the SSIS_Import package
Dim pkgLocation As String
Dim pkg As New Package
Dim app As New Microsoft.SqlServer.Dts.Runtime.Application
Dim pkgResults As DTSExecResult
Dim eventListener As New EventListener()
Try
pkgLocation = "C:\SSIS_DataTransfer\ImportPackage.dtsx"
'TO-DO: pass databasePath variable to SSIS package here ???
pkg = app.LoadPackage(pkgLocation, eventListener)
pkgResults = pkg.Execute(Nothing, Nothing, eventListener, Nothing, Nothing)
Select Case pkgResults
Case DTSExecResult.Completion
MsgBox("Data import completed!")
Case DTSExecResult.Success
MsgBox("Data import was successful!")
Case DTSExecResult.Failure
MsgBox("Data import was not successful!")
End Select
Catch ex As Exception
MsgBox(ex.Message)
End Try
```
1. How do I pass the .mdb file location to my SSIS package? LoadPackage maybe?
2. How do I use the dynamic file location in my Data Connection for my SSIS package?
It is quite simple to upload an .mdb file that is NOT dynamic. Setting the source and destination is quite easy until you introduce the DYNAMIC aspect of user selection. How is this possible in SSIS?
any help is greatly appreciated.
Thank you. | This will change some, depending on the connection and execution method you use but it is basically the same to get the variables into the package. It's been a while since I've used SSIS so it may be a little off. But it's mostly straightforward once you get the initial steps figured out.
To get variables into the package:
* Create a variable in the package to hold the file name. Click the designer surface to ensure you are at the package level scope, open the Variables windows, click New and specify the name of the variable ("filePath"), the type ("String"), and give it a default value.
* Set the variable from your VB.Net code:
In VB.NET:
```
pkg = app.LoadPackage(pkgLocation, eventListener)
' Set the file path variable in the package
' NB: You may need to prefix "User::" to the variable name depending on the execution method
pkg.Variables("filePath").Value = databasePath
pkgResults = pkg.Execute(Nothing, Nothing, eventListener, Nothing, Nothing)
```
* You should now have access to the variable in the package.
Depending on the connection you are using to import the Access db, you may have to do a few different things. If you are using an OLEDB Connection, there is a connection string and ServerName property. Set the ServerName property to use the variable that has your file path (`@[User::filePath]`) and the connection string to also use the filePath variable (`"Data Source=" + @[User::filePath] + ";Provider=Microsoft.Jet.OLEDB.4.0;"`)
Check out [this text file example](http://blogs.conchango.com/jamiethomson/archive/2006/03/11/SSIS-Nugget_3A00_-Setting-expressions.aspx) for how to use expressions to set the connection string dynamically. [This one is for Access](http://www.mssqltips.com/tip.asp?tip=1437) but is complicated with connection strings from a database. | I don't call SSIS packages from programs, so I don't know how to configure them that way. I do know that when I use an OLEDB Connection Manager and use the "Native OLE DB Jet 4.0 Provider", that I can set the ServerName property of the connection manager to the path to the .MDB file. | How to Set SSIS package dynamic .mdb connection When Running Package from .NET Application | [
"",
"sql",
"ms-access",
"dynamic",
"ssis",
"filepath",
""
] |
I'm trying to call the HtmlTidy library dll from C#. There's a few examples floating around on the net but nothing definitive... and I'm having no end of trouble. I'm pretty certain the problem is with the p/invoke declaration... but danged if I know where I'm going wrong.
I got the libtidy.dll from <http://www.paehl.com/open_source/?HTML_Tidy_for_Windows> which seems to be a current version.
Here's a console app that demonstrates the problem I'm having:
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication5
{
class Program
{
[StructLayout(LayoutKind.Sequential)]
public struct TidyBuffer
{
public IntPtr bp; // Pointer to bytes
public uint size; // # bytes currently in use
public uint allocated; // # bytes allocated
public uint next; // Offset of current input position
};
[DllImport("libtidy.dll")]
public static extern int tidyBufAlloc(ref TidyBuffer tidyBuffer, uint allocSize);
static void Main(string[] args)
{
Console.WriteLine(CleanHtml("<html><body><p>Hello World!</p></body></html>"));
}
static string CleanHtml(string inputHtml)
{
byte[] inputArray = Encoding.UTF8.GetBytes(inputHtml);
byte[] inputArray2 = Encoding.UTF8.GetBytes(inputHtml);
TidyBuffer tidyBuffer2;
tidyBuffer2.size = 0;
tidyBuffer2.allocated = 0;
tidyBuffer2.next = 0;
tidyBuffer2.bp = IntPtr.Zero;
//
// tidyBufAlloc overwrites inputArray2... why? how? seems like
// tidyBufAlloc is stomping on the stack a bit too much... but
// how? I've tried changing the calling convention to cdecl and
// stdcall but no change.
//
Console.WriteLine((inputArray2 == null ? "Array2 null" : "Array2 not null"));
tidyBufAlloc(ref tidyBuffer2, 65535);
Console.WriteLine((inputArray2 == null ? "Array2 null" : "Array2 not null"));
return "did nothing";
}
}
}
```
All in all I'm a bit stumpped. Any help would be appreciated! | You are working with an old definition of the TidyBuffer structure. The new structure is larger so when you call the allocate method it is overwriting the stack location for inputArray2. The new definition is:
```
[StructLayout(LayoutKind.Sequential)]
public struct TidyBuffer
{
public IntPtr allocator; // Pointer to custom allocator
public IntPtr bp; // Pointer to bytes
public uint size; // # bytes currently in use
public uint allocated; // # bytes allocated
public uint next; // Offset of current input position
};
``` | For what it's worth, we tried Tidy at work and switched to HtmlAgilityPack. | Strange problem calling a .DLL from C# | [
"",
"c#",
"pinvoke",
"htmltidy",
""
] |
I'm developing a web application using a cookie to store session information. I've manually deleted the session cookies because I'm working on another part of the code where I don't want a login session. However, after a couple reloads of the page, the session cookie mysteriously reappears, including an earlier cookie that I had only set once for testing purposes, then deleted and never used again.
I keep manually deleting the cookies in question, but still, when I reload the page after a while, the cookies are back. I've double-checked my code and I am positive I'm not setting those cookies anywhere. My code is all in one file at the moment, and I'm not including anything, so there's no possibility that I'm overlooking something.
My code is in PHP and used the setcookie() call when I initially created those cookies.
I've not set an expiry date on the cookies.
Using Safari 4 Beta and the GlimmerBlocker proxy.
What's the explanation for this weird behaviour? | There are known problems with certain browsers cookie handling.
See the following paper:
[iSEC Cleaning Up After Cookies](http://www.isecpartners.com/files/iSEC_Cleaning_Up_After_Cookies.pdf)
Also see [this discussion](http://discussions.apple.com/thread.jspa?messageID=9262463) on Apple.com regarding the case of the reappearing cookie. | Try this, it *should* remove all of your session cookies:
```
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// Finally, destroy the session.
session_destroy();
``` | What's the reason for cookies mysteriously reappearing? | [
"",
"php",
"cookies",
"safari",
"zombie-process",
""
] |
The code below is what I'm using for a website menu which moves the link for the current month's page to the top of the link list on the change of the month.
But this fails on the 31st of some months, such as April; I get two links to the same month for most of the links. I've read through the issues with the way php generates dates, but can't figure out how to change this code.
Anyone php Ph.D's want to take a stab at it? Thanks
```
<?php $month1 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+1 , date('d'), date('Y'))));
$month2 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+2 , date('d'), date('Y'))));
$month3 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+3 , date('d'), date('Y'))));
$month4 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+4 , date('d'), date('Y'))));
$month5 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+5 , date('d'), date('Y'))));
$month6 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+6 , date('d'), date('Y'))));
$month7 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+7 , date('d'), date('Y'))));
$month8 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+8 , date('d'), date('Y'))));
$month9 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+9 , date('d'), date('Y'))));
$month10 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+10 , date('d'), date('Y'))));
$month11 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+11 , date('d'), date('Y')))); ?>
<a href="http://mydomain.com/<?php echo strtolower(date('F')); ?>/" title="<?php echo ucfirst(date('F')); ?>"><?php echo (date('F')); ?></a><br />
<a href="http://mydomain.com/<?php echo strtolower($month1); ?>/" title="<?php echo $month1; ?>"><?php echo $month1; ?></a><br />
...(2 through 10)...
<a href="http://mydomain.com/<?php echo strtolower($month11); ?>/" title="<?php echo $month11; ?>"><?php echo $month11; ?></a><br />
``` | `<?php`
```
$current_month = date('n');
$MONTHS = array();
for ($m=0; $m<12; $m++) {
$display_month = $m + $current_month;
$MONTHS[] = date('F',mktime(1,1,1,$display_month,1,date("Y")));
}
foreach ($MONTHS as $month) {
echo "
<a
href=\"http://mydomain.com/".strtolower($month)."\"
title=\"$month\">$month</a><br />";
}
?>
``` | You can look into using [strtotime()](http://is.php.net/manual/en/function.strtotime.php) instead of mktime. Since in strtotime() to can do
```
strtotime("-1 day", time());
```
On the 1st of some month and it will go back one day exactly. Even counting in leap years. | How would I fix the last day of the month errors that result with this php code? | [
"",
"php",
"date",
"mktime",
""
] |
I have what I'm pretty sure is a bug in the optimizer in Visual studio 2005. The problem is with an STL map.
Here's the relevant code:
```
MyMapIterator myIt = m_myMap.find(otherID);
if (myIt != m_myMap.end() && myIt->second.userStatus == STATUS_A)
{
//Prints stuff. No side-effects whatsoever.
}
else if (myIt != m_myMap.end() && myIt->second.userStatus == STATUS_B && myIt->second.foo == FOO_A)
{
//Prints stuff. No side-effects whatsoever.
}
else if (myIt != m_myMap.end() && myIt->second.userStatus == STATUS_B && myIt->second.foo == FOO_B && /*other meaningless conditions */)
{
//Prints stuff. No side-effects whatsoever.
}
```
Works flawlessly in debug, used to crash in release, and disabling global optimizations "fixed it" Now, nothing works. I get a:
```
Microsoft Visual Studio C Runtime Library has detected a fatal error in [...]
Press Break to debug the program or Continue to terminate the program.
```
This happens on the **first MyMapIterator::operator-> of the last else if**
The map is empty, I know that find should have returned end(), The first two comparisons to that effect work. But somehow, the third time 'myIt != m\_myMap.end()' returns true, and the right side of the && is executed.
Various other places fail like this with a variant of 'myIt != m\_myMap.end()' returning true in that same file, but this is, to me, the one that rules out most other possibilities. I used to think it was a buffer overflow that was stomping on my map, but take a look back at the code. I am positive that no other thread is stomping on it, and this is 100% reproductible.
So, what do I do from here. This is not performance sensitive in the slightest. I just need it to work as it should. Any option is acceptable. Yes I know I could surround the whole thing with the iterator equality check and it isn't the nicest code. The point is, it should still work, and if that fails, anything else can.
**EDIT**
The last else-if doesn't generate any jump !
```
if (myIt != m_myMap.end() && myIt->second.userStatus == STATUS_A)
009270BE mov ecx,dword ptr [this]
009270C4 add ecx,0Ch
009270C7 lea eax,[ebp-90h]
009270CD call std::_Tree<std::_Tmap_traits<unsigned __int64,lux::Foo,std::less<unsigned __int64>,std::allocator<std::pair<unsigned __int64 const ,lux::Foo> >,0> >::end (8A21E0h)
009270D2 mov esi,eax
009270D4 lea edi,[myIt]
009270D7 call std::_Tree<std::_Tmap_traits<unsigned __int64,lux::Foo,std::less<unsigned __int64>,std::allocator<std::pair<unsigned __int64 const ,lux::Foo> >,0> >::const_iterator::operator!= (8A2220h)
009270DC movzx ecx,al
009270DF test ecx,ecx
009270E1 je lux::Bar::DoStuff+0E4h (927154h)
009270E3 lea esi,[myIt]
009270E6 call std::_Tree<std::_Tmap_traits<unsigned __int64,lux::Foo,std::less<unsigned __int64>,std::allocator<std::pair<unsigned __int64 const ,lux::Foo> >,0> >::iterator::operator-> (8A21F0h)
009270EB cmp dword ptr [eax+8],1
009270EF jne lux::Bar::DoStuff+0E4h (927154h)
{
Stuff
}
else if (myIt != m_myMap.end() && myIt->second.userStatus == STATUS_B)
00927154 mov ecx,dword ptr [this]
0092715A add ecx,0Ch
0092715D lea eax,[ebp-98h]
00927163 call std::_Tree<std::_Tmap_traits<unsigned __int64,lux::Foo,std::less<unsigned __int64>,std::allocator<std::pair<unsigned __int64 const ,lux::Foo> >,0> >::end (8A21E0h)
00927168 mov esi,eax
0092716A lea edi,[myIt]
0092716D call std::_Tree<std::_Tmap_traits<unsigned __int64,lux::Foo,std::less<unsigned __int64>,std::allocator<std::pair<unsigned __int64 const ,lux::Foo> >,0> >::const_iterator::operator!= (8A2220h)
00927172 movzx edx,al
00927175 test edx,edx
00927177 je lux::Bar::DoStuff+17Ah (9271EAh)
00927179 lea esi,[myIt]
0092717C call std::_Tree<std::_Tmap_traits<unsigned __int64,lux::Foo,std::less<unsigned __int64>,std::allocator<std::pair<unsigned __int64 const ,lux::Foo> >,0> >::iterator::operator-> (8A21F0h)
00927181 cmp dword ptr [eax+8],2
00927185 jne lux::Bar::DoStuff+17Ah (9271EAh)
{
//Stuff
}
else if (myIt != m_myMap.end() && myIt->second.userStatus == STATUS_C)
009271EA mov ecx,dword ptr [this]
009271F0 add ecx,0Ch
009271F3 lea eax,[ebp-0A0h]
009271F9 call std::_Tree<std::_Tmap_traits<unsigned __int64,lux::Foo,std::less<unsigned __int64>,std::allocator<std::pair<unsigned __int64 const ,lux::Foo> >,0> >::end (8A21E0h)
009271FE mov esi,eax
00927200 lea edi,[myIt]
00927203 call std::_Tree<std::_Tmap_traits<unsigned __int64,lux::Foo,std::less<unsigned __int64>,std::allocator<std::pair<unsigned __int64 const ,lux::Foo> >,0> >::const_iterator::operator!= (8A2220h)
00927208 lea esi,[myIt]
0092720B call std::_Tree<std::_Tmap_traits<unsigned __int64,lux::Foo,std::less<unsigned __int64>,std::allocator<std::pair<unsigned __int64 const ,lux::Foo> >,0> >::iterator::operator-> (8A21F0h)
{
//Stuff in the condition and after
``` | Well guys. After much pain and tears. To fix it at least temporarily I had to rework the code a bit to the form suggested by most people, which is how it should have been in the first case:
```
if (myIt != m_myMap.end())
{
if (myIt->second.userStatus == STATUS_A)
{
//Prints stuff. No side-effects whatsoever.
}
else if (myIt->second.userStatus == STATUS_B && myIt->second->foo == FOO_A)
{
//Prints stuff. No side-effects whatsoever.
}
else if (myIt->second.userStatus == STATUS_B && myIt->second->foo == FOO_B && /*other meaningless conditions */)
{
//Prints stuff. No side-effects whatsoever.
}
}
```
However, the bug was still present. This gem fixed it:
```
if (myIt != m_myMap.end())
if (myIt != m_myMap.end())
{
if (myIt->second.userStatus == STATUS_A)
{
//Prints stuff. No side-effects whatsoever.
}
else if (myIt->second.userStatus == STATUS_B && myIt->second->foo == FOO_A)
{
//Prints stuff. No side-effects whatsoever.
}
else if (myIt->second.userStatus == STATUS_B && myIt->second->foo == FOO_B && /*other meaningless conditions */)
{
//Prints stuff. No side-effects whatsoever.
}
}
```
Yes. Doubling the if resulted in a jump instruction being emitted after the test. | I suspect you have code elsewhere that has a buffer over run in it.
This other code is managing to wreck the memory that the posted code is using.
In debug mode the extra memory padding will change the behavior.
Changing other random code will also change the behaviour as it will shift the relative position of things.
Basically you'll need to review a lot of code or use a tool like BoundsChecker to find the error.
Concentrate on arrays or any raw pointer maths. Also any use of deleted pointers.
Bugs like this can hide for a long time if they write to place that doesn't cause a crash. For the same reason they often mysteriously disappear. | Perplexing STL bug in Release in Visual Studio | [
"",
"c++",
"optimization",
"crash",
"memory-corruption",
""
] |
I have an internal WPF client application that accesses a database.
The application is a central resource for a Support team and as such includes Remote Access/Login information for clients. At the moment this database is not available via a web interface etc, but one day is likely to.
The remote access information includes the username and passwords for the client's networks so that our client's software applications can be remotely supported by us. I need to store the usernames and passwords in the database and provide the support consultants access to them so that they can login to the client's system and then provide support. Hope this is making sense.
So the dilemma is that I don't want to store the usernames and passwords in cleartext on the database to ensure that if the DB was ever compromised, I am not then providing access to our client's networks to whomever gets the database.
I have looked at two-way encryption of the passwords, but as they say, two-way is not much different to cleartext as if you can decrypt it, so can an attacker... eventually. The problem here is that I have setup a method to use a salt and a passcode that are stored in the application, I have used a salt that is stored in the db, but all have their weaknesses, ie if the app was reflected it exposes the salts etc.
How can I secure the usernames and passwords in my database, and yet still provide the ability for my support consultants to view the information in the application so they can use it to login?
This is obviously different to storing user's passwords as these are one way because I don't need to know what they are. But I do need to know what the client's remote access passwords are as we need to enter them in at the time of remoting to them.
Anybody have some theories on what would be the best approach here?
**update**
The function I am trying to build is for our CRM application that will store the remote access details for the client. The CRM system provides call/issue tracking functionality and during the course of investigating the issue, the support consultant will need to remote in. They will then view the client's remote access details and make the connection | A similar situation occurs at our company, where the database administrators wish to maintain a pool of credentials amongst themselves.
I was originally going to post this idea, but [erickson beat me to it](https://stackoverflow.com/questions/835826/a-security-encryption-dilemma/836442#836442). However, it may be worth while to post some pseudo code to elaborate, so I suppose my time answering the question isn't completely wasted...
Things you will need:
* A database management system
* An [asymmetric cipher](http://en.wikipedia.org/wiki/Public-key_cryptography) (example: [RSA](http://en.wikipedia.org/wiki/RSA)):
* A [symmetric cipher](http://en.wikipedia.org/wiki/Symmetric-key_algorithm) (example: [AES](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard))
* A [key derivation function](http://en.wikipedia.org/wiki/Key_derivation_function) (example: [PBKDF2](http://en.wikipedia.org/wiki/PBKDF2), thanks erickson!)
+ This requires a [cryptographic hash function](http://en.wikipedia.org/wiki/Cryptographic_hash_function) (example: [SHA-512](http://en.wikipedia.org/wiki/SHA_hash_functions))
First off, let's set up the database schema. These tables will be demonstrated shortly.
```
CREATE TABLE users (
user_id INTEGER,
authentication_hash BINARY,
authentication_salt BINARY,
public_key BINARY,
encrypted_private_key BINARY,
decryption_key_salt BINARY,
PRIMARY KEY(user_id)
)
CREATE TABLE secrets (
secret_id INTEGER,
-- WHATEVER COLUMNS YOU REQUIRE TO ACCURATELY MODEL YOUR PASSWORDS (CLIENT INFO, ETC)
PRIMARY KEY(secret_id)
)
CREATE TABLE granted_secrets (
secret_id INTEGER,
recipient_id INTEGER,
encrypted_data BINARY,
PRIMARY KEY(secret_id, recipient_id),
FOREIGN KEY(secret_id) REFERENCES secrets(secret_id)
FOREIGN KEY(recipient_id) REFERENCES users(user_id)
)
```
Before a user can begin using this system, they must be registered.
```
function register_user(user_id, user_password) {
authentication_salt = generate_random_salt()
authentication_hash = hash(authentication_salt, user_password);
(public_key, private_key) = asymmetric_cipher_generate_random_key_pair();
decryption_key_salt = generate_random_salt()
decryption_key = derive_key(decryption_key_salt, user_password)
encrypted_private_key = symmetric_cipher_encrypt(
input => private_key,
key => decryption_key
)
// IMPORTANT: The decryption_key_hash is never stored
execute("INSERT INTO users (user_id, authentication_hash, authentication_salt, public_key, encrypted_private_key, decryption_key_salt) VALUES (:user_id, :authentication_hash, :authentication_salt, :public_key, :encrypted_private_key, :decryption_key_salt)")
}
```
The user can sign in to the system.
```
function authenticate_user(user_id, user_password)
correct_authentication_hash = query("SELECT authentication_hash FROM users WHERE user_id = :user_id")
authentication_salt = query("SELECT authentication_salt FROM users WHERE user_id = :user_id")
given_authentication_hash = hash(authentication_salt, user_password)
return correct_authentication_hash == given_authentication_hash
```
A secret can then be granted to a recipient user.
```
function grant_secret(secret_id, secret_data, recipient_id) {
recipient_public_key = query("SELECT public_key FROM users WHERE user_id = :recipient_id")
encrypted_secret_data = asymmetric_cipher_encrypt(
input => secret_data,
public_key => recipient_public_key
)
execute("INSERT INTO granted_secrets (secret_id, recipient_id, encrypted_data) VALUES (:secret_id, :recipient_id, :encrypted_secret_data)")
}
```
Finally, a user that have been granted access to a secret (the recipient) can retrieve it.
```
void retrieve_secret(secret_id, recipient_id, recipient_password)
encrypted_recipient_private_key = query("SELECT encrypted_private_key FROM users WHERE user_id = :recipient_id")
recipient_decryption_key_salt = query("SELECT decryption_key_salt FROM users WHERE user_id = :recipient_id")
recipient_decryption_key = derive_key(recipient_decryption_key_salt, recipient_password)
recipient_private_key = symmetric_cipher_decrypt(
input => encrypted_recipient_private_key,
key => recipient_decryption_key
)
encrypted_secret_data = query("SELECT encrypted_data FROM granted_secrets WHERE secret_id = :secret_id AND recipient_id = :recipient_id")
secret_data = asymmetric_cipher_decrypt(
input => encrypted_secret_data,
private_key => recipient_private_key
)
return secret_data
```
Hopefully this can help. It certainly helped me flesh out my ideas. | There are a few ways to do this; the best solution will depend on how your support team accesses the clients' sites, how many members belong to the support team, and the architecture of you application.
The best way to do something like this is to use something like Kerberos. This way, members of the support team don't have to be entrusted with the clients' passwords—passwords that they could write down and use later to attack customers. The support team can instantly revoke the access of member without any action by the client.
However, I'm guessing that this is a more dangerous system where team members get a password to access client systems via Remote Desktop, SSH, or something like that. In that case, a great liability is assumed when client passwords are revealed to team members.
Personally, I wouldn't accept that kind of risk. It isn't that I don't feel like I can trust my team, but more that I can't trust my customers. If something happens at their site (or even if they merely pretend that something happened), all of the sudden I'm a suspect. I'd rather design a system where no one can access the customer systems acting alone. This protects the customer from a bad apple on my team, and protects me from false accusations.
Anyway, one approach would be to generate keys for each team member. These could be password-based symmetric encryption keys, but then some secret key must be kept centrally. Better would be to use an asymmetric algorithm like RSA. Then only public keys of team members are kept centrally.
When a new password is received from a client, encrypt it with the public key of each team member that needs a copy. This encrypted password can be stored in the database, and given to a team member each time they request it, or it can be actively pushed out to team members for them to store. In either case, when it is needed, the password is decrypted with the private key held by the team member (in a key store encrypted with a password that they choose).
There are downsides to this. Reiterating the point above, team members get access to the clients password. Are they worthy of this trust? What if the client has a security breach unrelated to this system, but wants to pin the blame on someone? Second, while no decryption keys are stored at the server, trust still needs to be established for the public key of each team member. Otherwise, an attacker could slip their own, rogue public key into the collection and receive passwords that they can decrypt. | A Security (encryption) Dilemma | [
"",
"c#",
".net",
"wpf",
"database",
"encryption",
""
] |
using Fast CGI I can't get it to read the php.ini file. See my phpinfo below.
System Windows NT WIN-PAFTBLXQWYW 6.0 build 6001
Build Date Mar 5 2009 19:43:24
Configure Command cscript /nologo configure.js "--enable-snapshot-build" "--enable-debug-pack" "--with-snapshot-template=d:\php-sdk\snap\_5\_2\vc6\x86\template" "--with-php-build=d:\php-sdk\snap\_5\_2\vc6\x86\php\_build" "--disable-zts" "--disable-isapi" "--disable-nsapi" "--with-pdo-oci=D:\php-sdk\oracle\instantclient10\sdk,shared" "--with-oci8=D:\php-sdk\oracle\instantclient10\sdk,shared" "--enable-htscanner=shared"
Server API CGI/FastCGI
Virtual Directory Support disabled
Configuration File (php.ini) Path C:\Windows
**Loaded Configuration File (none)**
Scan this dir for additional .ini files (none)
My php.ini file is residing in both my c:\php and my c:\windows I've made sure it has read permissions in both places from network service.
I've added various registry settings, Environment Variables and followed multiple tutorials found on the web and no dice as of yet. Rebooted after each.
My original install was using MS "Web Platform Installer" however I have since rebooted.
Any ideas on where to go from here would be most welcome. | I finally figured out the problem. Windows Server 2008 by default apparently has "hide file extensions for known file types" enabled by default. I hadn't noticed it because it was displaying the extensions for other files around it
I had renamed my file to php.ini.ini at some point accidentally and it was appearing to me as php.ini due to the setting.
Felt really dumb when I figured it out. But looking at the directory with that setting on it's actually very difficult to tell. | Does the configuration file path match where you've put php.ini?
Just create a file called getinfo.php with the following:
```
<?php phpinfo(); ?>
```
Save it in your root directory, and go to <http://www.yourwebsite.com/getinfo.php> to see what it is. | PHP Configuration file won't load IIS7 x64 | [
"",
"load",
"64-bit",
"php",
""
] |
I have a problem with MouseEvents on my WinForm C# application.
I want to get *all* mouse clicks on my application, but I don't want to put a listener in every child component neither use Windows mouse hook.
On Flash I could put a listener on Stage to get all the MouseEvents on the movie.
Is there such thing on C#? A global MouseListener?
---
**Edit:**
I create this class from IMessageFilter ans used Application.AddMessageFilter.
```
public class GlobalMouseHandler : IMessageFilter{
private const int WM_LBUTTONDOWN = 0x201;
public bool PreFilterMessage(ref Message m){
if (m.Msg == WM_LBUTTONDOWN) {
// Do stuffs
}
return false;
}
}
```
And put this code on the Controls that need listen global clicks:
```
GlobalMouseHandler globalClick = new GlobalMouseHandler();
Application.AddMessageFilter(globalClick);
``` | One straightforward way to do this is to add a message loop filter by calling `Application.AddMessageFilter` and writing a class that implements the `IMessageFilter` interface.
Via `IMessageFilter.PreFilterMessage`, your class gets to see any inputs messages that pass through your application's message loop. `PreFilterMessage` also gets to decide whether to pass these messages on to the specific control to which they're destined.
One piece of complexity that this approach introduces is having to deal with Windows messages, via the Message struct passed to your `PreFilterMessage` method. This means referring to the Win32 documention on `WM\_LBUTTONDOWN, WM\_MOUSEMOVE`, `WM\_LBUTTONUP` etc, instead of the conventional `MouseDown`, `MouseMove` and `MouseUp` events. | **Sample Class**
```
class CaptureEvents : IMessageFilter
{
#region IMessageFilter Members
public delegate void Callback(int message);
public event Callback MessageReceived;
IntPtr ownerWindow;
Hashtable interestedMessages = null;
CaptureEvents(IntPtr handle, int[] messages)
{
ownerWindow = handle;
for(int c = 0; c < messages.Length ; c++)
{
interestedMessages[messages[c]] = 0;
}
}
public bool PreFilterMessage(ref Message m)
{
if (m.HWnd == ownerWindow && interestedMessages.ContainsKey(m.Msg))
{
MessageReceived(m.Msg);
}
return true;
}
#endregion
}
``` | Capturing mouse events from every component | [
"",
"c#",
"winforms",
"mouseevent",
""
] |
I'm a newbie to programming. I had 1 semester of computer science (we used java). I got an A in the course and was able to do everything assigned, however I'm not sure I really understood it. I ignored the text and learned by looking at sample programs and then trial and error. I was ahead of the class except for two guys who came in knowing java or another OOP language.
I'd like to learn Python. I'm also going to build a second PC from extra parts I have and use linux. Basically, I want to enhance my knowledge of computers. Thats my motivation.
Now on learning python are there any good programming theory books that would be useful? Or should I read up on more on how computers operate on the lowest levels? I don't think I know enough to ask the question I want.
I guess to make it simple, I am asking what should I know to make the most of learning python. This is not for a career. This is from a desire to know. I am no longer a computer science major (it also would not have any direct applications to my anticipated career.)
I'm not looking to learn in "30 days" or "1 week" or whatever. So, starting from a very basic level is fine with me.
Thanks in advance. I did a search and didn't quite find what I was looking for.
UPDATE: Thanks for all the great advice. I found this site at work and couldn't find it on my home computer, so I am just getting to read now. | My recommendation is always to start at the high level of abstraction. You don't need to know how logic gates work and how you can use them to build a CPU -- it's cool stuff, but it's cool stuff that makes a *lot* more sense once you've messed around at the higher levels. Python is therefore an excellent choice as a learning aid.
[How to Think Like A Computer Scientist: Learning With Python](http://www.greenteapress.com/thinkpython/thinkCSpy/) is available on the Internet and is an excellent introduction to the high-level concepts that make computers go. And it's even Python-specific.
If you're looking to have your brain turned inside-out, [SICP](http://mitpress.mit.edu/sicp/full-text/book/book.html) will do a good job of it. I don't recommend it as a first text, though; it's heavy going.
Both of these books are high-level. They won't teach you anything about the low-level details like memory structures or what a CPU actually does, but that's something I would reserve for later anyway.
D'A | Specifically for the Python part of your question I can highly recommend <http://www.diveintopython3.net/> by Mark Pilgrim. That's free and pretty well structured.
Python is a nice choice, you will have fun! | Newbie teaching self python, what else should I be learning? | [
"",
"python",
"theory",
""
] |
Have a SomeLib.pro file that contains:
```
CONFIG += debug
TEMPLATE = lib
TARGET = SomeLib
..
```
Then in a dependent SomeApp.pro:
```
..
debug:LIBS += -lSomeLib_debug
..
```
How can I force SomeApp to build if I touched SomeLib in qmake? | It's ugly because you need to give the exact library file name, but this should work:
TARGETDEPS += libfoo.a | QT Creator will do the work if you click "Add library..." in the context menu of the project that should include the library.
These variables are configured automatically for you:
* LIBS
* INCLUDEPATH
* DEPENDPATH
* PRE\_TARGETDEPS
See also <http://doc.qt.digia.com/qtcreator-2.1/creator-project-qmake-libraries.html> | How do a specify a library file dependency for qmake in Qt? | [
"",
"c++",
"qt",
"dependencies",
"qmake",
""
] |
I would like to take a simple query on a list of members that are indexed by a number and group them into 'buckets' of equal size. So the base query is:
```
select my_members.member_index from my_members where my_members.active=1;
```
Say I get 1000 member index numbers back, now I want to split them into 10 equally sized groups by a max and min member index. Something like:
Active members in 0 through 400 : 100
Active members in 401 through 577 : 100
...
Active members in 1584 through 1765 : 100
The best I could come up with is repeatedly querying for the max(my\_members.member\_index) with an increasing rownum limit:
```
for r in 1 .. 10 loop
select max(my_members.member_index)
into ranges(r)
from my_members
where my_members.active = 1
and rownum < top_row
order by my_members.member_index asc;
top_row := top_row + 100;
end loop;
``` | NTILE is the way to go - worth reading up on analytic functions as they can hugely simplify your SQL.
Small comment on the original code - doing a rownum restriction *before* an ORDER BY can produce adverse results
```
for r in 1 .. 10 loop
select max(my_members.member_index)
into ranges(r)
from my_members
where my_members.active = 1
and rownum < top_row
order by my_members.member_index asc;
top_row := top_row + 100;
```
end loop;
Try the following :
```
create table example_nums (numval number)
begin
for i in 1..100 loop
insert into example_nums values (i);
end loop;
end;
SELECT numval FROM example_nums
WHERE rownum < 5
ORDER BY numval DESC;
```
To get the result you expect you need to do
```
SELECT numval FROM
(SELECT numval FROM example_nums
ORDER BY numval DESC)
WHERE rownum < 5
```
(Note - behind the scenes, Oracle will translate this into an efficient sort that only ever holds the 'top 4 items'). | It's simple and much faster using the NTILE analytic function:
```
SELECT member_index, NTILE(10) OVER (ORDER BY member_index) FROM my_members;
```
Oracle 10g documentation: *"NTILE is an analytic function. It divides an ordered data set into a number of buckets indicated by expr and assigns the appropriate bucket number to each row. The buckets are numbered 1 through expr."* | Separating SQL Results Into Ranges | [
"",
"sql",
"plsql",
"split",
"partitioning",
""
] |
Friends,
I'm new to both Javascript and Regular Expressions and hope you can help!
Within a Javascript function I need to check to see if a comma(,) appears 1 or more times. If it does then there should be one or more numbers either side of it.
e.g.
1,000.00 is ok
1,000,00 is ok
,000.00 is not ok
1,,000.00 is not ok
If these conditions are met I want the comma to be removed so 1,000.00 becomes 1000.00
What I have tried so is:
var x = '1,000.00';
var regex = new RegExp("[0-9]+,[0-9]+", "g");
var y = x.replace(regex,"");
alert(y);
When run the alert shows ".00" Which is not what I was expecting or want!
Thanks in advance for any help provided.
**strong text**
Edit
**strong text**
Thanks all for the input so far and the 3 answers given. Unfortunately I don't think I explained my question well enough.
What I am trying to achieve is:
If there is a comma in the text and there are one or more numbers either side of it then remove the comma but leave the rest of the string as is.
If there is a comma in the text and there is not at least one number either side of it then do nothing.
So using my examples from above:
1,000.00 becomes 1000.00
1,000,00 becomes 100000
,000.00 is left as ,000.00
1,,000.00 is left as 1,,000.00
Apologies for the confusion! | Your regex isn't going to be very flexible with higher orders than 1000 and it has a problem with inputs which don't have the comma. More problematically you're also matching and replacing the part of the data you're interested in!
Better to have a regex which matches the forms which are a problem and remove them.
The following matches (in order) commas at the beginning of the input, at the end of the input, preceded by a number of non digits, or followed by a number of non digits.
```
var y = x.replace(/^,|,$|[^0-9]+,|,[^0-9]+/g,'');
```
As an aside, all of this is much easier if you happen to be able to do [lookbehind](http://www.regular-expressions.info/lookaround.html) but almost every JS implementation doesn't.
**Edit based on question update:**
Ok, I won't attempt to understand why your rules are as they are, but the regex gets simpler to solve it:
```
var y = x.replace(/(\d),(\d)/g, '$1$2');
``` | I would use something like the following:
```
^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)$
```
* [0-9]{1,3}: 1 to 3 digits
* (,[0-9]{3})\*: [Optional] More digit triplets seperated by a comma
* (\.[0-9]+): [Optional] Dot + more digits
If this regex matches, you know that your number is valid. Just replace all commas with the empty string afterwards. | Using Regular Expressions with Javascript replace method | [
"",
"javascript",
"regex",
""
] |
I'm in charge of maintaining a learning management system and this is an issue that I've been dealing with on and off over the past few months.
A single student (among thousands) is claiming that his essay submissions are being "eaten" by the website. After form submission he says his essay has been replaced by the following text:
> Warning: mysql\_connect()
> [function.mysql-connect]: Lost
> connection to MySQL server at 'reading
> initial communication packet', system
> error: 111 in
> /home/web/solomon\_1.3/classes/db.class.php
> on line 84
>
> Fatal error: Error connecting to
> database server: in
> /home/web/solomon\_1.3/classes/db.class.php
> on line 85
The preceding warning and fatal error are stored in the database as his submission. But how could this be as the error clearly states that a connection could not be made? The essay submission page is about as basic as it gets: A single DB connection is made, the form data is saved to the DB, user is redirected back to the submission page.
Lines 84-86 of db.class.php are:
```
if (!($sql_id=mysql_connect($server, $user, $pwd,$new))){
trigger_error("[Error connecting to database server]: {$sql_id}", E_USER_ERROR);
}
```
Notice how the error reported by the student lacks square brackets around the Fatal Error description string as shown in the PHP source file. Those square brackets were added nearly two months ago after the student's first error report with the suspicion that he was just pasting an error string into the submission box as a way to avoid work. I guess it's the 21st-century version of "the dog ate my homework".
As recently as a week ago the student still reports the original error **without brackets**. A server-wide grep verified that the error the student keeps "getting" is based on a string that simply doesn't exist.
Now, the most **reasonable** explanation is that the student is screwing with us. That DB connection error has happened in the past but not within at least the last three months.
There's a chance the student could get expelled over this so I wanted to make absolutely sure that my evidence is solid. Can you think of any alternate theories likely or otherwise? | As [tpdi](https://stackoverflow.com/questions/798288/mysql-php-connection-error-possible-user-fabrication/798439#798439) pointed out correctly: *an innocent person wouldn't be trying to prove that innocence.*
And yes, you should log errors to a file, possibly even email the system administrator a copy of serious errors. But all that is not helping you now.
**First thoughts:**
Although there is no direct evidence that the student is making up a digital dog to eat his homework, I've never seen an error message being inserted into any table instead of the expected contents.
If a real error in the script causes the error message to end up in a new record, the on-screen error would most likely be completely different. So if the student's mother claims to have seen this error, I find that even harder to believe.
**The missing angled brackets in the error message:**
I've seen many unexpected crashes, even in code that 'could not possibly be wrong' (tm).
The fact that the brackets are missing is, as others have pointed out, no evidence in itself.
The error could be copied & pasted from on old e-mail or even be changed by a custom error handler (which you do not seem to have, but just to point out the possibility).
But, if an genuine error in the script causes the error message to ends up in a newly inserted database record, this error message is script-generated. The missing angled brackets however, strongly suggest that the error message originated from outside the script.
**Then the script lines themselves:**
```
84: if (!($sql_id=mysql_connect($server, $user, $pwd,$new))){
85: trigger_error("[Error connecting to database server]: {$sql_id}", E_USER_ERROR);
86: }
```
As far as I can see, if the script fails to set up a valid connection (line 84) it triggers the user error on line 85.
In reverse, if the user error (line 85) is triggered, the script failed to obtain a valid MySQL link identifier.
As far as I know there is no way for a PHP-script to affect any data on the server without a valid MySQL link identifier.
In addition to the the missing MySQL link identifier, there is no code in the lines above whatsoever that touches the data. So even if there was a valid connection, these lines would not trigger the insert of a new record.
I find it extremely unlikely, bordering on impossible, that an error in the process of opening a connection to the Database server would ever cause a record to be inserted, let alone a record holding a perfectly readable PHP-styled error message.
**My conclusion *bases upon the information you posted:***
The student has a copy of an error message that was shown in the browser after a real error that has occurred somewhere in the past. He now posts a copy of the error message to the script. The script stores the posted information in the database. | Don't you log when errors like this occur?
It does look like he's making it up though...
As Jeff says in [Exception-Driven Development](https://blog.codinghorror.com/exception-driven-development/)
> If you're waiting around for **users to
> tell you about problems with your
> website or application**, you're only
> seeing a tiny fraction of all the
> problems that are actually occurring.
> The proverbial tip of the iceberg. | MySQL/PHP connection error, possible user fabrication | [
"",
"php",
"mysql",
""
] |
I have a object which contains unicode data and I want to use that in its representaion
e.g.
```
# -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode("utf-8")
__str__ = __repr__
a = A()
s1 = u"%s"%a # works
#s2 = u"%s"%[a] # gives unicode decode error
#s3 = u"%s"%unicode([a]) # gives unicode decode error
```
Now even if I return unicode from **repr** it still gives error
so question is how can I use a list of such objects and create another unicode string out of it?
platform details:
```
"""
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
'Linux-2.6.24-19-generic-i686-with-debian-lenny-sid'
"""
```
also not sure why
```
print a # works
print unicode(a) # works
print [a] # works
print unicode([a]) # doesn't works
```
python group answers that
<http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137> | `s1 = u"%s"%a # works`
This works, because when dealing with 'a' it is using its unicode representation (i.e. the **unicode** method),
when however you wrap it in a list such as '[a]' ... when you try to put that list in the string, what is being called is the unicode([a]) (which is the same as repr in the case of list), the string representation of the list, which will use 'repr(a)' to represent your item in its output. This will cause a problem since you are passing a 'str' object (a string of bytes) that contain the utf-8 encoded version of 'a', and when the string format is trying to embed that in your unicode string, it will try to convert it back to a unicode object using hte default encoding, i.e. ASCII. since ascii doesn't have whatever character it's trying to conver, it fails
what you want to do would have to be done this way: `u"%s" % repr([a]).decode('utf-8')` assuming all your elements encode to utf-8 (or ascii, which is a utf-8 subset from unicode point of view).
for a better solution (if you still want keep the string looking like a list str) you would have to use what was suggested previously, and use join, in something like this:
u`'[%s]' % u','.join(unicode(x) for x in [a,a])`
though this won't take care of list containing list of your A objects.
My explanation sounds terribly unclear, but I hope you can make some sense out of it. | Try:
```
s2 = u"%s"%[unicode(a)]
```
Your main problem is that you are doing more conversions than you expect. Lets consider the following:
```
s2 = u"%s"%[a] # gives unicode decode error
```
From [Python Documentation](http://docs.python.org/library/stdtypes.html#string-formatting-operations),
```
's' String (converts any python object using str()).
If the object or format provided is a unicode string,
the resulting string will also be unicode.
```
When the %s format string is being processed, str([a]) is applied. What you have at this point is a string object containg a sequence of unicode bytes. If you try and print this there is no problem, because the bytes pass straight through to your terminal and are rendered by the terminal.
```
>>> x = "%s" % [a]
>>> print x
[©au]
```
The problem arises when you try to convert that back to unicode. Essentially, the function unicode is being called on the string which contains the sequence of unicode-encoded bytes, and that is what causes the ascii codec to fail.
```
>>> u"%s" % x
Traceback (most recent call last):
File "", line 1, in
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1: ordinal not in range(128)
>>> unicode(x)
Traceback (most recent call last):
File "", line 1, in
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1: ordinal not in range(128)
``` | how to use list of python objects whose representation is unicode | [
"",
"python",
"unicode",
""
] |
I've been trying to make an AJAX request to an external server.
I've learned so far that I need to use getJSON to do this because of security reasons ?
Now, I can't seem to make a simple call to an external page.
I've tried to simplify it down as much as I can but it's still not working.
I have 2 files, test.html & test.php
my test.html makes a call like this, to localhost for testing :
```
$.getJSON("http://localhost/OutVoice/services/test.php", function(json){
alert("JSON Data: " + json);
});
```
and I want my test.php to return a simple 'test' :
```
$results = "test";
echo json_encode($results);
```
I'm probably making some incredible rookie mistake but I can't seem to figure it out.
Also, if this works, how can I send data to my test.php page, like you would do like test.php?id=15 ?
---
The test.html page is calling the test.php page on localhost, same directory
I don't get any errors, just no alert .. | It *could* be that you haven't got a callback in test.php. Also, `json_encode` only accepts an array:
```
$results = array("key" => "value");
echo $_GET['callback'] . '(' . json_encode($results) . ')';
// the callback stuff is only needed if you're requesting from different domains
```
jQuery automatically switches to JSONP (i.e. using script tags instead of `XMLHttpRequest`) when you use `http://`. If you have test.html and test.php on the same domain, try using relative paths (and no callbacks). | Be careful with moff's answer. It's got a common XSS vulnerability: <http://www.metaltoad.com/blog/using-jsonp-safely> | jQuery getJSON to external PHP page | [
"",
"php",
"jquery",
"ajax",
"json",
"getjson",
""
] |
Isn't there a convenient way of getting from a java.util.Date to a XMLGregorianCalendar? | I should like to take a step back and a modern look at this 10 years old question. The classes mentioned, `Date` and `XMLGregorianCalendar`, are old now. I challenge the use of them and offer alternatives.
* `Date` was always poorly designed and is more than 20 years old. This is simple: don’t use it.
* `XMLGregorianCalendar` is old too and has an old-fashioned design. As I understand it, it was used for producing dates and times in XML format for XML documents. Like `2009-05-07T19:05:45.678+02:00` or `2009-05-07T17:05:45.678Z`. These formats agree well enough with ISO 8601 that the classes of java.time, the modern Java date and time API, can produce them, which we prefer.
## No conversion necessary
For many (most?) purposes the modern replacement for a `Date` will be an `Instant`. An `Instant` is a point in time (just as a `Date` is).
```
Instant yourInstant = // ...
System.out.println(yourInstant);
```
An example output from this snippet:
> 2009-05-07T17:05:45.678Z
It’s the same as the latter of my example `XMLGregorianCalendar` strings above. As most of you know, it comes from `Instant.toString` being implicitly called by `System.out.println`. With java.time, in many cases we don’t need the conversions that in the old days we made between `Date`, `Calendar`, `XMLGregorianCalendar` and other classes (in some cases we do need conversions, though, I am showing you a couple in the next section).
## Controlling the offset
Neither a `Date` nor in `Instant` has got a time zone nor a UTC offset. The previously accepted and still highest voted answer by Ben Noland uses the JVMs current default time zone for selecting the offset of the `XMLGregorianCalendar`. To include an offset in a modern object we use an `OffsetDateTime`. For example:
```
ZoneId zone = ZoneId.of("America/Asuncion");
OffsetDateTime dateTime = yourInstant.atZone(zone).toOffsetDateTime();
System.out.println(dateTime);
```
> 2009-05-07T13:05:45.678-04:00
Again this conforms with XML format. If you want to use the current JVM time zone setting again, set `zone` to `ZoneId.systemDefault()`.
## What if I absolutely need an XMLGregorianCalendar?
There are more ways to convert `Instant` to `XMLGregorianCalendar`. I will present a couple, each with its pros and cons. First, just as an `XMLGregorianCalendar` produces a string like `2009-05-07T17:05:45.678Z`, it can also be built from such a string:
```
String dateTimeString = yourInstant.toString();
XMLGregorianCalendar date2
= DatatypeFactory.newInstance().newXMLGregorianCalendar(dateTimeString);
System.out.println(date2);
```
> 2009-05-07T17:05:45.678Z
Pro: it’s short and I don’t think it gives any surprises. Con: To me it feels like a waste formatting the instant into a string and parsing it back.
```
ZonedDateTime dateTime = yourInstant.atZone(zone);
GregorianCalendar c = GregorianCalendar.from(dateTime);
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
System.out.println(date2);
```
> 2009-05-07T13:05:45.678-04:00
Pro: It’s the official conversion. Controlling the offset comes naturally. Con: It goes through more steps and is therefore longer.
## What if we got a Date?
If you got an old-fashioned `Date` object from a legacy API that you cannot afford to change just now, convert it to `Instant`:
```
Instant i = yourDate.toInstant();
System.out.println(i);
```
Output is the same as before:
> 2009-05-07T17:05:45.678Z
If you want to control the offset, convert further to an `OffsetDateTime` in the same way as above.
If you’ve got an old-fashioned `Date` and absolutely need an old-fashioned `XMLGregorianCalendar`, just use the answer by Ben Noland.
## Links
* [Oracle tutorial: Date Time](https://docs.oracle.com/javase/tutorial/datetime/) explaining how to use java.time.
* [XSD Date and Time Data Types](https://www.w3schools.com/xml/schema_dtypes_date.asp) on W3Schools.
* [Wikipedia article: ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) | ```
GregorianCalendar c = new GregorianCalendar();
c.setTime(yourDate);
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
``` | java.util.Date to XMLGregorianCalendar | [
"",
"java",
"xml",
"date",
"xmlgregoriancalendar",
""
] |
I'm trying to use parallelization to improve the refresh rate for drawing a 3D scene with heirarchically ordered objects. The scene drawing algorithm first recursively traverses the tree of objects, and from that, builds an ordered array of essential data that is needed to draw the scene. Then it traverses that array multiple times to draw objects/overlays, etc. Since from what I've read OpenGL isn't a thread-safe API, I assume the array traversal/drawing code must be done on the main thread, but I'm thinking that I might be able to parallelize the recursive function that fills the array. The key catch is that the array must be populated in the order that the objects occur in the scene, so all functionality that associates a given object with an array index must be done in the proper order, but once the array index has been assigned, I can fill the data of that array element (which isn't necessarily a trivial operation) using worker threads. So here's the pseudo code that I'm trying to get at. I hope you get the idea of the xml-ish thread syntax.
```
recursivepopulatearray(theobject)
{
<main thread>
for each child of theobject
{
assign array index
<child thread(s)>
populate array element for child object
</child thread(s)>
recursivepopulatearray(childobject)
}
</main thread>
}
```
So, is it possible to do this using OpenMP, and if so, how? Are there other parallelization libraries that would handle this better?
**Addendum:** In response to [Davide's request for more clarification](https://stackoverflow.com/questions/835893/openmp-parallelization-on-a-recursive-function/835974#835974), let me explain a little more in detail. Let's say that the scene is ordered like this:
```
-Bicycle Frame
- Handle Bars
- Front Wheel
- Back Wheel
-Car Frame
- Front Left Wheel
- Front Right Wheel
- Back Left Wheel
- Back Right Wheel
```
Now, each of these objects has lots of data associated with it, i.e. location, rotation, size, different drawing parameters, etc. Additionally, I need to make multiple passes over this scene to draw it properly. One pass draws the shapes of the objects, another pass draws text describing the objects, another pass draws connections/associations between the objects if there are any. Anyway, getting all the drawing data out of these different objects is pretty slow if I have to access it multiple times, so I've decided to use one pass to cache all that data into a one-dimensional array, and then all the actual drawing passes just look at the array. The catch is that because I need to do OpenGL pushes/pops in the right order, the array must be in the proper depth-first search order that is representative of the tree heirarchy. In the example above, the array must be ordered as follows:
```
index 0: Bicycle Frame
index 1: Handle Bars
index 2: Front Wheel
index 3: Back Wheel
index 4: Car Frame
index 5: Front Left Wheel
index 6: Front Right Wheel
index 7: Back Left Wheel
index 8: Back Right Wheel
```
So, the ordering of the array must be serialized properly, but once I have assigned that ordering properly, I can parallelize the filling of the array. For example once I've assigned Bicycle Frame to index 0 and Handle Bars to index 1, one thread can take the filling of the array element for the Bicycle Frame while another takes the the filling of the array element for Handle Bars.
OK, I think in clarifying this, I've answered my own question, so thanks Davide. So I've posted my own [answer](https://stackoverflow.com/questions/835893/openmp-parallelization-on-a-recursive-function/836657#836657). | Here's a modified piece of pseudo-code that should work.
```
populatearray(thescene)
{
recursivepopulatearray(thescene)
#pragma omp parallel for
for each element in array
populate array element based on associated object
}
recursivepopulatearray(theobject)
{
for each childobject in theobject
{
assign array index and associate element with childobject
recursivepopulatearray(childobject)
}
}
``` | I think you should clarify better your question (e.g. what exactly must be done serially and why)
OpenMP (like many other parallelization libraries) does **not** guarantee the order in which the various parallel sections will be executed, and since they are truly parallel (on a multicore machine) there might be race conditions if different sections write the same data. If that's ok for your problem, surely you can use it. | OpenMP parallelization on a recursive function | [
"",
"c++",
"drawing",
"openmp",
""
] |
I would like to know the best method for solving this problem:
I would like to create a blank template xml from a xml schema. All the required elements and attributes would be created and their values would be all empty strings.
The next step is how to determine which child xml nodes a certain node could have. eg. I would select a node has has minOccurs="0", maxOccurs="unbounded" for one of its children. I would be able to determine everything about that child, its attributes, its name, its value type, etc.
To give more context on the situation, I am working on a tool that allows users to edit xml files in a more user friendly setting. For eg, They could add a new account to the 'account db' node and they would see that the only available node is an account node. Next, when they try to add children to the account node and the choices would be name node (required), password node (required), settings node (optional), etc. How do I determine programmatically what children the account node has available to it and what the attributes and settings are on those children?
This is in C# 2.0 with .NET 2.0.
In summary, which classes do I use to read a schema and parse it to get useful information for creating a xml? In my naivety I had hope that since xsd was xml in itself there would be some sort of DOM model that I could traverse through.
I would like this to be confined to my program so no use of external tools such as OxygenXml, VS, xsd.exe, etc. | It sounds like what you want to do is replicated the functionality behind XML intellisense in most good XML Editors. ie read an xml schema and work out which elements and attributes can come next.
We have done something very similar on a project we worked on some time ago. To produce something that works most of the time is a lot of work, to product something that works all the time is loads of work!
Basically you need to load the XSD (the XmlSchema objects in .net allow you to do this). But the SOM object model they expose is very raw, so you need to do quite a lot of work to interpret it. If you ignore concepts like substitution groups, complexType extension, chameleon schemas and namesapces, you should be able to navigate the SOM reasonably easily.
You next need to figure out where you are in the XML document with relation to your schema. Once you known were you are in the SOM you can then start to work out the available options.
To do this properly is 1,000' of lines of code and 4-12 man weeks of work. You may be able to get something basic together in a few weeks? | I've been bleeding my eyes out with the MSDN docs and I think I've picked up a scent.
Load a schema using XmlSchema.Read and compile it. The Elements property will contain a collection of the 'top level' elements. You'll have to hardcode the qualified name of the root element or something. Then that's it. I haven't found how to find the 'contents' under a given schema element yet.
Edit: I've found some more paths to go but it's still not crystal clear.
XmlSchemaElements have a schema type property. This is either simple or complex. Complex types in xml schema can have attributes, sequences, groups, etc. The sequences have a property called particle which can be an element. And the cycle repeats. But I think the hard part in implementation would be to make sure you cover all possible cases (simple type, complex type with attribute, complex type with attribute and elements, extensions, the whole shebang).
Edit: Use the XmlSchema object's Element property to get an XmlSchemaElement. Use the XmlSchemaElement's SchemaType property to get simple or complex type. Use the XmlSchemaComplexType's Attribute property to get attributes or ContentModel to get 'simple content'/'complex content' or Particle to get 'sequence'/'choice'/'all'. Basically a lot of travelling down properties and checking types and casting objects left and right and checking all the possible arrangements of xsd objects. To create a library would be long and cumbersome and error-prone. And this is with xml schemas, with dtds I don't even want to begin thinking. Wow, xml schemas are necessary but why do they have to be so evil. | Creating an xml file from xsd in .NET | [
"",
"c#",
".net",
"xml",
"xsd",
""
] |
Basically I want to get a handle of the python interpreter so I can pass a script file to execute (from an external application). | This works in Linux & Windows:
**Python 3.x**
```
>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe
```
**Python 2.x**
```
>>> import sys
>>> print sys.executable
/usr/bin/python
``` | sys.executable is not reliable if working in an embedded python environment. My suggestions is to deduce it from
```
import os
os.__file__
``` | How to get the python.exe location programmatically? | [
"",
"python",
""
] |
Trying to figure out whether PHP supports features like method overloading, inheritance, and polymorphism, I found out:
* it does not support method overloading
* it does support inheritance
but I am unsure about polymorphism. I found this Googling the Internet:
> I should note that in PHP the
> polymorphism isn't quite the way it
> should be. I mean that it does work,
> but since we have a weak datatype, its
> not correct.
So is it really polymorphism?
**Edit**
Just can't quite place a definite YES or NO next to `PHP supports polymorphism`. I would be loath to state: "PHP does not support polymorphism", when in reality it does. Or vice-versa. | ```
class Animal {
var $name;
function __construct($name) {
$this->name = $name;
}
}
class Dog extends Animal {
function speak() {
return "Woof, woof!";
}
}
class Cat extends Animal {
function speak() {
return "Meow...";
}
}
$animals = array(new Dog('Skip'), new Cat('Snowball'));
foreach($animals as $animal) {
print $animal->name . " says: " . $animal->speak() . '<br>';
}
```
You can label it all you want, but that looks like polymorphism to me. | although PHP does not support method overloading the way you have experienced in other languages, say Java. but you CAN have method overloading in PHP, but the definition method is different.
if you want to have different functionality for a given method, with different set of parameters in PHP, you can do something like this:
```
class myClass {
public function overloadedMethod() {
// func_num_args() is a build-in function that returns an Integer.
// the number of parameters passed to the method.
if ( func_num_args() > 1 ) {
$param1 = func_get_arg(0);
$param2 = func_get_arg(1);
$this->_overloadedMethodImplementation2($param1,$param2)
} else {
$param1 = func_get_arg(0);
$this->_overloadedMethodImplementation1($param1)
}
}
protected function _overloadedMethodImplementation1($param1) {
// code 1
}
protected function _overloadedMethodImplementation2($param1,$param2) {
// code 2
}
}
```
there could be cleaner implementation, but this is just a sample.
PHP supports inheritance and interfaces. so you can have polymorphism using them. you can have an interface like this:
```
// file: MyBackupInterface.php
interface MyBackupInterface {
// saves the data on a reliable storage
public function saveData();
public function setData();
}
// file: myBackupAbstract.php
require_once 'MyBackupInterface.php';
class MyBackupAbstract implements MyBackupInterface {
protected $_data;
public function setData($data) {
$this->_data= $data;
}
// there is no abstract modifier in PHP. so le'ts avoid this class to be used in other ways
public function __construct() {
throw new Exception('this class is abstract. you can not instantiate it');
}
}
// file: BackupToDisk.php
require_once 'MyBackupAbstract.php';
class BackupToDisk extends MyBackupAbstract {
protected $_savePath;
// implement other methods ...
public function saveData() {
// file_put_contents() is a built-in function to save a string into a file.
file_put_contents($this->_savePath, $this->_data);
}
}
// file: BackupToWebService.php
require_once 'MyBackupAbstract.php';
class BackupToWebService extends MyBackupAbstract {
protected $_webService;
// implement other methods ...
public function saveData() {
// suppose sendData() is implemented in the class
$this->sendData($this->_data);
}
}
```
now in your application, you might use it like this:
```
// file: saveMyData.php
// some code to populate $myData
$backupSolutions = array( new BackupToDisk('/tmp/backup') , new BackupToWebService('webserviceURL') );
foreach ( $backupSolutions as $bs ) {
$bs->setData($myData);
$bs->saveData();
}
```
you are right, PHP is not strong typed language, we never mentioned that any of your $backupSolutions would be a 'MyBackupAbstract' or 'MyBackupInterface', but that would not stop us from having the nature of polymorphism which is different functionality over using the same methods. | Is what seems like polymorphism in PHP really polymorphism? | [
"",
"php",
"oop",
"programming-languages",
"polymorphism",
""
] |
What is the proper multi-character wildcard in the LIKE operator in Microsoft Jet and what setting affects it (if any)? I am supporting an old ASP application which runs on Microsoft Jet (on an Access database) and it uses the % symbol in the LIKE operator, but I have a customer who apparently has problems in his environment because the % character is understood as a regular character, and I assume that his multi-character wildcard is \*. Also, I'm almost sure that in the past I have written application with queries using \* instead of %. Finally, Microsoft Access (as an application) also works only with \* and not % (but I'm not sure how relevant it is).
I just spent about 20 minutes searching the Internet without any useful results, and so I thought it would be useful ask on stackoverflow. Somebody may already know it, and it's better to keep the potential answers on stackoverflow than any other random discussion forum anyway. | The straight answer is that the behaviour of the wildcard characters is dependent on the ANSI Query Mode of the interface being used.
ANSI-89 Query Mode ('traditional mode') uses the `*` character, ANSI-92 Query Mode ('SQL Server compatibility mode') uses the `%` character. These modes are specific to ACE/Jet and bear only a passing resemblance to the ANSI/ISO SQL-89 and SQL-92 Standards.
The ADO interface (OLE DB) always uses ANSI-92 Query Mode.
The DAO interface always uses ANSI-89 Query Mode.
When using ODBC the query mode can be explicitly specified via the [ExtendedAnsiSQL](http://msdn.microsoft.com/en-us/library/ms710959%28v=vs.85%29.aspx) flag.
The MS Access user interface, from the 2003 version onwards, can use either query mode, so don't assume it is one or the other at any given time (e.g. do not use query-mode-specific wildcard characters in Validation Rules).
ACE/Jet SQL syntax has an `ALIKE` keyword, which allows the ANSI-92 Query Mode characters (`%` and `_`) regardless of the query mode of the interface, however has the slight disadvantage of the `ALIKE` keyword not being SQL-92 compatible (however `ALIKE` remains highly portable). The main disadvantage, however, is that I understand the `ALIKE` keyword is not officially supported (though I can't imagine it will disappear or have altered behaviour anytime soon). | If you're using DAO, use asterisk (and question mark for single symbol placeholder). If you're using ADO, use percent sign (and underscore). | Microsoft Jet wildcards: asterisk or percentage sign? | [
"",
"sql",
"ms-jet-ace",
""
] |
I need 2 simple reg exps that will:
1. Match if a string is contained within square brackets (`[]` e.g `[word]`)
2. Match if string is contained within double quotes (`""` e.g `"word"`) | ```
\[\w+\]
"\w+"
```
**Explanation:**
The \[ and \] escape the special bracket characters to match their literals.
The \w means "any word character", usually considered same as alphanumeric or underscore.
The + means one or more of the preceding item.
The " are literal characters.
NOTE: If you want to ensure the whole string matches (not just part of it), prefix with `^` and suffix with `$`.
And next time, you should be able to answer this yourself, by reading **[regular-expressions.info](http://regular-expressions.info)**
**Update:**
Ok, so based on your comment, what you appear to be wanting to know is if the first character is [ and the last ] or if the first and last are both " ?
If so, these will match those:
```
^\[.*\]$ (or ^\\[.*\\]$ in a Java String)
"^.*$"
```
However, unless you need to do some special checking with the centre characters, simply doing:
```
if ( MyString.startsWith("[") && MyString.endsWith("]") )
```
and
```
if ( MyString.startsWith("\"") && MyString.endsWith("\"") )
```
Which I suspect would be faster than a regex. | Important issues that may make this hard/impossible in a regex:
1. Can `[]` be nested (e.g. `[foo [bar]]`)? If so, then a traditional regex cannot help you. Perl's extended regexes can, but it is probably better to write a parser.
2. Can `[`, `]`, or `"` appear escaped (e.g. `"foo said \"bar\""`) in the string? If so, see [How can I match double-quoted strings with escaped double-quote characters?](https://stackoverflow.com/questions/481282/how-can-i-match-double-quoted-strings-with-escaped-double-quote-characters)
3. Is it possible for there to be more than one instance of these in the string you are matching? If so, you probably want to use the non-greedy quantifier modifier (i.e. `?`) to get the smallest string that matches: `/(".*?"|\[.*?\])/g`
Based on comments, you seem to want to match things like `"this is a "long" word"`
```
#!/usr/bin/perl
use strict;
use warnings;
my $s = 'The non-string "this is a crazy "string"" is bad (has own delimiter)';
print $s =~ /^.*?(".*").*?$/, "\n";
``` | Regular expression to match strings enclosed in square brackets or double quotes | [
"",
"java",
"regex",
""
] |
```
int i =132;
byte b =(byte)i; System.out.println(b);
```
Mindboggling. Why is the output `-124`? | In Java, an `int` is 32 bits. A `byte` is 8 `bits` .
Most primitive types in Java are signed, and `byte`, `short`, `int`, and `long` are encoded in two's complement. (The `char` type is unsigned, and the concept of a sign is not applicable to `boolean`.)
In this number scheme the most significant bit specifies the sign of the number. If more bits are needed, the most significant bit ("MSB") is simply copied to the new MSB.
So if you have byte `255`: `11111111`
and you want to represent it as an `int` (32 bits) you simply copy the 1 to the left 24 times.
Now, one way to read a negative two's complement number is to start with the least significant bit, move left until you find the first 1, then invert every bit afterwards. The resulting number is the positive version of that number
For example: `11111111` goes to `00000001` = `-1`. This is what Java will display as the value.
What you probably want to do is know the unsigned value of the byte.
You can accomplish this with a bitmask that deletes everything but the least significant 8 bits. (0xff)
So:
```
byte signedByte = -1;
int unsignedByte = signedByte & (0xff);
System.out.println("Signed: " + signedByte + " Unsigned: " + unsignedByte);
```
Would print out: `"Signed: -1 Unsigned: 255"`
What's actually happening here?
We are using bitwise AND to mask all of the extraneous sign bits (the 1's to the left of the least significant 8 bits.)
When an int is converted into a byte, Java chops-off the left-most 24 bits
```
1111111111111111111111111010101
&
0000000000000000000000001111111
=
0000000000000000000000001010101
```
Since the 32nd bit is now the sign bit instead of the 8th bit (and we set the sign bit to 0 which is positive), the original 8 bits from the byte are read by Java as a positive value. | `132` in digits ([base 10](http://en.wikipedia.org/wiki/Decimal)) is `1000_0100` in bits ([base 2](http://en.wikipedia.org/wiki/Binary_number)) and Java stores `int` in 32 bits:
```
0000_0000_0000_0000_0000_0000_1000_0100
```
Algorithm for int-to-byte is left-truncate; Algorithm for `System.out.println` is [two's-complement](http://en.wikipedia.org/wiki/Two%27s_complement) (Two's-complement is if leftmost bit is `1`, interpret as negative [one's-complement](http://en.wikipedia.org/wiki/Ones%27_complement) (invert bits) minus-one.); Thus `System.out.println(int-to-byte(` `))` is:
* interpret-as( if-leftmost-bit-is-1[ negative(invert-bits(minus-one(] left-truncate(`0000_0000_0000_0000_0000_0000_1000_0100`) [)))] )
* =interpret-as( if-leftmost-bit-is-1[ negative(invert-bits(minus-one(] `1000_0100` [)))] )
* =interpret-as(negative(invert-bits(minus-one(`1000_0100`))))
* =interpret-as(negative(invert-bits(`1000_0011`)))
* =interpret-as(negative(`0111_1100`))
* =interpret-as(negative(124))
* =interpret-as(-124)
* =-124 Tada!!! | Odd behavior when Java converts int to byte? | [
"",
"java",
""
] |
Has anybody got recent experience with deploying a Django application with an SQL Server database back end? Our workplace is heavily invested in SQL Server and will not support Django if there isn't a sufficiently developed back end for it.
I'm aware of mssql.django-pyodbc and django-mssql as unofficially supported back ends. Both projects seem to have only one person contributing which is a bit of a worry though the contributions seem to be somewhat regular.
Are there any other back ends for SQL Server that are well supported? Are the two I mentioned here 'good enough' for production? What are your experiences? | Use the below **official Microsoft package** to connect the SQL server to Django.
```
pip install mssql-django
```
**Settings**
```
DATABASES = {
'default': {
'ENGINE': 'mssql',
'NAME': 'mydb',
'USER': 'user@myserver',
'PASSWORD': 'password',
'HOST': 'myserver.database.windows.net',
'PORT': '',
'OPTIONS': {
'driver': 'ODBC Driver 17 for SQL Server',
},
},
}
# set this to False if you want to turn off pyodbc's connection pooling
DATABASE_CONNECTION_POOLING = False
```
**More Information**: <https://github.com/microsoft/mssql-django> | As has been stated, django-pyodbc is a good way to go. PyODBC is probably the most mature SQL Server library for Python there is.
The only thing you may have problems with is that pyodbc doesn't support stored procedures very well (you can call them, but you have no way to get results from them). You *can* call them using pymssql, but I would avoid it if at all possible as it doesn't support the standard DB-API interface and may be subject to changes. If you need to do this, your best bet is to use [adodbapi](http://adodbapi.sourceforge.net/) directly (it's included with the python win32 package, which you'll probably end up installing anyway). | Using Sql Server with Django in production | [
"",
"python",
"sql-server",
"django",
"pyodbc",
""
] |
Is there any way to bind arguments to slots ala [boost::bind](http://www.boost.org/doc/libs/1_38_0/libs/bind/bind.html "boost::bind")?
Here's a for-instance. I have a window with a tree view, and I want to allow the user to hide a column from a context menu. I end up doing something like:
```
void MyWindow::contextMenuEvent (QContextMenuEvent* event) {
m_column = view->columnAt (event->x());
QMenu menu;
menu.addAction (tr ("Hide Column"), this, SLOT (hideColumn ()));
// .. run the menu, etc
}
```
I need to capture the index of the column over which the context menu was activated and store it in a member variable that is used by my window's `hideColumn` slot:
```
void MyWindow::hideColumn () {
view->setColumnHidden (m_column, true);
}
```
What I'd really like is to be able to bind the column number to my slot when I create the menu so I don't need this member variable. Basically the Qt equivalent of:
```
menu.addAction (tr ("Hide Column"),
boost::bind (&MyWindow::hideColumn, this,
event->columnAt (event->x()));
```
Or even better yet adapting the [QAction::triggered](http://doc.trolltech.com/4.3/qaction.html#triggered) signal and attaching it to the [QTreeView::hideColumn](http://doc.trolltech.com/4.3/qtreeview.html#hideColumn) slot, which takes the column index as an argument:
```
menu.addAction (tr ("Hide Column"),
boost::bind (&QTreeView::hideColumn, view,
event->columnAt (event->x())));
```
Is any of this do-able? | AFAIK the only way is to create a QSignalMapper object to do this. It's like an extra level of indirection that can be used to generate a new signal providing the column index. It's a little bit clumsy IME, you can end up with lots of QSignalMapper objects hanging around all the time, but seems to be the best way at this time. (Ideally, IMO, you would be able to just supply any value such as the column index to connect() which would get passed as an argument to the slot, but you can't.) | [LibQxt](http://libqxt.org) makes this possible through QxtBoundFunction and QxtMetaObject (the former does not show up in their [documentation](http://doc.libqxt.org/0.5.0/) for some reason). It's an Open Source project, so you can grab the source if you're interested in the implementation. It uses the following syntax:
```
connect(
button,
SIGNAL(clicked()),
QxtMetaObject::bind(
lineEdit,
SLOT(setText(QString)),
Q_ARG(QString, "Hello World!)
)
);
```
[LibQxt](http://libqxt.org) has some other very useful features like the ability to [emit signals over a QIODevice](http://doc.libqxt.org/0.5.0/classQxtRPCService.html), such as network connection. | Qt: adapting signals / binding arguments to slots? | [
"",
"c++",
"qt",
"boost",
""
] |
I need a very simple process that listens on a directory and
does some operation when a new file is created on that directory.
I guess I need a thread pool that does that.
This is very easy to implement using the spring framework, which I normally use but I can't use it now.
I can only use tomcat, How can I implement it? what is the entry point that "starts" that thread?
Does it have to be a servlet ?
thanks | since you refined the question, here comes another answer: how to start a daemon in tomcat:
first, register your Daemons in web.xml:
< listener >
my.package.servlet.Daemons
< /listener >
then implement the Daemons class as an implementation of `ServletContextListener` like this:
the code will be called every 5 seconds, tomcat will call contextDestroyed when your app shuts down. note that the variable is volatile, otherwise you may have troubles on shutdown on multi-core systems
```
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class Daemons implements ServletContextListener {
private volatile boolean active = true;
Runnable myDeamon = new Runnable() {
public void run() {
while (active) {
try {
System.out.println("checking changed files...");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
public void contextInitialized(ServletContextEvent servletContextEvent) {
new Thread(myDeamon).start();
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
active = false;
}
}
``` | You could create a [listener](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/Servlets4.html) to start the thread, however this isn't a good idea. When you are running inside a Web container, you shouldn't start your own threads. There are a couple of questions in Stack Overflow for why is this so. You could use [Quartz](http://www.quartz-scheduler.org/) (a scheduler framework), but I guess you couldn't achieve an acceptable resolution.
Anyway, what you are describing isn't a Web application, but rather a daemon service. You could implement this independently from your web application and create a means for them to communicate with each other. | file listener process on tomcat | [
"",
"java",
"tomcat",
"servlets",
"jakarta-ee",
""
] |
Is am using this:
```
SetWindowsHookEx(WH_CALLWNDPROC, ...);
```
I can see the messages I want to process, but I want to prevent those message from reaching the target window. So I tried this:
```
SetWindowsHookEx(WH_GETMESSAGE, ...);
```
When I do this I can modify the message, and prevent the target window from processing it, but this hook doesn't see the messages I need to process. I presume this is because it is being posted to the target window's queue, not sent? Is there a way around this issue? I have heard that window sub-classing might be able to accomplish this, but can I subclass a window in a different process? Is there a way to do this using hooks? | You can't subclass a window in a another process, but the hook DLL should be able to subclass the window you're interested in. WH\_GETMESSAGE and WH\_CALLWNDPROC hooks run in the context of the process receiving the message, so at that point you have an "in" to subclass the target's window. | You could try [subclassing](http://msdn.microsoft.com/en-us/library/ms644898(VS.85).aspx) the target window and then filter the messages. | Window Hooking Questions | [
"",
"c++",
"winapi",
"hook",
"subclass",
""
] |
I have a pointer to a given class. Lets say, for example, the pointer is:
```
0x24083094
```
That pointer points to:
```
0x03ac9184
```
Which is the virtual function table of my class. That makes sense to me. In windbg, everything looks correct.
I delete said pointer. Now at `0x24083094` is:
```
0x604751f8
```
But it isn't some random garbage, that address is put in there every time, it is consistently `0x604751f8`! So much so that I can actually use that address to determine if that pointer was deleted, between executions of my application!
But Why? How does it determine that `0x604751f8` should be written there?
For the record, I am using windows, building under visual studio 2003.
I know I can't rely on that value being set, even if it does appear to be consistent, but can I rely on it being different? I.e., `0x03ac9184` will not be at `0x24083094` if the pointer is deleted, right? What is put there? It Could be anything, but `0x03ac9184` will definitely not be there (or else I could still call methods, since that is the virtual function table). Am I right?
I feel like I have answer. can't rely on anything after it is deleted. Maybe some background will help people see where I am coming from. Essentially, I am trying to fix a bug where a pointer gets deleted out from under me. It's a long story, I won't go into the details.
Basically, I am trying to detect that I am in this situation, so I can exit gracefully from my function. I suppose the easiest and best way is to just figure out who actually owns this pointer, and ask him if anything has changed. So I am going to implement a fix like that. It avoids any of this C++ delete hacker-y I was discussing.
**However**, the interesting thing is that in our code we have a class called 'BogusObject' that essentially acts as a tray catching people that accidentally dereference freed objects. Basically, we hook our own delete functions and bash the BogusObject class into the vtable of any freed class.
Then if someone calls something they get a nice message saying something to the effect of "hey, something is wrong dude.". This is happening in my case. I.e., `0x604751f8+(someoffset)` is inside the BogusObject class. **But we no longer use BogusObject!** It literally isn't set up anywhere (even links properly if I completely remove the BogusObject class), and yet I still end up getting the nice message saying something is wrong! But I am now of the opinion that it is a coincidence.
For some reason the runtime is putting that `0x604751f8` value in this pointer when it is deleted, and that just happens to correspond with the one class that has a purpose to catch situations like this! | Nothing in the standard determines what gets written there. Visual studio (at least in debug mode) will often write sentinal values all over the place to help in catching bugs early.
This value is not something you can rely on, but if you ever find that value popping up in your program mysteriously, you can assume that somewhere you are referencing deleted memory. See [this answer](https://stackoverflow.com/questions/370195/when-and-why-will-an-os-initialise-memory-to-0xcd-0xdd-etc-on-malloc-free-new/370362#370362) for a list of values under one compiler.
It's also entirely possible that it's a free list pointer, pointing to the next piece of free memory. Most memory allocators keep their free memory in a linked list of sorts, using the free memory they are tracking to store the tracking data.
In any case, you MUST NOT use that pointer value for anything you want to keep working, unless you call up microsoft and get some documentation saying why that value is what it is, and get them to guarantee that it will not change. And even then, know that your code is now tied to one compiler's behaviour. In C++, accessing unallocated memory is undefined and evil.
Edit:
You can't even rely on that value changing after a delete. There's nothing that says a compiler needs to modify the data on delete. | One you delete an object the memory it was using gets put back into the free store (heap). Of course the free store will have its own data structures (and possibly debugging data) that it will apply to that memory.
What the particular value you're looking at means? Could be almost anything. | What determines what is written to a C++ pointer when delete is called? | [
"",
"c++",
"windows",
"pointers",
"memory-management",
""
] |
[CampFireNow](http://campfirenow.com/tour) has a voice chat over the browser. It seems that you do not need any plugins to install to get it working. This is a contrast to Gmail, where I needed to install an app.
I would like to implement a similar feature for my application. Is there a way to do this without requiring a plugin? | Flash or Java would be the only things that would be browser agnostic. Else, you definitely need a plugin, unless the specific browser provides you a method to record. | I've never used CampFireNow, but it probably uses Flash | Is it possible to implement voice chat in a browser without plugins? | [
"",
"javascript",
"chat",
""
] |
I've got a table structure that can be summarized as follows:
```
pagegroup
* pagegroupid
* name
```
has 3600 rows
```
page
* pageid
* pagegroupid
* data
```
references pagegroup;
has 10000 rows;
can have anything between 1-700 rows per pagegroup;
the data column is of type mediumtext and the column contains 100k - 200kbytes data per row
```
userdata
* userdataid
* pageid
* column1
* column2
* column9
```
references page;
has about 300,000 rows;
can have about 1-50 rows per page
The above structure is pretty straight forwad, the problem is that that a join from userdata to page group is terribly, terribly slow even though I have indexed all columns that should be indexed. The time needed to run a query for such a join (userdata inner\_join page inner\_join pagegroup) exceeds 3 minutes. This is terribly slow considering the fact that I am not selecting the data column at all. Example of the query that takes too long:
```
SELECT userdata.column1, pagegroup.name
FROM userdata
INNER JOIN page USING( pageid )
INNER JOIN pagegroup USING( pagegroupid )
```
Please help by explaining why does it take so long and what can i do to make it faster.
## Edit #1
Explain returns following gibberish:
```
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE userdata ALL pageid 372420
1 SIMPLE page eq_ref PRIMARY,pagegroupid PRIMARY 4 topsecret.userdata.pageid 1
1 SIMPLE pagegroup eq_ref PRIMARY PRIMARY 4 topsecret.page.pagegroupid 1
```
## Edit #2
```
SELECT
u.field2, p.pageid
FROM
userdata u
INNER JOIN page p ON u.pageid = p.pageid;
/*
0.07 sec execution, 6.05 sec fecth
*/
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE u ALL pageid 372420
1 SIMPLE p eq_ref PRIMARY PRIMARY 4 topsecret.u.pageid 1 Using index
SELECT
p.pageid, g.pagegroupid
FROM
page p
INNER JOIN pagegroup g ON p.pagegroupid = g.pagegroupid;
/*
9.37 sec execution, 60.0 sec fetch
*/
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE g index PRIMARY PRIMARY 4 3646 Using index
1 SIMPLE p ref pagegroupid pagegroupid 5 topsecret.g.pagegroupid 3 Using where
```
## Moral of the story
Keep medium/long text columns in a separate table if you run into performance problems such as this one. | What's the data type and purpose of columnX in the userdata table? It should be noted that any text data type (i.e excluding char, varchar) forces any temporary tables to be created on disk. Now since you're doing a straight join without conditions, grouping or ordering, it probably won't need any temporary tables, except for aggregating the final result.
I think it would also be very helpful if you show us how your indexes are created. One thing to remember is that while InnoDB concatenates the primary key of the table to each index, MyISAM does not. This means that if you index column *name* and search for it with LIKE, but still want to get the *id* of the page group; Then the query would still need to visit the table to get the *id* instead of being able to retrieve it from the index.
What this means, in your case, if I understand your comment to **apphacker** correctly, is to get the name of each users pagegroups. The query optimizer would want to use the index for the join, but for each result it would also need to visit the table to retrieve the page group name. If your datatype on *name* is not bigger than a moderate varchar, i.e. no text, you could also create an index (id, name) which would enable the query to fetch the name directly from the index.
As a final try, you point out that the whole query would probably be faster if the mediumtext was not in the page table.
1. This column is excluded from the query you are running I presume?
2. You could also try to separate the page data from the page "configuration", i.e. which group it belongs to. You'd then probably have something like:
* Pages
+ pageId
+ pageGroupId
* PageData
+ pageId
+ data
This would hopefully enable you to join quicker since no column in Pages take up much space. Then, when you needed to display a certain page, you join with the PageData table on the pageId-column to fetch the data needed to display a particular page. | The easy way to figure out what MySQL is doing with your query is to have it explain the query to you. Run this and have a look at the output:
```
EXPLAIN SELECT userdata.column1, pagegroup.name
FROM userdata
INNER JOIN page USING( pageid )
INNER JOIN pagegroup USING( pagegroupid )
```
MySQL will tell you in which order it processes the queries and what indexes it uses. The fact that you created indexes does not mean that MySQL actually uses them.
See also [Optimizing queries with EXPLAIN](http://dev.mysql.com/doc/refman/5.0/en/using-explain.html)
**EDIT**
The output of your EXPLAIN looks fine. It does a full table scan on the userdata table, but that is normal since you want to return all rows in it. The best way to optimize this is to rethink your application. Do you really need to return all 372K rows? | MySQL MyISAM table performance... painfully, painfully slow | [
"",
"sql",
"mysql",
"performance",
"query-optimization",
"myisam",
""
] |
I have a list of possible substrings, e.g. `['cat', 'fish', 'dog']`. In practice, the list contains hundreds of entries.
I'm processing a string, and what I'm looking for is to find the index of the first appearance of any of these substrings.
To clarify, for `'012cat'` the result is 3, and for `'0123dog789cat'` the result is 4.
I also need to know which substring was found (e.g. its index in the substring list or the text itself), or at least the length of the substring matched.
There are obvious brute-force ways to achieve this, I wondered if there's any elegant Python/regex solution for this. | I would assume a regex is better than checking for each substring individually because *conceptually* the regular expression is modeled as a [DFA](https://en.m.wikipedia.org/wiki/Deterministic_finite_automaton), and so as the input is consumed all matches are being tested for at the same time (resulting in one scan of the input string).
So, here is an example:
```
import re
def work():
to_find = re.compile("cat|fish|dog")
search_str = "blah fish cat dog haha"
match_obj = to_find.search(search_str)
the_index = match_obj.start() # produces 5, the index of fish
which_word_matched = match_obj.group() # "fish"
# Note, if no match, match_obj is None
```
***UPDATE:***
Some care should be taken when combining words in to a single pattern of alternative words. The following code builds a regex, but [escapes any regex special characters](http://docs.python.org/2.7/library/re.html#re.escape) and sorts the words so that longer words get a chance to match before any shorter prefixes of the same word:
```
def wordlist_to_regex(words):
escaped = map(re.escape, words)
combined = '|'.join(sorted(escaped, key=len, reverse=True))
return re.compile(combined)
>>> r.search('smash atomic particles').span()
(6, 10)
>>> r.search('visit usenet:comp.lang.python today').span()
(13, 29)
>>> r.search('a north\south division').span()
(2, 13)
>>> r.search('012cat').span()
(3, 6)
>>> r.search('0123dog789cat').span()
(4, 7)
```
***END UPDATE***
It should be noted that you will want to form the regex (ie - call to re.compile()) as little as possible. The best case would be you know ahead of time what your searches are (or you compute them once/infrequently) and then save the result of re.compile somewhere. My example is just a simple nonsense function so you can see the usage of the regex. There are some more regex docs here:
<http://docs.python.org/library/re.html>
Hope this helps.
***UPDATE:*** I am unsure about how python implements regular expressions, but to answer Rax's question about whether or not there are limitations of re.compile() (for example, how many words you can try to "|" together to match at once), and the amount of time to run compile: neither of these seem to be an issue. I tried out this code, which is good enough to convince me. (I could have made this better by adding timing and reporting results, as well as throwing the list of words into a set to ensure there are no duplicates... but both of these improvements seem like overkill). This code ran basically instantaneously, and convinced me that I am able to search for 2000 words (of size 10), and that and of them will match appropriately. Here is the code:
```
import random
import re
import string
import sys
def main(args):
words = []
letters_and_digits = "%s%s" % (string.letters, string.digits)
for i in range(2000):
chars = []
for j in range(10):
chars.append(random.choice(letters_and_digits))
words.append(("%s"*10) % tuple(chars))
search_for = re.compile("|".join(words))
first, middle, last = words[0], words[len(words) / 2], words[-1]
search_string = "%s, %s, %s" % (last, middle, first)
match_obj = search_for.search(search_string)
if match_obj is None:
print "Ahhhg"
return
index = match_obj.start()
which = match_obj.group()
if index != 0:
print "ahhhg"
return
if words[-1] != which:
print "ahhg"
return
print "success!!! Generated 2000 random words, compiled re, and was able to perform matches."
if __name__ == "__main__":
main(sys.argv)
```
***UPDATE:*** It should be noted that the order of of things ORed together in the regex *matters*. Have a look at the following test inspired by [TZOTZIOY](https://stackoverflow.com/users/6899/):
```
>>> search_str = "01catdog"
>>> test1 = re.compile("cat|catdog")
>>> match1 = test1.search(search_str)
>>> match1.group()
'cat'
>>> match1.start()
2
>>> test2 = re.compile("catdog|cat") # reverse order
>>> match2 = test2.search(search_str)
>>> match2.group()
'catdog'
>>> match2.start()
2
```
This suggests the order matters :-/. I am not sure what this means for Rax's application, but at least the behavior is known.
***UPDATE:*** I posted [this questions about the implementation of regular expressions in Python](https://stackoverflow.com/questions/844183/python-regular-expression-implementation-details) which will hopefully give us some insight into the issues found with this question. | ```
subs = ['cat', 'fish', 'dog']
sentences = ['0123dog789cat']
import re
subs = re.compile("|".join(subs))
def search():
for sentence in sentences:
result = subs.search(sentence)
if result != None:
return (result.group(), result.span()[0])
# ('dog', 4)
``` | What's the most efficient way to find one of several substrings in Python? | [
"",
"python",
"regex",
"string",
"substring",
""
] |
Can anyone tell me how to execute a .bat file from a PHP script?
I have tried:
```
exec("C:\[path to file]");
system("C:\[path to file]");
```
Nothing is working. I've checked the PHP manuals and googled around but can't find a good answer. Anyone know where I'm going wrong?
I'm running Windows 2003 Server and have successfully manually run the .bat file and it does what I need it to; I just need to be able to launch it programatically. | You might need to run it via `cmd`, eg:
```
system("cmd /c C:[path to file]");
``` | ```
<?php
exec('c:\WINDOWS\system32\cmd.exe /c START C:\Program Files\VideoLAN\VLC\vlc.bat');
?>
``` | How do you run a .bat file from PHP? | [
"",
"php",
"system",
"exec",
"batch-file",
""
] |
I have a somewhat weird requirement to be able to listen to a number of network interfaces from Java on a Linux machine and determine if one of them receives UDP packets of a certain type. The output data which I need is the IP address of the interface in question. Is there any way to do this in Java?
Listening on the wildcard address (new DatagramSocket(port)) doesn't help because while I do get the broadcast packets, I can't determine the local IP address of the interface they came through. Listening to broadcasts while being bound to a certain interface (new DatagramSocket(port, address)) doesn't receive the packets at all. This case deserves a code example which shows what I'm trying to do:
```
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) interfaces.nextElement();
Enumeration addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = (InetAddress)addresses.nextElement();
if (address.isLoopbackAddress() || address instanceof Inet6Address)
continue; //Not interested in loopback or ipv6 this time, thanks
DatagramSocket socket = new DatagramSocket(PORT, address);
//Try to read the broadcast messages from socket here
}
}
```
I also tried to to initialize the socket with the broadcast address constructed based on the beginning of the real IP of the interface and the rest according to the correct netmask:
```
byte [] mask = { (byte)255, 0, 0, 0 };
byte[] addrBytes = InetAddress.getByName("126.5.6.7").getAddress();
for (int i=0; i < 4; i++) {
addrBytes[i] |= ((byte)0xFF) ^ mask[i];
}
InetAddress bcastAddr = InetAddress.getByAddress(addrBytes);
```
That just throws a BindException when constructing the DatagramSocket.
**EDIT:** BindException (java.net.BindException: Cannot assign requested address) from calling DatagramSocket's constructor with a broadcast-address (e.g. 126.255.255.255) only comes with the latest Ubuntu 9.04 (probably not Ubuntu, but kernel-version specific issue though). With Ubuntu 8.10 this worked, as well as with the Red Hat release (RHEL 4.x) I am dealing with.
Apparently not receiving the packets while bound to a certain local IP is the [correct behaviour](http://www.developerweb.net/forum/showthread.php?t=5722), although in windows this works. I need to get it working on Linux (RHEL and Ubuntu). With low-level C-code there is a workaround setsockopt(SO\_BINDTODEVICE) which I can't find in the Java-APIs. [This](https://bugs.java.com/bugdatabase/view_bug?bug_id=4212324) doesn't exactly make me burst with optimism though :-) | This was an IPV6 Linux kernel issue in the end. Usually I have disabled IPV6, because it causes all kind of headaches. However in Ubuntu 9.04 it is so hard to disable IPV6 that I gave up, and that bit me.
To listen to broadcast messages from a certain interface, I'll first create the "broadcast version" of the interface's IP address:
```
byte [] mask = { (byte)255, 0, 0, 0 };
byte[] addrBytes = InetAddress.getByName("126.5.6.7").getAddress();
for (int i=0; i < 4; i++) {
addrBytes[i] |= ((byte)0xFF) ^ mask[i];
}
InetAddress bcastAddr = InetAddress.getByAddress(addrBytes);
```
Granted, this doesn't really bind me to a certain interface if many interfaces have an IP which starts with the same network part, but for me this solution is sufficient.
Then I create the datagramsocket with that address (and the desired port), and it works. But not without passing the following system properties to the JVM:
```
-Djava.net.preferIPv6Addresses=false -Djava.net.preferIPv4Stack=true
```
I have no idea how IPV6 manages to break listening to broadcasts, but it does, and the above parameters fix it. | To restate your problem, you need to determine which interface broadcast UDP packets were received on.
* If you bind to the wildcard address you receive the broadcasts, but there is no way to determine which network address the packet was received on.
* If you bind to a specific interface you know which interface address you are receiving on, but no longer receive the broadcasts (at least on the Linux TCP/IP stack.).
As others have mentioned, there are third party raw sockets libraries for Java such as [RockSaw](http://www.savarese.org/software/rocksaw/index.html) or [Jpcap](http://netresearch.ics.uci.edu/kfujii/jpcap/doc/), which may help you determine the address of the actual interface. | Java on Linux: Listening to broadcast messages on a bound local address | [
"",
"java",
"linux",
"networking",
"udp",
"broadcast",
""
] |
After reading [Hibernate: hbm2ddl.auto=update in production?](https://stackoverflow.com/questions/221379/hibernate-hbm2ddl-autoupdate-in-production) some questions arose.
First of all, the reason for I'm using Hibernate is to be database vendor independent (no need to write 10 versions of the "same" sql query, eg. tsql vs. sql).
My problem appears when it's time to create the database schemas (production environment). As far as I can see I have two alternatives.
1. hbm2dll = update
2. pure sql (ddl) scripts.
The first alternative is widely discussed in the thread above.
The second alternative is bad because that means I'm back to my first problem: "Don't want to create sql statements that are database vendor dependent". (This statement could be false if "all" (atlast the databases Hibernate support) are implementing the [DDL](http://docs.rinet.ru/O8/glossary.htm) (The subset of SQL used for defining and examining the structure of a database.) equal). | Do all changes in development/staging mode and transfer and execute scripts in production manually (or automatically, but don't let hibernate run them). The scripts may need some tunning since hbm2ddl update does not cover all cases.
In fact I never let hibernate run ddl against any database. I use hbm2ddl to generate text:
```
org.hibernate.tool.hbm2ddl.SchemaExport --config=hibernate.cfg.xml --text --format --delimiter=;
org.hibernate.tool.hbm2ddl.SchemaUpdate --config=hibernate.cfg.xml --text --format --delimiter=;
``` | [How to update a database schema without losing your data with Hibernate?](https://stackoverflow.com/questions/737989/how-to-update-a-database-schema-without-losing-your-data-with-hibernate) | How to creata database Schema using Hibernate | [
"",
"java",
"database",
"hibernate",
"hbm2ddl",
""
] |
i'm tired of reinventing the wheel on PHP and loving jQuery to death so which framework fits my needs? | <http://www.symfony-project.org/plugins/sfJqueryReloadedPlugin>
<http://bakery.cakephp.org/articles/view/jquery-helper>
<http://framework.zend.com/manual/en/zendx.jquery.html>
<http://qcu.be/> | [Agile Toolkit](http://agiletoolkit.org/) is a **PHP UI framework**, which comes with Object-Oriented User Interface. Pure HTML is produced when objects are rendered recursively. jQuery and jQuery UI widgets are used to **enhance** the output and implement AJAX. Here is a simple code snippet:
```
class page_users extends Page {
function page_index(){
$crud=$this->add('CRUD');
$crud->setModel('User',null,array('id','email','name','status'));
if($crud->grid){
$crud->grid->addColumn('expander','more','More...');
}
}
function page_more(){
$tt=$this->add('Tabs');
$tabs=$this->add('Tabs');
$tab=$tt->addTab('BasicInfo');
$tab->add('MVCForm')->setModel('User')->loadData($_GET['id']);
$tabs->addTabURL('../password','Password');
$tabs->addTabURL('../activity','Activity');
$tabs->addTabURL('../engage','Engage');
}
}
```
Interface is based on jQuery UI CSS Framework and therefore can be themed using Themeroller. Interaction with HTML, JS or AJAX is handled by Agile Toolkit but can be enhanced or replaced by developer. Above code **alone** will produce this:

The object structure is well-designed and can be used in major web projects. Agile Toolkit is available under OpenSource license.
See also: [atk4](/questions/tagged/atk4 "show questions tagged 'atk4'")
I'm [one of the authors](http://agiletoolkit.org/about/authors) of this wonderful toolkit. | PHP Framework with full jQuery integration? | [
"",
"php",
"jquery",
"frameworks",
""
] |
I cannot seem to get this to work. Any thoughts?
```
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Select Video Test</title>
<script type="text/javascript">
function selectVideo(){
var urlString = "http://www.mycookingsite.com/";
var selectedVideo = this.options[this.selectedIndex];
if (selectedVideo.value != "nothing"){
window.location = urlString + selectedVideo.value;
}
}
</script>
</head>
<body>
<form>
<select onchange="selectVideo()">
<option value="nothing">Select video from this list</option>
<option value="how-to-grill-burgers">How to Grill Burgers</option>
<option value="how-to-hard-boil-eggs">How to Make Hard-Boiled Eggs</option>
</select>
</form>
</body>
</html>
``` | You can only use `this` when you are in the event code. When you are in the function, `this` referrs to the window object. Send the reference as a parameter to the function:
```
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Select Video Test</title>
<script type="text/javascript">
function selectVideo(obj){
var urlString = "http://www.mycookingsite.com/";
var selectedVideo = obj.options[obj.selectedIndex];
if (selectedVideo.value != "nothing"){
window.location = urlString + selectedVideo.value;
}
}
</script>
</head>
<body>
<form>
<select onchange="selectVideo(this)">
<option value="nothing">Select video from this list</option>
<option value="how-to-grill-burgers">How to Grill Burgers</option>
<option value="how-to-hard-boil-eggs">How to Make Hard-Boiled Eggs</option>
</select>
</form>
</body>
</html>
``` | I'm not sure what the value of `this` is in your code, but it's not the `<select>` element. Here's some working code:
```
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Select Video Test</title>
<script type="text/javascript">
function selectVideo(){
var urlString = "http://www.mycookingsite.com/";
var videos = document.getElementById('videos');
var selectedVideo = videos.options[videos.selectedIndex];
if (selectedVideo.value != "nothing"){
window.location = urlString + selectedVideo.value;
}
}
</script>
</head>
<body>
<form>
<select id='videos' onchange="selectVideo()">
<option value="nothing">Select video from this list</option>
<option value="how-to-grill-burgers">How to Grill Burgers</option>
<option value="how-to-hard-boil-eggs">How to Make Hard-Boiled Eggs</option>
</select>
</form>
</body>
</html>
``` | Using Javascript to change URL based on option selected in dropdown | [
"",
"javascript",
"forms",
"dom",
""
] |
This is a simplified version of a query we are running where we need to find all rows in the main parent table where the child rows match. The query below returns no results when one of the child tables is empty.
The main table has two child tables:
```
CREATE TABLE main (id INT PRIMARY KEY, name VARCHAR(8));
CREATE TABLE child1(id INT PRIMARY KEY, main_id int, name VARCHAR(8));
ALTER TABLE child1 add constraint fk_child1_main foreign key (main_id) references main (id);
CREATE TABLE child2(id INT PRIMARY KEY, main_id int, name VARCHAR(8));
ALTER TABLE child2 add constraint fk_child2_main foreign key (main_id) references main (id);
INSERT INTO main (id, name) VALUES (1, 'main');
INSERT INTO child1 (id, main_id, name) VALUES (2, 1, 'child1');
```
There are no rows in child2 and the following query returns no rows when it is empty:
```
SELECT
main.*
FROM
main
INNER JOIN
child1
ON
main.id = child1.main_id
INNER JOIN
child2
ON
main.id = child2.main_id
WHERE
child1.name = 'child1' OR
child2.name = 'DOES NOT EXIST';
```
If a row is added to child2, even if it doesn't match the WHERE clause, then the SELECT does return the row in the main table.
```
INSERT INTO child2 (id, main_id, name) VALUES (4, 1, 'child2');
```
I've tested this on Derby and SQLite, so this looks to be something general with databases.
Why is this behaving this way?
What can I do to fix it?
I could change to UNION separate SELECTs, but that's much more verbose, and plus, we're generating the SQL dynamically and I'd rather not have to change our code.
Another fix is just to add a dumb row to the database, but that's messy.
PS The main table is a session table in an asset management system that records the assets that clients look up. There are different types of lookups and each kind gets a separate child table, plus there is an attributes child table for key/value pairs for the session that can be searched on. | When child2 has no rows, the query returns no rows because of the inner join to the child2 table. If you inner join to a table that has no rows, you will never get any results - you would have to outer join to child2 instead if you want to get results when child2 is empty.
When child2 does have a row, the reason your query returns results is because of the where clause:
```
WHERE
child1.name = 'child1' OR
child2.name = 'DOES NOT EXIST';
```
The inner join says there has to be something in child2 with a matching ID, but the where clause has an OR in it, so you will get results just because child1.name = 'child1'. After that, the database doesn't have to bother looking at the child2 tables.
To fix it:
I have hunch that you only want to return the child rows when some condition is met. You should outer-join to both of them, and perhaps also move your extra conditions from the where clause to the join clause, like this:
```
SELECT
main.*
FROM
main
LEFT OUTER JOIN
child1
ON
main.id = child1.main_id
AND child1.name = 'child1'
LEFT OUTER JOIN
child2
ON
main.id = child2.main_id
AND child2.name = 'whatever'
```
* The outer joins mean you have the chance of getting results even if one table is empty.
* Moving the extra conditions (child1.name = ...) from the WHERE clause to the outer join means you only get the tables info if the condition is true. (I think this might be what you are trying to do, but maybe not, in which case leave the conditions in the WHERE clause where you originally had them.) | It's returning nothing because you are using inner joins.
Change your inner joins to left joins | Why does this query only return results with non-empty child tables? | [
"",
"sql",
"database",
"database-agnostic",
""
] |
The idea is to produce utility class , so that whenever the guys hack the best currently known algorithms and new one comes to the market the only think that the Developer would have to do is to add the NewHighTechEncryptingAlgorithm\_Encryptor class and change a global application setting for NewHighTechEncryptingAlgorithm\_As\_String
so that the call would be
string myNewEncryptedString = Encryptor.Encrypt(StringToEncrypt , strAlgorithmName)
Edit: I removed the old code and pasted the answer, provided by rwwilden with the calling code
I quess the proper wording would be "Enhashing" as oppose of "Encryption" since no salt is envolved here ... this seems to be the best solution according to the proposed "specs"
```
using System;
using System.Text;
using System.Security.Cryptography;
namespace GenApp.Utils.Security
{
/// <summary>
/// Summary description for Encrypter
/// </summary>
public class Encrypter
{
/// <summary>
/// Encrypts according to the passed plain name for hasing algorithm
/// see CryptoConfig class from MSDN for more details
/// </summary>
/// <param name="strPlainTxt">the plain text to encrypt</param>
/// <param name="strAlgorithmName">The plain name of the hashing algorithm </param>
/// <returns> the encrypted string </returns>
public static string Encrypt ( string strPlainTxt, string strAlgorithmName )
{
string strHashedTxt = String.Empty;
byte[] bytPlain = System.Text.Encoding.UTF8.GetBytes ( strPlainTxt );
using (HashAlgorithm objAlgorithm = HashAlgorithm.Create ( strAlgorithmName ))
{
byte[] bytHash = objAlgorithm.ComputeHash ( bytPlain );
strHashedTxt = Convert.ToBase64String ( bytHash );
return strHashedTxt;
}
} //eof method
///// OLD CODE - REQUIRES RECODING
///// <summary>
///// Encrypts according to the passed plain name for hasing algorithm
///// see CryptoConfig class from MSDN for more details
///// </summary>
///// <param name="strPlainTxt">the plain text to encrypt</param>
///// <param name="strAlgorithmName">The plain name of the hashing algorithm </param>
///// <returns> the encrypted string </returns>
//public static string Encrypt ( string strPlainTxt, string strAlgorithmName )
//{
// string strHashedTxt = String.Empty;
// byte[] bytPlains = System.Text.Encoding.UTF8.GetBytes ( strPlainTxt );
// byte[] bytHash;
// //CryptoConfig objCryptoConfig = new CryptoConfig ();
// switch (strAlgorithmName)
// {
// case "SHA1":
// SHA1CryptoServiceProvider objProvForSHA1alg =
// (SHA1CryptoServiceProvider)CryptoConfig.CreateFromName ( strAlgorithmName );
// bytHash = objProvForSHA1alg.ComputeHash ( bytPlains );
// objProvForSHA1alg.Clear ();
// strHashedTxt = Convert.ToBase64String ( bytHash );
// break;
// case "MD5" :
// MD5CryptoServiceProvider objProvForMD5alg =
// (MD5CryptoServiceProvider)CryptoConfig.CreateFromName ( strAlgorithmName );
// bytHash = objProvForMD5alg.ComputeHash ( bytPlains );
// strHashedTxt = Convert.ToBase64String ( bytHash );
// objProvForMD5alg.Clear ();
// break;
// } //eof switch
// if (String.IsNullOrEmpty ( strHashedTxt ))
// throw new Exception ( "Encryption provider called by invalide simple name " );
// return strHashedTxt;
//} //eof method
} //eof class
class Program
{
static void Main ( string[] args )
{
string strPlainTxt = "UnEncryptedText";
string strAlgorithmName = "SHA1"; //the type of al
string strHashedTxt = String.Empty;
//START WITH ONE ALGORITHM
Console.WriteLine ( "Using the " + strAlgorithmName + " START " );
Console.WriteLine ( "The plain text is " + strPlainTxt );
Console.WriteLine ( "The encrypting algorithm is " + strAlgorithmName );
strHashedTxt = Encrypter.Encrypt ( strPlainTxt, strAlgorithmName );
Console.WriteLine ( "The hashed text is " + strHashedTxt );
Console.WriteLine ( "Using the " + strAlgorithmName + " END " );
//NOW CHANGE THE ALGORITHM
strAlgorithmName = "MD5";
Console.WriteLine ( "Using the " + strAlgorithmName + " START " );
Console.WriteLine ( "The plain text is " + strPlainTxt );
Console.WriteLine ( "The encrypting algorithm is " + strAlgorithmName );
strHashedTxt = Encrypter.Encrypt ( strPlainTxt, strAlgorithmName );
Console.WriteLine ( "The hashed text is " + strHashedTxt );
Console.WriteLine ( "Using the " + strAlgorithmName + " END " );
strAlgorithmName = "SHA256";
Console.WriteLine ( "Using the " + strAlgorithmName + " START " );
Console.WriteLine ( "The plain text is " + strPlainTxt );
Console.WriteLine ( "The encrypting algorithm is " + strAlgorithmName );
strHashedTxt = Encrypter.Encrypt ( strPlainTxt, strAlgorithmName );
Console.WriteLine ( "The hashed text is " + strHashedTxt );
Console.WriteLine ( "Using the " + strAlgorithmName + " END " );
Console.WriteLine ( "Hit enter to exit" );
Console.ReadLine ();
}
}
} //eof namespace
``` | You should take a look at the [CryptoConfig](http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptoconfig.aspx) class. Especially the method [CreateFromName](http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptoconfig.createfromname.aspx). It provides a way to obtain a cryptographic algorithm based on a name (that you supply in your configuration). Changing the name in your configuration automatically changes the algorithm used.
If you have made a choice on whether to use symmetric or asymmetric encryption, you should use the more specific [SymmetricAlgorithm.Create(string)](http://msdn.microsoft.com/en-us/library/k74a682y.aspx) or [AsymmetricAlgorithm.Create(string)](http://msdn.microsoft.com/en-us/library/bf2t8ayw.aspx) methods.
Since you require a hashing solution, you should use [HashAlgorithm.Create(string)](http://msdn.microsoft.com/en-us/library/wet69s13.aspx). The reason for implementing it as I do below is that you do not have to change any code when you decide to use another hashing algorithm. In your code you have to add another `case` statement.
```
public static string Encrypt(string toEncrypt, string algorithmName)
{
byte[] bytePlain = System.Text.Encoding.UTF8.GetBytes ( strPlainTxt );
using (HashAlgorithm algorithm = HashAlgorithm.Create(algorithm))
{
byte[] byteHash = algorithm.ComputeHash(bytePlain);
string strHashedTxt = Convert.ToBase64String (byteHash);
return strHashedTxt;
}
}
``` | I'd suggest a copy of Resharper or Coderush to fix that coders blindness :) Brace highlighting comes in the box.
Also, this is classic, or basic, interfaces + factory pattern. As others have said, the MEF and ICryptoTransform is most likely the cleanest place to start, as the framework provides it for you, but if you want to know the basics:
Make an interface:
```
public interface IEncrypter {
string Encrypt(string plaintext);
}
```
then implement it:
```
public class MD5Encrypter : IEncrypter {
public string Encrypt(string plaintext) {
//code goes here.
}
}
public class SHA1Encrypter : IEncrypter {
public string Encrypt(string plaintext) {
//code goes here.
}
}
```
then, make a factory:
```
public class EncryptionFactory {
public static IEncrypter GetEncrypter() {
//work out which one to return, maybe based on a config value?
// I'm just going to return an MD5, but you'd want to use a switch statement etc
// to decide which one to return.
return new MD5Encrypter();
}
}
```
And use it like this:
```
IEncrypter encrypter = EncryptionFactory.GetEncrypter();
string garbageText = encrypter.Encrypt("Hello, world");
```
All you change is the factory, or better yet, the config the factory reads in, to make it use something else. Hell, you can base it on the time of day if you really want :) The code you write which uses the interface doesn't care what the object actually is - it just cares that is has a: string Encrypt(string) method.
The MEF does this for you, in some ways.
Using the interfaces also means you could return a dummy, fake IEncrypter which does nothing, so you can write unit tests against it without actually doing the encryption. Not SUPER useful in this case, but it's good practice in general.
Also, you could use @rwwilden's suggestion in the Factory to generate it - you read a string from config, and use the Asymetric/Symetric create method thing he's talking about to create the underlying class..... | How to create "upgradable" encrypting class | [
"",
"c#",
"asp.net",
"security",
"encryption",
""
] |
Is it possible to redirect an image to a dynamically generated image(using PHP)?
I have a dynamically created image and it has an extension ".PHP" (obviously) and that server is not under my control. So I want to redirect "somename.jpg" (on my server) to "remoteserver/dynamicimage.php" (on some remote server not under my control) so that I can right away link it as `<img src="somename.jpg"/>` and the dynamically generated image is shown.
Please let me know if this is possible. | Browsers follows redirects for images. Create a php-file called "somename.jpg" and add:
```
<?php
header('Location: http://www.otherserver.com/image.php');
```
Use the Apache directive [ForceType](http://httpd.apache.org/docs/1.3/mod/mod_mime.html#forcetype) in an .htaccess file to tell the server to process the .jpg file as php:
```
<Files somename.jpg>
ForceType application/x-httpd-php
</Files>
```
Or just call the file somename.php if you don't really need the .jpg extension.
You could probably accomplish this using [mod\_alias](http://httpd.apache.org/docs/1.3/mod/mod_alias.html#redirect) as well, although I haven't tried it:
```
Redirect somename.jpg http://www.otherserver.com/image.php
```
This would go in an .htaccess file as well. | Try adding something like this to your .htaccess file
```
RewriteEngine on
RewriteRule ^(.*)\.jpg$ /scripts/$1.php
``` | Point an <img> tag to a image dynamically generated by PHP? | [
"",
"php",
"mod-rewrite",
""
] |
I am always confused with the different ways of expressing nulls. There is the null reference type (aka "null"). Then I've seen that throughout my application, developers have used MinValue to represent nulls. Ex: Double.MinValue or DateTime.MinValue except for a String for which they use "null"
Then there is System.DBNull (and System.DBNull.Value - not sure what to use when). To add to the confusion, there are also `System.Nullable` and `System.Nullable<T>` namespaces.
Can someone help me clear this null confusion?
Thanks | Sure.
`System.DBNull` is a class that was (and still is) used by ADO.NET to represent a `null` value in a database.
`null` is actually a `null` reference, and in your application code any reference type should use `null` as its, well, `null` value.
The usage of `MinValue` for various primitive types (which, since they are value types cannot be assigned `null`) dates back to the dark days before C# 2.0, which introduced generics. Now the preferred method for representing a nullable primitive type is to use the `Nullable<T>` generic type, usually represented in shorthand with a question mark after the primitive type. For example, I could declare a nullable `int` variable named `foo` in C# as:
```
Nullable<int> foo;
```
or
```
int? foo;
```
Both are identical. | * `null` is only valid for *reference* types: types that are a `class` rather than a `structure`.
* .Net also has value types: int, double, DateTime, etc. Value types cannot be null, you so you normally compare those to their default value, which is very often `type.MinValue`, but might be something (consider Boolean, for example).
* `Nullable<T>` is for when you have a value type that might genuinely be null. The default value (maybe MinValue) is also valid and you need to distinguish it from when the variable has not been assigned yet. In C#, you can use a ? with a value type as a short hand notation (for example: `int?`), but you're still creating the same `Nullable<T>`.
* `DBNull` specifically refers to NULL values from a database. It's not the same thing as using null elsewhere in the language: it's only for talking to a database so you can know when a query returned a null value.
* When using generics, you'll also see the `default(T)` construct used, where T is a type parameter. This allows you to set a type's default value without knowing whether that type is a reference type or a value type, much less what a specific value type's default value might be. | Confusion with NULLs in C# | [
"",
"c#",
".net",
".net-2.0",
""
] |
I've got my current location lat long and I've got a list of places and there lat long.
What I'd like to do is figure out if I'm nearby one of the places, nearby would be something like +100m. I don't want to display a map, just know if I'm near it.
What kind of php libraries are available for comparing location/lat long? Or can I solve it with math?
Thanks | [Using Longitude and Latitude to Determine Distance](http://www.mathforum.com/library/drmath/view/51711.html)
> This problem can be most easily solved by using spherical coordinates on the
> earth. Have you dealt with those before? Here's the transformation from
> spherical coordinates to normal rectangular coordinates, where a=latitude
> and b=longitude, and r is the radius of the earth:
>
> x = r Cos[a] Cos[b]
> y = r Cos[a] Sin[b]
> z = r Sin[a]
>
> Then we'll use the following property of the dot product (notated [p,q]):
>
> [p,q] = Length[p] \* Length[q] \* Cos[angle between p & q]
>
> (...)
at least, if height isn't important to you.
if you need the height and/or distance dependend on roads or walkability (is this even a word?), i think google maps would be more exact. | It's not hard to calculate distance between two points, given their spherical coordinates (latitude/longitude). A quick search for "latitude longitude distance" on Google reveals the equation.
Apparently it's something like this:
```
acos(cos(a.lat) * cos(a.lon) * cos(b.lat) * cos(b.lon) +
cos(a.lat) * sin(a.lon) * cos(b.lat) * sin(b.lon) +
sin(a.lat) * sin(b.lat)) * r
```
where `a` and `b` are your points and `r` is the earth's mean radius (6371 km).
Once you're able to calculate the distance between two points given their coordinates, you'll want to loop through all the landmarks and see if your current location is near one.
However, if you have many landmarks, you might want to use a spatial search algorithm (maybe using a [Quadtree](http://en.wikipedia.org/wiki/Quadtree) or a similar data structure). | Figure out if I'm nearby something | [
"",
"php",
"geolocation",
"gps",
"gis",
"location",
""
] |
I am wondering if there is any difference with regards to performance between the following
```
SELECT ... FROM ... WHERE someFIELD IN(1,2,3,4)
SELECT ... FROM ... WHERE someFIELD between 0 AND 5
SELECT ... FROM ... WHERE someFIELD = 1 OR someFIELD = 2 OR someFIELD = 3 ...
```
or will MySQL optimize the SQL in the same way compilers optimize code?
---
### EDIT
Changed the `AND`'s to `OR`'s for the reason stated in the comments. | The accepted answer doesn't explain the reason.
Below are quoted from High Performance MySQL, 3rd Edition.
> In many database servers, IN() is just a synonym for multiple OR clauses, because the two are logically equivalent. Not so in MySQL, which sorts the values in the IN() list and uses a fast binary search to see whether a value is in the list. This is O(Log n) in the size of the list, whereas an equivalent series of OR clauses is O(n) in the size of the list (i.e., much slower for large lists) | I needed to know this for sure, so I benchmarked both methods. I consistenly found `IN` to be much faster than using `OR`.
Do not believe people who give their "opinion", science is all about testing and evidence.
I ran a loop of 1000x the equivalent queries (for consistency, I used `sql_no_cache`):
`IN`: 2.34969592094s
`OR`: 5.83781504631s
*Update:*
*(I don't have the source code for the original test, as it was 6 years ago, though it returns a result in the same range as this test)*
In request for some sample code to test this, here is the simplest possible use case. Using Eloquent for syntax simplicity, raw SQL equivalent executes the same.
```
$t = microtime(true);
for($i=0; $i<10000; $i++):
$q = DB::table('users')->where('id',1)
->orWhere('id',2)
->orWhere('id',3)
->orWhere('id',4)
->orWhere('id',5)
->orWhere('id',6)
->orWhere('id',7)
->orWhere('id',8)
->orWhere('id',9)
->orWhere('id',10)
->orWhere('id',11)
->orWhere('id',12)
->orWhere('id',13)
->orWhere('id',14)
->orWhere('id',15)
->orWhere('id',16)
->orWhere('id',17)
->orWhere('id',18)
->orWhere('id',19)
->orWhere('id',20)->get();
endfor;
$t2 = microtime(true);
echo $t."\n".$t2."\n".($t2-$t)."\n";
```
> 1482080514.3635
> 1482080517.3713
> **3.0078368186951**
```
$t = microtime(true);
for($i=0; $i<10000; $i++):
$q = DB::table('users')->whereIn('id',[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])->get();
endfor;
$t2 = microtime(true);
echo $t."\n".$t2."\n".($t2-$t)."\n";
```
> 1482080534.0185
> 1482080536.178
> **2.1595389842987** | MySQL OR vs IN performance | [
"",
"mysql",
"sql",
"performance",
"optimization",
""
] |
Haven't seen anything about it here but it seems to solve one of the problems with GWT - the fact that you have to write Java code to generate your GUI. Instead [this software](http://www.instantiations.com/gwtdesigner/) allows you to design the GUI using drag-and-drop tools - a WYSIWYG interface.
I'm not trying to sell the product, by the way.
I just want to know whether it works as advertised, is effective, easy to use, etc?
Anyone have any experience to answer these questions? | I don't think that the lack of a GUI editor is a problem with GWT. Consider HTML, there are plenty of WYSIWYG editors for that (like Dreamweaver) but most experienced web designers don't touch that stuff with a barge pole, they hand code it. Not because they're masochists, but because they want control over the source, they want to make it clean and readable. Coding is a scientific artwork, best left to Human Beings ;)
I tried GWT Designer very early on, and I found that it was fairly poor (and only worked on Windows because it had some dlls that went along with it), but things may have changed drastically since then. | GWT-Designer is now freely available as the product has been acquired by Google. <http://googlewebtoolkit.blogspot.com/2010/09/google-relaunches-instantiations.html>
Google will improve the product which is already quite good. | Has anyone used "GWT Designer"? | [
"",
"java",
"gwt",
"ide",
"wysiwyg",
"gwt-designer",
""
] |
Suppose we have two tables. Post and Comment. Post has many Comments. Pretend they are somewhat filled so that the number of comments per post is varied. I want a query which will grab all posts but only the newest comment per post.
I have been directed to joins and sub queries but I can't figure it out.
Example Output:
Post1:
Comment4 (newest for post1)
Post2:
Comment2 (newest for post2)
Post3:
Comment 10 (newest for post3)
etc...
Any help would be greatly appreciated. Thanks. | This answer assumes that you have a unique identifier for each comment, and that it's an increasing number. That is, later posts have higher numbers than earlier posts. Doesn't have to be sequential, just have to be corresponding to order of input.
First, do a query that extracts the maximum comment id, grouped by post id.
Something like this:
```
SELECT MAX(ID) MaxCommentID, PostID
FROM Comments
GROUP BY PostID
```
This will give you a list of post id's, and the highest (latest) comment id for each one.
Then you join with this, to extract the rest of the data from the comments, for those id's.
```
SELECT C1.*, C2.PostID
FROM Comments AS C1
INNER JOIN (
SELECT MAX(ID) MaxCommentID, PostID
FROM Comments
GROUP BY PostID
) AS C2 ON C1.CommentID = C2.MaxCommentID
```
Then, you join with the posts, to get the information about those posts.
```
SELECT C1.*, P.*
FROM Comments AS C1
INNER JOIN (
SELECT MAX(ID) MaxCommentID, PostID
FROM Comments
GROUP BY PostID
) AS C2 ON C1.CommentID = C2.MaxCommentID
INNER JOIN Posts AS P ON C2.PostID = P.ID
```
---
An alternate approach doesn't use the PostID of the inner query at all. First, pick out the maximum comment id for all unique posts, but don't care about which post, we know they're unique.
```
SELECT MAX(ID) AS MaxCommentID
FROM Comments
GROUP BY PostID
```
Then do an IN clause, to get the rest of the data for those comments:
```
SELECT C1.*
FROM Comments
WHERE C1.ID IN (
SELECT MAX(ID) AS MaxCommentID
FROM Comments
GROUP BY PostID
)
```
Then simply join in the posts:
```
SELECT C1.*, P.*
FROM Comments AS C1
INNER JOIN Posts AS P ON C1.PostID = P.ID
WHERE C1.ID IN (
SELECT MAX(ID) AS MaxCommentID
FROM Comments
GROUP BY PostID
)
``` | Select the newest comment from a subquery
e.g
```
Select *
from Posts po
Inner Join
(
Select CommentThread, CommentDate, CommentBody, Post from comments a
inner join
(select commentthread, max(commentdate)
from comments b
group by commentthread)
on a.commentthread = b.commentthread
and a.commentdate = b.commentdate
) co
on po.Post = co.post
``` | SQL Query Question: X has many Y. Get all X and get only the newest Y per X | [
"",
"sql",
"mysql",
"database",
"join",
""
] |
I need to loop lot of arrays in different ways and display it in a page. The arrays are generated by a module class. I know that its better not to include functions on 'views' and I want to know where to insert the functions file.
I know I can 'extend' the helpers, but I don't want to extend a helper. I want to kind of create a helper with my loop functions.. Lets call it loops\_helper.php | A CodeIgniter helper is a PHP file with multiple functions. *It is not a class*
Create a file and put the following code into it.
```
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('test_method'))
{
function test_method($var = '')
{
return $var;
}
}
```
Save this to **application/helpers/** . We shall call it "new\_helper.php"
The first line exists to make sure the file cannot be included and ran from outside the CodeIgniter scope. Everything after this is self explanatory.
# Using the Helper
---
This can be in your **controller**, **model** or **view** (not preferable)
```
$this->load->helper('new_helper');
echo test_method('Hello World');
```
If you use this helper in a lot of locations you can have it load automatically by adding it to the autoload configuration file i.e. `<your-web-app>\application\config\autoload.php`.
```
$autoload['helper'] = array('new_helper');
```
-Mathew | Some code that allows you to use CI instance inside the helper:
```
function yourHelperFunction(){
$ci=& get_instance();
$ci->load->database();
$sql = "select * from table";
$query = $ci->db->query($sql);
$row = $query->result();
}
``` | CodeIgniter: Create new helper? | [
"",
"php",
"codeigniter",
"codeigniter-helpers",
""
] |
(I believe this is the same problem as [this one](https://stackoverflow.com/questions/785291/why-is-linq-to-sql-entity-association-creating-a-new-duplicate-row-when-inserti), but there's no answer there, and I think I can express the problem better here...)
I have two Linq-to-SQL classes, `State` and `County`, where `County` has a FK to `State`. Here's some test code:
```
State s = State.GetState("NY"); // here I do a load of a State class via the Linq DataContext
County c = new County();
c.Name = "Rockland";
c.State = s;
MyDataContext.GetTable<County>().InsertOnSubmit(c);
MyDataContext.SubmitChanges(); // throws an exception
```
The exception thrown is `"Violation of PRIMARY KEY constraint 'PK_State'. Cannot insert duplicate key in object 'dbo.State'"`.
In other words, what appears to be happening here is that despite my having loaded `s` as an existing record, when I attempt to insert `c`, Linq is assuming that all related objects, `State` included, also need to be inserted!
This is completely absurd, and I cannot believe that Microsoft would have made such a huge blunder - so it must be that somewhere my own understanding is faulty.
Can anyone please explain what I am doing wrong, and what the correct approach here is?
Thanks! | Is the `State.GetState(...)` function using the same datacontext as `MyDataContext.GetTable<County>()`? | Something isn't right here. I'm assuming State -> Count is a one to many relationship. In which case, the correct way of doing this is:
```
State s = State.GetState("NY"); // here I do a load of a State class via the Linq DataContext
County c = new County();
c.Name = "Rockland";
s.Counties.Add(c);
db.SubmitChanges();
```
Since State is the parent table, you need to add the counties to the state's counties collection. | Linq problem with inserting new rows that have references to existing records | [
"",
"c#",
".net",
"linq",
"linq-to-sql",
""
] |
I need to create a strongly typed dataset during run-time for the user preferred target database. Visual studio has massive design time support for creating typed datasets. I need to automate the process of generating typed datasets for the target database at runtime.
It should create...
1.) XSD file.
2.) Typed dataset represnting the Database
3.) Typed wrappers for all database tables and columns within the tables.
4.) TableAdapters for each table.
So I need to generate the same typed dataset at runtime which is generally created while design time using Typed dataset designer of the Visual Studio. | I tend to agree with jcollum on this one, using a Typed Dataset at runtime is probably the wrong way to go. If on the other hand, you just want to be able to get structured data ( aka, a DataTable ) from a database at runtime, you could use reflection to create a TableAdapter from an arbitrary data result.
```
var results = (from data in db.SomeTable select data).ToArray();
DataTable dt = ObjectArrayToDataTable(results);
// At this point you have a properly structure DataTable.
// Here is your XSD, if absolutely needed.
dt.WriteXMLSchema("c:\somepath\somefilename.xsd");
private static System.Data.DataTable ObjectArrayToDataTable(object[] data)
{
System.Data.DataTable dt = new System.Data.DataTable();
// if data is empty, return an empty table
if (data.Length == 0) return dt;
Type t = data[0].GetType();
System.Reflection.PropertyInfo[] piList = t.GetProperties();
foreach (System.Reflection.PropertyInfo p in piList)
{
dt.Columns.Add(new System.Data.DataColumn(p.Name, p.PropertyType));
}
object[] row = new object[piList.Length];
foreach (object obj in data)
{
int i = 0;
foreach (System.Reflection.PropertyInfo pi in piList)
{
row[i++] = pi.GetValue(obj, null);
}
dt.Rows.Add(row);
}
return dt;
}
```
You could apply the same principal to create a structured DataSet and easily create a DataAdapter to it.
Or perhaps I am mis-reading your requirements. | You could probably use `XSD.EXE`. Fire it up from your program... | How do I create strongly typed dataset during runtime using C#? | [
"",
"c#",
"code-generation",
"strongly-typed-dataset",
""
] |
Very basic, but would like to know the difference/security ramifications etc of using " vs. '.
Can someone provide an example that explains when to use each one? | There are a lot of subtle differences, you'll want to read the [php documentation](http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single) to get a lot of the details, but the important detail are:
Double quotes are parsed whereas single quotes are literals.
You can use variables inline with double quotes, but not with single quotes.
There are some catches though:
```
<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works; "'" is an invalid character for variable names
echo "He drank some $beers"; // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>
```
Single quotes are slightly faster. | When a string is enclosed in double quotes, then escape sequences such as `\n` and variable identifiers such as `$var` are interpreted.
See the [PHP strings manual](http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single) for specific details and examples. | What's the difference between " and ' when creating strings in PHP? | [
"",
"php",
""
] |
I have this bit of code that is outputting the wrong results.
```
#include <stdio.h>
#include <string.h>
int main()
{
unsigned char bytes[4];
float flt=0;
bytes[0]=0xde;
bytes[1]=0xad;
bytes[2]=0xbe;
bytes[3]=0xef;
memcpy( &flt, bytes, 4);
printf("bytes 0x%x float %e\n", flt, flt);
return 0;
}
```
the output that I get is
> bytes 0xc0000000 float -2.000001e+00
I am expecting to get
> bytes 0xdeadbeef float -6.2598534e+18
edit #1
as was pointed out the endianness could be different which would result in the following
> bytes 0xefbeadde float -1.1802469e+29
what I don't understand is the cast from float to unsigned int resulting in 0xc0000000 (the float in the same printf statement being -2.0000 I would attribute to compiler optimization)
this was working before on a different computer. It could be an architecture change. | It is not problem of memcpy.
1. `float` is allways converted to `double` when passed over `...` of printf, so you just can't get 4 bytes on most of intel architectures.
2. when you expacting `0xdeadbeef` in this code, you assume that your architecture is BIG endian. There are many little endian architectures, for example Intel x86. | You do realise that floats are promoted to double when passed to a variable parameters function like printf()? So when you say:
```
printf("bytes 0x%x float %e\n", flt, flt);
```
you are trying to treat what is really two 8-byte values like two 4-byte
values, giving (I believe) undefined behaviour. | memcpy not doing as it is supposed to | [
"",
"c++",
"c",
"memcpy",
""
] |
**Question:** I have just wrote my first code using c# lambda expressions. It works, but I am not sure if this is the best way to do it. Any recommendations on a better way to do the lambda expression? It seems odd to have numerous lines of code in the expression like I do below.
**Background:** I have a generic list of delegates. Each delegate function returns an enum value indicating what happened in the function. Upon evaluation of the delegate, I need to add the enum to a List if it was not a specific enum value.
**Disclaimer:** Code here is very generic, the real code actually does stuff in the delegates to determine the return value!
---
```
class Class1
{
public enum WhatHappened
{
ThingA,
ThingB,
Nothing
}
private delegate WhatHappened del();
public static List<WhatHappened> DoStuff()
{
List<del> CheckValues = new List<del>();
List<WhatHappened> returnValue = new List<WhatHappened> { };
CheckValues.Add(delegate { return method1(); });
CheckValues.Add(delegate { return method2(); });
CheckValues.ForEach(x =>
{
WhatHappened wh = x();
if (wh != WhatHappened.Nothing)
returnValue.Add(wh);
});
return returnValue;
}
private static WhatHappened method1()
{
return WhatHappened.Nothing;
}
private static WhatHappened method2()
{
return WhatHappened.ThingA;
}
}
```
**Note:** I originally had the lambda like adding all the items (see below), then removing the ones I didn't want (WhatHappened.Nothing).
```
CheckValues.ForEach(x => returnValue.Add(x()));
``` | Okay, a few suggestions:
* Don't call your delegate `del`. In this case, I'd use `Func<WhatHappened>` - but if you *do* want to declare your own delegate type, give it a more descriptive name, and obey the .NET naming conventions.
* Instead of using anonymous methods to add to `CheckValues`, you can just use:
```
CheckValues.Add(method1);
CheckValues.Add(method2);
```
The compiler will convert the method groups into delegates.
* I'd recommend not using Pascal case for a local variable name to start with.
* Your collection initializer for `returnValues` isn't really doing anything for you - just call the `List<T>` constructor as normal, or use my code below which doesn't require a local variable to start with.
* If your list *really* only has two delegates in it, I'd just call them separately. It's a lot simpler.
* Otherwise you can indeed use LINQ as Jared suggests, but I'd do it slightly differently:
```
return CheckValues.Select(x => x())
.Where(wh => wh != WhatHappened.Nothing)
.ToList();
```
EDIT: As suggested, here's the full example. It's not quite the same as Denis's though... I've made a couple of changes :)
```
public static List<WhatHappened> DoStuff()
{
var functions = new List<Func<WhatHappened>> { Method1, Method2 };
return functions.Select(function => function())
.Where(result => result != WhatHappened.Nothing)
.ToList();
}
```
(I'm assuming that `method1` and `method2` have been renamed to fit the naming convention. Of course in real life I'm sure they'd have more useful names anyway...) | You can go lambda all the way by chaining Select (map) and Where (filter) instead of multiple FOR loops and IF statements
```
// get results from the list of functions
var results = CheckValues.Select(x => x());
// filter out only the relevant ones.
var returnValues = results.Where(x => x != WhatHappened.Nothing);
```
Basically, you should think more **[declaratively](http://en.wikipedia.org/wiki/Declarative_programming)** instead of **[imperatively](http://en.wikipedia.org/wiki/Imperative_programming)** when work ing with lambdas. It'll help you write more elegant code. | c# lambda expression - add delegate results to generic list | [
"",
"c#",
".net",
".net-3.5",
"lambda",
""
] |
I have an array:
```
$arr_nav = array( array( "id" => "apple",
"url" => "apple.html",
"name" => "My Apple"
),
array( "id" => "orange",
"url" => "orange/oranges.html",
"name" => "View All Oranges",
),
array( "id" => "pear",
"url" => "pear.html",
"name" => "A Pear"
)
);
```
Which I would like to use a foreach loop to replace (which only allows me to set the number:
```
for ($row = 0; $row < 5; $row++)
```
with the ability to display a `.first` and `.last` class for the relevant array values
**Edit**
I would like the data to be echoed as:
```
<li id="' . $arr_nav[$row]["id"] . '"><a href="' . $v_url_root . $arr_nav[$row]["url"] . '" title="' . $arr_nav[$row]["name"] . '">"' . $arr_nav[$row]["name"] . '</a></li>' . "\r\n";
```
Many thanks for your quick responses. StackOverflow rocks! | ```
$last = count($arr_nav) - 1;
foreach ($arr_nav as $i => $row)
{
$isFirst = ($i == 0);
$isLast = ($i == $last);
echo ... $row['name'] ... $row['url'] ...;
}
``` | ```
<?php
$php_multi_array = array("lang"=>"PHP", "type"=>array("c_type"=>"MULTI", "p_type"=>"ARRAY"));
//Iterate through an array declared above
foreach($php_multi_array as $key => $value)
{
if (!is_array($value))
{
echo $key ." => ". $value ."\r\n" ;
}
else
{
echo $key ." => array( \r\n";
foreach ($value as $key2 => $value2)
{
echo "\t". $key2 ." => ". $value2 ."\r\n";
}
echo ")";
}
}
?>
```
**OUTPUT:**
```
lang => PHP
type => array(
c_type => MULTI
p_type => ARRAY
)
``` | PHP foreach loop through multidimensional array | [
"",
"php",
"arrays",
"loops",
"multidimensional-array",
""
] |
I want to write the following function which should be used in an Excel worksheet:
```
=GetRecField("Foo Record Key", "FooField1")
```
...which will connect internally through ODBC to an SQL database, execute there an
```
SELECT FooField1 FROM MyTable WHERE KEY_FIELD='Foo Record Key';
```
and will return the resulting value as the result of the function GetRecField. The above SQL is granted to return only one record (IOW KEY\_FIELD has an unique constraint).
Of course, the above function can be called multiple times in a worksheet so, please try to avoid a blind `QueryTables.Add`
TIA. | You can write a custom function to do that
1. Open the VBA editor (ALT-F11)
2. Open Tools -> References, and make sure the "Microsoft ActiveX Data Objects 2.8 Library" and "Microsoft ActiveX Data Objects Recordset 2.8 Library" are selected
3. Right click VBAProject, and choose Insert -> Module
4. Open the module. Now you can create a custom function, like:
```
Public Function GetItem(field As String, id As Integer) As String
Set oConnection = New ADODB.Connection
Dim oRecordset As ADOR.Recordset
oConnection.Open "provider=sqloledb;data source=yourserver;" & _
"Trusted_Connection=yes;initial catalog=yourdatabase;"
Set oRecordset = oConnection.Execute( & _
"select " & field & " from table where id = " & id)
If oRecordset.EOF Then
GetItem = "n/a"
Else
GetItem = oRecordset(field)
End If
End Function
```
5. You can now call the function from a cell:
=GetItem("fieldname";2)
The module is required because non-module functions can't be called from inside the spreadhseet. | Why not use Excel's built-in database query functionality on a separate sheet (Data menu, Import External Data, New Database Query), then use `VLOOKUP` to extract values from that sheet? | How to write an Excel function which returns a value from an SQL database? | [
"",
"sql",
"excel",
"odbc",
""
] |
I have a user registration form and I only want the user to specify their first and last name (i.e. Donalg Doonsberry). If the user doesn't provide their name in this fashion, the input will be rejected. I thought something like this would work for my regex user validation in cakephp:
```
'name'=>array('Name has to be comprised of letters.
'=>array('rule'=>array('custom', '/[A-Za-z ]+/')
)),
``` | You have to be careful validating names... what about:
* Donalg McDonald <- capital in the middle of a word
* Donalg Fooble-Whiffery <- hyphenated
* Donalg Déénsbnérry-McDonald Sr. 3rd <- you get the idea
To validate names in the format you specified:
```
/[A-Z][a-z]+ [A-Z][a-z]+/
```
Being a bit more lenient:
```
/([\w.-]+ )+[\w+.-]/
``` | Personally, I wouldn't bother with first/last name validation. You can only validate their length (there is a built-in validation rule in cake for that) and make sure you put "allowEmpty" => true, if that's what you want. | How can I do alphanumeric with space regex model validation in CakePHP? | [
"",
"php",
"regex",
"validation",
"cakephp",
""
] |
I have a list-generic that has a property (class type). I need a sort method for Z parameters (TrainingSet):
```
public override List<TrainingSet> CalculatedDistancesArray
(List<TrainigSet> ts, double x, double y, int k)
{
for (int i =0; i < ts.Count; i++)
{
ts[i].Z = (Math.Sqrt(Math.Pow((ts[i].X - x), 2)
+ Math.Pow((ts[i].Y - y), 2)));
}
// I want to sort according to Z
ts.Sort(); //Failed to compare two elements in the array.
List<TrainingSet> sortedlist = new List<TrainingSet>();
for (int i = 0; i < k; i++)
{
sortedlist.Add(ts[i]);
}
return ts;
}
public class TrainigSet
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public string Risk { get; set; }
}
``` | Just sorting on a single property is easy. Use the overload which takes a `Comparison<T>`:
```
// C# 2
ts.Sort(delegate (TrainingSet o1, TrainingSet o2)
{ return o1.Z.CompareTo(o2.Z)); }
);
// C# 3
ts.Sort((o1, o2) => o1.Z.CompareTo(o2.Z));
```
Sorting on multiple properties is a bit trickier. I've got classes to build up comparisons in a compound manner, as well as building "projection comparisons" but if you really only want to sort by Z then the above code is going to be as easy as it gets.
If you're using .NET 3.5 and you don't really need the list to be sorted in-place, you can use OrderBy and ThenBy, e.g.
```
return ts.OrderBy(t => t.Z);
```
or for a more complicated comparison:
```
return ts.OrderBy(t => t.Z).ThenBy(t => t.X);
```
These would be represented by `orderby` clauses in a query expression:
```
return from t in ts
orderby t.Z
select t;
```
and
```
return from t in ts
orderby t.Z, t.X
select t;
```
(You can also sort in a descending manner if you want.) | ```
var sortedList =
list.OrderBy(i => i.X).ThenBy(i => i.Y).ThenBy(i => i.Z).ToList();
``` | How to sort list type generic if more than one property? | [
"",
"c#",
".net",
"asp.net",
"generics",
""
] |
### Duplicate:
> [New to C#, why does Property Set throw StackOverflow exception?](https://stackoverflow.com/questions/367192/new-to-c-why-does-property-set-throw-stackoverflow-exception)
I have a simple class call myClass that has a property called isAuthenticated with the following code:
```
public class myClass
{
public myClass()
{
this.isAuthenticated = false;
}
public bool isAuthenticated
{
get { return isAuthenticated; }
set { isAuthenticated = value; }
}
}
```
When I initalize the class I get a stackoverflow on the set {...} line, what am I doing wrong? | The getter/setter is calling itself. Add a member variable.
```
{
bool isAuthenticated;
public myClass()
{
IsAuthenticated = false;
}
public bool IsAuthenticated
{
get { return isAuthenticated; }
set { isAuthenticated = value; }
}
}
``` | Because you are setting the myClass.IsAuthenticated property itself.
You have to save the value in a local variable or if you use C# 3.0 or greater just do (automatic property)
```
public bool IsAuthenticated {get; set;}
``` | StackOverFlow on class property | [
"",
"c#",
""
] |
Ok. So I have some code that maps certain controls on a winForm to certain properties in an object, in order to do certain things to the controls when certain things happen to the data. All well and good, works fine. Not the problem. The issue is, to add items to the mapping, I call a function that looks like:
```
this.AddMapping(this.myControl,myObject,"myObjectPropertyName");
```
The problem I run into is that it is very difficult to tell, at compile time, the difference between the above line and the below:
```
this.AddMapping(this.myControl,myObject,"myObjectPropretyName");
```
Since the last parameter is a string, there's no compile time checking or anything like that that would enforce that the string itself actually corresponds to a valid property name on the given object. Additionally, things like Refactor and "Find All References" miss out on this sort of reference, resulting in hilarity when the name of the property itself changes. So what I'm wondering is if there's some way to change the function such that what I'm passing in is still a string representing the property name in some way, but with compile time checking of the actual value going in. Someone said I could do this with Expression Trees, but I've read up on them and don't seem to see the connection. I'd love to do something like:
```
this.AddMapping(this.myControl,myObject,myObject.myObjectPropertyName);
```
or even
```
this.AddMapping(this.myControl,myObject.myObjectPropertyName);
```
would be sweet!
Any ideas? | in 3.5, Expression is one way to specify member names as code; you could have:
```
public void AddMapping<TObj,TValue>(Control myControl, TObj myObject,
Expression<Func<TObj, TValue>> mapping) {...}
```
and then parse the expression tree to get the value. A little inefficient, but not too bad.
Here's example code:
```
public void AddMapping<TSource, TValue>(
Control control,
TSource source,
Expression<Func<TSource, TValue>> mapping)
{
if (mapping.Body.NodeType != ExpressionType.MemberAccess)
{
throw new InvalidOperationException();
}
MemberExpression me = (MemberExpression)mapping.Body;
if (me.Expression != mapping.Parameters[0])
{
throw new InvalidOperationException();
}
string name = me.Member.Name;
// TODO: do something with "control", "source" and "name",
// maybe also using "me.Member"
}
```
called with:
```
AddMapping(myControl, foo, f => f.Bar);
``` | To make things easier with the Expression based lamda workaround, I wrote it as an extension method.
```
public static string GetPropertyName<T>(this object o, Expression<Func<T>> property)
{
var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
if (propertyInfo == null)
throw new ArgumentException("The lambda expression 'property' should point to a valid Property");
var propertyName = propertyInfo.Name;
return propertyName;
}
```
Call like this
```
class testclass
{
public string s { get; set; }
public string s2 { get; set; }
public int i { get; set; }
}
[TestMethod]
public void TestMethod2()
{
testclass x = new testclass();
string nameOfPropertyS = this.GetPropertyName(() => x.s);
Assert.AreEqual("s", nameOfPropertyS);
string nameOfPropertyI = x.GetPropertyName(() => x.i);
Assert.AreEqual("i", nameOfPropertyI);
}
```
Okay, using as an extension method is really for convenience as you can in fact call the method on one class for properties of anther class. I'm sure it could be improved. | Extracting Property Names For Reflection, with Intellisense and Compile-Time Checking | [
"",
"c#",
"reflection",
"mapping",
"intellisense",
"compile-time",
""
] |
I prefer the use of external css and javascript files. There are however many cases where the content of a javascript or css file needs to be dynamic. I'll usually just transfer the javascript or css to inline or inpage code in my aspx page and handle the dynamic stuff there.
Does anyone have a better approach? Would there be a way to generate entire js or css files using asp.net's regular templating language?
I'm currently using webforms but I'd be interested in solving this issue in MVC as well.
Thanks | I've used a [HTTPHandler](http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.aspx) to send back dynamic javascript before. But not something that inherits from System.Web.UI.Page.
Using a HTTPHandler and an [ASHX](http://www.aspcode.net/Creating-an-ASHX-handler-in-ASPNET.aspx) or [AXD](http://weblogs.asp.net/jeff/archive/2005/07/18/419842.aspx) is the "ASP.Net" way to send back resources dynamically. | I have used handlers for dynamic css. Depending on what you need, you can do the same for js files.
I had a css file with placeholders for the pieces that needed to be dynamic like ##bacgroundcolor##, and the handler just replaced as appropriate.
I have also used an approach where I use css classes to mark html elements that need special behaviors. Then the static js, looks for this elements and hook the appropriate handlers. This is something that certainly would be even easier with jquery (I did it with regular js back then :(). | Does anyone use ASP.net (webforms) to dynamically generate javascript and/or css files? | [
"",
"asp.net",
"javascript",
"css",
"templating",
""
] |
There seems to be multiple extremes when supporting embeddable Java HTTP servers. I have seen minimalist approaches such as NanoHTTPD and leveraging the com.sun.net.httpserver package to attempting to embed Jetty and Tomcat. The ideal embeddable HTTP server would be implemented such that it could be launched via Executor and come with Servlet/JSP support but otherwise should allow for using the logger of its parent and allow for integrating its JMX hooks.
Likewise, it should also be modular enough where you can have the option of NOT including certain pieces of functionality. Has anyone ran across any Java-based HTTP servers with this characteristic? | I think grizzly is an ideal solution for you. <https://grizzly.dev.java.net/> . Out of box it's simply a NIO server, but there are different packages with support for HTTP, Servlets\JSP and etc. | [jetty](http://www.mortbay.org/jetty/):
* [JMX integration](http://docs.codehaus.org/display/JETTY/JMX)
* configurable logging (both for request and debugging)
* [JSP 2.0 and 2.1](http://docs.codehaus.org/display/JETTY/JSP+2.0+v+JSP+2.1) | Embeddable Java HTTP Servers | [
"",
"java",
"tomcat",
"web-applications",
"jetty",
"nanohttpd",
""
] |
I need to create ZIP archives on demand, using either Python zipfile module or unix command line utilities.
Resources to be zipped are often > 1GB and not necessarily compression-friendly.
How do I efficiently estimate its creation time / size? | Extract a bunch of small parts from the big file. Maybe 64 chunks of 64k each. Randomly selected.
Concatenate the data, compress it, measure the time and the compression ratio. Since you've randomly selected parts of the file chances are that you have compressed a representative subset of the data.
Now all you have to do is to estimate the time for the whole file based on the time of your test-data. | I suggest you measure the average time it takes to produce a zip of a certain size. Then you calculate the estimate from that measure. However I think the estimate will be very rough in any case if you don't know how well the data compresses. If the data you want to compress had a very similar "profile" each time you could probably make better predictions. | Estimating zip size/creation time | [
"",
"python",
"zip",
"time-estimation",
""
] |
I have a couple of CSS selectors like this:
```
table.SearchCustomerResults > thead > tr > th[sortOrder="0"] {}
table.SearchCustomerResults > thead > tr > th[sortOrder="1"] {}
```
then I set the sortOrder extension attribute for each of the cells in JavaScript. However, the changed style is not visible in the browser (IE7, perhaps other) until I move the cursor a bit. How can I force styles to be re-evaluated?
Edit: I didn't use IE6 as originally stated, but IE7. The question still remains, though. | There are various hack-y ways to force re-rendering. [script.aculo.us](http://script.aculo.us) has a method called `forceRerendering` (naturally) that looks like this:
```
someElement.appendChild(document.createTextNode(' '));
someElement.removeChild(someElement.lastChild);
```
That ought to work in this case, too. | IE6 doesn't support attribute or child selectors, so this shouldn't work at all. Are you using [ie7-js](http://code.google.com/p/ie7-js/)?
---
OK, I see now. This looks like a bug in IE (using `div` and `title` for `th` and `sortOrder` has the same problem).
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style>
th[sortOrder="0"] {color:red}
th[sortOrder="1"] {color:blue}
</style>
<script>
function changeSortOrder() {
// swap the orders so that blue is actually red and vice versa
document.getElementById("hdr0").setAttribute("sortOrder","1");
document.getElementById("hdr1").setAttribute("sortOrder","0");
//document.getElementById("hdr0").innerHTML += "";
//document.getElementById("hdr1").innerHTML += "";
}
</script>
</head>
<body onload="changeSortOrder()">
<table class="SearchCustomerResults">
<thead><tr>
<th sortOrder="0" id="hdr0">red</th>
<th sortOrder="1" id="hdr1">blue</th>
</tr></thead>
</table>
</body>
</html>
```
The lines that modify `innerHTML` seem to work around the bug. Can't find any references on Google, though. | How can I force Internet Explorer to apply CSS styles | [
"",
"javascript",
"internet-explorer",
"css-selectors",
""
] |
I was wondering whenever exists a solution to perform synchronization in JavaScript code. For example I have the following case: I'm trying to cache some response values from AJAX call, the problem is, that it's possible to perform simultaneously several calls, therefore it leads to race condition in the code. So I'm very curious to find solution for that? Any one has idea that to do? | I have found solution for my problem. I have to say it's not that perfect as I was looking for, but so far it works and I think about that more as temporarily work around.
```
$.post( "url1", function( data)
{
// do some computation on data and then
setSomeValue( data);
});
var setSomeValue = ( function()
{
var cache = {};
return function( data)
{
if ( cache[data] == "updating")
{
setTimeout( function(){ setSomeValue( data);}, 100);
return;
}
if ( !cache[date])
{
cache[date] = updating;
$.post( "url2", function( another_data)
{
//make heavy computation on another_data
cache[data] = value;
// update the UI with value
});
}
else
{
//update the UI using cached value
}
}
})();
``` | I can offer a possible solution, but without seeing the code ... not completely sure what you are doing, but there is no reason why you couldn't do this.
Basic code in jQuery : (not tested and abbreviated ... but I have done things similar)
```
var needAllThese = {};
$(function(){
$.ajax("POST","/somepage.aspx",function(data) {
needAllThese.A = "VALUE";
});
$.ajax("POST","/somepage2.aspx",function(data) {
needAllThese.B = "VALUE";
});
$.ajax("POST","/somepage3.aspx",function(data) {
needAllThese.C = "VALUE";
});
startWatching();
});
function startWatching() {
if (!haveEverythingNeeded()) {
setTimeout(startWatching,100);
return;
}
everythingIsLoaded();
}
function haveEverythingNeeded() {
return needAllThese.A && needAllThese.B && needAllThese.C;
}
function everythingIsLoaded() {
alert("Everything is loaded!");
}
```
EDIT: (re: your comment)
You're looking for callbacks, the same way jQuery would do it.
```
var cache = {};
function getSomeValue(key, callback) {
if (cache[key]) callback( cache[key] );
$.post( "url", function(data) {
setSomeValue(key,data);
callback( cache[key] );
});
}
function setSomeValue(key,val) {
cache[key] = val;
}
$(function(){
// not sure you would need this, given the code above
for ( var i = 0; i < some_length; ++i) {
$.post( "url", function(data){
setSomeValue("somekey",data);
});
}
getSomeValue("somekey",function(val){
$("#element").txt( val );
};
});
``` | JavaScript synchronization options | [
"",
"javascript",
"ajax",
"caching",
"synchronization",
""
] |
Say I have this query:
```
SELECT bugs.id, bug_color.name FROM bugs, bug_color
WHERE bugs.id = 1 AND bugs.id = bug_color.id
```
Why would I use a join? And what would it look like? | Joins are synticatic sugar, easier to read.
Your query would look like this with a join:
```
SELECT bugs.id, bug_color.name
FROM bugs
INNER JOIN bug_color ON bugs.id = bug_color.id
WHERE bugs.id = 1
```
With more then two tables, joins help make a query more readable, by keeping conditions related to a table in one place. | The `join` keyword is the new way of joining tables.
When I learned SQL it did not yet exist, so joining was done the way that you show in your question.
Nowadays we have things like joins and aliases to make the queries more readable:
```
select
b.id, c.name
from
bugs as b
inner join
bug_color as c on c.id = b.id
where
b.id = 1
```
Also there are other variations of joins, as `left outer join`, `right outer join` and `full join`, that is harder to accomplish with the old syntax. | What's the difference between just using multiple froms and joins? | [
"",
"sql",
"join",
""
] |
Let's say I have a SQL Server 2000 table, any name will do, it's irrelevant for this topic. On this table I have a trigger that runs after update or insert.
The user is able to insert and update the table on which the trigger is attached, but not on other tables that the trigger targets.
If the user modifies data in the original table, I get an exception complaining that the user doesn't have permission to modify data in the target tables of the trigger.
I assume this is caused by the fact that the trigger is running in the context of the user. Is there a way to have the trigger run in its own context or am I not interpreting the cause of this exception correctly?
**Edit:** I should point out that I'm using SQL Server 2000, so using EXECUTE AS won't work. | Triggers do normally operate with the permissions of the user who made the initial change. A workaround for something like this is for the trigger to write the data into a temporary table and then have a separate process (logged in as a higher-level user) check for data in the temporary table every so often and move it into the target table. | [MSDN resource](http://msdn.microsoft.com/en-us/library/ms189799.aspx)
> EXECUTE AS Specifies the security
> context under which the trigger is
> executed. Enables you to control which
> user account the instance of SQL
> Server uses to validate permissions on
> any database objects that are
> referenced by the trigger. | Can a trigger be forced to run in a separate context than the user in SQL Server 2000? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2000",
""
] |
In the j2ee applications I plan on standardizing the exception handling strategy. No more swallowing exceptions and basically converting all checked exceptions into unchecked (except for some that actually **can** be recovered from. The standard will be that all Exception will be thrown back up to the container (eg: <http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html>). Exceptions such as SQLException cannot be recovered from, and if it occurs deep within the data layer I am going to force it back upward. **However**, small sub-routines such as email notifications will be wrapped in a try catch to prevent an exception occurring from breaking the entire application flow. (EG: Why stop an entire process from completing because the user didn't get an email notification that they didn't need anyway!)
Any advice on this? Again to reiterate I am basically re-throwing all exceptions back up to the container which has its own error page, which then logs it to log4j as well. | I think the e-mail example is the best defense of checked exceptions. You have something that can go wrong and is transient, so the existence of a checked exception makes you think about it. If everything was a Runtime exception, your application would just blow up for trivial reasons and no one would think about it.
Anyway, if for your project, the general answer is throw it up to the top, then wrapping in a Runtime Exception is perfectly valid. A couple of things to think about:
Insist on Exception Chaining. The only reason to not do this is if you are serializing the exception, then things could get interesting with some exceptions containing non-serializable members. That doesn't seem to be the case, so don't allow exception swallowing. Use initCause if you have to. Here is a little helper method in our project:
```
public static <T extends Throwable> T initCause(T newException, Throwable cause) {
return (T) newException.initCause(cause);
}
```
This helps people avoid the need to cast the exceptions.
I prefer avoiding unnecessary chaining of RuntimeException and Error Throwables that inevitably happen when there are many different Checked Exceptions on a method and the developer just catches Exception, so I recommend a static method that does something like this:
```
public static void throwRuntimeExceptionFromThrowable(Throwable e) {
if (e == null) {
return;
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else if (e instanceof Error) {
throw (Error) e;
} else {
throw new RuntimeException(e.getMessage(), e);
}
}
```
There are two options with this. One is to make it void (as this code does), which has the upside of the caller never forgetting to throw the result. The downside is if you have something like this:
```
public Object someMethod() {
try {
return getTheObject();
} catch (Exception e) {
throwRuntimeExceptionFromThrowable(e);
}
}
```
The compiler won't like you. You will have to return after the catch, and declare a variable before the try.
The other option is to return the Exception as a RuntimeException (just throw the Error) and have the caller do the throw. The compiler is happier, but the caller may forget to do it, and call the method without a throw in front of it, and then the exception gets swallowed. | Exceptions should be handled by the layer that concerns it.
Because an exception is checked does not mean you can handle it or that you must handle it at every layer of your app. And it is at this point you may want to turn them into runtime exception. So you have exceptions you can ignore (log them), exceptions that you can't recover from and exceptions you can recover. The problem is the same exception type, for example SQLException, can enter in more than one category. IOException would also be another example.
Programming errors that cannot be recovered should be runtime exceptions and should be caught close to the container for logging purpose or to have your app to fail "gently". Accessing an invalid index in a jdbc PreparedStatement is a programming error.
Having connection problem is not. So at the data layer, you manage to make the distinction, then convert your unrecoverable exception into a runtime exception and throw it. And sometimes it does not mean that retrying to connect will work.
Business methods should thake care of bussiness related exception only, that is why you don't handle NullPointerExceptions or ArrayIndexOutOfBoundsException everywhere in your code and you don't have to put them in your method signature. Same logic applies to a data source agnostic business method calculating the average salary of employees of dept., it should not throw SQLExceptions but should throw things such as InvalidDeptException if the user supplies a wrong dept. code.
Throws declarations is also self documenting the code, if you throw your own runtime exceptions instead, be sure to document properly. | Exception Handling Standards Advice | [
"",
"java",
"logging",
"jakarta-ee",
"exception",
""
] |
I don't mean dynamic casting in the sense of casting a lower interface or base class to a more derived class, I mean taking an interface definition that I've created, and then dynamically casting to that interface a different object NOT derived from that interface but supporting all the calls.
For example,
```
interface IMyInterface
{
bool Visible
{
get;
}
}
TextBox myTextBox = new TextBox();
IMyInterface i = (dynamic<IMyInterface>)myTextBox;
```
This could be achieved at compile time for known types, and runtime for instances declared with dynamic. The interface definition is known, as is the type (in this example) so the compiler can determine if the object supports the calls defined by the interface and perform some magic for us to have the cast.
My guess is that this is not supported in C#4 (I was unable to find a reference to it), but I'd like to know for sure. And if it isn't, I'd like to discuss if it should be included in a future variant of the language or not, and the reasons for and against. To me, it seems like a nice addition to enable greater polymorphism in code without having to create whole new types to wrap existing framework types.
**Update**
Lest someone accuse me of plagiarism, I was not aware of [Jon Skeet having already proposed this](http://msmvps.com/blogs/jon_skeet/archive/2008/10/30/c-4-0-dynamic-lt-t-gt.aspx). However, nice to know we thought of exceedingly similar syntax, which suggests it might be intuitive at least. Meanwhile, "have an original idea" remains on my bucket list for another day. | I think Jon Skeet has had such a proposal (<http://msmvps.com/blogs/jon_skeet/archive/2008/10/30/c-4-0-dynamic-lt-t-gt.aspx>), but so far, I haven't heard that C# 4.0 is going to have it. | I think that's problematic. You are introducing coupling between two classes which are not coupled.
Consider the following code.
```
public interface IFoo
{
int MethodA();
int MethodB();
}
public class Bar
{
int MethodA();
int MethodB();
}
public class SomeClass
{
int MethodFoo(IFoo someFoo);
}
```
should this then be legal?
```
int blah = someClass.MethodFoo((dynamic<IFoo>)bar);
```
It *seems* like it should be legal, because the compiler should be able to dynamically type bar as something that implements IFoo.
However, at this point you are coupling IFoo and Bar through a call in a completely separate part of your code.
If you edit Bar because it no longer needs MethodB, suddenly someClass.MethodFood doesn't work anymore, even though Bar and IFoo are not related.
In the same way, if you add MethodC() to IFoo, your code would break again, even though IFoo and Bar are ostensibly not related.
The fact is, although this would be useful in select cases where there are similarities amongst objects that you do not control, there is a reason that interfaces have to be explicitly attached to objects, and the reason is so that the compiler can guarantee that the object implements it. | Will C#4 allow "dynamic casting"? If not, should C# support it? | [
"",
"c#",
"dynamic",
"polymorphism",
"c#-4.0",
""
] |
I would like to make a simple but non trivial manipulation of DOM Elements with PHP but I am lost.
Assume a page like Wikipedia where you have paragraphs and titles (`<p>`, `<h2>`). They are siblings. I would like to take both elements, in sequential order.
I have tried `GetElementbyName` but then you have no possibility to organize information.
I have tried `DOMXPath->query()` but I found it really confusing.
Just parsing something like:
```
<html>
<head></head>
<body>
<h2>Title1</h2>
<p>Paragraph1</p>
<p>Paragraph2</p>
<h2>Title2</h2>
<p>Paragraph3</p>
</body>
</html>
```
into:
```
Title1
Paragraph1
Paragraph2
Title2
Paragraph3
```
With a few bits of HTML code I do not need between all.
Thank you. I hope question does not look like homework. | I think `DOMXPath->query()` is the right approach. This XPath expression will return all nodes that are either a `<h2>` or a `<p>` on the same level (since you said they were siblings).
```
/html/body/*[name() = 'p' or name() = 'h2']
```
The nodes will be returned as a [node list](https://www.php.net/manual/en/class.domnodelist.php) in the right order (document order). You can then construct a foreach loop over the result. | I have uased a few times simple html dom by S.C.Chen.
Perfect class for access dom elements.
Example:
```
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
```
Check it out here. [simplehtmldom](http://simplehtmldom.sourceforge.net/)
May help with future projects | DOM Manipulation with PHP | [
"",
"php",
"dom",
"parsing",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.