Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Probably a C# noob question, so don't flame me. I was trying to do this:
```
if (ConfigurationManager.ConnectionStrings["PrimaryConnectionString"].ConnectionString != null)
{
// ...
}
```
But I kept getting a `System.NullReferenceException`. I thought since it returns a string that I could just check for `null` and move on. It took me a while to find the right way to do it:
```
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["PrimaryConnectionString"];
if (cs != null)
{
this.Connection.ConnectionString = cs.ConnectionString;
}
```
So in other instances, like checking a `Session` object for some value I would do a check for `null` like this:
```
if (Session["EmployeeID"] != null)
{
_EmployeeID = System.Convert.ToInt32(Session["EmployeeID"]);
}
```
So I just wanted to know how do you know when you can or can't do a check for `null`? | Your null reference exception happened in parent object (ConfigurationManager.ConnectionStrings["PrimaryConnectionString"]). Once you check it also, you are fine.
try this:
```
if ((ConfigurationManager.ConnectionStrings["PrimaryConnectionString"] != null)
&& (ConfigurationManager.ConnectionStrings["PrimaryConnectionString"].ConnectionString != null))
{ etc etc }
```
Notice that if you use more methods from it, it would be useful to separate these checks. | Your problem was that you were checking:
```
ConfigurationManager
.ConnectionStrings["PrimaryConnectionString"]
.ConnectionString
```
for a null pointer.
In actual fact,
```
ConfigurationManager
.ConnectionStrings["PrimaryConnectionString"]
```
was null so that, when you tried to dereference *that* to get the connection string, that's when you got the exception. Effectively, what you're doing is:
```
null.ConnectionString
```
which is problematic.
I tend to either avoid many layers of dereferencing in a single statement or place an exception handler around the whole thing to catch problems at any point. | Why couldn't I check for a null reference on a connection string? | [
"",
"c#",
"asp.net",
"null",
"connection-string",
"nullreferenceexception",
""
] |
We have a defined a set of rules in Eclipse for code formatting and clean up.
is there a way to run the code clean up using ant task ?
I know that there are tools like [checkstyle](http://checkstyle.sourceforge.net/) but these tool have thier own configurations and rules, and I don't want to maintain 2 sets of rules.
I'm looking for an ant task that will use the same exact configuration and rules defined for eclipse code formatting / clean up
-- Thanks
Yonatan | Have you considered using the Java -> Editor -> Save Actions to enable reformatting on save instead? | This link has what you are looking for I believe: [Batch Code Formatting using Eclipse Code Formatter, but without Eclipse.](http://www.nirving.com/2007/06/01/batch-code-formatting-using-eclipse-code-formatter-but-without-eclipse/ "Batch Code Formatting using Eclipse Code Formatter, but without Eclipse.") | How to do source cleanup / code formatting (defined in eclipse) using ant task | [
"",
"java",
"eclipse",
"coding-style",
"naming-conventions",
""
] |
I am attempting to write a C# application connecting to a Cognos TM1 datastore using the tm1api.dll. I have created a basic shell project in VS C# Express 2008, and added the following code
```
public partial class MainPortal : Window
{
[System.Runtime.InteropServices.DllImport(@"C:\\Program Files\\Cognos\\TM1\\bin\\tm1api.dll", EntryPoint="TM1APIInitialise")]
public static extern void TM1APIInitialise();
public MainPortal()
{
InitializeComponent();
TM1APIInitialise();
}
}
```
I can build this project with no errors, but when running I get the following error:
"Unable to find an entry point named 'TM1APIInitialise' in DLL 'C:\\Program Files\\Cognos\\TM1\\bin\\tm1api.dll'."
I have used 'dumpbin /exports tm1api.dll' to determine its entry point:
```
101 5D 00008360 TM1APIFinalize
```
Now I am at a loss, it seems to have an entry point but does recognize it. Can anyone point me in the right direction?
PS. I am completely new to C#, so I may be making extremely basic mistakes :) | Thanks JP and ArsenMkrt, your answers both lead to me working out the issue.
I had it defined as TM1APIInitialise and it should have been TM1APIInitialize.
Note the 's' instead of the 'z' (damn American spelling) :). | try this
```
public partial class MainPortal : Window
{
[System.Runtime.InteropServices.DllImport(@"C:\Program Files\Cognos\TM1\bin\tm1api.dll", EntryPoint="TM1APIFinalize")]
public static extern void TM1APIFinalize();
public MainPortal()
{
InitializeComponent();
TM1APIInitialise();
}
}
``` | Unable to find entry point in tm1api.dll | [
"",
"c#",
"cognos-tm1",
""
] |
I've been wrestling with an issue I was hoping to solve with regex.
Let's say I have a string that can contain any alphanumeric with the possibility of a substring within being surrounded by square brackets. These substrings could appear anywhere in the string like this. There can also be any number of bracket-ed substrings.
Examples:
* aaa[bb b]
* aaa[bbb]ccc[d dd]
* [aaa]bbb[c cc]
You can see that there are whitespaces in some of the bracketed substrings, that's fine. My main issue right now is when I encounter spaces outside of the brackets like this:
* a aa[bb b]
Now I want to preserve the spaces inside the brackets but remove them everywhere else.
This gets a little more tricky for strings like:
* a aa[bb b]c cc[d dd]e ee[f ff]
Here I would want the return to be:
* aaa[bb b]ccc[d dd]eee[f ff]
I spent some time now reading through different reg ex pages regarding lookarounds, negative assertions, etc. and it's making my head spin.
NOTE: for anyone visiting this, I was not looking for any solution involving nested brackets. If that was the case I'd probably do it pragmatically like some of the comments mentioned below. | This regex should do the trick:
```
[ ](?=[^\]]*?(?:\[|$))
```
Just replace the space that was matched with "".
Basically all it's doing is making sure that the space you are going to remove has a "[" in front of it, but not if it has a "]" before it.
That should work as long as you don't have nested square brackets, e.g.:
a a[b [c c]b]
Because in that case, the space after the first "b" will be removed and it will become:
aa[b[c c]b] | This doesn't sound like something you really want regex for. It's very easy to parse directly by reading through. Pseudo-code:
```
inside_brackets = false;
for ( i = 0; i < length(str); i++) {
if (str[i] == '[' )
inside_brackets = true;
else if str[i] == ']'
inside_brackets = false;
if ( ! inside_brackets && is_space(str[i]) )
delete(str[i]);
}
```
Anything involving regex is going to involve a lot of lookbehind stuff, which will be repeated over and over, and it'll be much slower and less comprehensible.
To make this work for nested brackets, simply change `inside_brackets` to a counter, starting at zero, incrementing on open brackets, and decrementing on close brackets. | regex to remove all whitespaces except between brackets | [
"",
"php",
"regex",
""
] |
I'm developing code using jQuery and need to store data associated with certain DOM elements. There are a bunch of other questions about *how* to store arbitrary data with an html element, but I'm more interested in why I would pick one option over the other.
Say, for the sake of extremely simplified argument, that I want to store a "lineNumber" property with each row in a table that is "interesting".
Option 1 would be to just set an expando property on each DOM element (I hope I'm using the term 'expando' correctly):
```
$('.interesting-line').each(function(i) { this.lineNumber = i; });
```
Option 2 would be to use jQuery's data() function to associate a property with the element:
```
$('.interesting-line').each(function(i) { $(this).data('lineNumber', i); });
```
Ignoring any other shortcomings of my sample code, are there strong reasons why you would choose one means of storing properties over the other? | If you are authoring a plugin you should use `$.data`. If you need to store the attribute often and rarely need to query the DOM for it then use `$.data`.
**Update 5 years later**: jQuery does *not* query the DOM based on expando properties set, and hasn't done so for a while. So use `$.data`. There's no reason to pollute the DOM when there is no pragmatic use to do so. | Using `$.data` will protect you from memory leaks.
In IE, when you assign a javascript object to an expando property on a DOM element, cycles that cross that link are not garbage collected. If your javascript object holds a reference to the dom object, the whole cycle will leak. It's entirely possible to end up with hidden references to DOM objects, due to closures, so you may leak without realizing it.
The jQuery datastore is set up to prevent these cycles from forming. If you use it, you will not leak memory in this way. Your example will not leak because you are putting primitives (strings) on the DOM element. But if you put a more complex object there, you risk leaking.
Use `$.data` so you won't have to worry. | Using jQuery's datastore vs. expando properties | [
"",
"javascript",
"jquery",
"expando",
""
] |
`display:none` means that the element isn't rendered as part of the DOM, so it's not loaded until the display property changes to something else.
`visibility:hidden` loads the element, but does not show it.
Why does jQuery use `display:none` for its show/hide functions instead of switching between `visibility:hidden` and `visibility:visible`? | Because in `display:none`, the element, for all purposes, ceases to exist -- it doesn't occupy any space.
However, in `visibility:hidden`, it's as if you had just added `opacity:0` to the element -- it occupies the same amount of space but just acts invisible.
The jQuery creators probably thought the former would be a better fit for `.hide()`. | `visibility: hidden` makes an element invisible but does not remove it from the layout of the page. It leaves an empty box where the element was. `display: none` removes it from the layout so it doesn't take up any space on the page, which is usually what people want when they hide something. | Why does jQuery show/hide use display:none instead of visibility:hidden? | [
"",
"javascript",
"jquery",
"visibility",
""
] |
In my website, I've integrated a php script that receive an IPN notification and send a license key to the customer. This script is in a folder with other 2 php files required by the php script... How can I protect this folder? If I place in it an `.htaccess` with:
```
order allow,deny
deny from all
```
I block the paypal notifications too.
How can I protect it? Do I need to? | You can safely limit access to your IPN script only to the following list of IP addresses:
```
216.113.188.202
216.113.188.203
216.113.188.204
66.211.170.66
```
This can be done in the following way:
```
if (!in_array($_SERVER['REMOTE_ADDR'],array('216.113.188.202','216.113.188.203','216.113.188.204','66.211.170.66')) {
header("HTTP/1.0 404 Not Found");
exit();
}
```
In this way ONLY Paypal will be able to access the IPN script.
This list of IP address has been rather stable for years. In case if Paypal adds a new address, you can add reporting to email and review such cases manually. | There are many things you can do:
1. Give your script an obscure name so that it is not easily guessable.
2. Disable directory listings in the folder
3. Check if the calling site is paypal.com (or related IP address etc.) | Protect php script that receive paypal IPN notifications | [
"",
"php",
"paypal",
"paypal-ipn",
""
] |
I have a query for sqlite3 database which provides the sorted data. The data are sorted on the basis of a column which is a `varchar` column "Name". Now when I do the query
```
select * from tableNames Order by Name;
```
It provides the data like this.
```
Pen
Stapler
pencil
```
Means it is considering the case sensitive stuff. The way I want is as follows
```
Pen
pencil
Stapler
```
So what changes should I make in sqlite3 database for the necessary results?
> Related [How to set Sqlite3 to be case insensitive when string comparing?](https://stackoverflow.com/questions/973541/how-to-set-sqlite3-to-be-case-insensitive-when-string-comparing) | The SQLite [Datatypes documentation](http://www.sqlite.org/datatype3.html) discusses user-defined collation sequences. Specifically you use COLLATE NOCASE to achieve your goal.
They give an example:
```
CREATE TABLE t1(
a, -- default collation type BINARY
b COLLATE BINARY, -- default collation type BINARY
c COLLATE REVERSE, -- default collation type REVERSE
d COLLATE NOCASE -- default collation type NOCASE
);
```
and note that:
-- Grouping is performed using the NOCASE collation sequence (i.e. values
-- 'abc' and 'ABC' are placed in the same group).
SELECT count(\*) GROUP BY d FROM t1; | To sort it Case insensitive you can use `ORDER BY Name COLLATE NOCASE` | How to change the collation of sqlite3 database to sort case insensitively? | [
"",
"sql",
"sqlite",
"sql-order-by",
"case-insensitive",
""
] |
So I'm trying to adopt good object oriented programming techniques with PHP. Most (read all) of my projects involve a MySQL database. My immediate problem deals with the users model I need to develop.
My current project has Agents and Leads. Both Agents and Leads are Users with much of the same information. So, obviously, I want a class Agents and a class Leads to extend a common class Users. Now, my question is as follows:
How should the SQL best be handled for loading these objects? I don't want to execute multiple SQL statements when I instantiate an Agent or a Lead. However, logic tells me that when the Users constructor is fired, it should execute a SQL statement to load the common information between Agents and Leads (username, password, email, contact information, etc). Logic also tells me that when the Agents or Leads constructor is fired, I want to execute SQL to load the data unique to the Agents or Leads class....But, again, logic also tells me that it's a bad idea to execute 2 SQL statements every time I need an Agent or Lead (as there may be thousands of each).
I've tried searching for examples of how this is generally handled with no success...Perhaps I'm just searching for the wrong thing? | You basically have three approaches to this problem (one of which I'll eliminate immediately):
1. One table per class (this is the one I'll eliminate);
2. A record type with optional columns; and
3. A record type with a child table depending on type that you join to.
For simplicity I generally recommend (2). So once you have your table:
```
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
type VARCHAR(10),
name VARCHAR(100)
);
```
where type can be 'AGENT' or 'LEAD' (for example). Alternatively you can use one character type codes. You can then start to fill in the blanks with the object model:
* You have a User parent class;
* You have two child classes: Lead and Agent;
* Those children have a fixed type.
and it should fall into place quite easily.
As for how to load in one statement, I would use some kind of factory. Assuming these barebones classes:
```
class User {
private $name;
private $type;
protected __construct($query) {
$this->type = $query['type'];
$this->name = $query['name'];
}
...
}
class Agent {
private $agency;
public __construct($query) {
parent::constructor($query);
$this->agency = $query['agency'];
}
...
}
class Lead {
public __consruct($query) {
parent::constructor($query);
}
...
}
```
a factory could look like this:
```
public function loadUserById($id) {
$id = mysql_real_escape_string($id); // just in case
$sql = "SELECT * FROM user WHERE id = $id";
$query = mysql_query($sql);
if (!query) {
die("Error executing $sql - " . mysql_error());
}
if ($query['type'] == 'AGENT') {
return new Agent($query);
} else if ($query['type'] == 'LEAD') {
return new Lead($query);
} else {
die("Unknown user type '$query[type]'");
}
}
```
Alternatively, you could have the factory method be a static method on, say, the User class and/or use a lookup table for the types to classes.
Perhaps polluting the classes with the query result resource like that is a questionable design in the strictest OO sense, but it's simple and it works. | Will you ever have a user that's not a Lead or Agent? Does that class really need to pull data from the database at all?
If it does, why not pull the SQL query into a function you can override when you create the child class. | PHP Inheritance and MySQL | [
"",
"php",
"mysql",
"inheritance",
""
] |
I know about `mysql_num_rows ( resource $result )` but I have read somewhere that is it not 100% accurate. I have seen other alternatives that actually gets each row and run a counter but that sounds pretty inefficient. I am interested in seeing what others do to get an accurate and efficient count. | use `mysql_num_rows()` when you've done a `SELECT` or `SHOW` query and `mysql_affected_rows()` in case of `INSERT, UPDATE, REPLACE or DELETE` queries.
both are accurate enough!! | `mysql_num_rows()` is accurate, as long as you are not using `mysql_unbuffered_query()`.
If you are using `mysql_query()`, `mysql_num_rows()` is accurate.
If you are using `mysql_unbuffered_query()`, `mysql_num_rows()` will return the wrong result until all rows are retrieved. | What is the tried and true way of counting the number of rows returned from PHP `mysql_query` function? | [
"",
"php",
"mysql",
"count",
"rows",
""
] |
How can you perform complex sorting on an object before passing it to the template? For example, here is my view:
```
@login_required
def overview(request):
physicians = PhysicianGroup.objects.get(pk=physician_group).physicians
for physician in physicians.all():
physician.service_patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order')
return render_to_response('hospitalists/overview.html', RequestContext(request, {'physicians': physicians,}))
```
The physicians object is not ordered correctly in the template. Why not?
Additionally, how do you index into a list inside the template? For example, (this doesn't work):
```
{% for note_type in note_types %}
<div><h3>{{ note_type }}</h3>
{% for notes in note_sets.index(parent.forloop.counter0) %}
#only want to display the notes of this note_type!
{% for note in notes %}
<p>{{ note }}</p>
{% endfor %}
{% endfor %}
</div>
{% endfor %}
```
Thanks a bunch, Pete | As others have indicated, both of your problems are best solved outside the template -- either in the models, or in the view. One strategy would be to add helper methods to the relevant classes.
Getting a sorted list of a physician's patients:
```
class Physician(Model):
...
def sorted_patients(self):
return self.patients.order_by('bed__room__unit',
'bed__room__order',
'bed__order')
```
And in the template, use `physician.sorted_patients` rather than `physician.patients`.
For the "display the notes of this note\_type", it sounds like you might want a `notes` method for the note\_type class. From your description I'm not sure if this is a model class or not, but the principle is the same:
```
class NoteType:
...
def notes(self):
return <calculate note set>
```
And then the template:
```
{% for note_type in note_types %}
<div><h3>{{ note_type }}</h3></div>
{% for note in note_type.notes %}
<p>{{ note }}</p>
{% endfor %}
</div>
{% endfor %}
``` | **"I'd like to do this from within a template:"**
Don't. Do it in the view function where it belongs.
Since the question is incomplete, it's impossible to guess at the data model and provide the exact solution.
```
results= physician.patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order')
```
Should be sufficient. Provide `results` to the template for rendering. It's in the proper order.
If this isn't sorting properly (perhaps because of some model subtletly) then you always have this kind of alternative.
```
def by_unit_room_bed( patient ):
return patient.bed.room.unit, patient.bed.room.order, patient.bed.order
patient_list = list( physician.patients )
patient_list.sort( key=by_unit_room_bed )
```
Provide `patient_list` to the template for rendering. It's in the proper order.
**"how do you index into a list inside the template"**
I'm not sure what you're trying to do, but most of the time, the answer is "Don't". Do it in the view function.
The template just iterate through simple lists filling in simple HTML templates.
If it seems too complex for a template, it is. Keep the template simple -- it's only presentation. The processing goes in the view function | Sorting and indexing into a list in a Django template? | [
"",
"python",
"django",
"django-templates",
""
] |
Lets pretend you have a 3 Gb jar file and your application only uses a small class within it. Does the JVM load the whole jar file into memory or does it read the Table of Contents and load only the pieces it needs? Is this behavior controllable? | JVM loads only the required classes from the Jar when invoked. If application needs a class then the class and all other dependent classes will be loaded. Not sure but I suppose this is the responsibility of the class loader to locate the class from the classpath and load. | Jar files are a form of zip files.
How these are handled is highly dependent upon JRE.
Old versions of the Sun JRE used to memory map the entire file. This would allocate logical memory, but not necessarily cause any of the data to be loaded from disk. (32-bit Windows is not generally capable of allocating 3 GB of contiguous memory, although you can do it on other OSs).
I believe the current behaviour is to memory map the central directory at the rear of the file under Windows. Under other OSs, it's just read. This is controlled by `#define`s in the source.
JDK7 is likely to do something else.
Classes are generally loaded lazily. Resources are reread each time. `java.util.ResourceBundle` caches. | Does the Java JVM load an entire jar or ear if it only uses one class from it? | [
"",
"java",
"class",
"loader",
""
] |
I found a blog entry which suggests that sometimes c# compiler may decide to put array on the stack instead of the heap:
[Improving Performance Through Stack Allocation (.NET Memory Management: Part 2)](http://www.atalasoft.com/cs/blogs/rickm/archive/2008/04/15/improving-performance-through-stack-allocation-net-memory-management-part-2.aspx)
This guy claims that:
> The compiler will also sometimes decide to put things on the stack on its own. I did an experiment with TestStruct2 in which I allocated it both an unsafe and normal context. In the unsafe context the array was put on the heap, but in the normal context when I looked into memory the array had actually been allocated on the stack.
**Can someone confirm that?**
I was trying to repeat his example, but everytime I tried array was allocated on the heap.
If c# compiler can do such trick without using 'unsafe' keyword I'm specially intrested in it. I have a code that is working on many small byte arrays (8-10 bytes long) and so using heap for each new byte[...] is a waste of time and memory (especially that each object on heap has 8 bytes overhead needed for garbage collector).
**EDIT:** I just want to describe why it's important to me:
I'm writing library that is communicating with Gemalto.NET smart card which can have .net code working in it. When I call a method that returns something, smart card return 8 bytes that describes me the exact Type of return value. This 8 bytes are calculated by using md5 hash and some byte arrays concatenations.
Problem is that when I have an array that is not known to me I must scan all types in all assemblies loaded in application and for each I must calculate those 8 bytes until I find the same array.
I don't know other way to find the type, so I'm trying to speed it up as much as possible. | From your line:
> I have a code that is working on many small byte arrays (8-10 bytes long)
Personally, I'd be more interested in allocating a spare buffer somewhere that different parts of your code can re-use (while processing the same block). Then you don't have any creation/GC to worry about. In most cases (where the buffer is used for very discreet operations) with a scratch-buffer, you can even always assume that it is "all yours" - i.e. every method that needs it can assume that they can start writing at zero.
I use this single-buffer approach in some binary serialization code (while encoding data); it is a big boost to performance. In my case, I pass a "context" object between the layers of serialization (that encapsulates the scratch-buffer, the output-stream (with some additional local buffering), and a few other oddities). | Author of the linked-to article here.
It seems impossible to force stack allocation outside of an unsafe context. This is likely the case to prevent some classes of stack overflow condition.
Instead, I recommend using a memory recycler class which would allocate byte arrays as needed but also allow you to "turn them in" afterward for reuse. It's as simple as keeping a stack of unused byte arrays and, when the list is empty, allocating new ones.
```
Stack<Byte[]> _byteStack = new Stack<Byte[]>();
Byte[] AllocateArray()
{
Byte[] outArray;
if (_byteStack.Count > 0)
outArray = _byteStack.Pop();
else
outArray = new Byte[8];
return outArray;
}
void RecycleArray(Byte[] inArray)
{
_byteStack.Push(inArray);
}
```
If you are trying to match a hash with a type it seems the best idea would be to use a Dictionary for fast lookups. In this case you could load all relevant types at startup, if this causes program startup to become too slow you might want to consider caching them the first time each type is used. | Is c# compiler deciding to use stackalloc by itself? | [
"",
"c#",
"compiler-construction",
"stackalloc",
""
] |
```
Hugs> 94535^445
1376320882321377050696053887661515621104890164005282153069726424773999801846841903244827702943487982707454966009456016735041878000604143500908532887464920380605164932112687039059526672109818924234920844448231612532570718657160234177285377733830104834041049076609912488237219608445995072867798430614935403219495883835042862802917980856774134757390782052200512932375660858045003581611863121089979673784484701791210379500218604466721285456487387736825167702127154268533859979529612671925052419513844416493584817268143587955662039327860394141299238613042312035808541735213479394437496215520277526351425482512084759462579494878772787079101513841720202004639843443083454387175700954018825292148776647553122504118229978165851660083576570848983047255050145168802863168613110619584686348869690774233051669081248424584219383477237544209892290799448207462345346336076966775224683516220960618177284844330167142846351091001423033864986042919757795382577032341453971393897073354841924116635150129850119992031076354249371062307034564093077675129303383786693131843907104175619570678630497198824622804914508555467550904967368926176118094672479099827962889569753303773699017596074205893197641101210911874606040804983166177455705972192827752532495287749766682029353154226049380290040508900715169403153139668217790502306177709467234413947747673881158973344492079455405942662489751581189327200960698310350121179918845099840977270519116578719881752429190273998774113278822810866144521416958558406602325070095207349450759264393913367193083149679216066539911941983836313340998945139132421885688290888674594474605510238217590823316979504437667252929278291853368754482552573193289277120902144178425726693671235675042499401282016643202758246845332593475338220708351934511933096882598943512036679145593929114103343255708217768511665236173107020739195152050863630870948954052925049746246549772984384435109578859863612603574306739909728739428192798727373799081111333186135697868385292787575475482883660605162944306327057220313320376280182432763977906971557137715710757099478269250731209785404487629107297262798803645379809868663503452656912571816192881412782623078761411808958183665272686617730596943579533808499348879195167683064937591552734375
```
Why can Haskell calculate such a large number, and other languages, such as Java, cannot (so easily)? | Java has the [BigInteger](http://java.sun.com/javase/6/docs/api/java/math/BigInteger.html) class.
It could have built this facility into the language, but (like many languages) it tends to make the primitive features map closely onto things that are supported by the CPU.
Haskell on the other hand emphasizes expressiveness in the style of mathematical notation, where "performance" considerations are largely irrelevant. | It's a **difference in design philosophy**:
* The designers of Haskell wanted to be sure that users would not be surprised by the seemingly arbitrary failure of an integer computation needing more than 32 bits.
* The designers of Java wanted to be sure that users would not be surprised by the seemingly arbitrary performance degradation caused by doing lots of computations over integers needing more than 32 bits.
In each language, you have to do something special to get the other kind of integer.
There's a long, honorable history of languages supporting arbitrarily large integers by default. Two of my favorites are [Icon](http://www.cs.arizona.edu/icon/) and [Smalltalk](http://www.squeak.org), which are both over 25 years old. | Why can Haskell handle very large numbers easily? | [
"",
"java",
"programming-languages",
"haskell",
"biginteger",
""
] |
In Google Analytics there is one option to know the connection information about the client access. I think everyone knows about this, but my question is how the Javascript knows these details?
Am not talking about the IP or http/https
suppose am using TATA Indicom, or cable connection for the use of Internet.
how google know about this?? | Javascript doesn't. Javascript can't provide Google your IP address.
Google then uses your IP address to analyze the network you're on and then provide the details to the Analytics users (of course, it's not always 100% accurate...but that's a given). | Javascript doesn't. That's done at google's end. It looks up who the requester's IP is registered to. | How Google Analytics knows which internet connection we are using? | [
"",
"javascript",
"google-analytics",
""
] |
I am using
TCHAR buffer[MAX\_SIZE];
after some set of steps i am gettig the relative path of folder say for ex:
c:\Microsoft.NET\Framework\v1.0.037\
Since the above path is in buffer of type TCHAR and i am trying to **concatenate**"RegAsm.exe"
After Appending i need to convert the path to the LPCTSTR since i need to pass it to
CreateProcess() which takes LPCTSTR type as argument
then the compiler giving error.I have tried but vexed.
can any one help me in this aspect.... | The problem is TCHAR and CreateProcess are macros that expand differently depending on whether you compile for Unicode or not. The caveat is that GetCORSystemDirectory() will only accept a Unicode buffer. To get rid of these ANSI/Unicode problems write this code part explicitly for Unicode.
Instead of TCHAR use WCHAR for the buffer. Instead of CreateProcess() use CreateProcessW() - it will happily accept the Unicode buffer. Use wcscat() for strings concatenation.
Something like this (error handling omitted):
```
WCHAR buffer[MAX_PATH + 1];
DWORD realLength;
GetCORSystemDirectory( buffer, MAX_PATH, &realLength );
*( buffer + realLength ) = 0;// Don't forget to null-terminate the string
wcscat( buffer, L"regasm.exe" );
CreateProcessW( /*pass buffer here*/ );
``` | ```
_tcscat_s
```
is the related method for TCHAR. It depends like TCHAR on the \_UNICODE & \_MBCS preprocessor swithch and will be resolved to strcat\_s or wcscat\_s.
```
TCHAR buffer[MAX_SIZE] = _T("c:\Microsoft.NET\Framework\v1.0.037\");
_tcscat_s(buffer, MAX_SIZE, _T("RegAsm.exe"));
```
but this is very good old C style. So while you are using TCHAR I would suggest that
you also use MFC stuff. So using CString which also is affected by \_UNICODE & \_MBCS would also solve your issue.
```
CString buffer;
buffer = _T("c:\Microsoft.NET\Framework\v1.0.037\");
buffer += _T("RegAsm.exe");
CreateProcess(buffer, ..
```
std::string or std::wstring will not help because they do not change their behavior related to the preprocessor switched but if you use CreateProcessA or CreateProcessW you can also use std::string or std::wstring. | How to do type conversion for the following Scenario? | [
"",
"c++",
"visual-c++",
""
] |
Does anyone know of an online CSV editor written in PHP that will allow a user to open, edit, and save a given CSV file?
All I can find are CSV classes and nothing that can handle dynamic files, just predefined lengths etc. | [Parse the CSV file into array.](https://www.php.net/manual/en/function.fgetcsv.php) Then, use an array of arrays to populate a matrix of text boxes in your web page. When you submit the form, read the data from `$_POST` and use `fputcsv()` to save it.
Think about validation, if relevant. | So you want to be able to open a file, edit it using a web based UI and save it?
Why not use Google Docs?
EDIT: Its irritating when people vote you down without leaving a comment as to why... Useless contributions... | PHP-based CSV editor? | [
"",
"php",
"csv",
"editor",
""
] |
From searching SO, this question was already asked, almost a year ago now.
So now with the new FF, Opera, IE, is it finally time to start developing sites with HTML5 or is it still a little premature and will cause compatibility issues?
Is using HTML5 just going to require us to use more and more JS on websites to 'trick' older browsers into working properly? | If you add nice features to your site, it is possible it will be talked about and reach the news sites for some free publicity.
Aside from that, It would make a good beta site and give you a head start for when it becomes the new technology. However, until HTML 5 enabled browsers are widespread (at least 20% of the market, possibly 50%) it makes little sense to alienate nearly the whole internet. | It's a great idea if used in a "[Progressive Enhancement](http://en.wikipedia.org/wiki/Progressive_enhancement)" way. ie. Code your website to work in "standard" HTML 4.01 mode, and then add some fancy HTML 5 bits to give it some extra flourishes in browsers that support HTML 5 | Is it time to start developing with HTML5? | [
"",
"javascript",
"html",
"standards",
"cross-browser",
""
] |
I have been researching for a good clean knowledgebase script. Something as clean as <http://expressionengine.com/knowledge_base/>
But all the scripts which I have seen are either $200 plus or have a monthly charge etc. I am wondering if I have missed out on either an opensource or a cheaper script.
Thank you for your time. | I don't know if this will help future users or not. But I ended up purchasing WPWIKITHEME from the following URL: <http://wpwikitheme.com/>
I am not sure if it is really worth it or not. But I guess I like the Wordpress admin interface and am quite used to it. | I haven't found any good dedicated scripts, but could you use a wiki for this? [Dokuwiki](http://www.dokuwiki.org/dokuwiki) would be my recommendation if you decided to go this route. | Good Knowledgebase Script | [
"",
"php",
""
] |
I'm facing a head-scratching moment similar to what [this person](http://groups.google.com/group/android-developers/browse_thread/thread/cdae98b7832b4754/567ffa7107a73f70) (from Jan 2008) experienced when I realized that there is no cancel button in Android's progress dialog or spinners. It is now July 2009 and I've just installed the cupcake version of Android. Has this thing changed? If not, are you adding a cancel button into the dialogs and how do you do it? | I'm no Android user or developer, but I think the answer given in the linked-to thread is pretty decent: there's a *hardware* "back" key on all Android devices. Users are supposed to know to press Back to back out of whatever activity they're currently in.
Thus, the UI designers feel it's unnecessary to include a GUI back/cancel button. This could be viewed as the UI application of the [DRY](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself) principle; if there's already one way of doing something, that's enough. | not sure about the whole cancel button...i've heard reports of the onCancel() method not firing properly. my solution just consists of making a normal button on the dialog with a call to return whenever the button is pressed.
```
private void createCancelProgressDialog(String title, String message, String buttonText)
{
cancelDialog = new ProgressDialog(this);
cancelDialog.setTitle(title);
cancelDialog.setMessage(message);
cancelDialog.setButton(buttonText, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Use either finish() or return() to either close the activity or just the dialog
return;
}
});
cancelDialog.show();
}
```
then just use a simple call method from elsewhere in your activity
```
createCancelProgressDialog("Loading", "Please wait while activity is loading", "Cancel");
```
rather simple solution, but it does the trick ;)
also just to note that cancelDialog is an activity wipe variable, if you dont need to call it from elsewhere, then you should be able to get away with just limiting the scope of the variable to that method. | Why is there no cancel button in Android's progress dialogs? | [
"",
"java",
"android",
"user-interface",
""
] |
I want to get a subset of a string in Javascript. Currently, I only know how to store the entire string:
I have this as a JSON variable with a callback to foo:
```
foo({"results":[
"<div id=\"following\"><span><a href=\"http://twitter.com/barackobama\">Obama</a></span></div>"
]})
```
And this is my callback function:
```
function foo(o){
var entireDiv = o.results[0];
}
```
**How do I store just the "< a href = ... > ... < / a>
" tag as a string in Javascript?** | With jQuery, you can parse in a piece of HTML as the second argument.
So, to update your `foo` function:
```
$j = jQuery.noConflict();
function foo(o)
{
var JustTheLink = $j( 'a' , o.results[0] ).parent().html();
}
```
**Update:**
With multiple links to handle, you can do this:
```
function foo(o)
{
$j('a',o.results[0]).each(handleSrc);
}
function handleSrc()
{
console.log(this); // tag
console.log($j(this).html()); // contents
}
``` | You can use a regular expression to find the anchor tag:
```
function foo(o){
var entireDiv = o.results[0];
var link = /<a.+?\/a>/.exec(entireDiv)[0];
}
``` | How to get subset of string using Javascript/JQuery/JSON? | [
"",
"javascript",
"jquery",
"regex",
"string",
"json",
""
] |
I have a JS script that works on IE8 compatibility mode, FF, Chrome, Opera, but not IE8 standards mode.
As I think standards mode is more strict than compatibility mode, maybe there's something wrong with my code. How can I debug? Is there something that shows me things that would work in compatibility mode but standard?
Also, in the short term, how can I change the user browser to use compatibility mode in JS. I don't want to change the entire site (ie, change the template doctype), how do I do it in JS?
Thanks. | For forcing compatibility mode, you need a custom header. See this link <http://weblogs.asp.net/joelvarty/archive/2009/03/23/force-ie7-compatibility-mode-in-ie8-with-iis-settings.aspx>
If you post the Javascript that is not working, may be we can point out the problem. | First of all, check the value of the `document.documentMode` value in JavaScript. If your page is in quirks mode, it goes back to IE 5 behavior, which can mess up your code.
To check the document mode, use this little piece of JavaScript.
```
var docMode = document.documentMode;
if (!docMode|| docMode < 8) {
// Old IE or IE8 or later compatibility mode.
// 5 for quirks mode, 7 for compatibility mode,
// undefined for IE7 or earlier.
} else {
// IE8 or later standards mode.
}
```
It's hard to tell what your problem is if you don't post code though. Maybe we can figure it out if you show us what code behaves differently. | Javascript Working in IE8 comp mode but not standards mode | [
"",
"javascript",
"jquery",
"internet-explorer",
"internet-explorer-8",
""
] |
I am trying to generate a PDF using XSL(XML-FO) to transform a generated XML from a database.
Because of complex rules in terms of paging for this document, calculations are done in determining the page breaks when I generate the XML that will be consumed by the XSL. I have noticed that I've been getting inconsistent results with these calculations. For instance, the required print area in terms of height is 9 inches which I then convert to points by multiplying it by 72 (being 72 points per inch) = 648 points.
So for every line, I use MeasureString to get the height of the line which I then subtract from 648 to see if there are still available space to print the line. But whenever a page break is determined, there would be a large whitespace that is left at the bottom. It is as if the 648pt conversion is wrong. Now I am also concerned that the height being returned by the MeasureString method may also be wrong.
I apologize for the long post but I appreciate any input/suggestion as to what I might be doing wrong.
Thanks a lot! | I think the biggest problem is that you're using GDI methods to measure a string that will be displayed in a PDF. That's just not going to be accurate enough. (Even if you get the fonts identical, they use different rendering techniques from what I remember.)
So, you ought to try other forms of calculation. One simple first step would be to estimate the characters per line and then the height of each line as it would come out in the PDF. Then, just use those numbers. Once that is close, you can improve the technique for estimation by paying attention to specific characters. (You probably don't want to get to the level of calculating kerning.)
Another technique could be to do something that I worked on in a past project. Using iTextSharp, we had to add hollow text diagonally across a page (as a sort of watermark). Since the text was unknown, we guessed at the original font size. Then the code went into a loop where it would measure the size of the rendered text, and adjust it up or down until it was just the right size to fill the page without clipping any of the text. (All of this guessing and measuring was done with iTextSharp.) | I assume that you are using the method `MeasureString` method on the `System.Drawing.Graphics` class. You have to set the `PageUnit` property to `GraphicsUnit.Point` to get measurements in points.
XSL-FO will most likely not render in the same way as GDI+. In particular algorithms for wrapping text will be different.
However, assuming that the `PageUnit` is correct and that you have a simple layout that doesn't involve text that has been wrapped you may have overlooked something obvious while estimating the size of the PDF produced by XSL-FO. Perhaps, you can try to change the page size from 1 to 9 inches in intervals of 1 inch. You can then use a ruler to measure the excess whitespace and try to determine the relation between page size and excess whitespace. You should then revisit your code to figure out where you have a bad assumption about the size of the text. | Calculating a formatted string's width & height in C# | [
"",
"c#",
"printing",
"xslt",
"gdi+",
"gdi",
""
] |
I have an interface
```
interface x {
A getValue();
}
```
and the implementation
```
class y implements x {
public B getValue() { return new B();}
}
```
B is a subclass of A. This works because of covariant overriding, I guess.
But if I rewrite the interface as
```
interface x{
<T extends A> T getValue();
}
```
I get a warning in the implementation that
> Warning needs a unchecked cast to
> conform to A.getValue()
What is the difference between 2 versions of the interface? I was thinking they are the same. | The second version of the interface is wrong. It says that the `getValue` will return any subclass you ask for - the return type will be inferred based on the expression on your left hand.
So, if you obtain a reference to an `x` (let's call it `obj`), you can legally make the following call without compiler warnings:
```
x obj = ...;
B b = obj.getValue();
```
Which is probably incorrect in your example, because if you add another class `C` that also extends `A`, you can also legally make the call:
```
C c = obj.getValue();
```
This is because `T` is not a type variable belonging to the interface, only to the method itself. | Basically when you are doing a `<T extends A>` you are saying that you want a specific subclass of A, not any A, because then you could just do:
```
A getValue();
```
The compiler is warning you that it can't ensure that a specific defined subclass of A is returned, only A itself.
EDIT: To try to explain this better, B is a subclass of A, but doesn't need to be the only subclass of A. Consider the following hierarchy.
B extends A
C extends A but not B
Now I have a method:
```
public void someMethod(x value) {
C c = x.getValue();
}
```
Following the generics, that should compile and guarantee no runtime class cast exception (there may be other issues with interfaces here but there are certainly cases that could be used to demonstrate this properly - I'm keeping with your example).
But what if you pass in an instance of y to this method?
Well, now I'm getting an B instead of a C. The compiler is warning you this could happen. | Java Generics: Warning needs a unchecked cast to conform to <InterfaceName> | [
"",
"java",
"generics",
""
] |
What is the best way to combine two uints into a ulong in c#, setting the high/low uints.
I know bitshifting can do it, but I don't know the syntax, or there maybe other APIs to help like BitConverter, but I don't see a method that does what I want. | ```
ulong mixed = (ulong)high << 32 | low;
```
The cast is very important. If you omit the cast, considering the fact that `high` is of type `uint` (which is 32 bits), you'll be shifting a 32 bit value 32 bits to the left. Shift operators on 32 bit variables will use shift stuff by `right-hand-side` mod 32. Effectively, *shifting a `uint` 32 bits to the left **is a no-op***. Casting to `ulong` prevents this.
Verifying this fact is easy:
```
uint test = 1u;
Console.WriteLine(test << 32); // prints 1
Console.WriteLine((ulong)test << 32); // prints (ulong)uint.MaxValue + 1
``` | ```
ulong output = (ulong)highUInt << 32 + lowUInt
```
The `<<` and `>>` operators bitshift to the left (higher) and right (lower), respectively. `highUInt << 32` is functionally the same as `highUInt * Math.Pow(2, 32)`, but may be faster and is (IMO) simpler syntax. | What is the best way to combine two uints into a ulong in c# | [
"",
"c#",
"bit-shift",
"uint",
"ulong",
""
] |
I'm wondering what's a good online judge for just practicing algorithms. I'm currently not very good at writing algorithms, so probably something easy (and least frustrating) would be good.
I've tried the UVA online judge, but it took me about 20 tries to get the first example question right; There was absolutely no documentation on how to read input, etc. I've read about Topcoder, but I'm not really looking to compete, merely to practice. | Take a better look at topcoder. Yes, they have competitions, but you can still easily just "play" by yourself. You are given a goal and a time limit and you choose your language, and then you code it. You can view the source code of the best coders to improve yourself.
I have used topcoder for awhile and have never been in any competition. Check it out.
You may also want to check out [Project Euler](http://projecteuler.net/). Not a judge, but there are mathematical problems and solutions available for many languages. | Have a look at [SPOJ](http://spoj.pl) | Best online judge with good Java support? | [
"",
"java",
""
] |
Otherwise known as a hard edge, this is a line over which the mouse cannot cross. Useful in games and the like.
Currently, I have a function that returns if my mouse cursor is in a polygon drawn on the screen. If it is not, I move my cursor to the last stored point that was in the polygon.
```
if (!PointInPolygon(local, polyGon))
{
Cursor.Position = safePoint;
}
else
{
safePoint = Cursor.Position;
}
```
I don't like this for a couple reasons:
* Due to slow update times or for whatever reason, I am sometimes able to break out of the box. This then stores that position as the safePoint, outside of the polygon. My mouse is then stuck in this position.
* Sloped edges should pust the mouse in the slope direction. Pushing the mouse right againts an "/" shaped wall should end up with the cursor in the top right corner. But due to the nature of this approach, going over the line will reset the cursor to where it previously was. Continuing to push right will only keep reseting the cursor, and will not push it "up the slope."
Are there any other approaches to tackle this problem? I'm mainly worried about the last issue: this slope transversal behavior is the main objective of my program and I need to get it working. Even if I use this basic method, any ideas for an optimization of that specific behavior?
---
EDIT:
It has been suggested by Reed that I instead return to the point that is CLOSEST to the current out-of-bounds point. Given the 4 corner points of a quadrilateral, how would I find the closest point in/on the shape? | 1. Find the equation of the edge line using the two endpoints.
2. -(1/slope) gives the slope of the perpendicular line.
3. Solve for line equation of perpendicular line using the known point across the edge (location of the true mouse)
4. Solve for intersection of edge line and perpendicular line.
5. Put the fake cursor at that location. | Instead of tracking a "safePoint", I would do the following:
If you find your outside of your polygon, instead of reverting to a last known safe point, put the mouse to the closest point on/in the polygon to the current mouse location. This will help the feel, as well, since the cursor will tend to (slowly) follow slopes on the edge of polygons, etc.
It also eliminates the need to save the state between calls (safepoint). | Implementing a mouse-bounding edge | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"xna",
""
] |
Why does this not work? How can I make it work? That is, how can I make gu accessible inside my decorated function?
```
def decorate(f):
def new_f():
def gu():
pass
f()
return new_f
@decorate
def fu():
gu()
fu()
```
Do I need to add gu to a dictionary of defined functions somehow? Or can I add gu to the local namespace of f before calling it? | In principle you can create a new function using the same code as the old one but substituting the global scope with an amended one:
```
import new
def with_bar(func):
def bar(x):
return x + 1
f_globals = func.func_globals.copy()
f_globals['bar'] = bar
return new.function(func.func_code, f_globals,
func.func_name, func.func_defaults, func.func_closure)
@with_bar
def foo(x):
return bar(x)
print foo(5) # prints 6
```
In practice you really should find a better way to do this. Passing in functions as parameters is one option. There might be other approaches too, but it's hard to tell what would fit without a high-level problem description. | If you need to pass `gu` to `fu` you need to do this explicitly by parameters:
```
def decorate(f):
def new_f():
def gu():
pass
f(gu)
return new_f
@decorate
def fu(gu):
gu()
fu()
``` | defining functions in decorator | [
"",
"python",
"aop",
"decorator",
"argument-passing",
""
] |
How would you find the value of string that is repeated and the data between it using regexes? For example, take this piece of XML:
```
<tagName>Data between the tag</tagName>
```
What would be the correct regex to find these values? (Note that `tagName` could be anything).
I have found a way that works that involves finding all the `tagName`s that are inbetween a set of `< >` and then searching for the first instance of the `tagName` from the opening tag to the end of the string and then finding the closing `</tagName>` and working out the data from between them. However, this is **extremely** inefficient and complex. There must be an easier way!
EDIT: Please don't tell me to use XMLReader; I doubt I will ever use my custom class for reading XML, I am trying to learn the best way to do it (and the wrong ways) through attempting to make my own.
Thanks in advance. | You can use: `<(\w+)>(.*?)<\/\1>`
Group #1 is the tag, Group #2 is the content. | Using regular expressions to parse XML is a terrible error.
This is efficient (it doesn't parse the XML into a DOM) and simple enough:
```
string s = "<tagName>Data between the tag</tagName>";
using (XmlReader xr = XmlReader.Create(new StringReader(s)))
{
xr.Read();
Console.WriteLine(xr.ReadElementContentAsString());
}
```
**Edit:**
Since the actual goal here is to learn something by doing, and not to just get the job done, here's why using regular expressions doesn't work:
Consider this fairly trivial test case:
```
<a><b><a>text1<b>CDATA<![<a>text2</a>]]></b></a></b>text3</a>
```
There are two elements with a tag name of "a" in that XML. The first has one text-node child with a value of "text1", and the second has one text-node child with a value of "text3". Also, there's a "b" element that contains a string of text that looks like an "a" element but isn't because it's enclosed in a CDATA section.
You can't parse that with simple pattern-matching. Finding `<a>` and looking ahead to find `</a>` doesn't *begin* to do what you need. You have to put start tags on a stack as you find them, and pop them off the stack as you reach the matching end tag. You have to *stop* putting anything on the stack when you encounter the start of a CDATA section, and not start again until you encounter the end.
And that's without introducing whitespace, empty elements, attributes, processing instructions, comments, or Unicode into the problem. | How to find a repeated string and the value between them using regexes? | [
"",
"c#",
"xml",
"regex",
"string",
""
] |
i have this :
```
class A {
public :
A(int i ) : m_S(i)
{
m_Pa = new Foo(*this) ;
}
private :
int m_S ;
Foo* m_Pa;
}
and derived class
class B : public A {
public :
B() : A (242)
{
// here i like to override the A class m_Pa member but i don't know how to do it right
}
}
``` | your m\_Pa should be protected than you can call like:
```
B() : A (242), m_Pa(12)
{
}
```
or
```
B() : A (242)
{
m_PA = 55
}
```
or you should make a public or protected function which changes m\_Pa
```
class A {
public :
A(int i ) : m_S(i)
{
m_Pa = new Foo(*this) ;
}
void setPA(int val)
{
m_PA = val;
}
``` | What is m\_Pa? You never had it declared. Assuming it's a private data member of type Foo\* in class A, you can't directly change it in the derived class unless you change A's interface. E.g., you can provide a protected setter member function:
```
class A {
....
protected:
void setFoo(const Foo* foo);
}
class B {
....
Foo *foo = new Foo(this);
setFoo(foo);
}
``` | How to override member of base class after inheritance in C++ | [
"",
"c++",
"inheritance",
"constructor",
""
] |
I've looked this up and the outlook seems bleak. I'm not interested in using a table. I have 6 or so 'a element' inline-blocks that make up a menu. It's slick, except all the 'a elements' are set to width: auto; to accommodate their text. Without an explicit width, I'm not able to center align them. I have a container div and a child div that wraps around my 'a elements'.
Any thoughts?
Thanks
Mike | You could set the style of the **a** element to **margin: 0 auto**, but that doesn't work in IE6. In IE6, you should set the wrapper div to **text-align: center**, and (optionally) set the text-alignment for the **a** element back to **text-align: left** | ```
<div style="width: auto; margin-left: auto; margin-right: auto">
div content
</div>
```
will align center on the page | How can I center align a div without knowing the width? | [
"",
"javascript",
"html",
"css",
""
] |
I just wrote a regexp to do a basic syntax checking if a string is a valid math formular.
I just define a group of valid chars and check if a string matches (I shortend the regex a little:
```
private static readonly String validFormuar = @"^[\d\+-\*\/]+$";
private static bool IsValidFormular(String value)
{
return Regex.IsMatch(value, validFormuar);
}
```
I will only allow digits, +, -, \* and / in this example.
Because +,\* and / are special chars in regular expressions I escaped them.
However this code throws an ArgumentException (translated from german)
```
"^[\d\+-\*\/]+$" is beeing analyzed - [x-y]-area in reversed Order.
```
If I double escape the \*
```
private static readonly String validFormuar = @"^[\d\+-\\*\/]+$";
```
the result is as expected.
Is this a bug in the System.Text.RegularExpressions parser? Because I consider my first regexp as correct. If not, why do I have to escape the "\*" twice? | I think you'll find `"-"` is a special character in regexes as well (at least within the `"[]"` bits). It specifies a range of characters, as in `"[0-9]"` meaning and of `"0123456789"`.
The reason your second one works but your first doesn't is because:
* `+` comes after `*` (error in range).
* `+` comes before `\` (no error in range).
To clarify, your second regex `(@"^[\d\+-\\*\/]+$")` actually means:
* `"\d"` ; or
* `"\+" thru "\\"` (quite a large range, including digits and uppercase letters) ; or
* `"*"` ; or
* `"\/"`
Although it compiles, it's not what you want (because of that second bullet point). I'd try this instead:
```
@"^[\d\+\-\*\/]+$"
``` | With @"" strings, you don't have to double-escape. In your sample, you also forgot to escape the "-". So the correct one would be:
```
@"^[\d\+\-\*\/]+$"
```
On the other hand, when inside [], you don't need to escape those (only "-"):
```
@"^[\d+\-*/]+$"
``` | Is this a bug in dotnet Regex-Parser? | [
"",
"c#",
".net",
"regex",
""
] |
I have this xml snippet as part of a xml file that will be deserialized to a c# object
```
<EmailConfiguration>
<SendTo>
<Address>myEmailAdress@bah.com</Address>
<Address>also send to</Address>
</SendTo>
<CC>
<Address>CC</Address>
</CC>
<BCC>
<Address>BCC</Address>
</BCC>
</EmailConfiguration>
```
Notice the SendToAddress is a collection of Addresses
```
<Address>myEmailAddress@bah.com</Address>
<Address>also send to</Address>
```
My Class currently looks like this
```
public class SendTo
{
public string Address
{
get;
set;
}
}
```
This is good for 1 address, how do I change the class so that it can handle more than 1 address.
I tried
```
public class SendTo
{
public string[] Address
{
get;
set;
}
}
```
But with this, nothing gets populated when the xml is deserialized to a class.
**Update**
tried...also without success....
```
public class SendTo
{
public List<string> Address
{
get;
set;
}
}
```
Here is the entire class
```
namespace myConfiguration
{
public class myConfiguration
{
private string myID;
public string MyID
{
get { return myID; }
set { myID = value; }
}
public Locale Locale
{
get;
set;
}
public EmailConfiguration EmailConfiguration
{
get;
set;
}
}
public class Locale
{
public string LocaleName
{
get;
set;
}
public string LocaleCode
{
get;
set;
}
}
public class EmailConfiguration
{
public SendTo SendTo
{
set;
get;
}
public SendTo CC
{
set;
get;
}
public SendTo BCC
{
set;
get;
}
}
public class SendTo
{
public List<string> Address
{
get;
set;
}
}
```
}
Here is the XML that I am deserializing from ...
```
<?xml version="1.0" encoding="utf-8" ?>
<MyConfiguration>
<MyID>vpfaewb</MyID>
<Locale>
<LocaleName>cs-CZ</LocaleName>
<LocaleCode>1029</LocaleCode>
</Locale>
<EmailConfiguration>
<SendTo>
<Address>my email address</Address>
<Address>also send to</Address>
</SendTo>
<CC>
<Address>CC</Address>
</CC>
<BCC>
<Address>BCC</Address>
</BCC>
</EmailConfiguration>
</MyConfiguration>
``` | Try this:
```
[XmlArrayItem("Address", IsNullable=false)]
public string[] SendTo
{
get
{
return this.sendToField;
}
set
{
this.sendToField = value;
}
}
``` | If you run your test XML file through the `xsd.exe` tool by Microsoft twice, first turning the XML into a XSD (`xsd.exe yourfile.xml` --> yourfile.xsd), and then generating a C# class from that XSD (`xsd.exe /c yourfile.xsd` --> yourfile.cs) that can deserialize that XML content, you'll end up with something like this (long and not very pretty.....)
```
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4016
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=2.0.50727.3038.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class EmailConfiguration {
private object[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("BCC", typeof(EmailConfigurationBCC), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlElementAttribute("CC", typeof(EmailConfigurationCC), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlElementAttribute("SendTo", typeof(EmailConfigurationSendTo), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public object[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class EmailConfigurationBCC {
private string addressField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Address {
get {
return this.addressField;
}
set {
this.addressField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class EmailConfigurationCC {
private string addressField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Address {
get {
return this.addressField;
}
set {
this.addressField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class EmailConfigurationSendTo {
private EmailConfigurationSendToAddress[] addressField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Address", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public EmailConfigurationSendToAddress[] Address {
get {
return this.addressField;
}
set {
this.addressField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class EmailConfigurationSendToAddress {
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
```
I would think this will work - it's not nice, but it'll work. You should be able to convert your complete XML file into a serializable / deserializable C# class that way. Try it!
Marc | Problem Serializing a Class Containing a Collection using XML Serialization | [
"",
"c#",
"xml-serialization",
""
] |
The following User History table contains **one record for every day a given user has accessed a website** (in a 24 hour UTC period). It has many thousands of records, but only one record per day per user. If the user has not accessed the website for that day, no record will be generated.
```
Id UserId CreationDate
------ ------ ------------
750997 12 2009-07-07 18:42:20.723
750998 15 2009-07-07 18:42:20.927
751000 19 2009-07-07 18:42:22.283
```
What I'm looking for is a SQL query on this table *with good performance*, that tells me which userids have accessed the website for (n) continuous days without missing a day.
In other words, **how many users have (n) records in this table with sequential (day-before, or day-after) dates**? If any day is missing from the sequence, the sequence is broken and should restart again at 1; we're looking for users who have achieved a continuous number of days here with no gaps.
Any resemblance between this query and [a particular Stack Overflow badge](https://stackoverflow.com/badges/71/woot-enthusiast) is purely coincidental, of course.. :) | The answer is obviously:
```
SELECT DISTINCT UserId
FROM UserHistory uh1
WHERE (
SELECT COUNT(*)
FROM UserHistory uh2
WHERE uh2.CreationDate
BETWEEN uh1.CreationDate AND DATEADD(d, @days, uh1.CreationDate)
) = @days OR UserId = 52551
```
**EDIT:**
Okay here's my serious answer:
```
DECLARE @days int
DECLARE @seconds bigint
SET @days = 30
SET @seconds = (@days * 24 * 60 * 60) - 1
SELECT DISTINCT UserId
FROM (
SELECT uh1.UserId, Count(uh1.Id) as Conseq
FROM UserHistory uh1
INNER JOIN UserHistory uh2 ON uh2.CreationDate
BETWEEN uh1.CreationDate AND
DATEADD(s, @seconds, DATEADD(dd, DATEDIFF(dd, 0, uh1.CreationDate), 0))
AND uh1.UserId = uh2.UserId
GROUP BY uh1.Id, uh1.UserId
) as Tbl
WHERE Conseq >= @days
```
**EDIT:**
[Jeff Atwood] This is a great fast solution and deserves to be accepted, but [Rob Farley's solution is also excellent](https://stackoverflow.com/questions/1176011/sql-to-determine-minimum-sequential-days-of-access/1176255#1176255) and arguably even faster (!). Please check it out too! | How about (and please make sure the previous statement ended with a semi-colon):
```
WITH numberedrows
AS (SELECT ROW_NUMBER() OVER (PARTITION BY UserID
ORDER BY CreationDate)
- DATEDIFF(day,'19000101',CreationDate) AS TheOffset,
CreationDate,
UserID
FROM tablename)
SELECT MIN(CreationDate),
MAX(CreationDate),
COUNT(*) AS NumConsecutiveDays,
UserID
FROM numberedrows
GROUP BY UserID,
TheOffset
```
The idea being that if we have list of the days (as a number), and a row\_number, then missed days make the offset between these two lists slightly bigger. So we're looking for a range that has a consistent offset.
You could use "ORDER BY NumConsecutiveDays DESC" at the end of this, or say "HAVING count(\*) > 14" for a threshold...
I haven't tested this though - just writing it off the top of my head. Hopefully works in SQL2005 and on.
...and would be very much helped by an index on tablename(UserID, CreationDate)
Edited: Turns out Offset is a reserved word, so I used TheOffset instead.
Edited: The suggestion to use COUNT(\*) is very valid - I should've done that in the first place but wasn't really thinking. Previously it was using datediff(day, min(CreationDate), max(CreationDate)) instead.
Rob | SQL to determine minimum sequential days of access? | [
"",
"sql",
"sql-server",
"date",
"gaps-and-islands",
""
] |
Currently I am using the site at <http://javascriptcompressor.com/> to compress my JavaScript.
Is there any other standalone JavaScript compressing tool? | The following are standalone:
* [JSMin](http://www.crockford.com/javascript/jsmin.html)
* [YUI Compressor](http://developer.yahoo.com/yui/compressor/)
* [packer](http://dean.edwards.name/download/#packer) | * <http://www.cortex-creations.com/phpjso/>
* <http://www.codeproject.com/KB/cs/jscompress.aspx> | What standalone JavaScript compressing tools are there? | [
"",
"javascript",
"minify",
"jscompress",
""
] |
What options are there to implement an own session management in PHP?
Is there a nice way to implement a component which performs all session tasks?
How can i construct a class which receives the HTTP Request and Response during one request process?
I only found the option "session\_save\_handler" which seems to define the storage handler. What I need is to replace the whole session management.
Is there another way using the PHP configuration or do I have to implement my own controller which receives all requests and calls my session management?
Thanks for your help
Regards Michael | No, I'm sorry to say, there is no interface to switch the built in 'modules' to your own. There are some hooks ( e.g: `session_save_handler(), set_error_handler()` ), and that's unfortunately it.
The $\_SESSION is a 'super global' and should IMO not be set directly either way if you're working on a bigger projects. Then it would be better to use a custom class responsible for handling sessions. Will make the code easier to debug and such on. | You said it yourself in one of the comments. Just wrap the $\_SESSION in a class. I don't think you can replace it, but you can certainly build your own interface to it.
You could, for example. Build a class that is constructed first thing and call session\_start() inside the constructor | Implementing own Session Management in PHP | [
"",
"php",
"session-management",
""
] |
Investigating a bug, I discovered it was due to this weirdness in c#:
```
sbyte[] foo = new sbyte[10];
object bar = foo;
Console.WriteLine("{0} {1} {2} {3}",
foo is sbyte[], foo is byte[], bar is sbyte[], bar is byte[]);
```
The output is "True False True True", while I would have expected "`bar is byte[]`" to return False. Apparently bar is both a `byte[]` and an `sbyte[]`? The same happens for other signed/unsigned types like `Int32[]` vs `UInt32[]`, but not for say `Int32[]` vs `Int64[]`.
Can anyone explain this behavior? This is in .NET 3.5. | UPDATE: I've used this question as the basis for a blog entry, here:
<https://web.archive.org/web/20190203221115/https://blogs.msdn.microsoft.com/ericlippert/2009/09/24/why-is-covariance-of-value-typed-arrays-inconsistent/>
See the blog comments for an extended discussion of this issue. Thanks for the great question!
---
You have stumbled across an interesting and unfortunate inconsistency between the CLI type system and the C# type system.
The CLI has the concept of "assignment compatibility". If a value x of known data type S is "assignment compatible" with a particular storage location y of known data type T, then you can store x in y. If not, then doing so is not verifiable code and the verifier will disallow it.
The CLI type system says, for instance, that subtypes of reference type are assignment compatible with supertypes of reference type. If you have a string, you can store it in a variable of type object, because both are reference types and string is a subtype of object. But the opposite is not true; supertypes are not assignment compatible with subtypes. You can't stick something only known to be object into a variable of type string without first casting it.
Basically "assignment compatible" means "it makes sense to stick these exact bits into this variable". The assignment from source value to target variable has to be "representation preserving". See my article on that for details:
<http://ericlippert.com/2009/03/03/representation-and-identity/>
One of the rules of the CLI is "if X is assignment compatible with Y, then X[] is assignment compatible with Y[]".
That is, arrays are covariant with respect to assignment compatibility. This is actually a broken kind of covariance; see my article on that for details.
<https://web.archive.org/web/20190118054040/https://blogs.msdn.microsoft.com/ericlippert/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance/>
That is NOT a rule of C#. C#'s array covariance rule is "if X is a reference type implicitly convertible to reference type Y, then X[] is implicitly convertible to Y[]". **That is a subtly different rule, and hence your confusing situation.**
In the CLI, uint and int are assignment compatible. But in C#, the conversion between int and uint is EXPLICIT, not IMPLICIT, and these are value types, not reference types. So in C#, it's not legal to convert an int[] to a uint[].
But it IS legal in the CLI. So now we are faced with a choice.
1. Implement "is" so that when the compiler cannot determine the answer statically, it actually calls a method which checks all the C# rules for identity-preserving convertibility. This is slow, and 99.9% of the time matches what the CLR rules are. But we take the performance hit so as to be 100% compliant with the rules of C#.
2. Implement "is" so that when the compiler cannot determine the answer statically, it does the incredibly fast CLR assignment compatibility check, and live with the fact that this says that a uint[] is an int[], even though that would not actually be legal in C#.
We chose the latter. It is unfortunate that C# and the CLI specifications disagree on this minor point but we are willing to live with the inconsistency. | Ran the snippet through Reflector:
```
sbyte[] foo = new sbyte[10];
object bar = foo;
Console.WriteLine("{0} {1} {2} {3}", new object[] { foo != null, false, bar is sbyte[], bar is byte[] });
```
The C# compiler is optimizing the first two comparisons (`foo is sbyte[]` and `foo is byte[]`). As you can see they have been optimized to `foo != null` and simply always `false`. | Why does my C# array lose type sign information when cast to object? | [
"",
"c#",
"arrays",
"types",
"command-line-interface",
""
] |
I'm trying to slowly knock out all of the intricacies of python. Basically, I'm looking for some way, in python, to take a string of characters and push them all over by 'x' characters.
For example, inputing abcdefg will give me cdefghi (if x is 2). | I would do it this way (for conceptual simplicity):
```
def encode(s):
l = [ord(i) for i in s]
return ''.join([chr(i + 2) for i in l])
```
Point being that you convert the letter to ASCII, add 2 to that code, convert it back, and "cast" it into a string (create a new string object). This also makes no conversions based on "case" (upper vs. lower).
Potential optimizations/research areas:
* Use of StringIO module for large strings
* Apply this to Unicode (not sure how) | My first version:
```
>>> key = 2
>>> msg = "abcdefg"
>>> ''.join( map(lambda c: chr(ord('a') + (ord(c) - ord('a') + key)%26), msg) )
'cdefghi'
>>> msg = "uvwxyz"
>>> ''.join( map(lambda c: chr(ord('a') + (ord(c) - ord('a') + key)%26), msg) )
'wxyzab'
```
(Of course it works as expected only if msg is lowercase...)
**edit**: I definitely second David Raznick's answer:
```
>>> import string
>>> alphabet = "abcdefghijklmnopqrstuvwxyz"
>>> key = 2
>>> tr = string.maketrans(alphabet, alphabet[key:] + alphabet[:key])
>>> "abcdefg".translate(tr)
'cdefghi'
``` | Using a caesarian cipher on a string of text in python? | [
"",
"python",
"encryption",
""
] |
I got started with threads `Thread.Start()` recently and **Long Running Tasks** and noticed several request related issues.
**EDIT**
What would you suggest to provide the user a feedback while the job is being processed, make efficient use of the thread pool and make use of HttpContext if possible? | You are quite possibly making a mistake in your use of threads in an ASP.NET application. Are you using asynchronous pages, or are you using new Thread().Start? The latter is a mistake, and can get you into some of those problems with HttpContext, when the request is complete, but the thread is still running.
Please edit your question to give more detail on what you're doing with threads. | For accessing data:
For data like Server.Identity.Name, I think collecting that information beforehand and passing it to your async code is a good approach. Its good decoupling as that code now only depends on those few properties.
For accessing behavior:
How are you using threads with ASP.NET? The two approaches that work are to implement and register IAsyncHttpHandler, or you're call Page.AddOnPreRenderCompleteAsync() from some ASP.NET page.
For IAsyncHttpHandler, the callback you implement is passed an HttpContext. You should be able to use that referenced context from any thread until you indicate to ASP.NET that request processing has finished. Of course you should only use that reference from one thread a time.
For Page.AddOnPreRenderCompleteAsync, it should be safe to call Page.Context from your callbacks under the same conditions.
For the existing code you have in App\_Code that uses HttpContext.Current, you need to refactor that so the code takes the HttpContext as an input parameter. Existing code can pass in HttpContext.Current, new code you're writing from threads can pass in one of the contexts described earlier in this answer. | Multi-Threading, HttpContext, Long Running Task? | [
"",
"c#",
"asp.net",
"multithreading",
"httpcontext",
""
] |
I am putting together a build system for my Qt app using a qmake .pro file that uses the 'subdirs' template. This works fine, and allows me to specify the order that each target is built, so dependencies work nicely. However, I have now added a tool to the project that generates a version number (containing the build date, SVN revision, etc,) that is used by the main app - I can build this version tool first but when it is built I want to execute it before any more targets are built (it generates a header file containing the version number that the main app includes.)
For example, my simple qmake file looks like something this:
```
TEMPLATE = subdirs
CONFIG += ordered
SUBDIRS = version \
lib \
tests \
mainapp
```
When 'version' is built I want to execute it (passing some arguments on the command-line) before 'lib' is built.
Does anyone know if this is possible? I see that qmake has a 'system' command that can execute apps, but I don't know how I could leverage this.
A related question concerns my unit tests. These live in the 'test' project and use the QTest framework. I want to execute the tests exe before building 'mainapp' and if the tests fail (i.e. the tests exe doesn't return zero) I want to quit the build process.
I realise that qmake is designed to generate makefiles, so I may be wishing for a little too much here but if anyone can give me some pointers it would be very welcome. | I posted a message on the Qt Interest mailing list about a 'pre build' step and it can be done using a combination of PRE\_TARGETDEPS and QMAKE\_EXTRA\_TARGETS. Here is the response:
> You can specify custom build steps,
> eg. this would call makemyversion.sh
> to create myversion.cpp every time
> before it builds something:
>
> ```
> versiontarget.target = myversion.cpp
> versiontarget.commands = ./makemyversion.sh
> versiontarget.depends = FORCE
>
> PRE_TARGETDEPS += myversion.cpp
> QMAKE_EXTRA_TARGETS += versiontarget
> ```
I am now using something similar to this to generate my app's version number each time it is built. | I currently use qmake to exec my unit tests automatically for two years - and it works fine.
Have a look here - I made a mini-howto for that:
[Qt: Automated Unit Tests with QMAKE](http://www.3dh.de/?p=97)
# Abridged summary:
---
## Structure
```
/myproject/
myproject.h
myproject.cpp
main.cpp
myproject.pro
/myproject/tests/
MyUnitTest.h
MyUnitTest.cpp
main.cpp
tests.pro
```
## Using QMake to automatically run unit tests on build
The QMake target QMAKE\_POST\_LINK will run a user defined command after linking.
**tests.pri (common file)**
```
TEMPLATE = app
DEPENDPATH += . ../
INCLUDEPATH += . ../
DESTDIR = ./
CONFIG += qtestlib
unix:QMAKE_POST_LINK=./$$TARGET
win32:QMAKE_POST_LINK=$${TARGET}.exe
```
**tests.pro (project-specific file)**
```
TARGET = MyUnitTest
HEADERS += MyUnitTest.h
SOURCES += MyUnitTest.cpp main.cpp
include(tests.pri)
```
## Running multiple unit tests in a single main()
**main.cpp**
```
#include "MyUnitTest1.h"
#include "MyUnitTest2.h"
int main(int argc, char** argv) {
QApplication app(argc, argv);
int retval(0);
retval +=QTest::qExec(&MyTest1(), argc, argv);
retval +=QTest::qExec(&MyTest2(), argc, argv);
return (retval ? 1 : 0);
}
```
This runs your tests on each build and aborts if an error is found.
## Note
If you get linker errors such as "LNK2005: xxx already defined...", add a new .cpp file for each test class header and move some test method implementations.
---
You can use exactly that mechanism to exec your versioning tool after compile/building - so your questions should be solved :-)
If you have any further questions don't hesitate to ask me.
PS: Here you can find more (undocumented) tricks around QMake: [Undocumented QMake](http://wiki.qtcentre.org/index.php?title=Undocumented_qmake) | QMake 'subdirs' template - executing a target? | [
"",
"c++",
"qt",
"qmake",
""
] |
I am very aware of compiling C++ programs with g++ in linux environment. But, may be I am missing something, I am getting this strange output/behaviour.
I have source file in test.cpp.
To compile this, I did
```
(1)
g++ -c test.cpp
g++ -o test test.o
./test
```
Everything works fine.
But when I did compling and linking in same stage, like this
```
(2)
g++ test.cpp -o test
./test => Works fine
(3)
g++ -c test.cpp -o test => Doesn't work
```
In my last case, test is generated but is no more executable; but in my guess it should work fine.
So, what is wrong or do I need to change some settings/configuration ??
I am using g++ 4.3.3
Thanks. | When you say:
```
g++ -c test.cpp -o test
```
The -c flag inhibits linking, so no executable is produced - you are renaming the .o file.
Basically, don't do that. | You are forcing compiler to produce an object file and name it like an executable.
Essentially your last line tells: compile this to an object file, but name it test, instead of test.obj. | C++ programs, compiling with g++ | [
"",
"c++",
"compiler-construction",
"g++",
""
] |
Im wondering about the real advantage of performing dml commands (inserts, updates, deletes) in the database via stored procedures for simple CRUD applications. Whats the beneffit with that appoach over just using some generic procedure in the front-end that generates the dml commands?
Thanks in advance. | Performance wise you are unlikely to see any benefit. I think it is more about security of the database.
The advantage of stored procedures in any case is the ability for the DBA to control the security access to the data differently. It often is a preference call by the DBA. Putting the CRUD access to the server in the server means they control 100% access to the server. Your code has to meet their stored proc "API".
If you include the logic in the Visual FoxPro code via a remote view, cursor adapter, or SQL Passthrough SQLExec() it means you have 100% of the code control and the DBA has to grant you access to the database components, or through the application role your code would use for the connection. Your code might be a bit more flexible with respect to building the CRUD SQL statement on the fly. The stored proc is going to have to handle flexible parameters to build the statements generically.
Rick Schummer | Visual Foxpro? For single record updates, I doubt that there is any performance benefit to SP's. The effort to maintain them certainly trumps any marginal performance gain you might get.
The stored procedures gurus might have thoughts on other benefits besides performance. | DML generated at front-end vs. Insert - Update - Delete performed by stored procedures | [
"",
"sql",
"t-sql",
""
] |
I have a machine running a java app talking to a mysql instance running on the same instance. the app
uses jdbc4 drivers from mysql. I keep getting com.mysql.jdbc.exceptions.jdbc4.CommunicationsException
at random times.
Here is the whole message.
Could not open JDBC Connection for transaction; nested exception is
```
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was25899 milliseconds ago.The last packet sent successfully to the server was 25899 milliseconds ago, which is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
```
For mysql, the value of global 'wait\_timeout' and 'interactive\_timeout' is set to 3600 seconds and 'connect\_timeout' is set to 60 secs. the wait timeout value is much higher than the 26 secs(25899 msecs). mentioned in the exception trace.
I use dbcp for connection pooling and here is spring bean config for the datasource.
```
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db"/>
<property name="username" value="xxx"/>
<property name="password" value="xxx" />
<property name="poolPreparedStatements" value="false" />
<property name="maxActive" value="3" />
<property name="maxIdle" value="3" />
</bean>
```
Any idea why this could be happening? Will using c3p0 solve the problem ? | Try setting up the Apache Commons DBCP correctly.
You need to set:
* validationQuery to SELECT 1+1
* testOnBorrow to true
That should fix the problem. | Can you describe how your app is handling connection pooling? I doubt that autoReconnect=true in the JDBC driver would re-pool connections from your app. The app needs to reconnect when it loses a connection. | jdbc4 CommunicationsException | [
"",
"java",
"mysql",
"jdbc",
"timeout",
"connection",
""
] |
I am trying to read from a process that produces long and time-consuming output. However, I want to catch it's output *as and when* it is produced. But using something like the following seems to be buffering the command's output, so I end up getting the output lines all at once:
```
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=0)
for line in p.stdout:
print line
```
I am trying this on MacOS 10.5 | The file iterator is doing some internal buffering [on its own](http://docs.python.org/library/stdtypes.html#file.next). Try this:
```
line = p.stdout.readline()
while line:
print line
line = p.stdout.readline()
```
You also need to make sure the process you are running is actually flushing its output buffers frequently. | Usually, every program will do more buffering on its input and/or output channels than you appear to desire... unless it's fooled into believing said channel's actually a terminal!
For that "fooling in a good cause" purpose, use [pexpect](http://pexpect.sourceforge.net/pexpect.html) -- it works just fine on a Mac (life is harder on Windows, though there are solutions that might help even there - fortunately we don't need to dwell on those as you use a Mac instead). | Unbuffered read from process using subprocess in Python | [
"",
"python",
"subprocess",
""
] |
Can Scala be used to script a Java application?
I need to load a piece of Scala code from Java, set up an execution scope for it (data exposed by the host application), evaluate it and retrieve a result object from it.
The Scala documentation shows how easy it is to call compiled Scala code from Java (because it gets turned into to regular JVM bytecode).
But how can I evaluate a Scala expression on the fly (from Java or if that is easier, from within Scala) ?
For many other languages, there is the javax.scripting interface. Scala does not seem to support it, and I could not find anything in the Java/Scala interoperability docs that does not rely on ahead-of-time compilation. | Scala is not a scripting language. It may *look* somewhat like a scripting language, and people may advocate it for that purpose, but it doesn't really fit well within the JSR 223 scripting framework (which is oriented toward dynamically typed languages). To answer your original question, Scala does not have an `eval` function just like Java does not have an `eval`. Such a function wouldn't really make sense for either of these languages given their intrinsically static nature.
My advice: rethink your code so that you don't need `eval` (you rarely do, even in languages which have it, like Ruby). Alternatively, maybe you don't want to be using Scala at all for this part of your application. If you really need `eval`, try using JRuby. JRuby, Scala and Java mesh very nicely together. It's quite easy to have part of your system in Java, part in Scala and another part (the bit which requires `eval`) in Ruby. | it's now 2011, and you can do so with `scala.tools.nsc.Interpreter`
see <http://blog.darevay.com/2009/01/remedial-scala-interpreting-scala-from-scala/>
use [`scala.tools.nsc.interpreter`](https://www.scala-lang.org/api/2.12.5/scala-compiler/scala/tools/nsc/interpreter/index.html) | "eval" in Scala | [
"",
"java",
"scala",
"scripting",
"embedding",
""
] |
I don't even want to think about how many man hours have been spent writing the same queries to join over the exact same tables at my company.
When I first started at my job I identified this as an inefficiency and started writing views in a separate schema for the sole purpose of developer convenience.
My boss didn't like this very much and recommended I start committing my common queries to source control in a separate folder from the production SQL. This makes sense because some scripts require parameters and not all are read only.
**What is a Common Query?**
* Script used to diagnose certain problems
* Script to view relationships between several tables (doing multiple joins)
* Script that we don't want in a stored procedure because it is often tweaked to diagnose the issue of the day
**Issues I want to Address**
* Discoverability, queries will be rewritten if nobody can find them
* IDE integration, want to be able to easily view queries in IDE. I've tried the SQL Server Solutions but they really suck because they lock you into only working on that set of files.
I was wondering how all the pro's out there share their common SQL queries.
Thanks | Seems like the op wants to know how to get the word out to the team about useful SQL that others can/should use so not to recreate.
How I have done this in the past is through two ways:
1. Create a team web wiki page that
details the SQL with examples of how
it is used.
2. Email the team when new SQL is
created that should be shared.
Of course, we always include the SQL code in version control, just the wiki and email are use in the "getting word out there" part. | If it is something that I would call "common" I would probably ***create a stored procedure*** that the folks with necessary permissions can run.
If the stored procedure route won't work well for your team, then the other option is to ***create a view.*** Creating a view comes with unique challenges though such as ensuring that everyone running the view has select permissions on all of the tables in the view as well.
Outside of storing the scripts in source control of some kind, maybe storing them on a Share Point site or a network file share would work OK for your team. The real challenge that you will have in sharing scripts is that people have different ways to identify what they are looking for. A wiki type of site that allows tagging the different types of things the queries do would be useful. | Sharing Common SQL Queries Amongst a Team | [
"",
"sql",
"sql-server-2005",
"organization",
""
] |
word 1
word 2
word 3
word 4
And so on... How can I turn that into a php array, here will be a lot of items so I don't want to write them all out into an array manually and I know there has to be a simple way
I mean do I have to do
```
<?PHP
$items = array();
$items['word 1'];
$items['word 2'];
$items['word 3'];
$items['word 4'];
?>
```
UPDATE got it thanks
```
<?php
$items = "word1 word2 word3 word4";
$items = explode(" ", $items);
echo $items[0]; // word1
echo $items[1]; // word2
?>
``` | If you mean:
```
word1 word2 word3
```
Then you want
```
$array = explode(' ', "word1 word2 word3");
```
If you actually mean "word 1 word 2 word 3", with numbers inbetween, then you'll need to get a little fancier with preg\_split() | If I understand the question, you have a set of variables, like this :
```
$word1 = 'a';
$word2 = 'b';
$word3 = 'c';
$word4 = 'd';
$word5 = 'e';
$word6 = 'f';
$word7 = 'g';
$word8 = 'h';
```
If yes, you could use PHP's [Variable variables](http://php.net/manual/en/language.variables.variable.php), like this :
```
$list = array();
for ($i = 1 ; $i <= 8 ; $i++) {
$variable_name = 'word' . $i;
$list[] = $$variable_name;
}
var_dump($list);
```
And you'd get, as output :
```
array
0 => string 'a' (length=1)
1 => string 'b' (length=1)
2 => string 'c' (length=1)
3 => string 'd' (length=1)
4 => string 'e' (length=1)
5 => string 'f' (length=1)
6 => string 'g' (length=1)
7 => string 'h' (length=1)
```
If I didn't understand the question and you only have one string at first... You'll probably have to use [explode](http://php.net/explode) to separate the words...
EDIT
*(Well, I didn't understand the question, it seems... There were not as many examples given when I first answered -- sorry ^^)* | How can I turn a list of items into a php array? | [
"",
"php",
"arrays",
""
] |
NO MySQL answers please!
The basic query is as follows (assume A is Key)
```
INSERT INTO destination (A,B,C)
SELECT a1,b1,c1
FROM source
WHERE (selectconditions) ;
```
Source contains many records that may or may not already be in destination, which means that the insert will fail as soon as a duplicate record is encountered.
Desired Behaviour: INSERT or IGNORE
> This is the desired scenario for the given problem. Insert if you can, otherwise continue.
Pseudo c#/java:
```
foreach(record in selectQuery)
{
try { destination.insert(record) }
catch(insertionException){//squelch}
}
```
This can be handled in SQL by adding
```
AND NOT EXISTS (SELECT A FROM destination INNER JOIN source on destination.A = source.a1)
```
to the end of the query -- In other words, check before you insert.
What are some other alternatives to handling this common situation? What are the pros and cons of these techniques? | Some database provide an explicit syntax for operations that involve a conditional insert/update/ignore.
[Oracle](http://www.adp-gmbh.ch/ora/sql/merge.html) and [SQLServer](http://technet.microsoft.com/en-us/library/bb510625.aspx), for example have the MERGE statement which can insert/update/delete/ignore a record based on a set of predicates.
Ignoring database-specific syntax, you can perform the insert using a predicate that excludes records that already exist:
```
INSERT INTO target( A, B, C )
SELECT SA, SB, SB FROM source
WHERE NOT EXISTS (select A, B, C from TARGET where A = SA, B = SB, C = SC)
``` | If you share a common Primary Key:
```
INSERT INTO destination
( A, B, C)
SELECT a1, b1, c1 FROM source
WHERE source.pk not in ( SELECT pk FROM destination );
```
If you don't:
```
INSERT INTO destination
( A, B, C)
SELECT a1, b1, c1 FROM source
WHERE a1 + b1 + c1 not in ( SELECT a+b+c FROM destination );
``` | Solutions for insertion of duplicate keys | [
"",
"sql",
"insert",
"bulkinsert",
""
] |
I have a Python 2.6 script that is gagging on special characters, encoded in Latin-1, that I am retrieving from a SQL Server database. I would like to print these characters, but I'm somewhat limited because I am using a library that calls the `unicode` factory, and I don't know how to make Python use a codec other than `ascii`.
The script is a simple tool to return lookup data from a database without having to execute the SQL directly in a SQL editor. I use the [PrettyTable](http://code.google.com/p/prettytable/) 0.5 library to display the results.
The core of the script is this bit of code. The tuples I get from the cursor contain integer and string data, and no Unicode data. (I'd use `adodbapi` instead of `pyodbc`, which would get me Unicode, but `adodbapi` gives me other problems.)
```
x = pyodbc.connect(cxnstring)
r = x.cursor()
r.execute(sql)
t = PrettyTable(columns)
for rec in r:
t.add_row(rec)
r.close()
x.close()
t.set_field_align("ID", 'r')
t.set_field_align("Name", 'l')
print t
```
But the `Name` column can contain characters that fall outside the ASCII range. I'll sometimes get an error message like this, in line 222 of `prettytable.pyc`, when it gets to the `t.add_row` call:
```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 12: ordinal not in range(128)
```
This is line 222 in `prettytable.py`. It uses `unicode`, which is the source of my problems, and not just in this script, but in other Python scripts that I have written.
```
for i in range(0,len(row)):
if len(unicode(row[i])) > self.widths[i]: # This is line 222
self.widths[i] = len(unicode(row[i]))
```
Please tell me what I'm doing wrong here. How can I make `unicode` work without hacking `prettytable.py` or any of the other libraries that I use? Is there even a way to do this?
EDIT: The error occurs not at the `print` statement, but at the `t.add_row` call.
EDIT: With Bastien Léonard's help, I came up with the following solution. It's not a panacea, but it works.
```
x = pyodbc.connect(cxnstring)
r = x.cursor()
r.execute(sql)
t = PrettyTable(columns)
for rec in r:
urec = [s.decode('latin-1') if isinstance(s, str) else s for s in rec]
t.add_row(urec)
r.close()
x.close()
t.set_field_align("ID", 'r')
t.set_field_align("Name", 'l')
print t.get_string().encode('latin-1')
```
I ended up having to decode on the way in and encode on the way out. All of this makes me hopeful that everybody ports their libraries to Python 3.x sooner than later! | Add this at the beginning of the module:
```
# coding: latin1
```
Or decode the string to Unicode yourself.
[Edit]
It's been a while since I played with Unicode, but hopefully this example will show how to convert from Latin1 to Unicode:
```
>>> s = u'ééé'.encode('latin1') # a string you may get from the database
>>> s.decode('latin1')
u'\xe9\xe9\xe9'
```
[Edit]
Documentation:
<http://docs.python.org/howto/unicode.html>
<http://docs.python.org/library/codecs.html> | Maybe try to decode the latin1-encoded strings into unicode?
```
t.add_row((value.decode('latin1') for value in rec))
``` | Latin-1 and the unicode factory in Python | [
"",
"python",
"unicode",
""
] |
I've found several pages and SO answers about the enter-as-tab problem in Java, but all propose either overriding methods of JTextField or adding a key listener to every component.
But isn't there any other way? Can't I override something of the LookAndFeel or install some global policy? | After some documentation crawling I found a solution: It is possible to set the focus traversal keys on `KeyboardFocusManager` instead of a `JComponent` instance.
```
// 1. Get default keys
Set<AWTKeyStroke> ftk = new HashSet<AWTKeyStroke>(
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.getDefaultFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
// 2. Add our key
ftk.add(KeyStroke.getKeyStroke("ENTER"));
// 3. Set new keys
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.setDefaultFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, ftk);
```
This adds the `enter` key to the list of keys which are used for forward traversal. (Backward traversal similar) | you can probably use <http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html>
to change the keyBinding for the enter key
or you can add focustravesal keys
```
setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, your keys here);
``` | Is it possible to use Enter as Tab without inheriting JTextField or mass-adding key listeners? | [
"",
"java",
"swing",
""
] |
I want to update the top 100 records in SQL Server. I have a table `T1` with fields `F1` and `F2`. `T1` has 200 records. I want to update the `F1` field in the top 100 records. How can I update based on `TOP 100` in SQL Server? | Note, the parentheses are required for `UPDATE` statements:
```
update top (100) table1 set field1 = 1
``` | Without an `ORDER BY` the whole idea of `TOP` doesn't make much sense. You need to have a consistent definition of which direction is "up" and which is "down" for the concept of top to be meaningful.
Nonetheless SQL Server allows it but [doesn't guarantee a deterministic result](http://blogs.technet.com/b/wardpond/archive/2007/07/19/database-programming-top-without-order-by.aspx).
The `UPDATE TOP` syntax in the accepted answer does not support an `ORDER BY` clause but it is possible to get deterministic semantics here by using a CTE or derived table to define the desired sort order as below.
```
;WITH CTE AS
(
SELECT TOP 100 *
FROM T1
ORDER BY F2
)
UPDATE CTE SET F1='foo'
``` | how can I Update top 100 records in sql server | [
"",
"sql",
"sql-server",
"t-sql",
"sql-update",
""
] |
Stemming from this question of mine: [I'm seeing artifacts when I attempt to rotate an image](https://stackoverflow.com/questions/1191093/im-seeing-artifacts-when-i-attempt-to-rotate-an-image)
In the source code there, I am loading a TIF because I can't for the life of me get any other image format to load the transparency parts correctly. I've tried PNG, GIF, & TGA. I'd would like to be able to load PNGs. I hope the source code given in the question above will be enough, if not, then let me know.
For a better description of what happens when I attempt to load some other format -- One of the images I was attempting was a 128\*128 orange triangle. Depending on the format, it would either make the entire 128\*128 square orange, or make the transparent parts of the image white. | OK, I'm new at OpenGL + SDL but here is what I have.. Loads all? formats SDL\_image supports except I can't get .xcf to work and don't have a .lbm to test with.
```
//called earlier..
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//load texture
SDL_Surface* tex = IMG_Load(file.c_str());
if (tex == 0) {
std::cout << "Could not load " << file << std::endl;
return false;
}
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
//nearest works but linear is best when scaled?
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
width = tex->w;
height = tex->h;
//IMG_is* doesn't seem to work right, esp for TGA, so use extension instead..
std::string ext = file.substr(file.length() - 4);
bool isBMP = (ext.compare(".bmp") == 0) || (ext.compare(".BMP") == 0);
bool isPNG = (ext.compare(".png") == 0) || (ext.compare(".PNG") == 0);
bool isTGA = (ext.compare(".tga") == 0) || (ext.compare(".TGA") == 0);
bool isTIF = ((ext.compare(".tif") == 0) || (ext.compare(".TIF") == 0) ||
(ext.compare("tiff") == 0) || (ext.compare("TIFF") == 0));
//default is RGBA but bmp and tga use BGR/A
GLenum format = GL_RGBA;
if(isBMP || isTGA)
format = (tex->format->BytesPerPixel == 4 ? GL_BGRA : GL_BGR);
//every image except png and bmp need to be converted
if (!(isPNG || isBMP || isTGA || isTIF)) {
SDL_Surface* fixedSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
SDL_BlitSurface(tex, 0, fixedSurface, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, format, GL_UNSIGNED_BYTE, fixedSurface->pixels);
SDL_FreeSurface(fixedSurface);
} else {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, format, GL_UNSIGNED_BYTE, tex->pixels);
}
SDL_FreeSurface(tex);
list = glGenLists(1);
glNewList(list, GL_COMPILE);
GLint vertices[] = {
0,0, 0,0,
0,1, 0,height,
1,1, width,height,
1,0, width,0
};
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glBindTexture(GL_TEXTURE_2D, texture);
glTexCoordPointer(2, GL_INT, 4*sizeof(GLint), &vertices[0]);
glVertexPointer(2, GL_INT, 4*sizeof(GLint), &vertices[2]);
glDrawArrays(GL_POLYGON, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glEndList();
```
And then to draw I set the color to opaque white (doesn't affect transparency?) then just call the list..
```
glColor4f(1,1,1,1);
glCallList(list);
```
And of course, any help for my code would be much appreciated too! :) | Make sure that you have alpha blending enabled with
```
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
```
otherwise primitives will draw solid colors where there should be transparency.
You may need a different blendfunc. This is a common setup. | I can't get the transparency in my images to work | [
"",
"c++",
"user-interface",
"opengl",
"sdl",
""
] |
We're considering converting a large solution from 2005 to 2008, but want to make sure that we don't hit any unforeseen issues. What are the things that we should be looking out for? Are we going to need to retest the entire project? Thanks! | We converted and did not have any issues. The conversion still uses the same .NET framework that you were originally using unless you update it. I don't think there will be any issues. | In my experience, going from 2005 to 2008 has always been surprisingly smooth! VS 2008 supports multi-targeting so you can still use a previous framework if you want.
I would still retest the project, though. | Converting Solution from Visual Studio 2005 to 2008 | [
"",
"c#",
".net",
"visual-studio",
"visual-studio-2008",
"visual-studio-2005",
""
] |
I have this bit of code in a .php file:
```
<?php ec3_get_events(
5, // limit
'%DATE%: <a href="%LINK%">%TITLE%</a> (%TIME%)', // template_event
'', // template_day
'j', // date_format
'<h2>%MONTH%</h2>' ); ?>
```
The link ... is only visible when the cursor is hovering over it. I suspect it is a style setting somewhere, but I can't figure out which one it is...
TIA for tips... | Use [firebug instector](http://getfirebug.com/) and you will find which style it is. | Try to find styles for `a` and `a:hover` in a css file (if any?). | Simple php/html question -- href not visible except when mouse is over | [
"",
"php",
""
] |
I have the following code:
```
newsplit.ToList().ForEach(x => x = "WW");
```
I would expect that all elements in the list are now "WW" but they are still the original value. How come? What do I have to do different? | Assuming that `newsplit` is an `IEnumerable<string>`, you want:
```
newsplit = newsplit.Select(x => "WW");
```
The code that you currently have is equivalent to the following:
```
foreach(string x in newsplit.ToList()) {
AssignmentAction(x);
}
...
public static void AssignmentAction(string x) {
x = "WW";
}
```
This method won't modify `x` because of the pass-by-value semantics of C# and the immutability of strings. | Other answers have explained why your current code doesn't work. Here's an extension method which would fix it:
```
// Must be in a static non-nested class
public static void ModifyEach<T>(this IList<T> source,
Func<T,T> projection)
{
for (int i = 0; i < source.Count; i++)
{
source[i] = projection(source[i]);
}
}
```
Then use like this:
```
newsplit.ModifyEach(x => "WW");
```
That will work with any implementation of `IList<T>` such as arrays and `List<T>`. If you need it to work with an arbitrary `IEnumerable<T>` then you've got a problem, as the sequence itself may not be mutable.
Using `Select()` is a more functional approach of course, but sometimes mutating an existing collection *is* worth doing... | Changing element value in List<T>.ForEach ForEach method | [
"",
"c#",
"linq",
"c#-3.0",
""
] |
i have againg a problem with completition. now i can't get any suggestion. Sure i can type var\_dump, but it is more comfortable with autocompletion.
I'm using Eclipse PHP Ide 3.5 with PDT 2.1. | I solved it....the problem is, that i import a project from subversion and its not e pure PHP Project. On PHP-Project is working fine. Yesterday i've imported the project first as PHP and not from Subversion ;) | Add "Core API" to "PHP Language Library" in Eclipse PHP Project.
***Solution***:
* Right click on your Eclipse PHP Project -> Properties -> PHP Build Path.
* Click on "Add Folder…", and select the source folders to use (application, library, public, …), and then click on "Ok".
* Click on "Ok" to save changes.
* Close Eclipse.
* Go to project path.
* Open ".buildpath" with text editor (gedit, VIM, notepad, etc).
* Add next line after "`<buildpath>`" line:
***`<buildpathentry kind="con" path="org.eclipse.php.core.LANGUAGE"/>`***
**Example**:
*Before*:
```
<?xml version="1.0" encoding="UTF-8"?>
<buildpath>
<buildpathentry kind="src" path="library"/>
<buildpathentry kind="src" path="public"/>
<buildpathentry kind="src" path="application"/>
</buildpath>
```
*After*:
```
<?xml version="1.0" encoding="UTF-8"?>
<buildpath>
<buildpathentry kind="con" path="org.eclipse.php.core.LANGUAGE"/>
<buildpathentry kind="src" path="library"/>
<buildpathentry kind="src" path="public"/>
<buildpathentry kind="src" path="application"/>
</buildpath>
```
* Save file and exit!
* Open Eclipse.
* WORK! | "No completions available" on var_ | [
"",
"php",
"eclipse",
"ide",
"autocomplete",
"eclipse-pdt",
""
] |
Is there a way to define a method, which is called everytime I call a get?
I have an Object Contact and don't want to set updateLastUsed(); in about 30 Getters for my Members. | I would have suggested AOP but if it's J2ME we're talking about you're most likely better off manually inserting "onGetCalled()" in each of your 30 accessors and then coding whatever you need within that method. You may want to pass in name of the method being called (or property accessed) in case you need it in the future. | Instead of accessing the getter for your properties, you could create one general getter that takes the property name as an input. The return type would need to be Object if your properties are of different types.
In this general getter you call the property getter and the updateLastUsed() method. To be safe make all property getters private. | Java Getters: Always execute specific method | [
"",
"java",
"java-me",
"getter",
""
] |
I can give it floating point numbers, such as
```
time.sleep(0.5)
```
but how accurate is it? If i give it
```
time.sleep(0.05)
```
will it really sleep about 50 ms? | The accuracy of the `time.sleep` function depends on your underlying OS's sleep accuracy. For non-real-time OSs like a stock Windows, the smallest interval you can sleep for is about 10-13ms. I have seen accurate sleeps within several milliseconds of that time when above the minimum 10-13ms.
Update:
Like mentioned in the docs cited below, it's common to do the sleep in a loop that will make sure to go back to sleep if it wakes you up early.
I should also mention that if you are running Ubuntu you can try out a pseudo real-time kernel (with the *RT\_PREEMPT* patch set) by installing the *rt kernel* package (at least in Ubuntu 10.04 LTS).
Non-real-time Linux kernels have minimum sleep intervals much closer to 1ms than 10ms, but it varies in a non-deterministic manner. | People are quite right about the differences between operating systems and kernels, but I do not see any granularity in Ubuntu and I see a 1 ms granularity in MS7. Suggesting a different implementation of time.sleep, not just a different tick rate. Closer inspection suggests a 1μs granularity in Ubuntu by the way, but that is due to the time.time function that I use for measuring the accuracy.
 | How accurate is python's time.sleep()? | [
"",
"python",
"time",
"sleep",
""
] |
In Python, I'm trying to extend the builtin 'int' type. In doing so I want to pass in some keywoard arguments to the constructor, so I do this:
```
class C(int):
def __init__(self, val, **kwargs):
super(C, self).__init__(val)
# Do something with kwargs here...
```
However while calling `C(3)` works fine, `C(3, a=4)` gives:
```
'a' is an invalid keyword argument for this function`
```
and `C.__mro__` returns the expected:
```
(<class '__main__.C'>, <type 'int'>, <type 'object'>)
```
But it seems that Python is trying to call `int.__init__` first... Anyone know why? Is this a bug in the interpreter? | The docs for the Python data model advise using `__new__`:
[object.**new**(cls[, ...])](http://docs.python.org/reference/datamodel.html#object.__new__)
> **new**() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.
Something like this should do it for the example you gave:
```
class C(int):
def __new__(cls, val, **kwargs):
inst = super(C, cls).__new__(cls, val)
inst.a = kwargs.get('a', 0)
return inst
``` | You should be overriding
`"__new__"`, not `"__init__"` as ints are immutable. | Python: extending int and MRO for __init__ | [
"",
"python",
"class-design",
"overriding",
""
] |
I wondered if anybody can come up with a shortened version for this code:
```
MyObject theObject = ObjectCollection.GrabAnObject();
if (theObject == null) return String.Empty;
else return theObject.myProperty;
```
Thank you! | ```
MyObject theObject = ObjectCollection.GrabAnObject();
return theObject == null ? String.Empty : theObject.myProperty;
``` | In c# 3.0 (framework 3.5) you can write:
```
return (ObjectCollection.GrabAnObject() ?? new MyObject(){ myProperty = ""} ).myProperty;
```
but I will write something more readable like:
return new MyObject(ObjectCollection.GrabAnObject())
and set the property accordly in the constructor
EDIT:
My memory make me a joke:
?? is not a c# 3.0 feature, but a 2.0 one ;)
[MSDN link](http://msdn.microsoft.com/en-us/library/ms173224%28VS.80%29.aspx) | C#: Shorten Code (Nullable Object, Return Property or String.Empty) | [
"",
"c#",
""
] |
Is there a way to read USB device serial number and data in a text file in USB using visual studio 2005? | Try this:
```
USBSerialNumber usb = new USBSerialNumber();
string serial = usb.getSerialNumberFromDriveLetter("f:\");
MessageBox.Show(serial);
```
Here's the internals for the USBSerialNumber class:
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace USBDriveSerialNumber {
public class USBSerialNumber {
string _serialNumber;
string _driveLetter;
public string getSerialNumberFromDriveLetter(string driveLetter) {
this._driveLetter = driveLetter.ToUpper();
if(!this._driveLetter.Contains(":")) {
this._driveLetter += ":";
}
matchDriveLetterWithSerial();
return this._serialNumber;
}
private void matchDriveLetterWithSerial() {
string[] diskArray;
string driveNumber;
string driveLetter;
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition");
foreach (ManagementObject dm in searcher1.Get()) {
diskArray = null;
driveLetter = getValueInQuotes(dm["Dependent"].ToString());
diskArray = getValueInQuotes(dm["Antecedent"].ToString()).Split(',');
driveNumber = diskArray[0].Remove(0, 6).Trim();
if(driveLetter==this._driveLetter){
/* This is where we get the drive serial */
ManagementObjectSearcher disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject disk in disks.Get()) {
if (disk["Name"].ToString() == ("\\\\.\\PHYSICALDRIVE" + driveNumber) & disk["InterfaceType"].ToString() == "USB") {
this._serialNumber = parseSerialFromDeviceID(disk["PNPDeviceID"].ToString());
}
}
}
}
}
private string parseSerialFromDeviceID(string deviceId) {
string[] splitDeviceId = deviceId.Split('\\');
string[] serialArray;
string serial;
int arrayLen = splitDeviceId.Length-1;
serialArray = splitDeviceId[arrayLen].Split('&');
serial = serialArray[0];
return serial;
}
private string getValueInQuotes(string inValue) {
string parsedValue = "";
int posFoundStart = 0;
int posFoundEnd = 0;
posFoundStart = inValue.IndexOf("\"");
posFoundEnd = inValue.IndexOf("\"", posFoundStart + 1);
parsedValue = inValue.Substring(posFoundStart + 1, (posFoundEnd - posFoundStart) - 1);
return parsedValue;
}
}
}
```
Source: <http://www.cfdan.com/posts/Retrieving_Non-Volatile_USB_Serial_Number_Using_C_Sharp.cfm> | Or, you can do it with much less code, here's the sample:
```
string driveletter = "D:";
var index = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition").Get().Cast<ManagementObject>();
var disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive").Get().Cast<ManagementObject>();
string serial = "";
try
{
var drive = (from i in index where i["Dependent"].ToString().Contains(driveletter) select i).FirstOrDefault();
var key = drive["Antecedent"].ToString().Split('#')[1].Split(',')[0];
var disk = (from d in disks
where
d["Name"].ToString() == "\\\\.\\PHYSICALDRIVE" + key &&
d["InterfaceType"].ToString() == "USB"
select d).FirstOrDefault();
serial = disk["PNPDeviceID"].ToString().Split('\\').Last();
}
catch
{
//drive not found!!
}
Response.WriteLine(serial);
``` | Read USB Device Serial number in C# | [
"",
"c#",
"visual-studio-2005",
"usb-drive",
""
] |
What's better way to format following sql statement considering both readability and performance. Thanks.
```
sql = (char *)" SELECT * ,rowid FROM tblEvent_basic "
" WHERE "
" service_id = ? AND "
" ("
" (start_time >= ? AND start_time <= ?) OR "
" (end_time > ? AND end_time <?) OR "
" (start_time < ? AND end_time > ?)"
" )"
" ORDER by start_time ASC";
```
EDIT:
1.sqlite3 Database engine ; using C API ;running on MIPS24K 250M Embedded CPU.
2.the 2nd , 4th , 6th parameter is same , and 3rd, 5th, 7th is same.
```
rc = sqlite3_bind_int(sql_stmt,1,service_id);
rc = sqlite3_bind_text(sql_stmt,2,ts.start, 5, SQLITE_TRANSIENT);
rc = sqlite3_bind_text(sql_stmt,3,ts.end , 5, SQLITE_TRANSIENT);
rc = sqlite3_bind_text(sql_stmt,4,ts.start, 5, SQLITE_TRANSIENT);
rc = sqlite3_bind_text(sql_stmt,5,ts.end , 5, SQLITE_TRANSIENT);
rc = sqlite3_bind_text(sql_stmt,6,ts.start, 5, SQLITE_TRANSIENT);
rc = sqlite3_bind_text(sql_stmt,7,ts.end , 5, SQLITE_TRANSIENT);
``` | Your temporal condition is currently:
```
" (start_time >= ? AND start_time <= ?) OR "
" (end_time > ? AND end_time <?) OR "
" (start_time < ? AND end_time > ?)"
```
We can immediately improve the readability (in constant width fonts) with some spaces:
```
" (start_time >= ? AND start_time <= ?) OR "
" (end_time > ? AND end_time < ?) OR "
" (start_time < ? AND end_time > ?)"
```
And from the commentary, we know that the same value will be passed to the placeholders 1, 3, 5, and a different value will be passed to placeholders 2, 4, 6 (but they all get the same value too). Further, if we call those times `t1` and `t2`, then we can assume that `t1 <= t2`.
So, what is this criterion looking for?
* start time falls in the range t1..t2
* end time falls in the range t1..t2
* start time is earlier than t1 and end time is later than t2
This is an overlaps criterion written the hard way - it should be replaced by:
```
"(start_time <= ? AND end_time >= ?)"
```
Except that placeholder one here corresponds to `t2` and placeholder two corresponds to `t1`. If you don't want events that meet the time range to be counted (that is, you do not want to count an event that ended at the instant `t1`, or an event that started at the instant `t2`), then change the '`>=`' and '`<=`' into '`>`' and '`<`' respectively.
This is the standard way of writing the overlaps predicate when including the end times.
The condition is much simpler - no OR terms - and is reliable. It will be faster in that the optimizer has less work to do, and possibly that the execution engine will have fewer criteria to apply. (A really good optimizer might spot the equivalence of the 2-placeholder and 6-placeholder versions, but I wouldn't want to bet on it doing so - not least because the optimizer cannot tell that placeholders 1,3,5 will be the same, nor that placeholders 2,4,6 will be the same; that can only be determined if it bothered to reoptimize when the statement is executed.) | For starters, you could use BETWEEN instead of >= and <=. This would make the query *much* more readable, without any impact on performance. As far as optimizing the query for performance, you should look into using your database's equivalent of the EXPLAIN plan to give you some pointers on where your query is taking most of its time. | What is the recommended way to write this sql statement? | [
"",
"sql",
"c",
"sqlite",
""
] |
Is there any way to detect search engines or crawlers on my site.
i have seen in **phpBB** at the admin we can see and allow search engines and also we can see the last visit of the bot(like Google Bot).
any script in PHP?
Not Google Analytic or same kind of application.
i need to implement that for my blog site, i think there is some way to find out? | You can go by either IP addresses or the 'User-Agent' string that the bot or web browser sends you.
When Googlebot (or most other well-behaving robots) visit your website, they'll send you a $\_SERVER['HTTP\_USER\_AGENT'] variable which identifies what they are. Some examples are:
Googlebot/2.1 (+<http://www.google.com/bot.html>)
NutchCVS/0.8-dev (Nutch; <http://lucene.apache.org/nutch/bot.html>
Baiduspider+(+<http://www.baidu.com/search/spider_jp.html>)
Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/531.4 (KHTML, like Gecko)
You can find many more examples at these websites:
[link text](http://www.user-agents.org/)
[link text](http://user-agent-string.info/)
You could then use PHP to examine those user-agent strings and determine if the user is a search engine or not. I use something like this often:
```
$searchengines = array(
'Googlebot',
'Slurp',
'search.msn.com',
'nutch',
'simpy',
'bot',
'ASPSeek',
'crawler',
'msnbot',
'Libwww-perl',
'FAST',
'Baidu',
);
$is_se = false;
foreach ($searchengines as $searchengine){
if (!empty($_SERVER['HTTP_USER_AGENT']) and
false !== strpos(strtolower($_SERVER['HTTP_USER_AGENT']), strtolower($searchengine)))
{
$is_se = true;
break;
}
}
if ($is_se) { print('Its a search engine!'); }
```
Remember that no detection method (Google Analytics or another statistics package or otherwise) is going to be 100% accurate. Some web browsers allow you to set a custom user-agent string, and some misbehaving web crawlers may not send a user-agent string at all. This method can be probably effective for 95%+ of crawlers/visitors though. | 1. You can try to detect them using their user-agent string. A list of them can be found here: <http://www.botsvsbrowsers.com/>
Search engines tend to use the words *crawler* and *robot*.
2. Search engines are almost the only internet user that visit [robots.txt](http://www.robotstxt.org/).
3. There are some IPs known to be bots like the GoogleBot. | how to detect search engine visites on my site? like phpBB | [
"",
"php",
"web-crawler",
""
] |
I am building a product catalog for a customer website under ASP.NET using .NET Framework 3.5 SP1. Each product has a part number and an OEM part number (all globally unique).
For SEO purposes I would like the OEM part number to be as close as possible to the actual domain name.
How do I build a routing rule that allows me to do this:
```
http://www.myDomain.com/oemPartNumber
http://www.myDomain.com/myPartNumber
```
while still being able to do this:
```
http://www.myDomain.com/welcome
http://www.myDomain.com/products
http://www.myDomain.com/services
http://www.myDomain.com/contact
```
I would also love to hear your other SEO suggestions (we are primarily interested in Google) if you have any.
Thanks.
**IMPORTANT: This not an MVC site, so I don't have controllers.** | You should be able to specify something like <http://www.mydomain.com/oempartnumber/oem> and <http://www.mydomain.com/mypartnumber/pn>. There must be something in the url that allows you to choose the controller you want to use and further more allow you to distinguish between a part number and an oem part number (unless those are also unique against one another. If there will never be overlap between oem and pn then you could have <http://www.mydomain.com/>{partnumber}/pn.
```
RouteTable.Routes.Add(new Route
{
Url = "[query]/pn",
Defaults = new { controller="PartNumber", action = "Details" },
RouteHandler = typeof(MvcRouteHanderl)
});
```
You could use some trickery with a route like this:
```
routes.MapRoute(
"Part number",
"{partNumber}",
new { controller = "Part", action = "Display" },
new
{
partNumber = @"\d+" // part number must be numeric
}
);
```
But the problem here is that an OEM part number that is not actually a part number (such as "ave-345") would not match!
**UPDATE:** In reading I noticed that you said "this is not an MVC site so I don't have controllers!"...OH! That changes things. In that case you can check to see if the directory exists where you pass in <http://www.mydomain.com/1234> and if not you can test it for a product number. This would have to be done in a HttpModule though so you can catch it before your page is executed. Then on the server side you can direct the page to <http://www.domain.com/productdetails?pid=1234>.
Take a look here to understand that: <http://www.15seconds.com/Issue/020417.htm>
For this you will have a class that inherits from IHttpModule. Then you can specify an Init method
```
public void Init(HttpApplication application)
{
//let's register our event handler
application.PostResolveRequestCache +=
(new EventHandler(this.Application_OnAfterProcess));
}
```
This then points to your Applicaton\_OnAfterProcess method:
private void Application\_OnAfterProcess(object source, EventArgs e)
```
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
...
```
Inside of here you can specify some rules about what you are looking for.
I usually do something along the lines of
```
if (!System.IO.File.Exists(application.Request.PhysicalPath)) //doesn't exist
{
//you test for your product ID here
...
//if you find it stuff it into a ProductID variable for later...
```
Once you isolate your product ID you can then rewrite the URL (server side) and direct the user to the proper productDetails.aspx page.
```
context.RewritePath("~/products/productDetails.aspx?ProductID=" + ProductID.ToString());
```
So while the user and google sees <http://www.mydomain.com/1234> your application will see <http://www.mydomain.com/products/productdetails.aspx?productid=1234> and you can code against it as usual.
I hope this is what you were looking for instead! | If there are specific formats to the part numbers you can use regex constraints on the route like this:
```
routes.MapRoute(
"Part number",
"{partNumber}",
new { controller = "Part", action = "Display" },
new
{
partNumber = @"\d+" // part number must be numeric
}
);
```
Text like "welcome" won't match the regex and so will ignore this route. | Routing Rule for ASP.NET Products Website | [
"",
"c#",
".net",
"asp.net",
".net-3.5",
"seo",
""
] |
```
$items = "word1 word2 word3 word4";
$items = explode(" ", $items);
```
$items is my array, how can I have it turn into this
Like how can I make word1 be a key and a value?
```
"word1" => "word1"
``` | `$newArray =` [`array_combine`](http://php.net/array_combine)`($items, $items);` | ```
foreach($items as $item) {
$newArr[$item] = $item;
}
``` | How to build this php array? | [
"",
"php",
"arrays",
""
] |
I am completely new to C++ development and am trying to learn it in Visual Studio. How can I be sure that I am learning only C++ and not the managed extensions? What configuration settings do I need to change? What project types should I stick to? Any other advice?
**Side issue:**
I have tried turning off Language Extensions under
> Project properties -> C/C++ -> Language -> Disable Language Extensions
but this has generated a compiler error:
> Error 1 Command line error D8016 : '/Za' and '/clr' command-line options are incompatible
I've no idea what's going on here .. | The fact that you have `/clr` switch in there means you're using a .Net project type - you need to choose a "Win32" project type to get a pure C++ project.
Avoid anything calling itself "managed" or "CLR". | In brief, all the Win32 C++ projects are native C++.
The ones including CLR in the name are managed C++.
Language extensions are nothing to do with .NET. It is a number of vendor-specific extensions to native C++. (So the effect of disabling language extensions is roughly similar specifying --ansi with the G++ compiler)
/clr is the flag you need to get rid of. | How to configure Visual Studio for native C++ (unmanaged) development? | [
"",
"c++",
"visual-studio",
""
] |
I'm about to start developing a small Windows application using Microsoft Visual C# 2008 (Express edition). I'm very new to C# and .NET, so this is a newbie question. Should I start with WPF or should I stick with the old WinForms?
My application has several screens, all having several text-boxes, check-boxes, combo-boxes, not anything more. The application will retrieve data from several COM objects, and communicate through standard TCP/IP sockets, both of which are unrelated to the UI.
The UI is not fancy in any way (and I don't need it to be). However, the world seems to be moving to WPF. What are the considerations of choosing WPF over WinForms for my case? What's the recommended approach?
Thanks | Interesting, how all answers target the developer: familiarity with a framework, the learning curve, the technical features of a framework etc.
If it's a simple application, none of the technical aspects really matter. You sound like you have some experience programming, in that case the chosen framework doesnt really matter. Focus on your users instead.
Can you guarantee that your users have the latest .net runtime installed? Are they willing/able to install it if they dont?
Will your users be put off by an "outdated" look and feel?
The way you phrased your question, i think you should use WinForms. You seem to imply ("stick with winforms") that you have experience in WinForms and that you dont have any fancy demands for the UI, so i see no reason to put yourself on a steep learning curve that WPF can be. | I have not used Forms enough to say anything about which is better, but I have found WPF to be easy enough to use for minor applications.
I figure that if it's the standard people are moving towards and it's not difficult, then it's good practice to start using it. | Simple non-fancy Windows application - should I start with WPF or WinForms? | [
"",
"c#",
"wpf",
"winforms",
""
] |
Suppose we want to loop through all the items in a dropdown list and no item is added or removed while we are looping. The code for it is as follows:
```
for (int i = 0; i < ddl.Items.Count; i++)
{
if (ddl.Items[i].Text == text)
{
found = true;
break;
}
}
```
If it is changed to this:
```
for (int i = 0, c = ddl.Items.Count; i < c; i++)
{
if (ddl.Items[i].Text == text)
{
found = true;
break;
}
}
```
Is there any performance gain? Does the compiler do something *clever* not to read the `Count` property every iteration? | I suggest another optimization. Cache the value of `Items` property. If `Items` property itself is performance intensive (as some WinForms properties are, contrary to how they look), it can be very inefficient to loop. For instance, see: [why foreach is faster than for loop while reading richtextbox lines](https://stackoverflow.com/questions/1136825/why-foreach-is-faster-than-for-loop-while-reading-richtextbox-lines/1136830#1136830).
Also, if you don't need the index, why don't you use `foreach`. It's easier to read and less prone to errors. | I've read that the JIT compiler is smart enough to figure out you are looping through the entire array and would therefore skip emitting bounds checking code inside the body of the loop.
It *might* not be smart enough to figure that out in the second case.
I guess the best answer is to profile it and see for yourself. | Loop Boundries and Performance Issues | [
"",
"c#",
"performance",
"loops",
""
] |
Suppose I have the following line of code in html, how to set the text color and size inside "MonitorInformation" DIV element in a programming way using Javascript in an easy way? Sorry for my stupid, I figured a long time but cannot figure out. :-(
```
<div id="MonitorInformation">Connecting...wait</div>
```
thanks in advance,
George | ```
var elem = document.getElementById("MonitorInformation");
elem.innerHTML = "Setting different HTML content";
elem.style.color = "Red";
elem.style.fontSize = "large";
``` | ```
var myDiv = document.getElementById("MonitorInformation");
myDiv.style.fontSize = "11px";
myDiv.style.color = "blue";
```
Take a look at the [JavaScript Style Attributes](http://www.comptechdoc.org/independent/web/cgi/javamanual/javastyle.html) | set html text color and size using javascript | [
"",
"javascript",
"html",
""
] |
I have a Customer class with a string property comments and I am trying to bind it like this:
```
<asp:TextBox ID="txtComments"
runat="server"
TextMode="MultiLine" Text=<%=customer.Comments %>>
</asp:TextBox>
```
However, it gives me the error:
Server tags cannot contain <% ... %> constructs.
I also have a method in the class called GetCreatedDate and in the aspx page, I am doing
<%=GetCreatedDate()%> and <%GetCreatedDate();%>. What is the difference? | Alternatively you can set the value in the Page\_Load event of the code behind file:
```
txtComments.Text = customer.Comments;
``` | you should use "<%# %>" for data binding
```
<asp:TextBox ID="txtComments"
runat="server"
TextMode="MultiLine" Text="<%# customer.Comments %>">
</asp:TextBox>
``` | How to bind a classes property to a TextBox? | [
"",
"c#",
"asp.net",
""
] |
```
<script>
var personX = 18;
var personY = 13;
function processArrowKeys(E) {
if (E.keyCode == 37 || E.keyCode == 38 || E.keyCode == 39 || E.keyCode==40) {
E.preventDefault();
}
if (E.keyCode == 37) {
if (currentterrain[personX - 1][personY] == 0 || currentterrain[personX - 1][personY] == 1 || currentterrain[personX - 1][personY] == 3) {
personX--;
}
}
if (E.keyCode == 39) {
if (currentterrain[personX + 1][personY] == 0 || currentterrain[personX + 1][personY] == 1 || currentterrain[personX + 1][personY] == 3) {
personX++;
}
}
if (E.keyCode == 38) {
for (i = 0; i < 3; i++) {
if (currentterrain[personX][personY - 1] == 0 || currentterrain[personX][personY - 1] == 1 || currentterrain[personX][personY - 1] == 3) {
personY--;
}
}
}
}
</script>
<body onkeydown="processArrowKeys(event)">
```
The IE debugger says that it expects an object and brakes on "handleArrowKeys(event)".
This works in FF and Chrome
I don't know why this fails, but it does. | changing this line fixed it:
```
if(E.keyCode==37||E.keyCode==38||E.keyCode==39||E.keyCode==40){if(navigator.appName!="Microsoft Internet Explorer"){E.preventDefault();}}
```
IE must not work with `preventDefault()` | Try the following:
```
/* ... */
function processArrowKeys(E) {
if (!E) E = window.event;
/* ... */
``` | JavaScript keydown error in IE | [
"",
"javascript",
"events",
""
] |
I have a native C Dll that calls 'LoadLibrary' to load another Dll that has the /clr flag turned on. I then use 'GetProcAddress' to get a function and call it on dynamically loaded dll. I would like to step into the dynamic library in the debugger, but the symbols never load. Any idea?
And I should have said I'm using Visual Studio 2008.
Update: Thanks to some tips below, I changed the project debugging to Mixed. It didn't work, but I think I know why. I am developing an addin to an existing application. The app I'm connecting to starts one exe then it starts another. So I have to use "Attach to process" to fire up the debugger. My guess is launching the debugger that way will default to "Auto". **Is there a way to change the default behavior of VS to use "Mixed" debugging?** | This is from VS2008, but if I remember correctly VS2005 was similar. In the native project's properties, under "Configuration Properties->Debugging" there is a "Debugger Type" which is set to "Auto" by default. You'll need to change it to "Mixed", because VS isn't smart enough to realize you need managed debugging | I've had mixed experiences with doing similar things like this in VisualStudio. You might consider using ProcMon to see where VisualStudio is looking for the PDB file. Alternatively, you might try using WinDbg. It seems to do better at loading symbols and if it doesn't, you can explicitly load them yourself. Using WinDbg involves riding a steep learning curve, but if you're burning time right now, isn't it worth it?
You can also run the exe on its own and from the source of the managed dll, attach to the process to debug it. | Native C/Managed C++ Debugging | [
"",
"c++",
"visual-studio",
"clr",
""
] |
Can't get my head around the parameter passing in Autofac, the following code doesn't work:
```
class Config {
public Config(IDictionary<string, string> conf) {}
}
class Consumer {
public Consumer(Config config) {}
}
void Main()
{
var builder = new Autofac.Builder.ContainerBuilder();
builder.Register<Config>();
builder.Register<Consumer>();
using(var container = builder.Build()){
IDictionary<string,string> parameters = new Dictionary<string,string>();
var consumer = container.Resolve<Consumer>(Autofac.TypedParameter.From(parameters));
}
}
```
that throws:
```
DependencyResolutionException: The component 'UserQuery+Config' has no resolvable constructors. Unsuitable constructors included:
Void .ctor(System.Collections.Generic.IDictionary`2[System.String,System.String]): parameter 'conf' of type 'System.Collections.Generic.IDictionary`2[System.String,System.String]' is not resolvable.
```
but the following code *does* work:
```
IDictionary<string,string> parameters = new Dictionary<string,string>();
var config = container.Resolve<Config>(Autofac.TypedParameter.From(parameters));
var consumer = container.Resolve<Consumer>(Autofac.TypedParameter.From(config));
``` | Repeating here the answer from the Autofac mailing list:
The parameters passed to Resolve only related to the direct implementer of
the service you're resolving, so passing Config's parameters to the resolve
call for Consumer won't work.
The way around this is to change your Consumer registration to:
```
builder.Register((c, p) => new Consumer(c.Resolve<Config>(p)));
``` | Autofac is obviously trying to resolve the parameter of your Config class in the assumption that the Dictionary itself is a resolvable type. I do not know the autofac syntax on how to do it. But you probably need to do more steps when registring the Config type, e. g. giving it a delegate that passes in a new Dictionary. | Autofac parameter passing and autowiring | [
"",
"c#",
"dependency-injection",
"autofac",
""
] |
I have a problem sending plain text emails using PHPMailer.
I have text that I read from a text file and mail it to mail recipient via PHPMailer
When the recipient gets the actual email, the formatting of the mail is not like in the text file, everything is in one line, no new lines and tabs are included in the email that I send. Text wrapping is totally off.
Code:
```
$mail->ContentType = 'text/plain';
$mail->IsHTML(false);
$address = "test@test.com";
$mail->AddAddress($address, "John Doe");
$mail->SetFrom(EMAIL_TEST_FROM);
$mail->AddReplyTo(EMAIL_TEST_REPLY);
$mail->Subject = $action." REGISTRATION ".$formName.$tld;
$mail->From = EMAIL_TEST;
$mail->MsgHTML(file_get_contents($newFile));
if($mail->Send()){
return true;
}
``` | You are setting `$mail->MsgHTML()` to a plain text message, and since whitespace formatting is ignored in HTML, you're getting an inline text.
I haven't used PHPMailer for a while, but from memory try:
```
$mail->Body = file_get_contents($newFile);
``` | ```
$mail->ContentType = 'text/plain';
$mail->IsHTML(false);
$address = "test@test.com";
$mail->AddAddress($address, "John Doe");
$mail->SetFrom(EMAIL_TEST_FROM);
$mail->AddReplyTo(EMAIL_TEST_REPLY);
$mail->Subject = $action." REGISTRATION ".$formName.$tld;
$mail->From = EMAIL_TEST;
// Very important: don't have lines for MsgHTML and AltBody
$mail->Body = file_get_contents($mailBodyTextFile);
// $mail->Body = $_POST["msg"]; //If using web mail form, use this line instead.
if($mail->Send()){
return true;
}
``` | Sending Plain text emails using PHPMailer | [
"",
"php",
"email",
"formatting",
"phpmailer",
"plaintext",
""
] |
In Java, for example, the `@Override` annotation not only provides compile-time checking of an override but makes for excellent self-documenting code.
I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python? | **Based on this and fwc:s answer I created a pip installable package <https://github.com/mkorpela/overrides>**
From time to time I end up here looking at this question.
Mainly this happens after (again) seeing the same bug in our code base: Someone has forgotten some "interface" implementing class while renaming a method in the "interface"..
Well Python ain't Java but Python has power -- and explicit is better than implicit -- and there are real concrete cases in the real world where this thing would have helped me.
So here is a sketch of overrides decorator. This will check that the class given as a parameter has the same method (or something) name as the method being decorated.
If you can think of a better solution please post it here!
```
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
```
It works as follows:
```
class MySuperInterface(object):
def my_method(self):
print 'hello world!'
class ConcreteImplementer(MySuperInterface):
@overrides(MySuperInterface)
def my_method(self):
print 'hello kitty!'
```
and if you do a faulty version it will raise an assertion error during class loading:
```
class ConcreteFaultyImplementer(MySuperInterface):
@overrides(MySuperInterface)
def your_method(self):
print 'bye bye!'
>> AssertionError!!!!!!!
``` | As of python 3.12 (release date fall 2023) this can be done. I would suggest you to look at this website <https://peps.python.org/pep-0698/>. It explains really well how to decorate methods in Python like in Java.
Here a code example, for more details you can check out the website above.
```
from typing import override
class Parent:
def foo(self) -> int:
return 1
def bar(self, x: str) -> str:
return x
class Child(Parent):
@override
def foo(self) -> int:
return 2
@override
def baz() -> int: # Type check error: no matching signature in ancestor
return 1
``` | In Python, how do I indicate I'm overriding a method? | [
"",
"python",
"inheritance",
"overriding",
"self-documenting-code",
""
] |
I'd like to send HTTP POST request to website and retrieve the resultant page using winapi. How can I do that? | The MSDN docs have sample code using WinHTTP:
* [IWinHttpRequest::Send Method](http://msdn.microsoft.com/en-us/library/aa384045(VS.85).aspx)
* [Posting Data to the Server](http://msdn.microsoft.com/en-us/library/aa384270(VS.85).aspx#Posting_data_to_the_) | Also consider using something like [Libwww](http://www.w3.org/Library/) or [libcurl](http://curl.haxx.se/). | How to send POST request to some website using winapi? | [
"",
"c++",
"c",
"winapi",
"post",
""
] |
We are trying to implement Oracle connection pooling with the help of Spring Framework. We are using DBCP connection pooling method. However the integration between DBCP and spring doesn't go down that well.
Problem that we face is that DBCP returns PoolableConnections Object while Oracle expects OracleConnection Objects. (Throws ClassCastException)
It seems that this problem has been handled in Oracle 11g. However I am curious as to how others have implemented Oracle connection pooling using spring framework for Oracle 10g (Using TOMCAT).
We use Ibatis as ORM framework.
I am sure there is a way. any help is appreciated. | I would use Oracles supplied solution, which in included in their ojdbc jars. The older way was with the class **OracleConnectionPoolDataSource** but now you can set a parameter on a regular **OracleDataSource** and get connection pooling.
Here is how to do it in Spring:
```
<bean id="datasource" class="oracle.jdbc.pool.OracleDataSource" destroy-method="close">
<property name="connectionCachingEnabled" value="true" />
<property name="URL" value="${jdbc.url}" />
...all your connection properties
<property name="connectionCacheProperties">
<props merge="default">
<prop key="MinLimit>3</prop>
<prop key="MaxLimit">20</prop>
</props>
</property>
</bean>
``` | I use C3PO to establish the connection. It has also the advantage to do connection pooling for you. Just define a *datasource* bean of type e.g. com.mchange.v2.c3p0.ComboPooledDataSource (or similar) through your spring config files. Before I run into troubles with connection pooling, I even used one of spring (DriverManagerDataSource) that is not advised for production use, because it is not actually doing the connection pooling.
Here is an example spring configuration.
```
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
<property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:XE"/>
<property name="user" value="username"/>
<property name="password" value="secret"/>
<property name="minPoolSize" value="5"/>
<property name="maxPoolSize" value="20"/>
<property name="acquireIncrement" value="1"/>
<property name="idleConnectionTestPeriod" value="100"/>
<property name="maxStatements" value="0"/>
<property name="checkoutTimeout" value="60000"/>
```
Spring then injects the dataSource bean into Hibernate and all is well. You will also need to have the c3pO jar file on your classpath... | Oracle - connection Pooling with spring framework | [
"",
"java",
"spring",
"tomcat",
"oracle10g",
"ibatis",
""
] |
I know I could use a `for` statement and achieve the same effect, but can I loop backwards through a `foreach` loop in C#? | When working with a list (direct indexing), you cannot do it as efficiently as using a `for` loop.
Edit: Which generally means, when you are *able* to use a `for` loop, it's likely the correct method for this task. Plus, for as much as `foreach` is implemented in-order, the construct itself is built for expressing loops that are independent of element indexes and iteration order, which is particularly important in [parallel programming](http://msdn.microsoft.com/en-us/library/dd321840.aspx). It is *my opinion* that iteration relying on order should not use `foreach` for looping. | If you are on .NET 3.5 you can do this:
```
IEnumerable<int> enumerableThing = ...;
foreach (var x in enumerableThing.Reverse())
```
It isn't very efficient as it has to basically go through the enumerator forwards putting everything on a stack then pops everything back out in reverse order.
If you have a directly-indexable collection (e.g. IList) you should definitely use a `for` loop instead.
If you are on .NET 2.0 and cannot use a for loop (i.e. you just have an IEnumerable) then you will just have to write your own Reverse function. This should work:
```
static IEnumerable<T> Reverse<T>(IEnumerable<T> input)
{
return new Stack<T>(input);
}
```
This relies on some behaviour which is perhaps not that obvious. When you pass in an IEnumerable to the stack constructor it will iterate through it and push the items onto the stack. When you then iterate through the stack it pops things back out in reverse order.
This and the .NET 3.5 `Reverse()` extension method will obviously blow up if you feed it an IEnumerable which never stops returning items. | Possible to iterate backwards through a foreach? | [
"",
"c#",
"foreach",
""
] |
I'm trying to customize the look of a checkbox in WPF. I was hoping I could grab the default control template for the BulletChrome class that's defined in PresentationFramework.Aero and work with that. However, BulletChrome is not a sublcass of Control, so there's no template to modify. Does anyone know I could do this? | If you want to place some sort of [BulletChrome](http://msdn.microsoft.com/en-us/library/microsoft.windows.themes.bulletchrome.aspx) in CheckBox' Template where the [BulletDecorator](http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.bulletdecorator.aspx) in the classic Template would go, you could do that, since BulletChrome inherits from [Decorator](http://msdn.microsoft.com/en-us/library/system.windows.controls.decorator.aspx), which inherits from [FrameworkElement](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.aspx).
The next part, how does the BulletChrome get its looks? Well, this is one of the rare parts from WPF where they handle rendering completely without xaml: The ButtonChrome's visual appearance is defined in its [`OnRender()`](http://msdn.microsoft.com/en-us/library/system.windows.uielement.onrender.aspx) method.
BulletChrome.OnRender(), from Reflector:
```
protected override void OnRender(DrawingContext drawingContext)
{
Rect bounds = new Rect(0.0, 0.0, base.ActualWidth, base.ActualHeight);
this.DrawBackground(drawingContext, ref bounds);
this.DrawDropShadows(drawingContext, ref bounds);
this.DrawBorder(drawingContext, ref bounds);
this.DrawInnerBorder(drawingContext, ref bounds);
}
```
Unfortunately, since all these methods called inside OnRender() are private, you can't mess with them even if you subclass the ButtonChrome, perhaps only overlay some of your rendering on top.
So basically, you either start digging through rendering code in Reflector and try to adapt and rewrite it to your needs, or roll your own Template/Decorator/whatever from scratch. (But then it really isn't important what you use as long as it works, right?)
Hope this answered your question, cheers. | You don't want to do this. Changing the control template is not supposed to change the behavior of the control, and a CheckBox control, by definition has three states (Checked, Unchecked, Indeterminate).
You're better off creating a custom 4-state (or n-state if you prefer) Control that borrows alot of Look/Feel from the CheckBox ControlTemplate. | Customizing the BulletChrome element in WPF | [
"",
"c#",
"wpf",
""
] |
I have a table in my database that has about 200 rows of data that I need to retrieve. How significant, if at all, is the difference in efficiency when retrieving all of them at once in one query, versus each row individually in separate queries? | The queries are usually made via a socket, so executing 200 queries instead of 1 represents a lot of overhead, plus the RDBMS is optimized to fetch a lot of rows for one query.
200 queries instead of 1 will make the RDBMS initialize datasets, parse the query, fetch one row, populate the datasets, and send the results 200 times instead of 1 time.
It's a lot better to execute only one query. | I think the difference will be significant, because there will (I guess) be a lot of overhead in parsing and executing the query, packaging the data up to send back etc., which you are then doing for every row rather than once.
It is often useful to write a quick test which times various approaches, then you have meaningful statistics you can compare. | Difference in efficiency of retrieving all rows in one query, or each row individually? | [
"",
"php",
"mysql",
""
] |
If I want to do an admin function like delete a user on the asp.net membership stuff that ships with the asp.net mvc sample.
I tried looking through the tables and realized that there was multiple tables that had rows added. I assume there must be a simpler way. | In your Membership provider there is a method:
```
public bool DeleteUser(string username, bool deleteAllRelatedData)
```
If this is the standard asp.net membership provider that method runs a stored proc that cleans the user from your DB.
Here is some more examples:
<https://web.archive.org/web/20210304121422/https://www.4guysfromrolla.com/articles/091207-1.aspx> | Use the [Membership API's](http://msdn.microsoft.com/en-us/library/ms998347.aspx#paght000022_membershipapis).
To delete a user, use the [Membership.DeleteUse](http://msdn.microsoft.com/en-us/library/w6b0zxdw.aspx)r method
```
Membership.DeleteUser(User.Identity.Name, true);
``` | Asp.net membership | [
"",
"asp.net",
"sql",
"asp.net-mvc",
"asp.net-membership",
""
] |
I'm working on a plugin that, when TinyMCE is in use as the Visual editor, uses TinyMCE commands to insert text into body content editing area. Currently, it works by just running the command. If it works, then TinyMCE is active and if not, then I have custom JS for working with the HTML editor.
My question, however: is there any way to check whether TinyMCE is active or not instead of just running the command and having it fail when it isn't? | And... I've answered the question for myself. The conditional you want to test for is as follows:
```
is_tinyMCE_active = false;
if (typeof(tinyMCE) != "undefined") {
if (tinyMCE.activeEditor == null || tinyMCE.activeEditor.isHidden() != false) {
is_tinyMCE_active = true;
}
}
```
The trick is that `tinyMCE.activeEditor` returns null when TinyMCE isn't activated. You can use the `isHidden()` method to make sure it isn't executing when you've switched back to HTML editor mode.
This is poorly documented on the TinyMCE website and forums. | Yes, I saw that code on wordpress: ABSPATH/wp-includes/js/autosave.js file
```
// (bool) is rich editor enabled and active
var rich = (typeof tinyMCE != "undefined") && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden();
``` | Way to check whether TinyMCE is active in WordPress | [
"",
"javascript",
"wordpress",
"tinymce",
""
] |
```
$dir_handle = @opendir($url) or die("Unable to open $url");
$count = "0";
while ($file = readdir($dir_handle)) {
if (!is_dir($url.'/'.$file) && ($file="*.jpg" || $file="*.gif" || $file="*.png") && $file!="picture0.*") {
$galleryEventFile[$count] = $file;
$count++;
}
}
closedir($dir_handle);
```
I think it has something to do with this line:
```
if (!is_dir($url.'/'.$file) && ($file="*.jpg" || $file="*.gif" || $file="*.png") && $file!="picture0.*")
```
but im not sure | I can see two things that will be causing you problems:
**Assignment/comparison:**
You have the code:
```
if ($file="*.jpg" //etc...
```
However, a single equal sign will perform an assignment, not a comparison - you need to use two equals signs (==) for this. See <http://php.net/manual/en/language.operators.comparison.php>. Essentially what you are doing by doing an assignment in an if statement is:
```
$file = '*.jpg';
if ($file) { }
```
**Wildcard matching of strings**
You also can't do wildcard matching like that ($file == "\*.jpg) on a string, you could look at using preg\_match() and regular expressions instead, e.g.
```
if (!preg_match('/\.jpg$/i', $file)) {
//not .jpg
}
```
It might be better to do something like this though:
```
//get file extension
$extension = pathinfo($file, PATHINFO_EXTENSION);
$allowedExtensions = array('jpg', 'png', 'gif');
//check in allowed list
if (!in_array(strtolower($extension), $allowedExtensions)) {
//not valid
}
``` | First, $count should be a number. Do:
```
$count = 0;
```
Second, AFAIK, PHP doesn't support wildcard matching like that. You can't use `"*"` to match. You'll need to use regular expressions to match in the conditional. | Why is $count not updating? | [
"",
"php",
"readdir",
""
] |
I have an `array[]` of objects, for certain reasons I cannot change it to a `List<>`, is it possible to sort on the `array[]` of objects, based on a value in 1 field of the object?
For example
```
arrayOfFruit[] fruit;
fruit.sort(name);
``` | Use Array..::.Sort Method (Array, IComparer)
<http://msdn.microsoft.com/en-us/library/aw9s5t8f.aspx> | If you want a clean distinction of the *selector* and *comparer*, you can use this helper class. It's too bad you can't have a "class extension method" to give `Array.Sort` a set of overloads that take a selector.
```
public static class SelectingComparer<T>
{
public static IComparer<T> Create<U>(Func<T, U> selector)
{
return new SelectingComparerImpl<U>(selector, null);
}
public static IComparer<T> Create<U>(Func<T, U> selector, IComparer<U> comparer)
{
return new SelectingComparerImpl<U>(selector, comparer.Compare);
}
public static IComparer<T> Create<U>(Func<T, U> selector, Comparison<U> comparison)
{
return new SelectingComparerImpl<U>(selector, comparison);
}
private class SelectingComparerImpl<U>
: IComparer<T>
{
private Func<T, U> selector;
private Comparison<U> comparer;
public SelectingComparerImpl(Func<T, U> selector, Comparison<U> comparer)
{
if (selector == null)
throw new ArgumentNullException();
this.selector = selector;
this.comparer = comparer ?? Comparer<U>.Default.Compare;
}
public int Compare(T x, T y)
{
return this.comparer(this.selector(x), this.selector(y));
}
}
}
```
In use:
```
public class Testing
{
public void Foo()
{
FileInfo[] files = new FileInfo[30];
// FILL THE FILE ARRAY
Array.Sort(files, SelectingComparer<FileInfo>.Create(file => file.Name));
Array.Sort(files, SelectingComparer<FileInfo>.Create(file => file.Name, StringComparer.OrdinalIgnoreCase));
}
}
``` | Sort an array of strongly typed objects based on a property of the object | [
"",
"c#",
"arrays",
""
] |
I am binding an ArrayList() to a Listbox control and assigning out an Displaymember and Value on data in the Array. My problem is that I Bind on startup but the Array gets filled after a few function calls. I have code on selectedIndexChanged to check the selectedValue but if the ArrayList is empty it returns an object, once it has data it returns the string I expect. I am still a confused why it runs selectedIndexChanged when the list has no data. Think it may run after I bind the Displaymember but before the value gets assigned:
```
lbCAT_USER.DataSource = USERS;
// Running here maybe?
lbCAT_USER.DisplayMember = "DisplayString";
// Or Here?
lbCAT_USER.ValueMember = "ID";
```
Either way my current work around is a try/catch of comparing the SelectedValue to a string and trying to rerun the function.
Simple workaround is maybe a way to check the datatype prior to the if statement? Any ideas of suggestions could be very helpful. Thanks | You have two ways to check this:
```
string value = list.SelectedValue as string;
// The cast will return null if selectedvalue was not a string.
if( value == null ) return;
//Logic goes here.
```
If you just want to do the comparison:
```
if( list.SelectedValue is string )
{
// ...
}
``` | If your question is how to check the datatype of a value via if-condition (title!), then here you go (example: check if value is of type 'string'):
```
if(value.GetType().Equals(typeof(string)))
{
...
}
```
EDIT: This is not the cleanest way to do it. Check Guard's answer for more sophisticated ways to check types. Using 'GetType().Equals' as I do is more precise than 'is' or 'as', since 'value' must be exactly of the type 'string'. 'is' and 'as' will work even if 'value' is a subclass of the checked type. This is irrelevant though when comparing with type 'string', since you cannot inherit from string. | C# - Check datatype of a value via if condtion | [
"",
"c#",
"listbox",
"events",
"types",
"arraylist",
""
] |
I am using MySQL 5.0 for a site that is hosted by GoDaddy (linux).
I was doing some testing on my web app, and suddenly I noticed that the pages were refreshing really slowly. Finally, after a long wait, I got to a page that said something along the lines of "MySQL Error, Too many connections...", and it pointed to my config.php file which connects to the database.
It has just been me connecting to the database, no other users. On each of my pages, I include the config.php file at the top, and close the mysql connection at the end of the page. There may be several queries in between. I fear that I am not closing mysql connections enough (mysql\_close()).
However, when I try to close them after running a query, I receive connection errors on the page. My pages are PHP and HTML. When I try to close a query, it seems that the next one won't connect. Would I have to include config.php again after the close in order to connect?
This error scared me because in 2 weeks, about 84 people start using this web application.
Thanks.
EDIT:
Here is some pseudo-code of my page:
```
require_once('../scripts/config.php');
<?php
mysql_query..
if(this button is pressed){
mysql_query...
}
if(this button is pressed){
mysql_query...
}
if(this button is pressed){
mysql_query...
}
?>
some html..
..
..
..
..
<?php
another mysql_query...
?>
some more html..
..
..
<?php mysql_close(); ?>
```
I figured that this way, each time the page opens, the connection opens, and then the connection closes when the page is done loading. Then, the connection opens again when someone clicks a button on the page, and so on...
EDIT:
Okay, so I just got off the phone with GoDaddy. Apparently, with my Economy Package, I'm limited to 50 connections at a time. While my issue today happened with only me accessing the site, they said that they were having some server problems earlier. However, seeing as how I am going to have 84 users for my web app, I should probably upgrade to "Deluxe", which allows for 100 connections at a time. On a given day, there may be around 30 users accessing my site at a time, so I think the 100 would be a safer bet. Do you guys agree? | Shared-hosting providers generally allow a pretty small amount of simultaneous connections for the same user.
What your code does is :
* open a connection to the MySQL server
* do it's stuff (generating the page)
* close the connection at the end of the page.
The last step, when done at the end of the page is not **mandatory** : (quoting [`mysql_close`](http://php.net/mysql_close)'s manual) :
> Using mysql\_close() isn't usually
> necessary, as non-persistent open
> links are automatically closed at the
> end of the script's execution.
But note you probably shouldn't use persistent connections anyway...
Two tips :
* use `mysql_connect` insead of `mysql_pconnect` *(already OK for you)*
* Set the fourth parameter of mysql\_connect to false *(already OK for you, as it's the default value)* : (quoting the manual) :
> If a second call is made to
> mysql\_connect() with the same
> arguments, no new link will be
> established, but instead, the link
> identifier of the already opened link
> will be returned.
>
> The new\_link
> parameter modifies this behavior and
> makes mysql\_connect() always open a
> new link, even if mysql\_connect() was
> called before with the same
> parameters.
---
What could cause the problem, then ?
Maybe you are trying to access several pages in parallel *(using multiple tabs in your browser, for instance)*, which will simulate several users using the website at the same time ?
If you have many users using the site at the same time and the code between `mysql_connect` and the closing of the connection takes lots of time, it will mean many connections being opened at the same time... And you'll reach the limit **:-(**
Still, as you are the only user of the application, considering you have up to 200 simultaneous connections allowed, there is something odd going on...
---
Well, thinking about "*too many connections*" and "`max_connections`"...
If I remember correctly, `max_connections` does not limit the number of connections **you** can open to the MySQL Server, but the **total number of connections** that can bo opened to that server, **by anyone connecting to it**.
Quoting MySQL's documentation on [Too many connections](http://dev.mysql.com/doc/refman/5.0/en/too-many-connections.html) :
> If you get a Too many connections
> error when you try to connect to the
> mysqld server, this means that all
> available connections are in use by
> other clients.
>
> The number of connections allowed is
> controlled by the max\_connections
> system variable. Its default value is
> 100. If you need to support more connections, you should set a larger
> value for this variable.
So, actually, the problem might not come from you nor your code *(which looks fine, actually)* : it might "just" be that you are not the only one trying to connect to that MySQL server *(remember, "shared hosting")*, and that there are too many people using it at the same time...
... And **if I'm right and it's that**, there's nothing you can do to solve the problem : as long as there are too many databases / users on that server and that `max_connection` is set to 200, you will continue suffering...
As a sidenote : before going back to GoDaddy asking them about that, it would be nice if someone could validate what I just said ^^ | I had about 18 months of dealing with this (<http://ianchanning.wordpress.com/2010/08/25/18-months-of-dealing-with-a-mysql-too-many-connections-error/>)
The solutions I had (that would apply to you) in the end were:
1. tune the database according to [MySQLTuner](http://mysqltuner.com/).
2. defragment the tables weekly based on this [post](http://blog.barfoo.org/2008/09/19/defragmenting-all-fragmented-myisam-tables/)
Defragmenting bash script from the post:
```
#!/bin/bash
# Get a list of all fragmented tables
FRAGMENTED_TABLES="$( mysql -e `use information_schema; SELECT TABLE_SCHEMA,TABLE_NAME
FROM TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','mysql') AND
Data_free > 0` | grep -v '^+' | sed 's,t,.,' )"
for fragment in $FRAGMENTED_TABLES; do
database="$( echo $fragment | cut -d. -f1 )"
table="$( echo $fragment | cut -d. -f2 )"
[ $fragment != "TABLE_SCHEMA.TABLE_NAME" ] && mysql -e "USE $database;
OPTIMIZE TABLE $table;" > /dev/null 2>&1
done
``` | MySQL Error "Too many connections" | [
"",
"php",
"mysql",
"connection",
""
] |
I'm putting together a portfolio website which includes a number of images, some of which I don't want to be viewable by the general public. I imagine that I'll email someone a user name and password, with which they can "log-in" to view my work.
I've seen various solutions to the "hide-an-image" problem on line including the following, which uses php's readfile. I've also seen another that uses .htaccess.
[Use php's readfile() or redirect to display a image file?](https://stackoverflow.com/questions/1050975/use-phps-readfile-or-redirect-to-display-a-image-file)
I'm not crazy about the readfile solution, as it seems slow to load the images, and I'd like to be able to use Cabel Sasser's FancyZoom, which needs unfettered access to the image, (his library wants a link to the full sized image), so that rules out .htaccess.
To recap what I'm trying to do:
1) Provide a site where I give users the ability to authenticate themselves as someone I'd like looking at my images.
2) Restrict random web users from being able see those images.
3) Use FancyZoom to blow up thumbnails.
I don't care what technology this ends up using -- Javascript, PHP, etc. -- whatever's cleanest and easiest.
By the way, I'm a Java Developer, not a web developer, so I'm probably not thinking about the problem correctly. | Instead of providing a link to an image. Provide a link to a cgi script which will automatically provide the proper header and content of the image.
For example:
image.php?sample.jpg
You can then make sure they are already authenticated (e.g. pass a session id) as part of the link.
This would be part of the header, and then your image data can follow.
```
header('Content-Type: image/jpeg');
```
Edit: If it has to be fast, you can write this in C/C++ instead of php. | Using .htaccess should be the *safest/simplest* method, as it's built in functionality of the webserver itself. | Restricting access to images on a website | [
"",
"php",
"html",
".htaccess",
"web",
""
] |
Assume a game in which one rolls 20, 8-sided die, for a total number of 8^20 possible outcomes. To calculate the probability of a particular event occurring, we divide the number of ways that event can occur by 8^20.
One can calculate the number of ways to get exactly 5 dice of the value 3. (20 choose 5) gives us the number of orders of 3. 7^15 gives us the number of ways we can not get the value 3 for 15 rolls.
```
number of ways to get exactly 5, 3's = (20 choose 5)*7^15.
```
The answer can also be viewed as how many ways can I rearrange the string 3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 (20 choose 5) times the total number of values we the zero's (assuming 7 legal values) 7^15 (is this correct).
* Question 1: How can I calculate the number of ways to get exactly 5 dice of the same value(That is, for all die values).
Note: if I just naively use my first answer above and multiply bt 8, I get an enormous amount of double counting?
I understand that I could solve for each of the cases (5 1's), (5, 2's), (5, 3's), ... (5's, 8) sum them (more simply 8\*(5 1's) ). Then subtract the sum of number of overlaps (5 1's) and (5 2's), (5 1's) and (5 3's)... (5 1's) and (5, 2's) and ... and (5, 8's) but this seems exceedingly messy. I would a generalization of this in a way that scales up to large numbers of samples and large numbers of classes.
* How can I calculate the number of ways to get **at least** 5 dice of the same value?
So 111110000000000000000 or 11110100000000000002 or 11111100000001110000 or 11011211222222223333, but not 00001111222233334444 or 000511512252363347744.
I'm looking for answers which either explain the math or point to a library which supports this (esp python modules). Extra points for detail and examples. | Double counting can be solved by use of the [Inclusion/Exclusion Principle](http://en.wikipedia.org/wiki/Inclusion-exclusion_principle)
I suspect it comes out to:
```
Choose(8,1)*P(one set of 5 Xs)
- Choose(8,2)*P(a set of 5 Xs and a set of 5 Ys)
+ Choose(8,3)*P(5 Xs, 5 Ys, 5 Zs)
- Choose(8,4)*P(5 Xs, 5 Ys, 5 Zs, 5 As)
P(set of 5 Xs) = 20 Choose 5 * 7^15 / 8^20
P(5 Xs, 5 Ys) = 20 Choose 5,5 * 6^10 / 8^20
```
And so on. This doesn't solve the problem directly of 'more then 5 of the same', as if you simply summed the results of this applied to 5,6,7..20; you would over count the cases where you have, say, 10 1's and 5 8's.
You could probably apply inclusion exclusion again to come up with that second answer; so, P(of at least 5)=P(one set of 20)+ ... + (P(one set of 15) - 7\*P(set of 5 from 5 dice)) + ((P(one set of 14) - 7\*P(one set of 5 from 6) - 7\*P(one set of 6 from 6)). Coming up with the source code for that is proving itself more difficult. | I suggest that you spend a little bit of time writing up a Monte Carlo simulation and let it run while you work out the math by hand. Hopefully the Monte Carlo simulation will converge before you're finished with the math and you'll be able to check your solution.
A slightly faster option might involve creating a SO clone for math questions. | Combinatorics Counting Puzzle: Roll 20, 8-sided dice, what is the probability of getting at least 5 dice of the same value | [
"",
"python",
"puzzle",
"combinatorics",
"discrete-mathematics",
"dice",
""
] |
I have an entity class:
### Cabbage.java
```
package womble;
public class Cabbage {
private int id;
// getters, setters, etc.
}
```
That I've got mapped to two separate database tables as follows:
### Cabbage.hbm.xml
```
<hibernate-mapping>
<class name="womble.Cabbage"> <!-- Using the default entity and table name. -->
<id name="id" unsaved-value="null">
<generator class="native"/>
</id>
</class>
</hibernate-mapping>
```
### CabbageBackup.hbm.xml
```
<hibernate-mapping>
<class name="womble.Cabbage" entity-name="CabbageBackup" table="cabbage_backup">
<id name="id">
<generator class="assigned"/>
</id>
</class>
</hibernate-mapping>
```
I'm trying to retrieve the last saved Cabbage instance like this:
### CabbageDao.java
```
package womble;
public class CabbageDao {
Session session; // Hibernate session
String GET_MAX_ID = "select max(id) from Cabbage";
public getLastCabbage() {
Object lastId = session.createQuery(GET_MAX_ID).uniqueResult();
return session.load(Cabbage.class, lastId);
}
}
```
This blows up with a `NonUniqueResultException`: "query did not return a unique result: 2"
Looking through the logs, Hibernate apparently queries both the tables and then joins the results together.
Is there a way to make Hibernate only query the default mapping for an entity? (That is, to specifically prevent it from magically querying both mappings when I use the simple class name.)
I tried using the above, using the criteria API passing Cabbage.class to #createCriteria(), as well as the string "Cabbage", both select from both tables. I'm trying to avoid specifying an entity name to the "main" mapping, because there's multiple classes like that in my code and I'd have to fix up all the relationships between them as well. | Try using an entity-name on both mappings, and specify which you'd like. I believe that is the contract of that attribute. | Firstly, Hibernate has no notion here of your "default" - both mappings are on an equal footing as far as it's concerned.
Do you ever need to access old cabbages (not a phrase I've ever used before) from the backup table, or are you just using that table for archiving old data?
If the latter, then there are probably better ways of achieving the same result, such as using a database trigger. | How to make Hibernate only query the default mapping? | [
"",
"java",
"hibernate",
""
] |
I would like to change all the characters entered into a textbox to upper case. The code will add the character, but how do I move the caret to the right?
```
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
textBox3.Text += e.KeyChar.ToString().ToUpper();
e.Handled = true;
}
``` | Set the [`CharacterCasing`](http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.charactercasing.aspx) property of the `TextBox` to `Upper`; then you don't need to process it manually.
Note that `textBox3.Text += e.KeyChar.ToString().ToUpper();` will append the new character to the end of the string *even if the input caret is in the middle of the string* (which most users will find highly confusing). For the same reason we cannot assume that the input caret should appear at the end of the string after inputting the character.
If you would still really want to do this in code, something like this should work:
```
// needed for backspace and such to work
if (char.IsControl(e.KeyChar))
{
return;
}
int selStart = textBox3.SelectionStart;
string before = textBox3.Text.Substring(0, selStart);
string after = textBox3.Text.Substring(before.Length);
textBox3.Text = string.Concat(before, e.KeyChar.ToString().ToUpper(), after);
textBox3.SelectionStart = before.Length + 1;
e.Handled = true;
``` | ```
tbNumber.SelectionStart = tbNumber.Text.ToCharArray().Length;
tbNumber.SelectionLength = 0;
``` | How to move the textbox caret to the right | [
"",
"c#",
"textbox",
"keypress",
""
] |
I would like to use Public/Private encryption where my web app would sign an xml document or a piece of data using a private key and it will be verified in the application using the public key,
Is it possible to use RSACryptoServiceProvider in .net 2.0 hosted environment if not what are other possible workarounds? | See here: <http://www.codeproject.com/KB/security/EZRSA.aspx> | Yes, quite possible.
If you export the cert you will use for data-signing into a .pfx file, you can get a digsig this way.
```
using System;
using System.Xml;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
// ...
static void SignWithPfxPrivateKey()
{
X509Certificate2 certificate = new X509Certificate2(certFile, pfxPassword);
RSACryptoServiceProvider rsaCsp = (RSACryptoServiceProvider) certificate.PrivateKey;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
if (loadFromString)
xmlDoc.LoadXml(rawXml); // load from a string
else
xmlDoc.Load("test.xml"); // load from a document
// Sign the XML document.
SignXml(xmlDoc, rsaCsp);
// Save the document.
xmlDoc.Save("RsaSigningWithCert.xml");
xmlDoc.Save(new XTWFND(Console.Out));
}
public static void SignXml(XmlDocument Doc, RSA Key)
{
// Check arguments.
if (Doc == null)
throw new ArgumentException("Doc");
if (Key == null)
throw new ArgumentException("Key");
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(Doc);
// Add the key to the SignedXml document.
signedXml.SigningKey = Key;
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
// Append the element to the XML document.
Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));
}
```
To use this, you will have to upload a .pfx file to the hosted server. You also need a password for that pfx file, which you should [store securely](http://www.bing.com/search?q=web.config+encrypt&form=QBRE&qs=n) in application config settings. You can do something similar with a .cer file.
You can also load the RSA key from regular XML. If you have an RSACryptoServiceProvider that you instantiated by loading a key from your *local* machine store, like this:
```
// Get the key pair from the key store.
CspParameters parms = new CspParameters(1);
parms.Flags = CspProviderFlags.UseMachineKeyStore;
parms.KeyContainerName = "SnapConfig";
parms.KeyNumber = 2;
RsaCsp = new RSACryptoServiceProvider(parms);
```
...then you can export that key with
```
RsaCsp.ToXmlString(true);
```
The result is a string, containing an XML document that you can save to a file, and then upload to the hosted server. An alternative to the .pfx file as a store for your key pair. **Be careful**. This xml document is not protected with a password, and is insecure. ([read the doc on ToXmlString()](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsa.toxmlstring.aspx)) You can encrypt this XML doc, just as you would encrypt any other settings. ([search](http://www.bing.com/search?q=web.config+encrypt&form=QBRE&qs=n))
In that case you can do this to get your csp:
```
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
csp.FromXmlString(keyPairXml);
``` | using RSACryptoServiceProvider or RSA in hosted environment | [
"",
"c#",
"encryption",
"rsa",
"digital-signature",
""
] |
I have a large namespace: Foo.Bar.Space.Station.Bar and I was to alias is as something shorter like, Station. How do I do that in the using section?
using Foo.Bar.Space.Station.Bar Object ???
so I can do this
Station.Object obj = new ...
instead of
Foo.Bar.Space.Station.Bar.Object obj = new ... | You can give an alias to a namespace in a using statement.
```
using Station = Foo.Bar.Space.Station.Bar;
``` | ```
using Station = Foo.Bar.Space.Station.Bar;
```
But in my opinion, having two namespaces named Bar is not a very good idea. :) Even if it's not real code. | How do you give a namespace an alias in C# | [
"",
"c#",
"namespaces",
""
] |
I have a result set that I want to trim a 2 digit suffix from. The strings will always be of varying lengths, but the suffixes will always be two digits separated by '-'.
Example:
APPTR-W302-01
NRSB-8920-09
Right now I am using the following. This is a hack because the '20' parameter is arbitrary.
```
REVERSE(SUBSTRING(REVERSE(COURSENAME),4,20))
```
Is there a better way? | Will the suffix always be '-##' ? If the suffix length doesn't change,
```
Left(COURSENAME,LEN(COURSENAME)-3)
``` | The following code shows three methods that are functionally equivalent in T-SQL. IMHO the "LEFT" method is the most readable.
```
DECLARE @courseName VARCHAR(20)
SET @courseName = 'APPTR-W302-01' -- we need to trim the trailing 2 digits and dash
SELECT
SUBSTRING(@courseName, 1, LEN(@courseName) - 3),
LEFT(@courseName, LEN(@courseName) - 3),
REVERSE(SUBSTRING(REVERSE(@courseName),4,20))
``` | Trimming alphanumeric characters from a strings of varying lengths in T-SQL | [
"",
"sql",
"sql-server",
"string",
""
] |
How can I match the three words in the following string with a Perl compatible regular expression?
word1#$word2#$word3
I don't know the actual words "word1, word2 and word3" in advance. I only know the separator, which is #$.
And I can't use the word boundary as I have a multibyte encoding. This means for instance that the string can contain non-ASCII characters like umlauts which are not detected by the \w control character. | Try this regular expression:
```
/(\w+)#\$(\w+)#\$(\w+)/
```
---
**Edit** After your provided us with more information (see the comments to this answer):
```
/((?:[^#]+|#[^$])*)#\$((?:[^#]+|#[^$])*)#\$((?:[^#]+|#[^$])*)/
``` | ```
#!/usr/bin/perl
use strict;
use warnings;
my $x = 'word1#$word2#$word3';
print $_, "\n" for split /#\$/, $x;
``` | PHP preg_match question | [
"",
"php",
"regex",
"preg-match",
""
] |
I am trying to delete all records that match a quiz id from the question table and the relationship table. The query works for a select statement, but won't allow the same statement to delete.
`@quizId` is a quiz Id value I pass into my stored procedure. Does anyone know how to delete from both tables using one statement? Is it possible?
```
DELETE tGeoQuestions as a, tGeoQuizToQuestion as b WHERE b.quizId = @quizId AND a.id = b.questionid
``` | You need to enable cascade delete then it would happen automagically, all you need to do is delete from the table with the PK and all the fk tables will be deleted automatically
otherwise it is a 2 step operation
something like this, put this in a tran
```
DELETE a
FROM tGeoQuestions as a
JOIN tGeoQuizToQuestion as b
ON a.id = b.questionid
AND b.quizId = @quizId
DELETE tGeoQuizToQuestion WHERE quizId = @quizId
```
your 3rd option is a trigger on the PK table that deletes everything from the FK table if it gets deleted in the PK table...I would't recommend the trigger | Try this:
```
DELETE a
FROM tGeoQuestions as a
INNER JOIN tGeoQuizToQuestion as b ON a.id = b.questionid
WHERE b.quizId = @quizId
```
By the way, your select statement acctually works (and I don't know wich is your statement...).
You must replace only
```
SELECT ...
```
with
```
DELETE [table name or alias]
```
and leave everything else the same. | SQL delete from related tables | [
"",
"sql",
"delete-row",
""
] |
This is a quick syntax question...
I need to block out an HTML element if two SQL statements are true w/ php.
If the status = 'closed', and if the current user is logged in. I can figure out the calls, I just need to see an example of the syntax. :)
So, If SQL status=closed, and if current\_user=is\_logged\_in()...something like that. | I'll assume you're trying to block out a login box if the user is logged in. Here's what you'll need to do:
In the view:
```
<?php if ($show_login): ?>
<!-- login box code here -->
<?php endif; ?>
```
In the controller's action that calls the view:
```
if (is_logged_in() && $this->my_model->check_something()) {
$data['show_login'] = false;
}
else {
$data['show_login'] = true;
}
$this->load->view('myview', $data);
```
In the model:
```
function check_something() {
// execute the SQL statements
// and return true/false depending on what you get
}
```
Refer to [CodeIgniter's Active Record documentation](http://codeigniter.com/user_guide/database/active_record.html) to figure out how to setup your SQL statements.
If this isn't what you were looking for, try making your question more detailed, maybe with whatever code you have. | figured it out:
I forgot that I had already called my $data...
```
<?php
if ($row['status'] == 'closed' && is_logged_in()) { ?>
```
I feel like a dummy... :) | CI PHP if statement w/ sql syntax | [
"",
"sql",
"codeigniter",
"if-statement",
""
] |
I need to be able to store data for a php application in a file. I need to be able to do this without any sort of external dependencies other than PHP itself.
Here are the requirements I have:
* Settings will not be updated/added/removed very often. So updating of settings does not have to be very efficient. However, I do want to be able to do this all through a PHP script, not through editing of files.
* Settings will be read constantly, so reading of settings must be very efficient.
* Settings are in a unique format, if I had them in an array it might be something like $Settings["Database"]["AccessSettings"]["Username"]["myDBUsername"];
$Settings["Database"]["AccessSettings"]["Password"]["myDBPassword"];
I would prefer to not have settings stored in arrays like I mentioned above. Instead I would prefer some access methods: getConfig("Database","Accesssettings","Username") would return 'myDBUsername'. The reason for this is I want to limit the variables I am storing in the global scope.
What would the best way of getting/retrieving these be?
Do the the hierarchy I was thinking possibly an xml file, but I wasn't sure what PHP was like for accessing xml files (particularly the fact that I need to be able to add, edit, and remove). If it should be XML what sort of xml access should I look into.
If it is another format, I would like some pointers to the right direction for what to look into for how to use that format. | Brian, [parse\_ini\_file](http://us.php.net/parse_ini_file) is what you need.
Ah, I missed the requirement that you'd be editing this via PHP.
In that case there is nothing native to PHP that you can use for this purpose. You'd have to roll your own.
You could save yourself a **ton** of time by simply using [Zend\_Config\_Ini](http://framework.zend.com/manual/en/zend.config.adapters.ini.html) though. I know you state that you don't want to use anything else, but Zend Framework is structured to allow you to use whatever pieces of it you need. Zend\_Config can be used on it's own. You can certainly just add these few classes to your project and let them handle your INI file parsing.
Here is an example using your samples above:
```
[config]
Database.AccessSettings.Username = myDBUsername
Database.AccessSettings.Password = myDBPassword
```
You would load and access this as simply as:
```
$config = new Zend_Config_Ini('/path/to/ini', 'config');
echo $config->Datbase->AccessSettings->Username; // prints "myDBUsername"
echo $config->Datbase->AccessSettings->Password; // prints "myDBPassword"
```
To edit and save your config you would use the following:
```
$config->Database->AccessSettings->Password = "foobar";
$writer = new Zend_Config_Writer_Ini(array('config' => $config,
'filename' => 'config.ini'));
$writer->write();
```
**Edit**
Not really sure why people are voting this down based on vog's misguided comments. It is very simple to make this writable by multiple persons by using an exclusive lock. Zend\_Config\_Writer uses [file\_put\_contents](http://php.net/file_put_contents) to do it's writing, which has **always** supported the the LOCK\_EX flag, which exclusively locks a file for writing. When using this flag, you cannot have multiple writers attempting to update the file at the same time.
To use this flag with Zend\_Config\_Writer it's as simple as follows:
```
$writer = new Zend_Config_Writer_Ini(array('config' => $config,
'filename' => 'config.ini'));
$writer->setExclusiveLock(true);
$writer->write();
```
An alternate syntax:
```
$writer = new Zend_Config_Writer_Ini();
$writer->write('config.ini', $config, true); // 3rd parameter is $exclusiveLock
``` | If you're not hand editing, use serialized data.
Writing config using [serialize](https://www.php.net/serialize):
```
file_put_contents('myConfig.txt', serialize($Settings));
```
Reading config using [unserialize](https://www.php.net/unserialize):
```
$Settings = unserialize(file_get_contents('myConfig.txt'));
```
You could write a class for modifying and getting values for this data using PHP magic functions \_\_get() and \_\_set(). | Storing, Updating, Retrieving settings for a PHP Application without a Database | [
"",
"php",
"xml",
"configuration-files",
""
] |
I'm working on a PHP project and am looking for a good authorize.net gateway. I want something with mature code that's tested. The goal is to avoid writing and testing the entire thing myself based on the authorize.net api docs.
Does anyone know of any good PHP libraries for this? I've search Google to no avail. | Authorize.net provides its own [SDK for PHP and other languages](http://developer.authorize.net/downloads/). There is probably no need to look elsewhere. | You're in luck. This is what I use (for the SIM gateway):
```
include("../../simdata.php");
...
<!--form action="https://test.authorize.net/gateway/transact.dll" method="POST"-->
<FORM action="https://secure.authorize.net/gateway/transact.dll" method="POST">
<?
$x_description = "website.com";
$currency = "";
$tstamp = time();
// Seed random number for security and better randomness.
srand(time());
$sequence = rand(1, 1000);
$data = "$x_loginid^$sequence^$tstamp^$total^$currency";
#echo "data = $data\n";
#echo $x_tran_key;
$fingerprint = bin2hex(mhash(MHASH_MD5, $data, $x_tran_key));
# php 5 only $fingerprint = hash_hmac("md5", $data, $x_tran_key);
echo ("<input type='hidden' name='x_fp_sequence' value='" . $sequence . "'>\n" );
echo ("<input type='hidden' name='x_fp_timestamp' value='" . $tstamp . "'>\n" );
echo ("<input type='hidden' name='x_fp_hash' value='" . $fingerprint . "'>\n" );
echo ("<input type=\"hidden\" name=\"x_description\" value=\"" . $x_description . "\">\n" );
echo ("<input type=\"hidden\" name=\"x_login\" value=\"$x_loginid\">\n");
echo ("<input type=\"hidden\" name=\"x_amount\" value=\"$total\">\n");
?>
<input type="hidden" name="x_first_name" value="<?=firstName($_SESSION['user']['name'])?>">
<input type="hidden" name="x_last_name" value="<?=lastName($_SESSION['user']['name'])?>">
<input type="hidden" name="x_company" value="<?=$_SESSION['user']['company']?>">
<input type="hidden" name="x_address" value="<?=$_SESSION['user']['address']?>">
<input type="hidden" name="x_city" value="<?=$_SESSION['user']['city']?>">
<input type="hidden" name="x_state" value="<?=$_SESSION['user']['state']?>">
<input type="hidden" name="x_zip" value="<?=$_SESSION['user']['zip']?>">
<input type="hidden" name="x_phone" value="<?=$_SESSION['user']['phone']?>">
<input type="hidden" name="x_email" value="<?=$_SESSION['user']['email']?>">
<input type="hidden" name="x_cust_id" value="<?=$_SESSION['user']['username']?>">
<INPUT TYPE="HIDDEN" name="x_logo_url" VALUE= "https://secure.authorize.net/mgraphics/logo_99999.gif">
<INPUT type="hidden" name="x_show_form" value="PAYMENT_FORM">
<!--INPUT type="hidden" name="x_test_request" value="TRUE"-->
<!--input type="hidden" name="x_receipt_link_method" value="POST">
<input type="hidden" name="x_receipt_link_text" value="Click for listings">
<input type="hidden" name="x_receipt_link_url" value="http://website.com/confirmation.php"-->
<input type="hidden" name="x_relay_response" value="TRUE">
<input type="hidden" name="x_relay_url" value="http://website.com/confirmation.php">
<input type="hidden" name="<?=session_name()?>" value="<?=session_id()?>">
<input type="hidden" name="" value="">
<input type="hidden" name="" value="">
<input type="hidden" name="" value="">
<? if ($total==0) { ?>
<a href="account.php">Your Account</a>
<? } else { ?>
<INPUT type="submit" value="Accept Order">
<? } ?>
</form>
```
And this is what I use for the confirmation.php
```
include("../../simdata.php");
#print_r($_POST);
// verify transaction comes from authorize.net and save user details
$responseCode = $_POST['x_response_code'];
if ( $responseCode == 1) { // approved
$md5 = $_POST['x_MD5_Hash'];
$transId = $_POST['x_trans_id'];
$amount = $_POST['x_amount'];
$myMD5 = strtoupper(md5("$x_tran_key$x_loginid$transId$amount"));
#echo $myMD5;
#print_r ($_POST);
#print_r ($_SESSION['user']);
if ($myMD5 == $md5) { // authenticated response from authorize.net
...
} else {
$error = "Unauthenticated response.";
}
} else if (isset($_POST['x_response_code'])) { // error
$error = $_POST['x_response_reason_text'].", #".$_POST['x_response_code'].'.'.$_POST['x_response_subcode'].
'.'.$_POST['x_response_reason_code'];
}
``` | Good authorize.net PHP libraries | [
"",
"php",
"payment-gateway",
"authorize.net",
""
] |
Are there faster alternatives to memcpy() in C++? | Unlikely. Your compiler/standard library will likely have a very efficient and tailored implementation of memcpy. And memcpy is basically the lowest api there is for copying one part of memory to another.
If you want further speedups, find a way to not need any memory copying. | First, a word of advice. Assume that the people who wrote your standard library are not stupid.
If there was a faster way to implement a general memcpy, they'd have done it.
Second, yes, there are better alternatives.
* In C++, use the `std::copy` function. It does the same thing, but it is 1) safer, and 2) potentially faster in some cases. It is a template, meaning that it can be specialized for specific types, making it potentially faster than the general C memcpy.
* Or, you can use your superior knowledge of *your* specific situation. The implementers of memcpy had to write it so it performed well in *every* case. If you have specific information about the situation where you need it, you might be able to write a faster version. For example, how much memory do you need to copy? How is it aligned? That might allow you to write a more efficient memcpy for *this* specific case. But it won't be as good in most other cases (if it'll work at all) | optimized memcpy | [
"",
"c++",
"optimization",
"memcpy",
""
] |
I am building a forum from scratch in PHP. I have used the most of phpBB:s database structure.
But now I am thinking about the search functionality?, what is a good design to be able to search really fast in all posts. I guess there must be some better way than just %query\_string% in mysql :)
Maybe explode all sentences into words, let the words be keys in a hash table, and the value is a comma separated list of all the post the word is in? Then there is little more trouble if you delete a post but I think that approach is better.
From start I guess I can use the simple solution, but I dont want to change the code when the forum grows bigger.
Thanks for any ideas or if you can point me to the right direction! | The best option for me today is [sphinx search](http://sphinxsearch.com/). It can be used with php, rails, perl and until now for me worked like a charm. You can check a [php solution](http://www.ibm.com/developerworks/library/os-php-sphinxsearch/). Craiglist for example use it. | [Zend Lucene](http://framework.zend.com/manual/en/zend.search.lucene.html) is a powerful way to add search to a PHP site.
Here's an article about how to do exactly that: [Roll Your Own Search Engine with Zend\_Search\_Lucene](http://devzone.zend.com/article/91) | Develop a fast search functionality in a big forum? | [
"",
"php",
"database",
"forum",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.