Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I want remove "Language" querystring from my url. How can I do this? (using Asp.net 3.5 , c#)
```
Default.aspx?Agent=10&Language=2
```
I want to remove "Language=2", but language would be the first,middle or last. So I will have this
```
Default.aspx?Agent=20
``` | I answered a [similar question](https://stackoverflow.com/questions/229925/outputing-a-manipulated-querystring-in-c/) a while ago. Basically, the best way would be to use the class `HttpValueCollection`, which the `QueryString` property actually is, unfortunately it is internal in the .NET framework.
You could use Reflector to grab it (and place it into your Utils class). This way you could manipulate the query string like a NameValueCollection, but with all the url encoding/decoding issues taken care for you.
`HttpValueCollection` extends `NameValueCollection`, and has a constructor that takes an encoded query string (ampersands and question marks included), and it overrides a `ToString()` method to later rebuild the query string from the underlying collection. | If it's the HttpRequest.QueryString then you can copy the collection into a writable collection and have your way with it.
```
NameValueCollection filtered = new NameValueCollection(request.QueryString);
filtered.Remove("Language");
``` | How can I remove item from querystring in asp.net using c#? | [
"",
"c#",
".net",
"asp.net",
"query-string",
""
] |
I am writing a web app in PHP, and it has come time to build an update system, one of the requirements is automatic updates, how should I do this?
I want to do it without a cron, so I'm going to have to check for updates when requests are made to the system, should I do this only when an admin, with significant privs, logs-in, I think this is going to be the best but at least 1 client has said they don't want this because they only intend to login every few month, and they still want to get the security updates. | Perhaps you can have a page on your site that returns a small XML file with the most current version number and a URL for download:
`<xml>
<version>1.x.y</version>
<url>http://example.com/current.tgz </url>
</xml>`
Then if the admin chooses to perform and upgrade, your application won't need to know anything other than the URL to the XML file and the current version number.
Of course this is a very limited example upon which you can expand to your hearts content. | Use versioning ofcourse!
I include this 'plugin' in most of my production sites:
Ofcourse, you need to create a limited-rights robot svn account for this first and svn must be installed on the server.
```
<?php
echo(' updating from svn<br>' );
$username = Settings::Load()->Get('svn','username');
$password = Settings::Load()->Get('svn','password');
echo(" <pre>" );
$repos = Settings::Load()->Get('svn' , 'repository');
echo system ("svn export --username={$username} --password {$password} {$repos}includes/ ".dirname(__FILE__)."/../includes --force");
echo system("svn export --username={$username} --password {$password} {$repos}plugins/ ".dirname(__FILE__)."/../plugins --force");
die();
```
Make sure you put this behind a .htpasswded site ofcourse, and make sure you do not update the 'production settings' from SVN.
Et voila, You update your complete code base with one HTTP query to your site :) SVN overwrites the files automatically, there's no hidden files or folders left behind and its easily adapted to update or revert to a specific version.
Now all your team needs to do is commit to their SVN repository, run this piece of code on the testing environment, make sure everything works and then run it on production :) | PHP Application Updates | [
"",
"php",
"updates",
""
] |
I'm using C# and have a windows form containing a property grid control.
I have assigned the SelectedObject of the propertygrid to a settings file, which displays and lets me edit the settings. However one of the settings is a password - and I'd like it to display asterisks in the field rather than the plain text value of the password setting.
The field will be encrypted when saved, but I want it to behave like a normal password entry box with asterisks displayed when the user is entering in the password.
I'm wondering if there is an attribute that can be applied to the setting property to mark it as being a password?
Thanks. | Starting with .Net 2, you can use the [PasswordPropertyTextAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.passwordpropertytextattribute.aspx) attached to your password property.
Hope this helps. | I don't think you can get PropertyGrid to swap to asterisks, but you could perhaps use a one-way type-converter and a modal editor... like so:
```
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
class Foo
{
[TypeConverter(typeof(PasswordConverter))]
[Editor(typeof(PasswordEditor), typeof(UITypeEditor))]
public string Password { get; set; }
// just to show for debugging...
public string PasswordActual { get { return Password; } }
}
class PasswordConverter : TypeConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType)
{
return destinationType == typeof(string) ? "********" :
base.ConvertTo(context, culture, value, destinationType);
}
}
class PasswordEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
IWindowsFormsEditorService svc = (IWindowsFormsEditorService)
provider.GetService(typeof(IWindowsFormsEditorService));
if (svc != null) {
TextBox tb;
Button btn;
Form frm = new Form { Controls = {
(tb = new TextBox { PasswordChar = '*', Dock = DockStyle.Top,
Text = (string)value}),
(btn = new Button { Text = "OK", Dock = DockStyle.Bottom, DialogResult = DialogResult.OK})
}, AcceptButton = btn};
if (frm.ShowDialog() == DialogResult.OK)
{
value = tb.Text;
}
}
return value;
}
}
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new Form {
Controls = {
new PropertyGrid {
Dock = DockStyle.Fill,
SelectedObject = new Foo { Password = "Bar"}
}
}
});
}
}
``` | Is it possible to mark a property shown in a property grid as a password field | [
"",
"c#",
"passwords",
"attributes",
"propertygrid",
""
] |
i have an `IList<Animals> farmAnimals;`
this list has three types,
* Cows
* Sheep
* Chickens
how can i remove all the Chickens from the list using a *lambda query* or *linq-to-objects* so i have a separate list of chickens and the original list now only has cows and sheep.
Do i have to make three lists (the original + 2 new ones, filtered) and then null the original list? or is there a trickier way?
result needs to be
```
IList<Aniamls> chickens;
IList<Animals> farmAnimals; // only contains the cows and sheep, now.
```
cheers!
## CLARIFICATION QUESTION:
what is more performant? FindAll & RemoveAll versus the Where suggestion? | Assuming:
```
public abstract class Animal {}
public class Chicken : Animal {}
```
you can do:
```
var chickens = animals.OfType<Chicken>().Cast<Animal>().ToList();
var nonChickens = animals.Except(chickens).ToList();
```
**Edit**
Any reasonable answer should be [O(n)](http://en.wikipedia.org/wiki/Big_O_notation), meaning each item in the original list is only processed once. Therefore, I would suggest an imperative approach:
```
var chickens = new List<Animal>();
var nonChickens = new List<Animal>();
foreach(var animal in animals)
{
var list = animal is Chicken ? chickens : nonChickens;
list.Add(animal);
}
``` | ```
var chickens = farmAnimals.ToList().FindAll (c => c.Type == "Chicken");
farmAnimals.RemoveAll(a => a.Type=="Chicken");
``` | How to extract some data from a collection using lambda/linq to objects? | [
"",
"c#",
".net",
"lambda",
"linq-to-objects",
""
] |
I was reading about threading and about locking. It is common practise that you can't (well should not) lock a value type.
So the question is, what is the recommended way of locking a value type? I know there's a few ways to go about doing one thing but I haven't seen an example. Although there was a good thread on MSDN forums but I can't seem to find that now.
Thanks | Use another object for the lock.
```
int valueType;
object valueTypeLock = new object();
void Foo()
{
lock (valueTypeLock)
{
valueType = 0;
}
}
``` | Your question is worded in such a way that it suggests to me that you don't entirely understand locking. You don't lock the data, you lock to protect the integrity of the data. The object you lock on is inconsequential. What matters is that you lock on the same object in other areas of your code that alter the data being protected. | How to properly lock a value type? | [
"",
"c#",
"locking",
""
] |
I can find a direct table foreign key in c# like:
```
foreach (ForeignKey key in CurrentTable.ForeignKeys) {
Console.WriteLine("FK:" + key.ReferencedTable);
}
```
The classic representation for a many to many relationship is achieved via an intermediate table that has a one to many relation to the two principal tables so there is not a direct link between the tables that have the many2many relation.
For the moment I try to find the many to many relation checking if the table I am analyzing has only two columns and both colums are foreign keys to different tables (in that case I recognise this as the intermediate table).
This is not the best solution as sometimes the intermediate table carries also other columns.
What would the best way to find this many2many relation programmatically? | As additional criteria you could use the fact that in many cases the couple of the two foreign keys represents the primary key of the join/intermediate table. | You seem to have posited your own solution. Rather than searching for tables that have two foreign keys referencing other distinct tables and with no other columns, just delete the phrase "and with no other columns".
In other words, look for "tables that have two foreign keys referencing other distinct tables". | How to programmatically find a many to many relation in an SQL Server 2005 database | [
"",
"c#",
"sql-server",
"sql-server-2005",
"code-generation",
"metadata",
""
] |
I have an array:
```
data.Dealer.car[0]
data.Dealer.car[1]
data.Dealer.car[2]
```
If I do this:
```
alert(data.Dealer.car.length);
delete data.Dealer.car[1];
alert(data.Dealer.car.length);
```
It gives me the same count each time. Does the removed element still exist? | JavaScript arrays aren't sparse, if you have a 0 and a 2, then element 1 must exist. Meaning the `length` is going to be 3. | If you want to remove an item, use the `splice` method:
```
alert(data.Dealer.car.length);
data.Dealer.car.splice(1, 1);
alert(data.Dealer.car.length);
```
But notice that the indices have changed. | Why doesn’t deleting from a Javascript array change its length? | [
"",
"javascript",
""
] |
Say I want to check if a record in a MySQL table exists. I'd run a query, check the number of rows returned. If 0 rows do this, otherwise do that.
```
SELECT * FROM table WHERE id=5
SELECT id FROM table WHERE id=5
```
Is there any difference at all between these two queries? Is effort spent in returning every column, or is effort spent in filtering out the columns we don't care about?
```
SELECT COUNT(*) FROM table WHERE id=5
```
Is a whole new question. Would the server grab all the values and then count the values (harder than usual), or would it not bother grabbing anything and just increment a variable each time it finds a match (easier than usual)?
I think I'm making a lot of false assumptions about how MySQL works, but that's the meat of the question! Where am I wrong? Educate me, Stack Overflow! | Optimizers are pretty smart (generally). They typically only grab what they need so I'd go with:
```
SELECT COUNT(1) FROM mytable WHERE id = 5
``` | The most explicit way would be
SELECT WHEN EXISTS (SELECT 1 FROM table WHERE id = 5) THEN 1 ELSE 0 END
If there is an index on (or starting with) id, it will only search, with maximum efficiency, for the first entry in the index it can find with that value. It won't read the record.
If you SELECT COUNT(\*) (or COUNT anything else) it will, under the same circumstances, count the index entries, but not read the records.
If you SELECT \*, it will read all the records. | What's the most efficient way to check the presence of a row in a table? | [
"",
"sql",
"mysql",
"performance",
""
] |
I have sequence of IDs I want to retrieve. It's simple:
```
session.query(Record).filter(Record.id.in_(seq)).all()
```
Is there a better way to do it? | Your code is absolutety fine.
`IN` is like a bunch of `X=Y` joined with `OR` and is pretty fast in contemporary databases.
However, if your list of IDs is long, you could make the query a bit more efficient by passing a sub-query returning the list of IDs. | The code as is is completely fine. However, someone is asking me for some system of hedging between the two approaches of doing a big IN vs. using get() for individual IDs.
If someone is really trying to avoid the SELECT, then the best way to do that is to set up the objects you need in memory ahead of time. Such as, you're working on a large table of elements. Break up the work into chunks, such as, order the full set of work by primary key, or by date range, whatever, then load everything for that chunk locally into a cache:
```
all_ids = [<huge list of ids>]
all_ids.sort()
while all_ids:
chunk = all_ids[0:1000]
# bonus exercise! Throw each chunk into a multiprocessing.pool()!
all_ids = all_ids[1000:]
my_cache = dict(
Session.query(Record.id, Record).filter(
Record.id.between(chunk[0], chunk[-1]))
)
for id_ in chunk:
my_obj = my_cache[id_]
<work on my_obj>
```
That's the real world use case.
But to also illustrate some SQLAlchemy API, we can make a function that does the IN for records we don't have and a local get for those we do. Here is that:
```
from sqlalchemy import inspect
def get_all(session, cls, seq):
mapper = inspect(cls)
lookup = set()
for ident in seq:
key = mapper.identity_key_from_primary_key((ident, ))
if key in session.identity_map:
yield session.identity_map[key]
else:
lookup.add(ident)
if lookup:
for obj in session.query(cls).filter(cls.id.in_(lookup)):
yield obj
```
Here is a demonstration:
```
from sqlalchemy import Column, Integer, create_engine, String
from sqlalchemy.orm import Session
from sqlalchemy.ext.declarative import declarative_base
import random
Base = declarative_base()
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
data = Column(String)
e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)
ids = range(1, 50)
s = Session(e)
s.add_all([A(id=i, data='a%d' % i) for i in ids])
s.commit()
s.close()
already_loaded = s.query(A).filter(A.id.in_(random.sample(ids, 10))).all()
assert len(s.identity_map) == 10
to_load = set(random.sample(ids, 25))
all_ = list(get_all(s, A, to_load))
assert set(x.id for x in all_) == to_load
``` | How can I get all rows with keys provided in a list using SQLalchemy? | [
"",
"python",
"select",
"sqlalchemy",
""
] |
I'm fairly new to Java (been writing other stuff for many years) and unless I'm missing something (and I'm happy to be wrong here) the following is a fatal flaw...
```
String foo = new String();
thisDoesntWork(foo);
System.out.println(foo);//this prints nothing
public static void thisDoesntWork(String foo){
foo = "howdy";
}
```
Now, I'm well aware of the (fairly poorly worded) concept that in java everything is passed by "value" and not "reference", but String is an object and has all sorts of bells and whistles, so, one would expect that unlike an int a user would be able to operate on the thing that's passed into the method (and not be stuck with the value set by the overloaded =).
Can someone explain to me what the reasoning behind this design choice was? As I said, I'm not looking to be right here, and perhaps I'm missing something obvious? | [This rant](http://javadude.com/articles/passbyvalue.htm) explains it better than I could ever even try to:
> In Java, primitives are passed by value. However, Objects are not
> passed by reference. A correct statement would be Object references
> are passed by value. | When you pass "foo", you're passing the *reference* to "foo" as a value to ThisDoesntWork(). That means that when you do the assignment to "foo" inside of your method, you are merely setting a local variable (foo)'s reference to be a reference to your new string.
Another thing to keep in mind when thinking about how strings behave in Java is that strings are immutable. It works the same way in C#, and for some good reasons:
* *Security*: Nobody can jam data into your string and cause a buffer overflow error if nobody can modify it!
* *Speed* : If you can be sure that your strings are immutable, you know its size is always the same and you don't ever have to do a move of the data structure in memory when you manipulate it. You (the language designer) also don't have to worry about implementing the String as a slow linked-list, either. This cuts both ways, though. Appending strings just using the + operator can be expensive memory-wise, and you will have to use a StringBuilder object to do this in a high-performance, memory-efficient way.
Now onto your bigger question. Why are objects passed this way? Well, if Java passed your string as what you'd traditionally call "by value", it would have to actually copy the entire string before passing it to your function. That's quite slow. If it passed the string by reference and let you change it (like C does), you'd have the problems I just listed. | Can someone explain to me what the reasoning behind passing by "value" and not by "reference" in Java is? | [
"",
"java",
"pass-by-reference",
"pass-by-value",
""
] |
For my Android application there is a timer that measures how much time has passed. Ever 100 milliseconds I update my TextView with some text like "Score: 10 Time: 100.10 seconds". But, I find the TextView only updates the first few times. The application is still very responsive, but the label will not update. I tried to call .invalidate(), but it still does not work. I don't know if there is some way to fix this, or a better widget to use.
Here is a example of my code:
```
float seconds;
java.util.Timer gametimer;
void updatecount() { TextView t = (TextView)findViewById(R.id.topscore);
t.setText("Score: 10 - Time: "+seconds+" seconds");
t.postInvalidate();
}
public void onCreate(Bundle sis) {
... Load the UI, etc...
gametimer.schedule(new TimerTask() { public void run() {
seconds+=0.1; updatecount();
} }, 100, 100);
}
``` | The general solution is to use android.os.Handler instead which runs in the UI thread. It only does one-shot callbacks, so you have to trigger it again every time your callback is called. But it is easy enough to use. A blog post on this topic was written a couple of years ago:
<http://android-developers.blogspot.com/2007/11/stitch-in-time.html> | What I think is happening is you're falling off the UI thread. There is a single "looper" thread which handles all screen updates. If you attempt to call "invalidate()" and you're not on this thread nothing will happen.
Try using "postInvalidate()" on your view instead. It'll let you update a view when you're not in the current UI thread.
More info [here](http://code.google.com/android/reference/android/view/View.html#postInvalidate()) | Android TextView Timer | [
"",
"java",
"android",
"timer",
"textview",
""
] |
I have an enterprise application written in JAVA with JSF (using RichFaces 3.3). Currently my URL looks like this:
**<http://localhost/WebApplication/faces/folder1/page.jsp>**
Question is how do I mask my url to make it like this:
**<http://localhost/folder1/page.jps>**
Basically i want to hide "Application/faces/"
Thanks | For rewriting URLs within your application you can use [UrlRewrite](http://tuckey.org/urlrewrite/). However, in this case it looks like you want to remove your web application's context path, in which case you have two options:
1. deploy your application to the context path `/` (how is application server-specific)
2. run Apache on port 80 and use mod\_proxy to proxy certain URLs to your application server running on a different port, using configuration something like the following.
Apache config:
```
<Proxy http://localhost:8080/*>
Order Allow,Deny
Allow From All
</Proxy>
ProxyPreserveHost On
ProxyPass / http://localhost:8080/WebApplication/
ProxyPassReverse / http://localhost:8080/WebApplication/
``` | PrettyFaces lets you rewrite your url.
If you prefer something more lightweight, extend NavigationHandler and override
handleNavigation, e.g. by calling context.getExternalContext().redirect() | Mask URL in JSF | [
"",
"java",
"jsf",
"glassfish",
"friendly-url",
""
] |
I am creating a set of widgets in Java that decodes and displays messages received at a serial interface.
The message type is defined by a unique identifier.
Each widget is only interested in a particular identifier.
How to I program the application in a way to distribute the messages correctly to the relevant widgets? | If this is for a single app (i.e. a main and couple of threads), JMS is overkill.
The basics of this is a simple queue (of which Java has several good ones, BlockingQueue waving its hand in the back over there).
The serial port reads its data, formats a some relevant message object, and dumps it on a central Message Queue. This can be as simple as a BlockingQueue singleton.
Next, you'll need a queue listener/dispatcher.
This is a separate thread that sits on the queue, waiting for messages.
When it gets a message it then dispatches it to the waiting "widgets".
How it "knows" what widgets get what is up to you.
It can be a simple registration scheme:
```
String messageType = "XYZ";
MyMessageListener listener = new MyMessageListener();
EventQueueFactory.registerListener(messageType, listener);
```
Then you can do something like:
```
public void registerListener(String type, MessageListener listener) {
List<MessageListener> listeners = registrationMap.get(type);
if (listeners == null) {
listeneres = new ArrayList<MessageListener>();
registrationMap.put(type, listeners);
}
listeners.add(listener);
}
public void dispatchMessage(Message msg) {
List<MessageListener> listeners = registrationMap.get(type);
if (listeners != null) {
for(MessageListener listener : listeners) {
listener.send(msg);
}
}
}
```
Also, if you're using Swing, it has a whole suite of Java Bean property listeners and what not that you could leverage as well.
That's the heart of it. That should give you enough rope to keep you in trouble. | sounds like a jms topic/subscription. why reinvent the wheel? | Java Message Distribution / Subscription? | [
"",
"java",
""
] |
I have a camera that returns raw images that can easily be converted to a bitmap that can be saved to a file by the following C# method (that I did not write). From various sources, I have determined that the pictures have 8 bits per pixel, and may or may not be grayscale.
```
private void rawImgToBmp(byte[] imgData, String fname) {
Bitmap bmp = new Bitmap(getWidth(), getHeight(),
System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
for (int i = 0; i < 256; i++)
{ bmp.Palette.Entries[i] = Color.FromArgb(255, i, i, i); }
//Copy the data from the byte array into the bitmap
BitmapData bmpData =
bmp.LockBits( new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat);
Marshal.Copy(imgData, 0, bmpData.Scan0, getWidth() * getHeight());
bmp.UnlockBits(bmpData); //Unlock the pixels
bmp.Save(FileName);
}
```
My question is: how would I go about writing the equivalent method in C++, using built in functions of Windows CE 4.2?
erisu: thanks for the palette code, I think it's right. I've resorted to filling in the rest of the structs manually, according to the [Wikipedia](http://en.wikipedia.org/wiki/BMP_file_format) page. | This is the code that works for me. It is based on erisu's answer and [Wikipedia's description of the BMP format](http://en.wikipedia.org/wiki/BMP_file_format). For anyone else using this answer, I recommend that you understand the BMP format as fully as possible, so you can adjust the header fields accordingly.
The complicated loop at the end is my workaround for an issue with my hardware/OS, where it would not write all of the data I supplied to fwrite. It should work in any environment, though.
```
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tchar.h>
#define NPAL_ENT 256
INT WINAPI WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
INT nShowCmd )
{
int w = 1920, h = 1080; // My values, yours may vary
//////////////////////// File Operations ///////////////////////////////
// Reading raw img
FILE* f = fopen("\\FlashDisk\\raw_img.bin","r");
if(NULL == f){printf("BAD");exit(1);}
// Obtaining size of raw img
fseek (f , 0L , SEEK_END);
DWORD fsize = (DWORD)ftell (f);
fseek (f , 0L , SEEK_SET);
char *imgData = (char*) malloc (sizeof(char)*fsize);
if(NULL == imgData) {printf("NOT imgData");exit(2);}
// Copy contents of file into buffer
DWORD result = fread(imgData,1,fsize,f);
if (result != fsize) {
printf ("Reading error. Expected: %d, Got: %d\n",fsize, result );
if(ferror(f)){printf("An error: %d\n", ferror(f)); }
if(feof(f)) {printf("EOF\n");}
delete[] imgData;
fclose(f);
exit (3);
}
fclose(f);
//////////////////////// BMP Operations ///////////////////////////////
/* A bitmap has the following components:
* 1. BMP file header
* 2. Bitmap Information (DIB) header
* 3. Color Palette
* 4. Raw Data
*/
BITMAPFILEHEADER bmfh;
ZeroMemory( &bmfh, sizeof( bmfh ) );
bmfh.bfType = 0x4D42; // Magic #
bmfh.bfSize = sizeof( bmfh ) + sizeof( BITMAPINFOHEADER )
+ NPAL_ENT*sizeof(PALETTEENTRY) + w*h; // Or total file size if w/h not known
bmfh.bfOffBits = sizeof( bmfh ) + sizeof( BITMAPINFOHEADER )
+ NPAL_ENT*sizeof(PALETTEENTRY);
BITMAPINFOHEADER bmih;
ZeroMemory( &bmih, sizeof( bmih ) );
bmih.biWidth = w;
bmih.biHeight = h;
bmih.biSize = sizeof(bmih);
bmih.biPlanes = 1;
bmih.biBitCount = 8;
bmih.biCompression = BI_RGB;
bmih.biSizeImage = w * h;
int palSize = NPAL_ENT*sizeof(PALETTEENTRY);
LOGPALETTE *logpal=(LOGPALETTE*)new BYTE[sizeof(LOGPALETTE)+palSize];
if(!logpal) {delete [] imgData; printf("!logpal\n"); exit(4);}
logpal->palVersion=0x300;
logpal->palNumEntries=NPAL_ENT;
int i=0;
do { // Exact palette format varies. This is what worked for me
logpal->palPalEntry[i].peRed=i;
logpal->palPalEntry[i].peGreen=i;
logpal->palPalEntry[i].peBlue=i;
logpal->palPalEntry[i].peFlags=NULL;
} while(++i<NPAL_ENT);
// Complete bitmap is now in memory, time to save it
TCHAR bmpfname[80];
wsprintf( bmpfname, (TCHAR*) TEXT( "\\USBDisk\\out.bmp" ) );
// open the file for writing
FILE *bmpFile = _wfopen(bmpfname,L"wb");
if(!bmpFile) { delete[] imgData; delete[] logpal; exit(6); }
// write the bitmap to file, in whatever chunks WinCE allows
size_t totWrit = 0, offset = 0, writeAmt = 0;
while(totWrit < bmfh.bfSize){
if(totWrit < sizeof(bmfh)){ // File header
offset = totWrit;
totWrit += fwrite( ((char*)&bmfh)+offset, 1, sizeof(bmfh)-offset, bmpFile );
}
else if(totWrit<sizeof(bmfh)+sizeof(bmih)){ // Image header
offset = totWrit - sizeof(bmfh);
totWrit += fwrite( ((char*)&bmih)+offset, 1, sizeof(bmih)-offset, bmpFile );
}
else if(totWrit<sizeof(bmfh)+sizeof(bmih)+palSize) { // Pallette
offset = totWrit - sizeof(bmfh) - sizeof(bmih);
totWrit += fwrite( ((char*)&logpal->palPalEntry)+offset, 1, palSize-offset, bmpFile );
}
else { // Image data
offset = totWrit - sizeof(bmfh) - sizeof(bmih) - palSize;
if(bmfh.bfSize-totWrit >= IO_SIZE) {
writeAmt = IO_SIZE;
}
else {
writeAmt = bmfh.bfSize-totWrit;
}
totWrit += fwrite( &imageBuffer[offset], 1, writeAmt, bmpFile );
}
// Close and open after each iteration to please WinCE
fflush(bmpFile);
fclose(bmpFile);
Sleep(4000);
bmpFile = _wfopen(bmpfname,L"ab");
if(!bmpFile) {flog->lprintf("Couldn't reopen bmpfile"); delete [] logpal; return 0;}
}
fclose(bmpFile);
if(totWrit != bmfh.bfSize) {
printf("BMP Size mismatch: %d/%d.",totWrit,bmfh.bfSize);
delete [] imgData;
delete [] logpal;
exit(-1);
}
// Cleanup
delete [] imgData;
delete [] logpal;
return 0;
}
``` | Typically I use CreateBitmap or CreateCompatibleBitmap to generate bitmaps in windows. I am unfamiliar with WinCE but the functions seem to be present. Your data looks to be in 8 bit per pixel with a 256 color palette so you will also most likely need CreatePalette, SelectPalette, and RealizePalette functions.
Something like (warning: untested code):
```
HBITMAP hBmp=CreateBitmap(width, height, 1, 8, imgData);
LOGPALETTE logpal=(LOGPALETTE)new BYTE[sizeof(LOGPALETTE)+256*sizeof(PALETTEENTRY)];
logpal.palVersion=0x300;
logpal.palNumEntries=256;
int i=0;
do { //no idea your palette's format, however it looks to be greyscale?
logpal->mypal[i].peRed=i;
logpal->mypal[i].peGreen=i;
logpal->mypal[i].peBlue=i;
logpal->mypal[i].peFlags=NULL;
while(++i<256);
HPALETTE hPal=CreatePalette(logpal);
//If your trying to display it to a window's DC called mywindowsDC
HDC hBmpDC = CreateCompatibleDC(mywindowsDC);
SelectObject(hBmpDC, hBmp);
SelectPalette(hBmpDC, hPal, TRUE);
BitBlt(mywindowsDC, 0, 0, width, height, hBmpDC, 0, 0, SRCCOPY);
RealizePalette(mywindowsDC);
//clean up
DeleteDC(hBmpDC);
delete [](BYTE *)logpal;
DeleteObject(hPal);
DeleteObject(hBmp);
``` | How to create a .bmp in WinCE | [
"",
"c++",
"image-processing",
"windows-ce",
"bmp",
""
] |
Say a user clicks on a link to download a file. The user gets the save as dialogue box but then clicks on cancel. How do you detect this? Meaning if the user hits the cancel link or doesn't get the whole file, the server should not record that the file was downloaded. | In the past I have done this:
```
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
flush()
log()
exit;
```
log should only run after readfile is complete meaning the entire file has been streamed to the user. It's been a while since I have done this and I don't know where the exact code is so this may not be exact but it should get you going.
EDIT I found the above code on php.net and it is more or less what I was describing, this method **should** work. | I think some HTTPd's don't log files into the access log until the request is rendered complete. You could try writing something that parses the log, greps the filename, and counts the number of lines.
Edit: Just tried with nginx. Confirmed my theory. I believe the same is true for Apache.
Edit #2: Why was this modded down? It's actually the correct answer according to the dupe-link on SO. I stand vindicated. | Best way to implement a download counter? | [
"",
"php",
""
] |
Is there a way to detect a right click followed by paste with JavaScript on IE and Firefox ?
Update:
I decided to use Jquery to do it:
```
$('#controlId').bind('paste', null, function() {
// code
});
```
It's not exactly what I was looking (because it gets fired on 'ctrl + v' as well as in 'right click + paste' but I can work around it.
Tested it on Chrome, Firefox 3, IE 7 and IE 6 and it's working | With IE you have onpaste
With Mozilla you can look into
oninput
and
```
elementReference.addEventListener("DOMCharacterDataModified", function(e){ foo(e);}, false);
```
There is no easy as pie solution.
Eric | I like this solution:
```
$('#txt_field').bind('input propertychange', function() {
console.log($(this).val());
});
``` | How to detect right mouse click + paste using JavaScript? | [
"",
"javascript",
"jquery",
""
] |
I want to write some javascript and have it call into the DOM for a page I am loading from a 3rd party domain. Can this be done? [This](https://stackoverflow.com/questions/335817) looks like what I've already tried using `IFRAME` but it would seem that doesn't work. Is these some other way like having FF run some javascript directly rather than as part of a page?
I know this has all kinds of security problems but I'm the guy writing the code and the only guy who will run it.
---
The backstory: I'm trying to automate some web site iterations.
My fist `IFRAME` pass didn't work because a web page from `file:////....` is not in the same domain as a page in `http://whatever.com`. Surprise, surprise. | If I understand the question correctly, you probably won't be able to do it using Javascript alone, because of the domain restriction that you experienced. However, if you have some knowlege on using shell scripts, or any scripting language, it should be no problem, all you need to do is invoke the good old curl.
Example in PHP:
```
<?php
$url = "http://www.example.com/index.html";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
$fp = curl_exec($ch);
curl_close($ch);
?>
```
And that's pretty much it. You have the actual HTML code in the $fp variable. So, all in all, what I would do is write a little Javascript Ajax function to PHP which does the curl and then returns the $fp variable via echo to the Javascript callback, and then maybe insert it on the document (using innerHTML or the DOM), and bam, you have access to all the stuff. Or you could just parse it in PHP. Either way, should work fine if you do it through curl. Hope that helps.
**Edit**: After some thought I seem to remember that Safari removes the cross domain restriction for localhost. After researching some more, I'm unable to find any documentation that supports this theory of mine, so I dug a little deeper and found a better (although hackier) way to accomplish this whole mess via Apache if you're using it (which you probably are).
> Apache’s mod\_proxy will take a request for something like “/foo” and actually tunnel the request to some remote destination like “<http://dev.domain.com/bar>”. The end result is that your web browser thinks you’ve made a call to <http://localhost/foo> but in reality you’re sending and retrieving data from a remote server. Security implications solved!
Example:
```
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule rewrite_module modules/mod_rewrite.so
```
Let’s assume that I want to access a file at <http://dev.domain.com/remote/api.php>. You would put all of the following into a :
```
# start mod_rewrite
RewriteEngine On
ProxyRequests Off
<Proxy>
Order deny,allow
Allow from all
</Proxy>
ProxyPass /apitest/ http://dev.domain.com/remote/api/
ProxyPassReverse /apitest/ http://dev.domain.com/remote/api/
RewriteRule ^/apitest/(.*)$ /remote/api/$1 [R]
```
[Source](http://www.ghidinelli.com/2008/12/27/how-to-bypass-cross-domain-restrictions-when-developing-ajax-applications)
**More edit:**
Seeing as how you want to avoid the whole server setup thing, I gave it a shot using an IFRAME on Safari (Mac), and it worked, at least for the domains I tried:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
</head>
<body>
<iframe src="http://www.stackoverflow.com/"></iframe>
</body>
</html>
``` | Read up on [bookmarklets](http://en.wikipedia.org/wiki/Bookmarklet). The basic idea is you create a bookmark that executes some Javascript code that dynamically injects Javascript into the page currently loaded in your browser. Most of the web page clipping applications do this. | Invoke JavaScript on 3rd party domain | [
"",
"javascript",
"dom",
"cross-domain-proxy",
""
] |
My use case is this, I want to call out to a webservice and if I am behind a proxy server that requires authentication I want to just use the default credentials...
```
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
```
Otherwise I'll just simply make the call, It would be very nice to determine if the auth is required up front, rather than handle the exception after I attempt to make the call.
Ideas? | `System.Net.WebProxy` has a property called `UseDefaultCredentials` that *may* be what you want (but I have to admit a bit of ignorance here). The link to the relevant documentation is [here](http://msdn.microsoft.com/en-us/library/system.net.webproxy_properties.aspx). | It was only after I had first deployed my [app](http://deepzoompublisher.com/viewer) that I realised some users were behind firewalls... off to work to test it. Rather than do a test for a '407 authentication required' I just do the same `Proxy` setup whether it might be needed or not...
```
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri.AbsoluteUri);
//HACK: add proxy
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
req.Proxy = proxy;
req.PreAuthenticate = true;
//HACK: end add proxy
req.AllowAutoRedirect = true;
req.MaximumAutomaticRedirections = 3;
req.UserAgent = "Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; DeepZoomPublisher.com)";
req.KeepAlive = true;
req.Timeout = 3 * 1000; // 3 seconds
```
I'm not sure what the relative advantages/disadvantages are (try{}catch{} without proxy first, versus just using the above), but this code now seems to work for me both at work (authenticating proxy) and at home (none). | How do I determine (elegantly) if proxy authentication is required in C# winforms app | [
"",
"c#",
"winforms",
"authentication",
"proxy",
""
] |
How can I generate a assembly qualified type name?
For an example, when configuring a membership provider, I would have to provide a assembly qualified type name for "SqlMembershipProvider" (in this example, i have copied the below configuration from somewhere) in "type" attribute.
How do you generate that assembly qualified type name?
Does it have to be typed manually everytime by examining an assembly type?
> ```
> <membership>
> <providers>
> <clear />
> <add name="AspNetSqlMembershipProvider"
> type="System.Web.Security.SqlMembershipProvider,
> System.Web, Version=2.0.0.0,
> Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
> connectionStringName="LocalSqlServer"/>
> </providers>
> </membership>
> ```
***[UPDATE]***: [Simpler PowerShell version](https://stackoverflow.com/questions/622902/powershell-tips-tricks-for-net-developers/622976#622976)
```
PS>([System.String]).AssemblyQualifiedName
System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
``` | This is a nice [handy tool](http://www.lennybacon.com/CommentView,guid,d571c376-42d0-427a-a7d0-ef9d22eab52c.aspx) (shell extension with source code) for copying the fully qualified name to clipboard by right clicking on any assembly.
**Update**: After seeing the comment from dance2die, thought of putting together a sample powershell script to export the type name to a csv file.
```
> [System.Reflection.Assembly]::LoadWithPartialName("System.Web")
> [System.Web.Security.SqlMembershipProvider] | select {$_.UnderlyingSystemType.AssemblyQualifiedName } | export-csv c:\typenames.csv
```
Using C#, if you want to generate the assembly qualified type name with all the references set, it is easy to build a test script using reflection..
```
using System;
using System.Reflection;
........
Type ty = typeof(System.Web.Security.SqlMembershipProvider);
string fullname = ty.AssemblyQualifiedName;
//"System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
``` | The easiest way to find that information is to use [Reflector](http://www.red-gate.com/products/reflector/), load the assembly, and copy the `Name` out of the assembly's manifest. The manifest information will be in the bottom pane of Reflector when your assembly is selected in the window above. | How can I retrieve an assembly's qualified type name? | [
"",
"c#",
"asp.net",
"configuration",
"powershell",
"web-config",
""
] |
Are `$_SESSION` variables stored on the client or the server? | The location of the `$_SESSION` variable storage is determined by PHP's `session.save_path` configuration. Usually this is `/tmp` on a Linux/Unix system. Use the `phpinfo()` function to view your particular settings if not 100% sure by creating a file with this content in the `DocumentRoot` of your domain:
```
<?php
phpinfo();
?>
```
Here is the link to the PHP documentation on this configuration setting:
<http://php.net/manual/en/session.configuration.php#ini.session.save-path> | As mentioned already, the contents are stored at the server. However the session is identified by a session-id, which is stored at the client and send with each request. Usually the session-id is stored in a cookie, but it can also be appended to urls. (That's the `PHPSESSID` query-parameter you some times see) | Where are $_SESSION variables stored? | [
"",
"php",
""
] |
I would like to take a multi-page pdf file and create separate pdf files per page.
I have downloaded [reportlab](http://www.reportlab.org/index.html) and have browsed the documentation, but it seems aimed at pdf generation. I haven't yet seen anything about processing PDF files themselves.
Is there an easy way to do this in python? | Updated solution for the latest release of PyPDF (3.0.0) and to split a range of pages.
```
from PyPDF2 import PdfReader, PdfWriter
file_name = r'c:\temp\junk.pdf'
pages = (121, 130)
reader = PdfReader(file_name)
writer = PdfWriter()
page_range = range(pages[0], pages[1] + 1)
for page_num, page in enumerate(reader.pages, 1):
if page_num in page_range:
writer.add_page(page)
with open(f'{file_name}_page_{pages[0]}-{pages[1]}.pdf', 'wb') as out:
writer.write(out)
``` | ```
from PyPDF2 import PdfWriter, PdfReader
inputpdf = PdfReader(open("document.pdf", "rb"))
for i in range(len(inputpdf.pages)):
output = PdfWriter()
output.add_page(inputpdf.pages[i])
with open("document-page%s.pdf" % i, "wb") as outputStream:
output.write(outputStream)
```
etc. | split a multi-page pdf file into multiple pdf files with python? | [
"",
"python",
"pdf",
""
] |
I'm currently developing a tutorial site for teaching the fundamentals of Web development (HTML, CSS, and JavaScript, for starters). I'd like a setup where I could give in-depth coverage of all sorts of topics and then provide a basic sandbox environment where the user could write code which solves the question asked at the end of each tutorial section.
For example, if I'd covered multiplication in a previous tutorial, and the user had just finished a lesson on functions being capable of returning values, I might request that they submit a function which returns the product of two parameters.
Is this not the *perfect* instance in which using dynamic function creation would be considered a good idea? Let's look at an example.
```
<script>
function check()
{
eval('var f = ' + document.getElementById('user_code').value);
if (f(5, 10) == 50)
{
// user properly wrote a function which
// returned the product of its parameters
}
}
</script>
```
Is this at all a bad idea? If so, please explain. | This sounds like it could work. However, the biggest challenge in your environment might be error handling. Students will surely make all sorts of errors:
* Compile time errors, that will be detected in `eval()`
* Run time errors, that will be detected when you call the function
* Undetectable run time errors, such as an infinite loop or a stack overflow
A more elaborate approach might parse the entered Javascript into a parse tree representation, then compare it to an expected parse tree. If it does not match, then point out what might be wrong and have the student try again. If it does match, then you can `eval()` and call the function, knowing that it will do what you expect.
Implementing a lexer and parser for Javascript in Javascript would be challenging but certainly not impossible. | Sounds like you want to remake [Firebug](http://getfirebug.com/) or even the new Developer Tools in IE8. Due to that, I'm going to have to say there is never a useful case. Not to mention the possibilities of script injection if this site goes public. | Is this a suitable case in which using dynamic function creation would be justified? | [
"",
"javascript",
"dynamic-function",
""
] |
I have looked all of the place for this and I can't seem to get a complete answer for this. So if the answer does already exist on stackoverflow then I apologize in advance.
I want a unique and random ID so that users in my website can't guess the next number and just hop to someone else's information. I plan to stick to a incrementing ID for the primary key but to also store a random and unique ID (sort of a hash) for that row in the DB and put an index on it.
From my searching I realize that I would like to avoid collisions and I have read some mentions of SHA1.
My basic requirements are
* Something smaller than a GUID. (Looks horrible in URL)
* Must be unique
* Avoid collisions
* Not a long list of strange characters that are unreadable.
An example of what I am looking for would be www.somesite.com/page.aspx?id=AF78FEB
I am not sure whether I should be implementing this in the database (I am using SQL Server 2005) or in the code (I am using C# ASP.Net)
EDIT:
From all the reading I have done I realize that this is security through obscurity. I do intend having proper authorization and authentication for access to the pages. I will use .Net's Authentication and authorization framework. But once a legitimate user has logged in and is accessing a legimate (but dynamically created page) filled with links to items that belong to him. For example a link might be www.site.com/page.aspx?item\_id=123. What is stopping him from clicking on that link, then altering the URL above to go www.site.com/page.aspx?item\_id=456 which does NOT belong to him? I know some Java technologies like Struts (I stand to be corrected) store everything in the session and somehow work it out from that but I have no idea how this is done. | [In response to the edit]
You should consider query strings as "evil input". You need to programmatically check that the authenticated user is allowed to view the requested item.
```
if( !item456.BelongsTo(user123) )
{
// Either show them one of their items or a show an error message.
}
``` | [Raymond Chen](https://devblogs.microsoft.com/oldnewthing) has a good article on why you shouldn't use "half a guid", and offers a suitable solution to generating your own "not quite guid but good enough" type value here:
> [GUIDs are globally unique, but substrings of GUIDs aren't](https://devblogs.microsoft.com/oldnewthing/20080627-00/?p=21823)
His strategy (without a specific implementiation) was based on:
> * Four bits to encode the computer number,
* 56 bits for the timestamp, and
* four bits as a uniquifier.
> We can reduce the number of bits to make the computer unique since the number of computers in the cluster is bounded, and we can reduce the number of bits in the timestamp by assuming that the program won’t be in service 200 years from now.
> You can get away with a four-bit uniquifier by assuming that the clock won’t drift more than an hour out of skew (say) and that the clock won’t reset more than sixteen times per hour. | Need a smaller alternative to GUID for DB ID but still unique and random for URL | [
"",
"c#",
"asp.net",
"database",
"url",
""
] |
I'm trying to return sequence.nextval to my program from a proc stored in a package. I'm pretty green when it comes to PL/SQL and I'm kind of at a loss as to what is happening. The error that is actually being return is
PLS-00306: Wrong number or types of arguments in call to PROCGET\_BOOKMARKID line 1, column 7 statement ignored.
Here is my package creation code...
```
create or replace
package BOOKMARKS AUTHID DEFINER is
type t_Bookmark is ref cursor;
procedure procGet_Bookmarked_Information(bookmarkId in NUMBER, bookmark out t_Bookmark);
procedure procInsert_Bookmark(bookmarkId in NUMBER, currExtent in VARCHAR2, selectedLayers in VARCHAR2);
procedure procGet_Bookmark_Id(bookmarkId out NUMBER);
end BOOKMARKS;
```
And the proc for get\_bookmark\_id looks like this (the other procs work fine so I'm not going to post them)...
```
procedure procGet_Bookmark_Id(bookmarkId out NUMBER)
IS
BEGIN
SELECT seq_bookmarks.nextval INTO bookmarkId
FROM dual;
END procGet_Bookmark_Id;
```
Now, I'm sure it's not my sequence. I can get the nextval if I just query the db directly from my code by doing this...
```
string sql = string.Format(@"select {0}.seq_bookmarks.nextval from dual", ApplicationSchema);
```
Where application schema is just the db I'm connecting to in this case.
So, it appears to me that the problem is completely in my PL/SQL and that would make sense because I've hardly used it. Any ideas?
**EDIT**
Ok, so here is the code that is actually making the call.
```
DataOperationResult result = DataAccess.GetBookmarkId();
DataRow currResult = result.DataTableResult.Rows[0];
```
Where DataAccess is a class of just queries and the following is the code there for this specific query.
```
string sql = string.Format("{0}.bookmarks.procGet_Bookmark_Id", ApplicationSchema);
DataOperation operation = new DataOperation(DataOperationType.ExecuteScalar, ConnectionString, System.Data.CommandType.StoredProcedure, sql);
return operation.PerformOperation();
```
Application Schema is just the database we want to query. ExecuteScalar is kind of long-winded and it's code I've not written that should be assumed to work (keyword being assumed). Hopefully this is enough to get an idea of what's happening though. | I've just compiled your package, in `PL/SQL Developer` it works fine.
The problem seems to be with the datatypes in your `C#` code.
From what I see in description, you don't bind any parameters. You should bind parameters somewhere in your code, like
```
OracleParameter bid = new OracleParameter("bookmarkID", OracleDbType.Number);
bid.Direction = ParameterDirection.Output;
command.Parameters.Add(bid);
```
If there are lots of abstractions you need to deal with, you may redefine you procedure as a function:
```
FUNCTION procGet_Bookmark_Id RETURN INTEGER
IS
res INTEGER;
BEGIN
SELECT seq_bookmarks.nextval
INTO res
FROM dual;
RETURN res;
END procGet_Bookmark_Id;
```
and call it in a `SELECT` query:
```
SELECT bookmarks.procGet_Bookmark_id FROM dual;
```
, which you seem to be able to do. | The error: "Wrong number or types of arguments in call to blah" refers to errors in the calling code, not the called code.
You should check the following:
* The parameter you're passing is a NUMBER or a type that can be easily converted from a NUMBER.
* The parameter you're passing is a variable, as opposed to a literal or constant. | PL/SQL issues returning a sequence scalar value | [
"",
"c#",
"oracle",
"stored-procedures",
"plsql",
""
] |
I’m having a little Architecture problem. In my project I have a Business Logic Layer (BLL) that contains all my business rules, models and OO API for the interface. Each object has static methods like getById that return an instance of said object. Each object also has methods like save and, delete. This is very straightforward OO code.
Now I have a DataAccess layer (DAL), contained in a separate namespace, for each BLL object I have a DataClass or “Repository” which executes the getById and save commands. So in a way, the BLL save and getById methods are a thin layer around the DataClass methods.
```
public static NewsItem GetByID(int id)
{
return DataFactory.GetNewsItemRepository().GetNewsItemById(id);
}
```
In order for the DataClasses to return BLL objects, they need to know the BLL. so now we have:
GUI ---> BLL <---->DAL
The DataFactory only returns objects that implement an Interface, so I can hide implementation details like “OracleNewsItemRepository”.
But now for the thing that has been bugging me ever since I started Object Oriented programming. In my current solution, both BLL and the DAL need to know each other. This is a Circular Dependency, and it is best practice to avoid circular dependencies. Also I only want to expose the interfaces (and my DataFactory) and not my classes. This can be done by placing the DAL layer in a separate Assembly. Which would make sense. However, Visual Studio does not allow two Assemblies to refer eachother. Another question about this: [C# internal access modifiers](https://stackoverflow.com/questions/457044/c-internal-access-modifiers)
Somehow I think I got my whole data access pattern wrong. It feels like I am convoluting the ActiveRecord pattern with other stuff like DataMappers. I have spent a lot of time on Martin Fowler’s site, but those patterns are described very generic and are illustrated by a very abstract UML diagram.
They don’t solve my problem. Maybe I’m a bit anal, and there is no such thing as a “perfect data access pattern”. And what I do now doesn’t seem terribly wrong. But how I do things now, seems off…
Any ideas? | I think your data access pattern is fine. What you are not doing is coupling your BLL to the OracleDAL. You are coupling to the DAL interfaces. A certain bit of coupling is absolutely required or you could never get anything done.
I assume that your DataFactory and the INewsItemRepository classes exist outside your DAL Layer. The following is an example of how my solutions are organized. I don't use ActiveRecord, so this may not suit you perfectly.
```
Core (Project)
Domain
Business Entities
Data
Repository Interfaces
**Your DataFactory**
OracleData (Project)
Data
Oracle Repository Implementations
SqlData (Project)
Data
Sql Repository Implementations
UI (Project)
```
Hope this helps. | In my opinion:
The Data Access Layer (DAL) should operate on POCOs (Plain old CLR objects) using operations such as: `SaveNewsItem ( NewsItemDAO newsItemDAO )`. The POCOs are your DAOs (Data Access Objects).
The Business Layer should contain the logic to convert a Data Access Object (DAO) into a rich business object, which is probably just the DAO plus some operations as well as any decoration/enrichment.
The DAL should have no knowledge at all about the Business Logic Layer. It should, in theory, be able to be called from any client. For example, what if you wanted to seperate the DAL from the application and deploy it as a seperate service exposing itself via WCF?
As mentioned, the DAL operations, e.g. SaveNewsItem should be be accessed by the BO via interfaces, perhaps via dependency injection/IoC. | Business Logic Layer and Data Access layer: circular dependency | [
"",
"c#",
"design-patterns",
"architecture",
""
] |
I am submitting a ColdFusion Form and I want to run some JavaScript to check field validation before I run my ColdFusion code to process the form as needed.
How can I do this? What do I do in JS to call my .cfm file after the form passes validation?
Thanks!
-Jason | You need
```
<form name="myform" action="myserverscript.cfm" onsubmit="return validate()">
```
if you return true the form submits, false it doesn't | i hope you're doing the validation on the server side as well. never rely on just javascript to scrub your data. | JavaScript on Form Submit | [
"",
"javascript",
"coldfusion",
""
] |
I'm doing some portlet development for IBM WebSphere Portal 6.1. However, the deployment process is painfully slow. As this is my first time doing portlet development, I'm not too familiar with the various portal servers out there. I'd like some recommendations for a lightweight portal server on which I can deploy quickly for development. | Pluto is the answer!
<http://portals.apache.org/pluto/>
I'm very happy now. :) | I believe Liferay has become Sun's [adopted strategy](http://www.liferay.com/web/guest/partners/sun), if that has any bearing. | Lightweight portal server for WebSphere Portal development? | [
"",
"java",
"websphere",
"portal",
"websphere-portal",
""
] |
In Visual Studio and C#, when using a built in function such as ToString(), IntelliSense shows a yellow box explaining what it does.
[](https://i.stack.imgur.com/P7MxK.jpg)
[](https://i.stack.imgur.com/OKDcw.jpg)
**How can I have that for functions and properties I write?** | To generate an area where you can specify a description for the function and each parameter for the function, type the following on the line before your function and hit `Enter`:
* **C#:** `///`
* **VB:** `'''`
See [Recommended Tags for Documentation Comments (C# Programming Guide)](https://msdn.microsoft.com/en-us/library/5ast78ax.aspx) for more info on the structured content you can include in these comments. | What you need is **xml comments** - basically, they follow this syntax (as vaguely described by Solmead):
**C#**
```
///<summary>
///This is a description of my function.
///</summary>
string myFunction() {
return "blah";
}
```
**VB**
```
'''<summary>
'''This is a description of my function.
'''</summary>
Function myFunction() As String
Return "blah"
End Function
``` | How to have comments in IntelliSense for function in Visual Studio? | [
"",
"c#",
"vb.net",
"visual-studio",
"visual-studio-2008",
"xml-comments",
""
] |
I'm a modest graduate student in a high energy particle physics department. With an unfounded distaste for C/C++ and a founded love of python, I have resorted to python for my data analysis so far (just the easy stuff) and am about to attempt backing python scripts against ROOT libraries and, particularly, utilize MINUIT for some parameter minimization.
As well as asking if anyone has any tips for the installation and usage of these, I wondered if it was worth it to even attempt it or just to slip into the "norm" of using C/C++, or if things like pyminuit are usable. Or do you think I could wrap entire C/C++ scripts into python code to make use of my existing self-written analysis methods (I have no wrapper experience as of yet). Sorry for the vagueness; I'm headed into a great unknown that far outweighs my current experience. | You are aware of [pyROOT](http://wlav.web.cern.ch/wlav/pyroot/), right?
Never tried it myself, so I don't know how it might stack up against your needs. | It's probably worth checking out [rootpy](http://ndawe.github.com/rootpy/). Maybe not totally mature yet, but it's a step in the right direction.
Yes, rootpy is built on top of [PyROOT](http://wlav.web.cern.ch/wlav/pyroot/), but with some additional features:
* it emphasizes a pythonic interface and hides some of the ugliness of ROOT;
* it integrates with [matlibplot](http://matplotlib.sourceforge.net/), which has a larger development community, and a greater presence on SO, not to mention better looking plots;
* it allows conversion to [HDF5](http://www.hdfgroup.org/HDF5/) files, which will allow you to share data with people who can't take the time to install the monolithic ROOT package.
Unfortunately, as long as you're working with something built on top of [CINT](http://root.cern.ch/drupal/content/cint) (which PyROOT is), you'll still have to deal with one of the [ugliest parts of ROOT](http://root.cern.ch/drupal/content/do-we-need-yet-another-custom-c-interpreter).
---
The other option, if you're sick of fumbling with PyROOT, is to use one of the [packages that converts ROOT directly to HDF5](https://github.com/dguest/ttree2hdf5) | Python, ROOT, and MINUIT integration? | [
"",
"python",
"word-wrap",
"data-analysis",
"root-framework",
""
] |
It seems that unsigned integers would be useful for method parameters and class members that should never be negative, but I don't see many people writing code that way. I tried it myself and found the need to cast from int to uint somewhat annoying...
Anyhow what are you thoughts on this?
### Duplicate
> [Why is Array Length an Int and not an UInt?](https://stackoverflow.com/questions/6301/why-is-array-length-an-int-and-not-an-uint) | Using the standard ones probably avoids the casting to unsigned versions. In your code, you can probably maintain the distinction ok, but lots of other inputs and 3rd party libraries wont and thus the casting will just drive people mad! | The idea, that unsigned will prevent you from problems with methods/members that should not have to deal with negative values is somewhat flawed:
* now you have to check for big values ('overflow') in case of error
+ whereas you could have checked for <=0 with signed
* use only one signed int in your methods and you are back to square "signed" :)
Use unsigned when dealing with bits. But don't use bits today anyway, except you have such a lot of them, that they fill some megabytes or at least your small embedded memory. | Why aren't unsigned variables used more often? | [
"",
"c#",
".net",
""
] |
I have 2 vector of with one has vec1{e1,e2,e3,e4} and the other one with vec2 {e2,e4,e5,e7}
How to effectively get three vector from above vectors such that 1.has elements that is available only in vec1 similarly 2 has only vec2 elements and 3.with common elements | `std::set_intersection` should do the trick, if both vectors are sorted:
<http://msdn.microsoft.com/en-us/library/zfd331yx.aspx>
```
std::set_intersection(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), std::back_inserter(vec3));
```
A custom predicate can be used for the comparison too:
```
std::set_intersection(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), std::back_inserter(vec3), my_equal_functor());
```
If they are not sorted, you may of course sort them first, or alternatively, you can iterate through vec1, and for each element, use std::find to see if it exists in vec2. | What you're asking for is that `vec3` be the *intersection* of the other two. Jalf demonstrates how to populate `vec3` using the `std::set_intersection` function from [the `<algorithm>` header](http://dinkumware.com/manuals/?manual=compleat&page=algorith.html). But remember that for the set functions to work, **the vectors must be sorted**.
Then you want `vec1` and `vec2` to be the *difference* between themselves and `vec3`. In set notation:
```
vec1 := vec1 \ vec3;
vec2 := vec2 \ vec3;
```
You can use the `std::set_difference` function for that, but you can't use it to modify the vectors in-place. You'd have to compute another vector to hold the difference:
```
std::vector<foo> temp;
std::set_difference(vec1.begin(), vec1.end(),
vec3.begin(), vec3.end(),
std::back_inserter(temp));
vec1 = temp;
temp.clear();
std::set_difference(vec2.begin(), vec2.end(),
vec3.begin(), vec3.end(),
std::back_inserter(temp));
vec2 = temp;
``` | Extract element from 2 vectors? | [
"",
"c++",
"vector",
"iterator",
"containers",
""
] |
I have a windows service installed using installutil and set to "Autostart". My problem is that when some servers are rebooted it attempts to start before "Microsoft SQL service" has started- I can see this by looking at the event log during a system restart. What is the best way of making my service "auto start" AFTER Sql server service has started?
I am toying with the idea of creating a SQL job set to start when "SQL server agent" starts that in turn starts the windows service. But hopefully, there is an easy, effective way of controlling the order in which automatic services start up. | Each Windows Service has a list of other services it depends on. That means it'll wait until its dependencies have started before it will attempt to start, and it'll start them for you if they weren't started automatically when yours is started.
If you're creating your Windows Service in .NET, there's a blog post here that might be helpful:
[How to: Code Service Dependencies](http://jschreuder.bloggingabout.net/2006/12/07/how-to-code-service-dependencies/)
Otherwise there's a Microsoft kb entry here that details a way to add service dependencies via the registry:
[How to delay loading of specific services](http://support.microsoft.com/kb/193888) | You can set dependencies between the services.
[See here:](http://support.microsoft.com/kb/193888) | Controlling start up sequence of a windows service | [
"",
"sql",
"windows-services",
"autostart",
"installutil",
""
] |
I am not very familiar with databases and the theories behind how they work. Is it any slower from a performance standpoint (inserting/updating/querying) to use Strings for Primary Keys than integers?
For Example I have a database that would have about 100 million row like `mobile number, name and email`. **mobile number and email** would be unique. so can I have the mobile number or email as a primary key,
well it effect my query performance when I search based on email or mobile number. similarly the primary key well be used as foreign key in 5 to 6 tables or even more.
I am using MySQL database | Technically yes, but if a string makes sense to be the primary key then you should probably use it. This all depends on the size of the table you're making it for and the length of the string that is going to be the primary key (longer strings == harder to compare). I wouldn't necessarily use a string for a table that has millions of rows, but the amount of performance slowdown you'll get by using a string on smaller tables will be minuscule to the headaches that you can have by having an integer that doesn't mean anything in relation to the data. | Another issue with using Strings as a primary key is that because the index is constantly put into sequential order, when a new key is created that would be in the middle of the order the index has to be resequenced... if you use an auto number integer, the new key is just added to the end of the index. | Strings as Primary Keys in MYSQL Database | [
"",
"mysql",
"sql",
"database",
"database-design",
"primary-key",
""
] |
I have a problem in my C# ASP.NET application, where the id and name tags are modified at runtime with a prefix "MainView\_" and "MainView$" respectively. So my code:
```
<asp:Button ID="OKToContinueCheckInButton" runat="server" CausesValidation="False" Visibility="false" Style="display: none" OnClick="btnOKToContinueCheckIn" />
<script type="text/javascript">
<!--
var answer = confirm("Some Warning");
if (answer)
document.getElementById('OKToContinueCheckInButton').click();
// -->
</script>
```
becomes:
```
<input type="submit" name="MainView$OKToContinueCheckInButton" value="" id="MainView_OKToContinueCheckInButton" Visibility="false" style="display: none" />
<script type="text/javascript">
<!--
var answer = confirm("Some Warning");
if (answer)
document.getElementById('OKToContinueCheckInButton').click();
// -->
</script>
```
getElementID() returns null because the name has changed. Can anyone tell me why this occurs and if there is a way to possibly disable it from changing the id and name values. Thanks!
-Sephrial | I think this would help you...
```
<script type="text/javascript">
<!--
var answer = confirm("Some Warning");
if (answer)
document.getElementById('<%= OKToContinueCheckInButton.ClientID %>').click();
// -->
</script>
```
This is the part that does the trick
```
<%= OKToContinueCheckInButton.ClientID %>
``` | This is a fundamental part of the way the Asp .Net Forms model work.
The IDs are changed so that you don't have to worry about keeping IDs unique across user controls, custom controls, repeaters etc.
You can use Cyril's method. I also find JQuery suits this model very well to because you can easily reference controls by their class or position in the document. | id and name attributes of HTML elements manipulated by ASP.NET | [
"",
"asp.net",
"javascript",
"html",
""
] |
how do I make a pointer to a multidimensional array, which have a unknown size? I've tried this:
`int **triangles;`
`triangles = new int[numTriangles][3];`
But i get this error:
`cannot convert 'int (*)[3]' to 'int**' in assignment` | ```
triangles = new int[numTriangles*3];
```
Then access it as:
```
triangles[numTriangles*triangleIndex+vertexIndex] = blah;
```
But this is tedious and error prone so I suggest using [boost.multi\_array](http://www.boost.org/doc/libs/1_38_0/libs/multi_array/doc/index.html) instead, or rolling your own (really simple):
```
template<class T>
class Matrix {
public:
Matrix(int _w, int _h) : data(_w*_h), w(_w), h(_h) {
}
T & operator()(int x, int y) { return data[y * w + x]; }
T const& operator()(int x, int y) const { return data[y * w + x]; }
private:
std::vector<T> data;
int w, h;
};
// usage:
int main() {
Matrix<float> triangles(numTriangles, 3);
triangles(triangleIndex, vertexIndex) = blah;
}
```
If, on the other hand, you actually want an array of triangles, rather than a twodimensional array, just use a `vector<Triangle>` where Triangle is a class :) | Well, the error message says it :) If you 'new an array, then new returns a pointer to its first element.
A multidimensional array is just another name for an array of arrays. You 'newed an array of `int[3]`, and precisely numTriangles elements of those. So what new does is returning a pointer to `int[3]`. The variable you assign the result to has to have that type, which is a pointer to an array of 3 integers:
```
int (*triangles)[3];
triangles = new int[numTriangles][3];
triangles[triangleIndex][vertexIndex] = 42;
```
Of course, typedefs also help here:
```
typedef int triangles_t[3];
triangles_t * triangles = new int[numTriangles][3];
```
The parentheses are needed because of the C++ precedence rules. They tell the compiler that it's not creating an array of three pointers to integers, but a pointer to an array of 3 integers. This is similar to the more common use on function pointers (`"void (*funptr)()"`)... | How do I make a pointer to a multidimensional array which has an unknown size? | [
"",
"c++",
"arrays",
"pointers",
"multidimensional-array",
""
] |
C++ is unable to make a template out of a typedef or typedef a templated class. I know if I inherit and make my class a template, it will work.
Examples:
```
// Illegal
template <class T>
typedef MyVectorType vector<T>;
//Valid, but advantageous?
template <class T>
class MyVectorType : public vector<T> { };
```
Is doing this advantageous so that I can "fake" a typedef or are there better ways to do this? | C++0x will add template typedefs using the `using` keyword.
Your solution declares a new type, not a type "alias", e.g. you cannot initialize a `MyVectorType &` (reference) with a `vector<T>`. This might not be a problem for you, but if it is, but you don't want to reference vector in your code, you can do:
```
template <typename T>
class MyVectorType {
public:
typedef std::vector<T> type;
};
``` | Inheritance is not what you want. A more idiomatic approach to emulating a templated typedef is this:
```
template <typename T> struct MyVectorType {
typedef std::vector<T> t;
};
```
Refer to the typedef like this:
```
MyVectorType<T>::t;
``` | Inheritance instead of typedef | [
"",
"c++",
"inheritance",
"templates",
"typedef",
""
] |
Over the past year I have heard alot about Velocity and NVelocity. Reading their documentation and doing searches on the net hasn't given me the answers I was looking for.
In what situation would I use this library in my development? What problem does it solve that didn't already have a solution? | Since the dawn of web apps, people started to think about separation of concerns in many applications, including web applications. The challenge is to separate what is view code from what is business code, or logic code. When jsps first arrived, many people where coding lots of logic in jsps directly (stuff like db access and other), breaking the basic principle of **separation of concerns** (jsps should be responsible for the presentation, not for the logic).
Velocity, Freemarker and others are templating engines that allows the separation of UI logic and business logic, thus facilitating changes in the presentation while minimizing the changes on the business side. These template engines have facilities for doing common UI tasks such as showing a block of html if some condition holds true, or iterating over a list **while maintaining logic code outside of the view**. This is fundamental for maintaining a complex application in the long run. | I think it's important to point out that compared to JSP/ASP.NET as a templating mechanisim, Velocity/NVelocity really 'ENFORCE' the seperation of concern.
With <% .. %> of JSP/ASP.NET, any Java/.NET code is allowed. Which is why sometimes you do see business logic code in these files.
With Velocity/NVelocity you can't embed long series of code. Instead you are really forced to pass in computed values, which Velocity/NVelocity picks up and displays them according to the way the template is designed.
Another point would be that they can work outside of a Web Container environment (at least Velocity can AFAIK). Imagine that you had designed a report template with JSP/ASP.NET. It works fine from the web. And then suddenly there is a change request to have it be done from a Desktop application. Rather than embed a Web Container in it, you could initialize Velocity/NVelocity, compute the values, then render the template. | Why do people use Velocity and/or NVelocity? | [
"",
"java",
".net",
"asp.net-mvc",
"templates",
"theory",
""
] |
I need to write some javascript to strip the hostname:port part from a url, meaning I want to extract the path part only.
i.e. I want to write a function getPath(url) such that getPath("<http://host:8081/path/to/something>") returns "/path/to/something"
Can this be done using regular expressions? | Quick 'n' dirty:
```
^[^#]*?://.*?(/.*)$
```
Everything after the hostname and port (including the initial /) is captured in the first group. | RFC 3986 ( <http://www.ietf.org/rfc/rfc3986.txt> ) says in Appendix B
The following line is the regular expression for breaking-down a
well-formed URI reference into its components.
```
^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
12 3 4 5 6 7 8 9
```
The numbers in the second line above are only to assist readability;
they indicate the reference points for each subexpression (i.e., each
paired parenthesis). We refer to the value matched for subexpression
as $. For example, matching the above expression to
```
http://www.ics.uci.edu/pub/ietf/uri/#Related
```
results in the following subexpression matches:
```
$1 = http:
$2 = http
$3 = //www.ics.uci.edu
$4 = www.ics.uci.edu
$5 = /pub/ietf/uri/
$6 = <undefined>
$7 = <undefined>
$8 = #Related
$9 = Related
```
where `<undefined>` indicates that the component is not present, as is
the case for the query component in the above example. Therefore, we
can determine the value of the five components as
```
scheme = $2
authority = $4
path = $5
query = $7
fragment = $9
``` | Regular expression to remove hostname and port from URL? | [
"",
"javascript",
"regex",
""
] |
We have various spreadsheets that employ deliciously complicated macros and third party extensions to produce complicated models. I'm working on a project that involves slightly tweaking various inputs and seeing the results. Rather than doing this by hand or writing VBA, I'd like to see if I can write a python script to drive this. In other words, the python script will start up, load the excel sheet, and then interact with the sheet by making minor changes in some cells and seeing how they affect other cells.
So, my question is twofold:
* What is the best library to use to drive excel from python in such fashion?
* Where's the best documentation/examples on using said library?
Cheers,
/YGA | For controlling Excel, use pywin32, like @igowen suggests.
Note that it is possible to use static dispatch. Use `makepy.py` from the pywin32 project to create a python module with the python wrappers. Using the generated wrappers simplifies development, since for instance ipython gives you tab completion and help during development.
Static dispatch example:
```
x:> makepy.py "Microsoft Excel 11.0 Object Library"
...
Generating...
Importing module
x:> ipython
```
```
> from win32com.client import Dispatch
> excel = Dispatch("Excel.Application")
> wb = excel.Workbooks.Append()
> range = wb.Sheets[0].Range("A1")
> range.[Press Tab]
range.Activate range.Merge
range.AddComment range.NavigateArrow
range.AdvancedFilter range.NoteText
...
range.GetOffset range.__repr__
range.GetResize range.__setattr__
range.GetValue range.__str__
range.Get_Default range.__unicode__
range.GoalSeek range._get_good_object_
range.Group range._get_good_single_object_
range.Insert range._oleobj_
range.InsertIndent range._prop_map_get_
range.Item range._prop_map_put_
range.Justify range.coclass_clsid
range.ListNames range.__class__
> range.Value = 32
...
```
Documentation links:
* The O'Reilly book [Python Programming on Win32](http://my.safaribooksonline.com/1565926218) has an [Integrating with Excel](http://my.safaribooksonline.com/1565926218/ch09-84996) chapter.
* Same book, free sample chapter [Advanced Python and COM](http://oreilly.com/catalog/pythonwin32/chapter/ch12.html) covers makepy in detail.
* [Tutorials](http://www.google.com/search?q=python+excel+tutorial)
* [win32com documentation](http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/docindex.html), I suggest you read [this](http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/QuickStartClientCom.html) first. | I've done this by using [pywin32](http://python.net/crew/mhammond/win32/Downloads.html). It's not a particularly pleasant experience, since there's not really any abstraction; it's like using VBA, but with python syntax. You can't rely on docstrings, so you'll want to have the MSDN Excel reference handy (<http://msdn.microsoft.com/en-us/library/aa220733.aspx> is what I used, if I remember correctly. You should be able to find the Excel 2007 docs if you dig around a bit.).
See [here](http://web.archive.org/web/20090916091434/http://www.markcarter.me.uk/computing/python/excel.html) for a simple example.
```
from win32com.client import Dispatch
xlApp = Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Add()
xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
xlApp.ActiveWorkbook.Close(SaveChanges=0) # see note 1
xlApp.Quit()
xlApp.Visible = 0 # see note 2
del xlApp
```
Good luck! | Driving Excel from Python in Windows | [
"",
"python",
"excel",
"scripting",
""
] |
When I attempt to use the iterator form of parsing for a Spirit grammar I get a argument passing conversion error from the iterator type to const char\*. How do I fix this?
There are some restrictions. I'm using an iterator adapter on large inputs, so it is not feasible for me to convert to a C style string.
Here is sample code demonstrating the issue:
```
#include <boost/spirit/core.hpp>
#include <boost/spirit/iterator/file_iterator.hpp>
#include <vector>
#include <string>
using std;
using boost::spirit;
struct ex : public grammar<route_grammar> {
template <typename ScannerT> struct defintion {
definition(ex const& self) {
expression = real_p;
}
rule<ScannerT> expression;
rule<ScannerT> const& start() const { return expression; }
};
int main() {
file_iterator<char> first;
file_iterator<char> last = first.make_end();
ex ex_p;
parse_info<file_iterator<char> > info = parse(first, last, ex_p, space_p);
return 0;
}
```
This code breaks with: error: cannot convert `const boost::spirit::file_iterator<char_t, boost::spirit::fileiter_impl::mmap_file_iterator<char_t> >` to `const char*` in argument passing | Hard to tell from the code as posted, since it contains a few basic errors.
After correction of these, it compiles fine on my machine (with MSVC++7.1):
```
#include <boost/spirit/core.hpp>
#include <vector>
#include <string>
using namespace std;
using namespace boost::spirit;
struct ex : public grammar<ex> {
template <typename ScannerT>
struct definition {
definition(ex const& self)
{
expression = real_p;
}
rule<ScannerT> expression;
rule<ScannerT> const& start() const { return expression; }
};
};
int main() {
vector<char> v;
v.push_back('3'); v.push_back('.'); v.push_back('2');
ex ex_p;
parse_info<vector<char>::iterator> info = parse(v.begin(), v.end(), ex_p, space_p);
return 0;
}
``` | Here is one way of getting the char \*'s pointing at the same elements as the iterators:
```
&v.front() // v.begin()
&v.back() + 1 // v.end()
```
I'm not sure how you got this to compile though:
```
vector<char> v;
v.push_back("3.2");
``` | Using Iterator parsing with Boost::Spirit Grammars | [
"",
"c++",
"boost",
"boost-spirit",
""
] |
I want to trigger the submit event of the form the current element is in. A method I know works sometimes is:
```
this.form.submit();
```
I'm wondering if there is a better solution, possibly using jQuery, as I'm not 100% sure method works in every browser.
Edit:
The situation I have is, as follows:
```
<form method="get">
<p><label>Field Label
<select onchange="this.form.submit();">
<option value="blah">Blah</option>
....
</select></label>
</p>
</form>
```
I want to be able to submit the form on change of the `<select>`.
What I'm looking for is a solution that works on any field within any form without knowing the id or name on the form. `$('form:first')` and `$('form')` won't work because the form could be the third on the page. Also, I am using jQuery on the site already, so using a bit of jQuery is not a big deal.
So, is there a way to have jQuery retrieve the form the input/select/textarea is in? | I think what you are looking for is something like this:
```
$(field).closest("form").submit();
```
For example, to handle the onchange event, you would have this:
```
$(select your fields here).change(function() {
$(this).closest("form").submit();
});
```
If, for some reason you aren't using jQuery 1.3 or above, you can call `parents` instead of `closest`. | ```
this.form.submit();
```
This is probably your best bet. Especially if you are not already using jQuery in your project, there is no need to add it (or any other JS library) just for this purpose. | Is there a better jQuery solution to this.form.submit();? | [
"",
"javascript",
"jquery",
"forms",
"submit",
""
] |
I have quite a lot of PHP view files, which I used to include in my controllers using simple include statements. They all use methods declared in a view class which they get like $view->method(); However I recently decided that it would be better if the including would also be done by this view class. This however changes the scope of the included file so that $view is no longer defined.
Here is a code example:
```
in someViewFile.php (BOTH siuations)
<html>
<head><title><?php echo $view->getAppTitle(); ?></title>
etc.
OLD SITUATION in controller:
$view = new view;
include('someViewFile.php'); //$view is defined in someViewFile.php
NEW SITUATION in controller:
$view = new view;
$view->show('someViewFile'); //$view is not defined in someViewFile.php
```
Right now I hacked my way around the problem using this in the view class:
```
public function show($file){
$view = &$this;
include($file.".php");
}
```
Is there anyway to declare the scope of the inluded file or is this the best way of solving the problem?
These examples are off coarse simplified. | You can't change include() scope, no, so your method is probably about as good as it gets in the situation you're describing. Though I'd skip the ugly PHP4-compat ampersand, myself. | Here' a simplified but functional view class that I've seen around quite a lot and use quite a lot.
As you can see in the code below: you instantiate a view with the filename of the template file.
The client code, probably a controller, can send data into the view. This data can be of any type you need even other views.
Nested views will be automatically rendered when the parent is rendered.
Hope this helps.
```
// simple view class
class View {
protected $filename;
protected $data;
function __construct( $filename ) {
$this->filename = $filename;
}
function escape( $str ) {
return htmlspecialchars( $str ); //for example
}
function __get( $name ) {
if( isset( $this->data[$name] ) ) {
return $this->data[$name];
}
return false;
}
function __set( $name, $value ) {
$this->data[$name] = $value;
}
function render( $print = false ) {
ob_start();
include $this->filename;
$rendered = ob_get_clean();
if( $print ) {
echo $rendered;
return;
}
return $rendered;
}
function __toString() {
return $this->render();
}
}
```
Usage
```
// usage
$view = new View( 'template.phtml' );
$view->title = 'My Title';
$view->text = 'Some text';
$nav = new View( 'nav.phtml' );
$nav->links = array( 'http://www.google.com' => 'Google', 'http://www.yahoo.com' => 'Yahoo' );
$view->nav = $nav;
echo $view;
```
The templates
```
//template.phtml
<html>
<head>
<title><?php echo $this->title ?></title>
</head>
<body>
<?php echo $this->nav ?>
<?php echo $this->escape( $this->text ) ?>
</body>
</html>
//nav.phtml
<?php foreach( $this->links as $url => $link ): ?>
<a href="<?php echo $url ?>"><?php echo $link ?></a>
<?php endforeach ?>
``` | PHP define scope for included file | [
"",
"php",
"include",
"scope",
""
] |
We are localising the user-interface text for a web application that runs on Java 5, and have a dilemma about how we output messages that are defined in properties files - the kind used by [java.util.Properties](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html).
Some messages include a placeholder that will be filled using [java.text.MessageFormat](http://java.sun.com/j2se/1.5.0/docs/api/java/text/MessageFormat.html). For example:
```
search.summary = Your search for {0} found {1} items.
```
MessageFormat is annoying, because a single quote is a special character, despite being common in English text. You have to type two for a literal single quote:
```
warning.item = This item''s {0} is not valid.
```
However, three-quarters of the application's 1000 or so messages do not include a placeholder. This means that we can output them directly, avoiding MessageFormat, and leave the single quotes alone:
```
help.url = The web page's URL
```
**Question:** should we use MessageFormat for all messages, for consistent syntax, or avoid MessageFormat where we can, so most messages do not need escaping?
There are clearly pros and cons either way.
Note that the API documentation for MessageFormat acknowledges the problem and suggests a non-solution:
> The rules for using quotes within
> message format patterns unfortunately
> have shown to be somewhat confusing.
> In particular, it isn't always obvious
> to localizers whether single quotes
> need to be doubled or not. Make sure
> to inform localizers about the rules,
> and tell them (for example, by using
> comments in resource bundle source
> files) which strings will be processed
> by MessageFormat. | Just write your own implementation of MessageFormat without this annoying feature. You may look at the code of [SLF4J Logger](http://www.slf4j.org/api/org/slf4j/Logger.html).
They have their own version of message formatter which can be used as followed:
```
logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);
```
Empty placeholders could be used with default ordering and numbered for some localization cases where different languages do permutations of words or parts of sentences. | In the end we decided to side-step the single quote problem by always using ‘curly’ quotes:
```
warning.item = This item\u2019s {0} is not valid.
``` | Should I use java.text.MessageFormat for localised messages without placeholders? | [
"",
"java",
"localization",
"messageformat",
""
] |
The Problem:
I need to receive different types of content from a number of different sources normalize them and then make them persistent through JDO.
Naive Solution?:
Create and listen on a specific port for each data type.
OR
Do a bunch of complicated parsing
A Seemingly Ideal Solution:
Have custom URL types i.e. FOO://myhost.tld, BAR://myhost.tld. any application could then send to the URL specific to the custom type and the host would ideally use Java's URLConnection and URLStreamHandler abstract classes to create a factory that would spawn the appropriate normalization thread. Or if there is anyway other way to retrieve the connection URL I think that would be sufficient
Is this possible? I have looked through the API and other docs put cannot figure out if it is possible to use these with a Java server socket.
I should mention that in some (many? most?) cases I am not responsible for the client code. | What you're calling "URL type" is the protocol part of the URL, and all it does is tell the client which protocol the server at that URL is going to expect it to talk.
It is NOT part of a "meta-protocol" that would allow the server to find out the URL it's being called with, unless you use a protocol that contains this information as a header - which is not commonly the case. Note also that protocols usually imply a default port unless the URL also specifies a port.
The entire URLConnection / URLStreamHandler API of Java is geared towards usage in a client, not a server, so I don't believe it can be used the way you want.
The first two alternatives you came up with are pretty much your options: either use different ports for the different kinds of input, or have the clients send a header that specifies the kind of input that follows. | [MIME](http://en.wikipedia.org/wiki/MIME) is a fairly standard way of communicating content type and disposition. | Receiving Disparate Content In Java | [
"",
"java",
"persistence",
"collections",
"normalization",
""
] |
Is it possible to have IF statements without braces in Java, e.g:
```
if (x == y)
z = x * y;
else
z = y - x;
```
It's possible in PHP, and I'm not sure if I'm doing something wrong.
**Clarification:** Here's my actual code that i'm using:
```
if (other instanceof Square)
Square realOther = (Square) other;
else
Rectangle realOther = (Rectangle) other;
```
But i got errors like "Syntax token on realOther , delete this token" and "realOther cannot be resolved" among others.
What am I doing wrong? | Yes, you can follow an `if` statement with a single statement without using curly braces (but do you really want to?), but your problem is more subtle. Try changing:
```
if (x=y)
```
to:
```
if (x==y)
```
Some languages (like PHP, for example) treat any non-zero value as true and zero (or `NULL`, `null`, `nil`, whatever) as `false`, so assignment operations in conditionals work. Java only allows boolean expressions (expressions that return or evaluate to a boolean) inside conditional statements. You're seeing this error because the result of `(x=y)` is the value of `y`, not `true` or `false`.
You can see this in action with this simple example:
```
if (1)
System.out.println("It's true");
if (true)
System.out.println("It's true");
```
The first statement will cause compilation to fail because `1` cannot be converted to a boolean.
**Edit:** My guess on your updated example (which you should have put in the question and not as a new answer) is that you are trying to access `realOther` after you assign it in those statements. This will not work as the scope of `realOther` is limited to the `if`/`else` statement. You need to either move the declaration of `realOther` above your `if` statement (which would be useless in this case), or put more logic in your `if` statement):
```
if (other instanceof Square)
((Square) other).doSomething();
else
((Rectangle) other).doSomethingElse();
```
To assist further we would need to see more of your **actual** code.
**Edit:** Using the following code results in the same errors you are seeing (compiling with `gcj`):
```
public class Test {
public static void Main(String [] args) {
Object other = new Square();
if (other instanceof Square)
Square realOther = (Square) other;
else
Rectangle realOther = (Rectangle) other;
return;
}
}
class Rectangle {
public Rectangle() { }
public void doSomethingElse() {
System.out.println("Something");
}
}
class Square {
public Square() { }
public void doSomething() {
System.out.println("Something");
}
}
```
Note that adding curly braces to that `if`/`else` statement reduces the error to a warning about unused variables. Our own [mmyers](https://stackoverflow.com/users/13531/mmyers) points out:
> <http://java.sun.com/docs/books/jls/third_edition/html/statements.html>
> says: "Every local variable
> declaration statement is immediately
> contained by a block." The ones in the
> `if` statement don't have braces around
> them, therefore they aren't in a
> block.
Also note that my other example:
```
((Square) other).doSomething()
```
compiles without error.
**Edit:** But I think we have established (while this is an interesting dive into obscure edge cases) that whatever you are trying to do, you are not doing it correctly. So what are you *actually* trying to do? | The following code *is* legal:
```
int x = 5;
int y = 2;
int z = 0;
if (x == y)
z = x * y;
else
z = y - x;
```
As Sean Bright mentioned, your problem is that you are trying to test a non-boolean expression. You should be using the `==` operator instead of the `=` operator in your `if` clause.
Another thing to mention is that it is considered, by many, bad practice to skip using the curly braces in an `if-then-else` statement. It can lead to errors down the road, such as adding another statement to the body of the `if` or `else` code blocks. It's the type of bug that might be a pain to figure out.
This isn't really an issue when using an `if-else` statement, because Java will catch this as a syntactic error (`else` statement without a preceding `if`). However, consider the following `if` statement:
```
if (x == y)
z = y * x;
```
Now, suppose later on you need to do more things if `x == y`. You could easily do the following without realizing the error.
```
if (x == y)
z = y * x;
w = x * y - 5;
```
Of course, the second statement `w = x * y - 5` will be executed regardless of the outcome of the `if` statement test. If you had curly braces to begin with, you would have avoided the problem.
```
if (x == y) {
z = y * x;
w = x * y - 5; // this is obviously inside the if statement now
}
``` | 1-line IF statements in java | [
"",
"java",
"conditional-statements",
""
] |
The C++0x standard is on its way to being complete. Until now, I've dabbled in C++, but avoided learning it thoroughly because it seems like it's missing a lot of modern features that I've been spoiled by in other languages. However, I'd be very interested in C++0x, which addresses a lot of my complaints. Any guesstimates, after the standard is ratified, as to how long it will take for major compiler vendors to provide reasonably complete, production-quality implementations? Will it happen soon enough to reverse the decline in C++'s popularity, or is it too little, too late? Do you believe that C++0x will become "the C++" within a few years, or do you believe that most people will stick to the earlier standard in practice and C++0x will be somewhat of a bastard stepchild, kind of like C99? | I see no reason why C++0x shouldn't be adopted. The C++ community is much more forward-looking than C. C was always meant to be a "portable assembler language", so people who use that aren't really super interested in fancy new features. C++ spans much wider, and I've yet to hear of a C++ programmer who *wasn't* looking forward to 0x. (It's also my impression that the C++ community is much "stricter", and really don't want to move outside the standard into undefined behavior, which implies you choose either C++03 or C++0X rather than a half-implemented hybrid. C programmers tend to be much more relaxed about that, and seem happy to use C89 with just a couple of C99 features and headers mixed in)
However, it'll take a few years before Microsoft catches up, at least. Visual Studio 2010 will support a small handful of C++0x features (lambdas, decltype and a couple of others), but the vast majority will *not* be supported. We'll have to wait for VS2012 or whatever the next version ends up being, to have somewhat complete support.
With GCC/G++, the situation is a lot better, since most of the standard has been implemented there already (the standard committee doesn't like adopting features that haven't been implemented and tested in a real compiler, and a GCC fork is often used for that)
But it'll probably still take some time to get that stable and production-ready.
About C++'s "decline in popularity", I don't really see it. I don't think C++ has declined significantly in popularity for the last years. RAD developers have already jumped ship, of course, to .NET, Python or other languages or platforms. But where C++ is used today, there aren't many viable alternatives, and no reason why it should decline in popularity. | I don't know about other vendors, but from [what](http://blogs.msdn.com/vcblog/archive/2008/10/28/lambdas-auto-and-static-assert-c-0x-features-in-vc10-part-1.aspx) I've [seen](http://www.codeguru.com/forum/showthread.php?t=466893), Microsoft plans to include four C++0x language features in Visual C++ 2010:
1. [rvalue references](http://en.wikipedia.org/wiki/C%2B%2B0x#Rvalue_reference_and_move_semantics)
2. [auto](http://en.wikipedia.org/wiki/C%2B%2B0x#Type_inference)
3. [lambdas](http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions)
4. [static assert](http://en.wikipedia.org/wiki/C%2B%2B0x#Static_assertions)
Although this is a small set of C++0x features, they are important ones. Some will enable programmers to write much more compact (auto, lambdas) and error free code. Some (like rvalue references) enable libraries to be more efficient. Microsoft likes lambdas as an [enabler for parallel computing](http://channel9.msdn.com/pdc2008/TL25/).
IMHO: `auto` alone will make it so much easier to use templates that more programmers will do so. And hopefully this will increase demand for more C++0x features from Microsoft and all vendors.
Microsoft will also be updating their C++ Standard Library implementation but I don't know the details. I believe they are modifying some container classes to take advantage of rvalue reference move semantics. And I believe they including more of TR1 . | C++0x implementation guesstimates? | [
"",
"c++",
"programming-languages",
"language-design",
"legacy",
""
] |
[A response on SO](https://stackoverflow.com/questions/503052/javascript-is-ip-in-one-of-these-subnets/503238#503238) got me thinking, does JavaScript guarantee a certain endian encoding across OSs and browsers?
Or put another way are bitwise shifts on integers "safe" in JavaScript? | Yes, they are safe. Although you're not getting the speed benefits you might hope for since JS bit operations are "[a hack](http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference#quickIDX4)". | Shifting is safe, but your question is flawed because endianness doesn't affect bit-shift operations anyway. Shifting left is the same on big-endian and little-endian systems in all languages. (Shifting right can differ, but only due to interpretation of the sign bit, not the relative positions of any bits.)
Endianness only comes into play when you have the option of interpreting some block of memory as bytes or as larger integer values. In general, Javascript doesn't give you that option since you don't get access to arbitrary blocks of memory, especially not the blocks of memory occupied by variables. [Typed arrays](http://www.khronos.org/registry/typedarray/) offer views of data in an endian-sensitive way, but the ordering depends on the host system; it's not necessarily the same for all possible Javascript host environments.
Endianness describes *physical* storage order, not *logical* storage order. Logically, the rightmost bit is *always* the least significant bit. Whether that bit's byte is the one that resides at the lowest memory address is a completely separate issue, and it only matters when your language exposes such a concept as "lowest memory address," which Javascript does not. Typed arrays do, but then only within the context of typed arrays; they still don't offer access to the storage of arbitrary data. | JavaScript Endian Encoding? | [
"",
"javascript",
"encoding",
"bit-manipulation",
"endianness",
""
] |
For various silly reasons, I'd like to be able to detect the rectangle of the browser window on screen. Title bar and all.
Is this possible, or is JavaScript limited to the view port of its page?
**Edit:** I may have been unclear, but view port is the portion of the page that's visible in the window. This may not be a term commonly used with browsers, but it's common in graphics. | For standards compliant browsers:
**X** - [`window.screenX`](https://developer.mozilla.org/en/DOM/window.screenX)
**Y** - [`window.screenY`](https://developer.mozilla.org/en/Window.screenY)
For IE:
**X** - [`window.screenLeft`](http://msdn.microsoft.com/en-us/library/ms534389(VS.85).aspx)
**Y** - [`window.screenTop`](http://msdn.microsoft.com/en-us/library/ms534390(VS.85).aspx)
Keep in mind, [implementations vary](http://www.quirksmode.org/dom/w3c_cssom.html). Beware of multi-monitor setups... | Take a look at the following properties:
* [window.screen.height](https://developer.mozilla.org/en/DOM/window.screen.height): Returns the height of the screen in pixels.
* [window.screen.top](https://developer.mozilla.org/en/DOM/window.screen.top): Returns the distance in pixels from the top side of the current screen.
* [window.screen.width](https://developer.mozilla.org/en/DOM/window.screen.width): Returns the width of the screen.
* [window.screen.left](https://developer.mozilla.org/en/DOM/window.screen.left): Returns the distance in pixels from the left side of the main screen to the left side of the current screen.
(These won't give you the window size or position, but may allow you to correctly interpret them when operating on a system with multiple monitors) | Determining position of the browser window in JavaScript? | [
"",
"javascript",
""
] |
I want to do something like:
```
DELETE FROM student WHERE
student.course, student.major IN
(SELECT schedule.course, schedule.major FROM schedule)
```
However, it seems that you can only use one column with the IN operator. Is that true? Seems like a query like this should be possible. | No, you just need parentheses:
```
DELETE FROM student WHERE
(student.course, student.major) IN
(SELECT schedule.course, schedule.major FROM schedule)
``` | You could also use the EXISTS clause:
```
DELETE FROM student WHERE
EXISTS
(
SELECT 1 FROM schedule
WHERE schedule.course=student.course
AND schedule.major=student.major
)
``` | Oracle Delete Rows Matching On Multiple Values | [
"",
"sql",
"oracle",
""
] |
I just ran across this error message while working in C#
> A property or indexer may not be passed as an out or ref parameter
I known what caused this and did the quick solution of creating a local variable of the correct type, calling the function with it as the `out`/`ref` parameter and then assigning it back to the property:
```
RefFn(ref obj.prop);
```
turns into
```
{
var t = obj.prop;
RefFn(ref t);
obj.prop = t;
}
```
Clearly this would fail if the property doesn't support get and set in the current context.
Why doesn't C# just do that for me?
---
The only cases where I can think of where this might cause problems are:
* threading
* exceptions
For threading that transformation affects when the writes happen (after the function call vs. in the function call), but I rather suspect any code that counts on that would get little sympathy when it breaks.
For exceptions, the concern would be; what happens if the function assigns to one of several `ref` parameters than throws? Any trivial solution would result in all or none of the parameters being assigned to when some should be and some should not be. Again I don't think this would be supported use of the language.
---
Note: I understand the mechanics of why this error messages is generated. What I'm looking for is the rationale for why C# doesn't automatically implement the trivial workaround. | Just for info, C# 4.0 *will* have something *like* this sugar, but only when calling interop methods - partly due to the sheer propensity of `ref` in this scenario. I haven't tested it much (in the CTP); we'll have to see how it pans out... | Because you're passing the *result* of the indexer, which is really the result of a method call. There's no guarantee that the indexer property also has a setter, and passing it by ref would lead to a false security on the developer's part when he thinks that his property is going to be set without the setter being called.
On a more technical level, ref and out pass the memory address of the object passed into them, and to set a property, you have to call the setter, so there's no guarantee that the property would actually be changed especially when the property type is immutable. ref and out don't just *set* the value upon return of the method, they pass the actual memory reference to the object itself. | C# property and ref parameter, why no sugar? | [
"",
"c#",
"properties",
"syntactic-sugar",
"reference-parameters",
""
] |
In a JSP page(index.jsp):
```
${requestContext.requestURL} is the URL
```
just shows the expression itself. It used to be evaluated to something like "<http://.../somerset/>"
I created the Maven project with maven-archetype-webapp archetype in Eclipse. The Jetty version is jetty-6.1.14.
My web.xml is simple:
```
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>SomersetServlet</servlet-name>
<display-name>SomersetServlet</display-name>
<description></description>
<servlet-class>com.foo.somerset.SomersetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SomersetServlet</servlet-name>
<url-pattern>/som.do</url-pattern>
</servlet-mapping>
</web-app>
``` | See [Javascript String.replace(/\$/,str) works weirdly in jsp file](https://stackoverflow.com/questions/472500/javascript-string-replace-str-works-weirdly-in-jsp-file/472573#472573) for some possible reasons.
Your web.xml should contain reference to web-app\_2\_4.xsd schema, like
```
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
```
This enables servlet 2.4 and jsp 2.0 processing, which includes EL.
Btw `requestContext` is not valid implicit object. | Incorrectly matched quotes can cause this behavior, where the expression just gets treated as a string. Your IDE would normally highlight this in a different color if this is the case. | EL in a JSP stopped evaluating | [
"",
"java",
"jsp",
"maven-2",
"jetty",
"el",
""
] |
I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.
My problem is that I can't come up with a pythonic macro definition syntax. I've posted several examples in two different syntaxes in answers below. Can anyone come up with a better syntax? It doesn't have to build off the syntax I've proposed in any way -- I'm completely open here. Any comments, suggestions, etc would be helpful, as would alternative syntaxes showing the examples I've posted.
A note about the macro structure, as seen in the examples I've posted: The use of MultiLine/MLMacro and Partial/PartialMacro tell the parser how the macro is applied. If it's multiline, the macro will match multiple line lists; generally used for constructs. If it's partial, the macro will match code in the middle of a list; generally used for operators. | After thinking about it a while a few days ago, and coming up with nothing worth posting, I came back to it now and came up with some syntax I rather like, because it nearly looks like python:
```
macro PrintMacro:
syntax:
"print", OneOrMore(Var(), name='vars')
return Printnl(vars, None)
```
* Make all the macro "keywords" look like creating python objects (`Var()` instead of simple `Var`)
* Pass the name of elements as a "keyword parameter" to items we want a name for.
It should still be easy to find all the names in the parser, since this syntax definition anyway needs to be interpreted in some way to fill the macro classes syntax variable.
needs to be converted to fill the syntax variable of the resulting macro class.
The internal syntax representation could also look the same:
```
class PrintMacro(Macro):
syntax = 'print', OneOrMore(Var(), name='vars')
...
```
The internal syntax classes like `OneOrMore` would follow this pattern to allow subitems and an optional name:
```
class MacroSyntaxElement(object):
def __init__(self, *p, name=None):
self.subelements = p
self.name = name
```
When the macro matches, you just collect all items that have a name and pass them as keyword parameters to the handler function:
```
class Macro():
...
def parse(self, ...):
syntaxtree = []
nameditems = {}
# parse, however this is done
# store all elements that have a name as
# nameditems[name] = parsed_element
self.handle(syntaxtree, **nameditems)
```
The handler function would then be defined like this:
```
class PrintMacro(Macro):
...
def handle(self, syntaxtree, vars):
return Printnl(vars, None)
```
I added the syntaxtree as a first parameter that is always passed, so you wouldn't need to have any named items if you just want to do very basic stuff on the syntax tree.
Also, if you don't like the decorators, why not add the macro type like a "base class"? `IfMacro` would then look like this:
```
macro IfMacro(MultiLine):
syntax:
Group("if", Var(), ":", Var(), name='if_')
ZeroOrMore("elif", Var(), ":", Var(), name='elifs')
Optional("else", Var(name='elseBody'))
return If(
[(cond, Stmt(body)) for keyword, cond, colon, body in [if_] + elifs],
None if elseBody is None else Stmt(elseBody)
)
```
And in the internal representation:
```
class IfMacro(MultiLineMacro):
syntax = (
Group("if", Var(), ":", Var(), name='if_'),
ZeroOrMore("elif", Var(), ":", Var(), name='elifs'),
Optional("else", Var(name='elseBody'))
)
def handle(self, syntaxtree, if_=None, elifs=None, elseBody=None):
# Default parameters in case there is no such named item.
# In this case this can only happen for 'elseBody'.
return If(
[(cond, Stmt(body)) for keyword, cond, body in [if_] + elifs],
None if elseNody is None else Stmt(elseBody)
)
```
I think this would give a quite flexible system. Main advantages:
* Easy to learn (looks like standard python)
* Easy to parse (parses like standard python)
* Optional items can be easily handled, since you can have a default parameter `None` in the handler
* Flexible use of named items:
+ You don't need to name any items if you don't want, because the syntax tree is always passed in.
+ You can name any subexpressions in a big macro definition, so it's easy to pick out specific stuff you're interested in
* Easily extensible if you want to add more features to the macro constructs. For example `Several("abc", min=3, max=5, name="a")`. I think this could also be used to add default values to optional elements like `Optional("step", Var(), name="step", default=1)`.
I'm not sure about the quote/unquote syntax with "quote:" and "$", but some syntax for this is needed, since it makes life much easier if you don't have to manually write syntax trees. Probably its a good idea to require (or just permit?) parenthesis for "$", so that you can insert more complicated syntax parts, if you want. Like `$(Stmt(a, b, c))`.
The ToMacro would look something like this:
```
# macro definition
macro ToMacro(Partial):
syntax:
Var(name='start'), "to", Var(name='end'), Optional("inclusive", name='inc'), Optional("step", Var(name='step'))
if step == None:
step = quote(1)
if inclusive:
return quote:
xrange($(start), $(end)+1, $(step))
else:
return quote:
xrange($(start), $(end), $(step))
# resulting macro class
class ToMacro(PartialMacro):
syntax = Var(name='start'), "to", Var(name='end'), Optional("inclusive", name='inc'), Optional("step", Var(name='step'))
def handle(syntaxtree, start=None, end=None, inc=None, step=None):
if step is None:
step = Number(1)
if inclusive:
return ['xrange', ['(', start, [end, '+', Number(1)], step, ')']]
return ['xrange', ['(', start, end, step, ')']]
``` | You might consider looking at how Boo (a .NET-based language with a syntax largely inspired by Python) implements macros, as described at [<http://boo.codehaus.org/Syntactic+Macros>](http://boo.codehaus.org/Syntactic+Macros). | Pythonic macro syntax | [
"",
"python",
"syntax",
"macros",
""
] |
I have an application that uses Ideablade Devforce as it's OR mapper. When the application starts up it wants to write to the debuglog.xml file in C:\Program Files\Application Name\ This works fine in Windows XP, but due to Vista's locked down write access to Program Files, the app throws and error.
Is there a way to stop Ideablade wanting to write to this file?
OR
Is there another place that is recommended to install applications that want to write to files in their install path? | I fixed it by setting the logging file option to a blank string within the IdeaBlade.ibconfig file.
It mentions in the help that if you don't supply a path it will save the file in the application's directory, but if you don't even supply the filename it will not save it anywhere. | csjohnst is correct. Setting the logfile element to an empty string in the ibconfig file will suppress creation of the debuglog. | How to stop Ideablade DevForce writing to C:\Program Files\AppName\debuglog.xml in Vista | [
"",
"c#",
"winforms",
"windows-vista",
"uac",
"devforce",
""
] |
I'm trying to make a ASP.NET (C#) poll that will ask a user a Yes/No question and log that vote to the database. To prevent spam I would like to be able to make sure users can only vote once. I've thought about logging the users IP address. If this is the answer can someone give me a tutorial that shows how this can be accomplished. If this is not the answer then give me your suggestions.
**Edit:** I'm not asking users to register as this is not my website. | Logged in sessions are the only way to prevent double-voting fraud but since you explicitly ask for a way to log the IP address, you can get at that through:
`HttpContext.Current.Request.UserHostAddress;`
or
`HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];`
Should be easy enough to save to DB and check if IP already exists on each poll. | You can only garuantee that each user has one vote if you can authenticate the user. So you'll need an authentication mechanism, that will allow you to prevent the user from registering multiple accounts.
I can only see this work in an environment where the user has invested something into his account, like a subscriber for an online newspaper or a reputation system as on StackOverflow. | How to make sure a user can only vote once on an ASP.NET poll | [
"",
"c#",
"asp.net",
"ip-address",
""
] |
I have some code that looks like this:
```
someFunc(value)
{
switch(value){
case 1:
case 2:
case 3:
#ifdef SOMEMACRO
case 4:
case 5:
#endif
return TRUE;
}
return FALSE;
}
```
SOMEMACRO is defined, and let's say the value is 4.. Why does case 4 and 5 get skipped and FALSE is returned instead? :(
Is it because I don't have a default case or am I not allowed to use an ifdef in the switch statement? | "switch" Isn't Broken
to, more or less, quote [The Pragmatic Programmer](https://rads.stackoverflow.com/amzn/click/com/020161622X).
Go ahead and look somewhere else for the error. To convince yourself add `value = 4` and `#define SOMEMACRO` right there in someFunc.
Make a clean build to make sure every dependancy is resolved. | Try the following:
```
someFunc(value)
{
switch(value){
case 1:
case 2:
case 3:
#ifdef SOMEMACRO
#error macro is defined
case 4:
case 5:
#else
#error macro is not defined
#endif
return TRUE;
}
return FALSE;
}
```
Compile this and see which of the two errors the compiler gives you. | #ifdef in switch statement bug? | [
"",
"c++",
"macros",
"switch-statement",
""
] |
How do you write (and run) a correct micro-benchmark in Java?
I'm looking for some code samples and comments illustrating various things to think about.
Example: Should the benchmark measure time/iteration or iterations/time, and why?
Related: [Is stopwatch benchmarking acceptable?](https://stackoverflow.com/questions/410437/is-stopwatch-benchmarking-acceptable) | Tips about writing micro benchmarks [from the creators of Java HotSpot](https://wiki.openjdk.org/display/HotSpot/MicroBenchmarks):
**Rule 0:** Read a reputable paper on JVMs and micro-benchmarking. A good one is [Brian Goetz, 2005](https://web.archive.org/web/20200606234821/https://www.ibm.com/developerworks/java/library/j-jtp02225/). Do not expect too much from micro-benchmarks; they measure only a limited range of JVM performance characteristics.
**Rule 1:** Always include a warmup phase which runs your test kernel all the way through, enough to trigger all initializations and compilations before timing phase(s). (Fewer iterations is OK on the warmup phase. The rule of thumb is several tens of thousands of inner loop iterations.)
**Rule 2:** Always run with `-XX:+PrintCompilation`, `-verbose:gc`, etc., so you can verify that the compiler and other parts of the JVM are not doing unexpected work during your timing phase.
**Rule 2.1:** Print messages at the beginning and end of timing and warmup phases, so you can verify that there is no output from Rule 2 during the timing phase.
**Rule 3:** Be aware of the difference between `-client` and `-server`, and OSR and regular compilations. The `-XX:+PrintCompilation` flag reports OSR compilations with an at-sign to denote the non-initial entry point, for example: `Trouble$1::run @ 2 (41 bytes)`. Prefer server to client, and regular to OSR, if you are after best performance.
**Rule 4:** Be aware of initialization effects. Do not print for the first time during your timing phase, since printing loads and initializes classes. Do not load new classes outside of the warmup phase (or final reporting phase), unless you are testing class loading specifically (and in that case load only the test classes). Rule 2 is your first line of defense against such effects.
**Rule 5:** Be aware of deoptimization and recompilation effects. Do not take any code path for the first time in the timing phase, because the compiler may junk and recompile the code, based on an earlier optimistic assumption that the path was not going to be used at all. Rule 2 is your first line of defense against such effects.
**Rule 6:** Use appropriate tools to read the compiler's mind, and expect to be surprised by the code it produces. Inspect the code yourself before forming theories about what makes something faster or slower.
**Rule 7:** Reduce noise in your measurements. Run your benchmark on a quiet machine, and run it several times, discarding outliers. Use `-Xbatch` to serialize the compiler with the application, and consider setting `-XX:CICompilerCount=1` to prevent the compiler from running in parallel with itself. Try your best to reduce GC overhead, set `Xmx`(large enough) equals `Xms` and use [`UseEpsilonGC`](http://openjdk.java.net/jeps/318) if it is available.
**Rule 8:** Use a library for your benchmark as it is probably more efficient and was already debugged for this sole purpose. Such as [JMH](http://openjdk.java.net/projects/code-tools/jmh/), [Caliper](https://github.com/google/caliper) or [Bill and Paul's Excellent UCSD Benchmarks for Java](http://cseweb.ucsd.edu/users/wgg/JavaProf/javaprof.html). | I know this question has been marked as answered but I wanted to mention two libraries that help us to write micro benchmarks
**[Caliper from Google](https://github.com/google/caliper)**
*Getting started tutorials*
1. <http://codingjunkie.net/micro-benchmarking-with-caliper/>
2. <http://vertexlabs.co.uk/blog/caliper>
**[JMH from OpenJDK](http://openjdk.java.net/projects/code-tools/jmh/)**
*Getting started tutorials*
1. [Avoiding Benchmarking Pitfalls on the JVM](http://www.oracle.com/technetwork/articles/java/architect-benchmarking-2266277.html)
2. [Using JMH for Java Microbenchmarking](http://nitschinger.at/Using-JMH-for-Java-Microbenchmarking)
3. [Introduction to JMH](https://web.archive.org/web/20181018130828/http://java-performance.info:80/jmh) | How do I write a correct micro-benchmark in Java? | [
"",
"java",
"jvm",
"benchmarking",
"jvm-hotspot",
"microbenchmark",
""
] |
I'm implementing [James Bennett](http://www.b-list.org/about/)'s excellent [django-contact-form](http://code.google.com/p/django-contact-form/) but have hit a snag. My contact page not only contains the form, but also additional flat page information.
Without rewriting the existing view the contact form uses, I'd like to be able to wrap, or chain, the views. This way I could inject some additional information via the context so that both the form and the flat page data could be rendered within the same template.
I've heard it mentioned that this is possible, but I can't seem to figure out how to make it work. I've created my own wrapper view, called the contact form view, and attempted to inspect the HttpResponse object for an attribute I can append to, but I can't seem to figure out which, if any, it is.
**EDIT:** James commented that the latest code can new be found [here](http://bitbucket.org/ubernostrum/django-contact-form/overview/) at BitBucket. | 1. Write a wrapper which uses the URL to look up the appropriate flat page object.
2. From your wrapper, call (and return the response from) the contact form view, passing the flat page in the `extra_context` argument (which is there for, among other things, precisely this sort of use case).
3. There is no third step. | There's a context processor that may do what you want.
<http://docs.djangoproject.com/en/dev/ref/templates/api/>
You can probably add your various pieces of "flat page information" to the context. | How to chain views in Django? | [
"",
"python",
"django",
"extension-methods",
"django-views",
"word-wrap",
""
] |
Which is your preference?
Let's say we have a generic Product table that has an ID, a name, and a foreign key reference to a category. Would you prefer to name your table like:
```
CREATE TABLE Products
(
ProductID int NOT NULL IDENTITY(1,1) PRIMARY KEY,
CategoryID int NOT NULL FOREIGN KEY REFERENCES Categories(CategoryID),
ProductName varchar(200) NOT NULL
)
```
using explicit naming for the columns (e.g. **Product**Name, **Product**ID), or something like:
```
CREATE TABLE Products
(
ID int NOT NULL IDENTITY(1,1) PRIMARY KEY,
CategoryID int NOT NULL FOREIGN KEY REFERENCES Categories(ID),
Name varchar(200) NOT NULL
)
```
From what I've seen, the convention in the .NET world is to be explicit -- the samples tend to use the first example, while the open source and RoR world favor the second. Personally I find the first easier to read and comprehend at first glance: `select p.ProductID, p.ProductName, c.CategoryName from Categories c inner join Products p on c.CategoryID = p.CategoryID` seems a lot more natural to me than `select p.ID AS ProductID, p.Name AS ProductName, c.Name AS CategoryName from Categories c inner join Products p on c.ID = p.CategoryID`
I suppose that given the rudimentary example I provided it's not a big deal, but how about when you are dealing with lots of data and tables? I would still find the first example to be better than the second, although possibly some combination of the two might be worth looking into (`<Table>ID` for the ID, but just `Name` for the name?). Obviously on an existing project you should follow the conventions already established, but what about for new development?
What's your preference? | The table name already gives the context.
No need to prefix columns name with it.
When joining tables use table.column syntax. | I'm a fan of option 3:
```
CREATE TABLE Products
(
ProductId int NOT NULL IDENTITY(1,1) PRIMARY KEY,
CategoryId int NOT NULL FOREIGN KEY REFERENCES Categories(CategoryId),
Name varchar(200) NOT NULL
)
```
So the primary key is the only column to gain the table's name as a prefix -- IMHO it makes it easier to see when a join has gone wrong. Then again, I also like using GUIDs for primary keys if there is any possibility of having to cope with a merge replication situation at any point in the future... | Do you prefer verbose naming when it comes to database columns? | [
"",
"sql",
"database-design",
"naming-conventions",
"naming",
""
] |
I have a C# application that scans a directory and gathers some information. I would like to display the account name for each file. I can do this on the local system by getting the SID for the FileInfo object, and then doing:
```
string GetNameFromSID( SecurityIdentifier sid )
{
NTAccount ntAccount = (NTAccount)sid.Translate( typeof( NTAccount ) );
return ntAccount.ToString();
}
```
However, this does not work for files on a network, presumably because the Translate() function only works with local user accounts. I thought maybe I could do an LDAP lookup on the SID, so I tried the following:
```
string GetNameFromSID( SecurityIdentifier sid )
{
string str = "LDAP://<SID=" + sid.Value + ">";
DirectoryEntry dirEntry = new DirectoryEntry( str );
return dirEntry.Name;
}
```
This seems like it will work, in that the access to "dirEntry.Name" hangs for a few seconds, as if it is going off and querying the network, but then it throws a System.Runtime.InteropServices.COMException
Does anyone know how I can get the account name of an arbitrary file or SID? I don't know much about networking or LDAP or anything. There's a class called DirectorySearcher that maybe I'm supposed to use, but it wants a domain name, and I don't know how to get that either - all I have is the path to the directory I'm scanning. | The SecurityReference object's Translate method does work on non-local SIDs but only for domain accounts. For accounts local to another machine or in a non-domain setup you would need to PInvoke the function LookupAccountSid specifying the specific machine name on which the look up needs to be performed. | See here for a good answer:
[The best way to resolve display username by SID?](https://stackoverflow.com/questions/380031/the-best-way-to-resolve-display-username-by-sid)
The gist of it is this bit:
```
string sid="S-1-5-21-789336058-507921405-854245398-9938";
string account = new System.Security.Principal.SecurityIdentifier(sid).Translate(typeof(System.Security.Principal.NTAccount)).ToString();
```
This approach works for me for non-local SID's over the active directory. | How can I convert from a SID to an account name in C# | [
"",
"c#",
"sid",
""
] |
I am looking into using only a ddl to run my query, not a ddl and a Button\_Click function. I am yet to find what to do. How do I do this? | In your as(p/c)x:
```
<asp:DropDownList runat="server"
id="ddl"
OnSelectedIndexChanged="SelectionChanged"
AutoPostBack="true">
<asp:ListItem Text="Page 1" Value="/page1.aspx" />
<asp:ListItem Text="Page 2" Value="/page2.aspx" />
</asp:DropDownList>
```
The "AutoPostBack" property tells ASP.NET to wire up a client-side (javascript) command that submits the form as soon as the drop down list changes, instead of waiting for a button click.
And in your codebehind, the event handler we referenced in the "OnSelectedIndexChanged" property will get fired:
```
protected void SelectionChanged(object sender, EventArgs e)
{
Response.Redirect(((DropDownList)sender).SelectedValue);
}
``` | Set the AutoPostBack property to true, then hook into the OnSelectedIndexChanged event
```
<asp:DropDownList
id="dropDownList1"
runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="dropDownList1_SelectedIndexChanged" />
```
Server Side
```
void dropDownList1_SelectedIndexChanged
(Object sender, EventArgs e) {
//run your query
}
``` | How do I redirect with a Drop Down List, and not a Button? | [
"",
"c#",
".net",
"asp.net",
""
] |
I am typing to get a sale amount (by input) to be multiplied by a defined sales tax (0.08) and then have it print the total amount (sales tax times sale amount).
I run into this error. Anyone know what could be wrong or have any suggestions?
```
salesAmount = raw_input (["Insert sale amount here \n"])
['Insert sale amount here \n']20.99
>>> salesTax = 0.08
>>> totalAmount = salesAmount * salesTax
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
totalAmount = salesAmount * salesTax
TypeError: can't multiply sequence by non-int of type 'float'
``` | `raw_input` returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: `"AB" * 3` is `"ABABAB"`; how much is `"L" * 3.14` ? Please do not reply `"LLL|"`). You need to parse the string to a numerical value.
You might want to try:
```
salesAmount = float(raw_input("Insert sale amount here\n"))
``` | Maybe this will help others in the future - I had the same error while trying to multiple a float and a list of floats. The thing is that everyone here talked about multiplying a float with a string (but here all my element were floats all along) so the problem was actually using the \* operator on a list.
For example:
```
import math
import numpy as np
alpha = 0.2
beta=1-alpha
C = (-math.log(1-beta))/alpha
coff = [0.0,0.01,0.0,0.35,0.98,0.001,0.0]
coff *= C
```
The error:
```
coff *= C
TypeError: can't multiply sequence by non-int of type 'float'
```
The solution - convert the list to numpy array:
```
coff = np.asarray(coff) * C
``` | Why do I get TypeError: can't multiply sequence by non-int of type 'float'? | [
"",
"python",
""
] |
I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed at Python web application programming. I understand that Python has built-in tools to assist. What would be the best way to learn about these outside of RTFM? I have searched on StackOverflow and found the Kent Beck's and David Astels book on the subject. I have also bookmarked the Wikipedia article as it has many of these types of resources.
Are there any particular ones you would recommend for this language/application? | I wrote a series of blogs on [TDD in Django](http://blog.cerris.com/category/django-tdd/) that covers some TDD with the [nose testing framework](http://somethingaboutorange.com/mrl/projects/nose/).
There are a lot of free online resources out there for learning about TDD:
* [The c2 wiki article](http://c2.com/cgi-bin/wiki?TestDrivenDevelopment) gives good background on general TDD philosophy.
* [The onlamp article](http://www.onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html) is a simple introduction.
* Here's a presentation on [TDD with game development in pygame](http://powertwenty.com/kpd/blog/index.php/python/test_driven_development_in_python) that really helped me understand TDD.
For testing web applications, test first or otherwise, I'd recommend [twill](http://twill.idyll.org/) and [selenium](http://seleniumhq.org/) as tools to use. | Can I plug my own tutorial, which covers the materials from the official Django tutorial, but uses full TDD all the way - including "proper" functional/acceptance tests using the Selenium browser-automation tool... <http://tdd-django-tutorial.com>
[update 2014-01] I now have a book, just about to be published by OReilly, that covers all the stuff from the tutorial and much more. The full thing is available online (free) at <http://www.obeythetestinggoat.com> | Resources for TDD aimed at Python Web Development | [
"",
"python",
"tdd",
"testing",
""
] |
I have been playing around with the EF to see what it can handle. Also many articles and posts explain the various scenarios in which the EF can be used, however if miss the "con" side somehow. Now my question is, **in what kind of scenarios should I stay away from the Entity Framework** ?
If you have some experience in this field, tell me what scenarios don't play well with the EF. Tell me about some downsides you experienced where you whished you would have chosen a different technology. | I'm also just at the 'playing around' stage, and although I was worried about the lack of built-in persistence agnosticism, I was sure there would be a "work-around".
In fact, not even a work-around in an n-tier architecture.
**WCF + EF**
If I've read the [article](http://msdn.microsoft.com/en-us/magazine/cc700340.aspx) correctly, then I don't see any problem serializing entities across the wire (using WCF) and also the persistence ignorance isn't a problem.
This is because I'd use PI mainly for unit-testing.
**Unit Testing *is* possible! (i think)**
In this system, we could simply use a mock service (by wrapping up the call to the service in ANOTHER interface based class which could be produced from a factory, for example). This would test OUR presenter code (there's no need to unit-test the EF/DAL - that's Microsoft's job!) Of course, integration tests would still be required to achieve full confidence.
If you wanted to write to a separate database, this would be done in the DAL layer, easily achieved via the config file.
**My Tuppence Worth**
My opinion - make up your own mind about the EF and don't be put off by all the doom and gloom regarding it that's doing the rounds. I'd guess that it's going to be around for a while and MS will iron out the faults in the next year or so. PI is definitely coming in according to Dan Simmons.
**EDIT**: I've just realised I jumped the gun and like a good politician didn't actually answer the question that was asked. Oops. But I'll leave this in in case anyone else finds it useful. | The [Vote of No Confidence](http://efvote.wufoo.com/forms/ado-net-entity-framework-vote-of-no-confidence/) lists several missteps and/or missing bits of functionality in the eyes of those who believe they know what features, and their implementations, are proper for ORM/Datamapper frameworks.
If none of those issues are a big deal to you, then I don't see why you shouldn't use it. I have yet to hear that it is a buggy mess that blows up left and right. All cautions against it are philosophical. I happen to agree with the vote of no confidence, but that doesn't mean you should. If you happen to like the way EF works, then go for it. At the same time I'd advise you to at least read the vote of no confidence and try to get a rudimentary understanding of each of the issues in order to make an informed decision.
Outside of that issue and to the heart of your question - You need to keep an eye on the Sql that is being generated so you can make tweaks before a performance problem gets into production. Even if you are using procs on the backend, I'd still look for scenarios where you may be hitting the database too many times and then rework your mappings or fetching scenarios accordingly. | When NOT to use the Entity Framework | [
"",
"c#",
".net",
"entity-framework",
"architecture",
""
] |
I need to change what rows are grabbed from the database based upon a few flags. How can I do this? My current code is like this:
```
this.tblTenantTableAdapter.Fill(this.rentalEaseDataSet.tblTenant);
```
Say if I wanted only rows that the id was greater than 50, how would I do that?
**Edit:**
The code to access the database was autogenerated by the original programmer a long time ago though VisualStudio. I don't know exactly how to get a connection from the autogenerated code. If I could do that I know how to use the SqlDataAdapter | Why wouldn't you use a `WHERE` clause in your SQL query?
Also, I would hope you don't use your `ID` field for anything like this. If you just want the first 50 selections, you may want to use a `TOP 50` clause or something similar.
For some info on how to do this with your TableAdapter: <http://www.shiningstar.net/ASPNet_Articles/DataSet/DataSetProject7.aspx> | On the server side you can use plaid old SQL:
```
SELECT * FROM TBLTENANT WHERE id > 50
```
On the client side:
```
rentalEaseDataSet.tblTenant.DefaultView.RowFilter = "id > 50";
``` | Selectively filling a dataset | [
"",
"c#",
"database",
".net-3.5",
""
] |
This question builds off of a previously asked question:
[Pass by reference multidimensional array with known size](https://stackoverflow.com/questions/529109/c-pass-by-reference-multidimensional-array-with-known-size)
I have been trying to figure out how to get my functions to play nicely with 2d array references. A simplified version of my code is:
```
unsigned int ** initialize_BMP_array(int height, int width)
{
unsigned int ** bmparray;
bmparray = (unsigned int **)malloc(height * sizeof(unsigned int *));
for (int i = 0; i < height; i++)
{
bmparray[i] = (unsigned int *)malloc(width * sizeof(unsigned int));
}
for(int i = 0; i < height; i++)
for(int j = 0; j < width; j++)
{
bmparray[i][j] = 0;
}
return bmparray;
}
```
I don't know how I can re-write this function so that it will work where I pass bmparray in as an empty unsigned int \*\* by reference so that I could allocate the space for the array in one function, and set the values in another. | Use a class to wrap it, then pass objects by reference
```
class BMP_array
{
public:
BMP_array(int height, int width)
: buffer(NULL)
{
buffer = (unsigned int **)malloc(height * sizeof(unsigned int *));
for (int i = 0; i < height; i++)
{
buffer[i] = (unsigned int *)malloc(width * sizeof(unsigned int));
}
}
~BMP_array()
{
// TODO: free() each buffer
}
unsigned int ** data()
{
return buffer;
}
private:
// TODO: Hide or implement copy constructor and operator=
unsigned int ** buffer
};
``` | ```
typedef array_type unsigned int **;
initialize_BMP_array(array_type& bmparray, int height, int width)
``` | C++ Passing a dynamicly allocated 2D array by reference | [
"",
"c++",
"arrays",
"reference",
"multidimensional-array",
""
] |
I'm new to WPF and come from a WinForms background and have a fairly basic question about binding vs event handling.
To try and maintain some separation of responsibility I've have a bunch of `Presentation` objects which simply have `Dependency Properties` to hold the UI data parts of a business object, the business object contains similar data but the data types are occationally different so that the `Presentation` object is correct for display purposes. So something like
```
public class MyPresentation
{
// bunch of dependency properties
public bool MyProperty
{
get { return (bool)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(bool), typeof(MyPresentationObject), new UIPropertyMetadata(false, MyPresentationObject.MyPropertyPropertyChanged));
MyBusinessObject RelatedBusinessObject { get; set;}
public MyPresentation(MyBusinessObject businessObejct)
{
this.RelatedBusinessObject = businessObject;
}
public static void MyPropertyPropertyChanged()
{
// Do some stuff to related business objects
}
}
```
The properties of `MyPresentation` are then data bound to various controls and I use `Trigger`s etc to change presentation dependency properties which causes business object changes in the `OnPropertyChanged` event
The question I have is am I using binding in the correct fashion? Normally (in Winforms) I'd have used click events etc to change my business objects (or the presentation versions of them) values but those sort of events and that sort of event handling seems superfluous now that you can use `Binding`, `Trigger`s and `OnPropertyChanged` events.
Am I missing something? | [Look here](http://msdn.microsoft.com/en-us/magazine/dd419663.aspx) this present the pattern Model View ViewModel, this permit you to take full advantages on the binding, and Command of WPF, without disturb your business objects (like implementing WPF stuff like INotifyPropertyChanged on your business objects) | You are correct in using the bindings this way. Also check out the Model View View-Model pattern as it is similar to what you are doing but a more definable template.
Also check out the interface INotifyPropertyChanged - this is a more accepted way of trapping that a property has changed locally and notifying the view (your form) that an object has changed. That way you get the best of both worlds: changes to objects might happen as the result of a button click, or from bindings. | WPF Binding vs Event Handling | [
"",
"c#",
"wpf",
"binding",
"event-handling",
""
] |
When you compile windows application in .NET you can set "Platform Target" to be x86 or x64. This would optimize your code to a specific architecture of the processor and allow to escape IL.
Does anyone know if there's something that would allow to achieve the same result for Windows Mobile application? I'm only interested in running my application on ARM architecture. | Use [Mono](http://go-mono.com/)'s [Ahead-of-Time](http://www.mono-project.com/AOT) (AOT) compilation. That's how they got [UNITY](http://unity3d.com/) scripting onto the iPhone which is an ARM platform. It will probably take some labour to get it up and running on Windows Mobile since, afaik, noone has done that particular platform port yet but the compiler etc should already be there.
You can see Miguel de Icaza's presentation of it at MS PDC [here](http://channel9.msdn.com/pdc2008/PC54/). | I don't believe specifying the platform target *does* optimise the generated IL for the given architecture. Instead, it says, "I only run on the specified architecture, because I contain P/Invoke calls specific to that architecture." At least, that's my understanding of it. It means that when running on an x64 machine, an executable can run under the 32 bit version of the CLR for compatibility.
How this fits in with the compact framework (which I assume is your actual platform?) I'm not sure. | Targeting ARM architecture with .NET compiler | [
"",
"c#",
".net",
"visual-studio",
"windows-mobile",
"compiler-construction",
""
] |
I'm trying to get a `JTabbedPane` where all tabs (the actual tabs, not the components) have the same width (either the minimum width needed for the widest label or a constant width).
I've tried to override `BasicTabbedPaneUI.getTabBounds(int tabIndex, Rectangle dest)`, but apparently this method isn't used by the painting methods of `BasicTabbedPaneUI`, instead it uses a rects array to determine the tabs size.
My next approach would be to override `JTabbedPane.insertTab(String title, Icon icon, Component component, String tip, int index)` and setting the preferred size of the label component, but this doesn't seem very elegant and I'm not even sure it would work at all.
Is there a way to achieve this? | The answer is simple.
When we put the name for the tab, just format the name using html.
say
tp - JTabbedPane object
```
tp.addTab("<html><body><table width='150'>Name</table></body></html>",Componentobject)
``` | I think it's not as complicated as you've done. Just use setTabComponentAt() with a JLabel on which you've set preferred size. | Tabs with equal (constant) width in JTabbedPane | [
"",
"java",
"swing",
"jtabbedpane",
""
] |
I'm looking for a quick and easy way to preload images with JavaScript. I'm using jQuery if that's important.
I saw this here ([http://nettuts.com...](http://nettuts.com/tutorials/javascript-ajax/the-definitive-guide-to-creating-a-practical-jquery-plugin/)):
```
function complexLoad(config, fileNames) {
for (var x = 0; x < fileNames.length; x++) {
$("<img>").attr({
id: fileNames[x],
src: config.imgDir + fileNames[x] + config.imgFormat,
title: "The " + fileNames[x] + " nebula"
}).appendTo("#" + config.imgContainer).css({ display: "none" });
}
};
```
But, it looks a bit over-the-top for what I want!
I know there are jQuery plugins out there that do this but they all seem a bit big (in size); I just need a quick, easy and short way of preloading images! | Quick *and* easy:
```
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
```
Or, if you want a jQuery plugin:
```
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
$(['img1.jpg','img2.jpg','img3.jpg']).preload();
``` | Here's a tweaked version of the first response that actually loads the images into DOM and hides it by default.
```
function preload(arrayOfImages) {
$(arrayOfImages).each(function () {
$('<img />').attr('src',this).appendTo('body').css('display','none');
});
}
``` | Preloading images with jQuery | [
"",
"javascript",
"jquery",
""
] |
I'm writing an SQL Query, where a few of the columns returned need to be calculated depending on quite a lot of conditions.
I'm currently using nested case statements, but its getting messy. Is there a better (more organised and/or readable) way?
(I am using Microsoft SQL Server, 2005)
---
A simplified example:
```
SELECT
col1,
col2,
col3,
CASE
WHEN condition
THEN
CASE
WHEN condition1
THEN
CASE
WHEN condition2
THEN calculation1
ELSE calculation2
END
ELSE
CASE
WHEN condition2
THEN calculation3
ELSE calculation4
END
END
ELSE
CASE
WHEN condition1
THEN
CASE
WHEN condition2
THEN calculation5
ELSE calculation6
END
ELSE
CASE
WHEN condition2
THEN calculation7
ELSE calculation8
END
END
END AS 'calculatedcol1',
col4,
col5 -- etc
FROM table
``` | You could try some sort of COALESCE trick, eg:
```
SELECT COALESCE(
CASE WHEN condition1 THEN calculation1 ELSE NULL END,
CASE WHEN condition2 THEN calculation2 ELSE NULL END,
etc...
)
``` | Wrap all those cases into one.
---
```
SELECT
col1,
col2,
col3,
CASE
WHEN condition1 THEN calculation1
WHEN condition2 THEN calculation2
WHEN condition3 THEN calculation3
WHEN condition4 THEN calculation4
WHEN condition5 THEN calculation5
ELSE NULL
END AS 'calculatedcol1',
col4,
col5 -- etc
FROM table
``` | Best way to do nested case statement logic in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2005",
"select",
"nested",
""
] |
So I am working on something in php where I have to get my images from a sql database where they will be encoded in base64. The speed of displaying these images is critical so I am trying to figure out if it would be faster turn the database data into an image file and then load it in the browser, or just echo the raw base64 data and use:
```
<img src="data:image/jpeg;base64,/9j/4AAQ..." />
```
Which is supported in FireFox and other Gecko browsers.
So to recap, would it be faster to transfer an actual image file or the base64 code. Would it require less http request when using ajax to load the images?
The images would be no more than 100 pixels total. | Well I don't agree with anyone of you. There are cases when you've to load more and more images. Not all the pages contain 3 images at all. Actually I'm working on a site where you've to load more than 200 images. What happens when 100000 users request that 200 images on a very loaded site. The disks of the server, returning the images should collapse. Even worse you've to make so much request to the server instead of one with base64. For so much thumbnails I'd prefer the base64 representation, pre-saved in the database. I found the solution and a strong argumentation at <http://www.stoimen.com/2009/04/23/when-you-should-use-base64-for-images/>. The guy is really in that case and made some tests. I was impressed and make my tests as well. The reality is like it says. For so much images loaded in one page the one response from the server is really helpful. | * Base64 encoding makes the file bigger and therefore slower to transfer.
* By including the image in the page, it has to be downloaded every time. External images are normally only downloaded once and then cached by the browser.
* It isn't compatible with all browsers | Base 64 encode vs loading an image file | [
"",
"php",
"mysql",
"html",
"image",
"base64",
""
] |
Just trying to get my head round Spring and figuring out how I wire up an Oracle connection in xml config file, and now find out I need yet another framework! - Hibernate, this is soooo frustrating as it feels like I'm getting deeper and deeper into more and more frameworks without actually getting what I need done!
I looked at Hibernate and it seems to do similar things to Spring, bearing in mind I just want to do some SQL inserts in Oracle.
I am reluctant and do not have time to learn 2 frameworks - could I get away with just adopting Hibernate for the simple things I need to do? | > *...could I get away with just adopting Hibernate for the simple things I need to do?*
Yes
Hibernate is for ORM ( object relational mapping ) that is, make your objects persistent to a RDBMS.
Spring goes further. It may be used also as a AOP, Dependency Injector, a Web Application and ORM among other things.
So if you only need ORM, just use Hibernate. Time will come when you need Spring, and you will learn it then.
Here's an architectural view of Spring:

And this is Hibernate:
 | Spring and Hibernate are totally different frameworks for different problems. Spring is a huge framework with many many features, Hibernate is an O/R bridge.
I would recommend using plain old JDBC in your case ('just some SQL inserts in Oracle'). | Spring vs Hibernate | [
"",
"java",
"hibernate",
"spring",
""
] |
In C#, is it possible to decorate an Enum type with an attribute or do something else to specify what the default value should be, without having the change the values? The numbers required might be set in stone for whatever reason, and it'd be handy to still have control over the default.
```
enum Orientation
{
None = -1,
North = 0,
East = 1,
South = 2,
West = 3
}
Orientation o; // Is 'North' by default.
``` | The default for an `enum` (in fact, any value type) is 0 -- even if that is not a valid value for that `enum`. It cannot be changed. | The default value of any enum is zero. So if you want to set one enumerator to be the default value, then set that one to zero and all other enumerators to non-zero (the first enumerator to have the value zero will be the default value for that enum if there are several enumerators with the value zero).
```
enum Orientation
{
None = 0, //default value since it has the value '0'
North = 1,
East = 2,
South = 3,
West = 4
}
Orientation o; // initialized to 'None'
```
If your enumerators don't need explicit values, then just make sure the first enumerator is the one you want to be the default enumerator since "By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1." ([C# reference](http://msdn.microsoft.com/en-us/library/sbbt4032.aspx))
```
enum Orientation
{
None, //default value since it is the first enumerator
North,
East,
South,
West
}
Orientation o; // initialized to 'None'
``` | Choosing the default value of an Enum type without having to change values | [
"",
"c#",
".net",
"enums",
""
] |
I would like to create a class that creates and manages log files. I would like the log file to be truncated when it exceeds a certain amount of text lines. Does any one have any recommendations on best practices to remove lines from the beginning of a text file. | Unless this is for a class assignment, why not use available open-source alternatives? Log4net allows you to roll between a specified number of log files. | In short: Don't
The long version
When you reach the limit of lines, create a new log file, keep the previous log file, but remove the one before that.
You are now guarenteed to have at leat n lines of log file at any given time. | c# log file truncation | [
"",
"c#",
""
] |
I understand that I need to use LoadLibrary(). But what other steps do I need to take in order to use a third-party DLL file?
I simply jumped into C++ and this is the only part that I do not get (as a Java programmer). I am just looking into how I can use a [Qt](https://en.wikipedia.org/wiki/Qt_%28software%29) Library and tesseract-ocr, yet the process makes no sense to me and is so difficult to google.
How do I tell the compiler of the functions that I am using? Should there be an include file from the third-party vendor? | As everyone else says, LoadLibrary is the hard way to do it, and is hardly ever necessary.
The DLL should have come with a .lib file for linking, and one or more header files to #include into your sources. The header files will define the classes and function prototypes that you can use from the DLL. You will need this even if you use LoadLibrary.
To link with the library, you might have to add the .lib file to the project configuration under Linker/Input/Additional Dependencies. | To incorporate third-party DLLs into my VS 2008 C++ project I did the following (you should be able to translate into 2010, 2012 etc.)...
I put the header files in my solution with my other header files, made changes to my code to call the DLLs' functions (otherwise why would we do all this?). :^) Then I changed the build to link the LIB code into my EXE, to copy the DLLs into place, and to clean them up when I did a 'clean' - I explain these changes below.
Suppose you have 2 third-party DLLs, A.DLL and B.DLL, and you have a stub LIB file for each (A.LIB and B.LIB) and header files (A.H and B.H).
* Create a "lib" directory under your solution directory, e.g. using Windows Explorer.
* Copy your third-party .LIB and .DLL files into this directory
(You'll have to make the next set of changes once for each source build target that you use (Debug, Release).)
1. Make your EXE dependent on the LIB files
* Go to Configuration Properties -> Linker -> Input -> Additional Dependencies, and list your .LIB files there one at a time, separated by *spaces*: `A.LIB B.LIB`
* Go to Configuration Properties -> General -> Additional Library Directories, and add your "lib" directory to any you have there already. Entries are separated by *semicolons*. For example, if you already had `$(SolutionDir)fodder` there, you change it to `$(SolutionDir)fodder;$(SolutionDir)lib` to add "lib".
2. Force the DLLs to get copied to the output directory
* Go to Configuration Properties -> Build Events -> Post-Build Event
* Put the following in for Command Line (for the switch meanings, see "XCOPY /?" in a DOS window):
`XCOPY "$(SolutionDir)"\lib\*.DLL "$(TargetDir)" /D /K /Y`
* You can put something like this for Description:
`Copy DLLs to Target Directory`
* Excluded From Build should be `No`.
Click `OK`.
3. Tell VS to clean up the DLLs when it cleans up an output folder:
* Go to Configuration Properties -> General -> Extensions to Delete on Clean, and click on "..."; add `*.dll` to the end of the list and click `OK`. | How do I use a third-party DLL file in Visual Studio C++? | [
"",
"c++",
"visual-studio",
"winapi",
"dll",
""
] |
How can I allow the users of my program to type in a value and have it auto-complete, however, I also what to prevent them from entering new data because it would cause the data to be unfindable (unless you had direct access to the database).
Does anyone know how to do this?
The reasoning behind not using just a dropdown style combobox is because entering data by typing it is and then refusing characters that are not part of an option in the list is because it's easier on the user.
If you have used Quickbook's Timer, that is the style of comboboxes I am going for. | Kudos to BFree for the help, but this is the solution I was looking for. The ComboBox is using a DataSet as it's source so it's not a custom source.
```
protected virtual void comboBoxAutoComplete_KeyPress(object sender, KeyPressEventArgs e) {
if (Char.IsControl(e.KeyChar)) {
//let it go if it's a control char such as escape, tab, backspace, enter...
return;
}
ComboBox box = ((ComboBox)sender);
//must get the selected portion only. Otherwise, we append the e.KeyChar to the AutoSuggested value (i.e. we'd never get anywhere)
string nonSelected = box.Text.Substring(0, box.Text.Length - box.SelectionLength);
string text = nonSelected + e.KeyChar;
bool matched = false;
for (int i = 0; i < box.Items.Count; i++) {
if (((DataRowView)box.Items[i])[box.DisplayMember].ToString().StartsWith(text, true, null)) {
matched = true;
break;
}
}
//toggle the matched bool because if we set handled to true, it precent's input, and we don't want to prevent
//input if it's matched.
e.Handled = !matched;
}
``` | This is my solution, I was having the same problem and modify your code to suit my solution using textbox instead of combobox, also to avoid a negative response after comparing the first string had to deselect the text before comparing again against autocomplet list, in this code is an AutoCompleteStringCollection shiper, I hope this solution will help
```
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
String text = ((TextBox)sender).Text.Substring(
0, ((TextBox)sender).SelectionStart) + e.KeyChar;
foreach(String s in this.shippers)
if (s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()) ||
e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Delete)
return;
e.Handled = true;
}
``` | Autocomplete AND preventing new input - combobox | [
"",
"c#",
".net",
"winforms",
"combobox",
"autocomplete",
""
] |
So the final menu will look something like this:
```
Item B
Item B-1
Item B-1-2
Item B-1-1
Item A
SubItem A-1
SubItem A-2
Item C
```
Based on the following DB records:
```
id menu_title parent_menu_id menu_level weight
1 Item A 0 1 1
2 Item B 0 1 0
3 Item C 0 1 2
4 SubItem A-2 1 2 1
5 Item B-1 2 2 0
6 Item B-1-1 5 3 1
7 SubItem A-1 1 2 0
8 Item B-1-2 5 3 0
```
**How would I go about displaying?** My guess is it'll involve storing all the items into a multidimensional array, then looping through it somehow... | Dealing with the data structure as you have it will often involve recursion or multiple queries to build the tree.
Have you considered other ways of storing a hierarchy? Check out modified pre-order traversal - here's a nice [PHP based article about this](http://www.sitepoint.com/article/hierarchical-data-database/). | Hierarchical data is somewhat annoying in a relationsal database (excluding Oracle, which has operators in `START WITH/CONNECT BY` to deal with this). There are basically [two models](http://extjs.com/forum/showthread.php?t=33096): adjacency list and nested sets.
You've chosen adjacency sets, which is what I typically do too. It's far easier to change than the nested set model, although the nested set model can be retrieved in the correct order in a single query. Adjacency lists can't be. You'll need to build an intermediate data structure (tree) and then convert that into a list.
What I would do (and have done recently in fact) is:
* select the entire menu contents in one query ordered by parent ID;
* Build a tree of the menu structure using associative arrays or classes/objects;
* Walk that tree to create nested unordered lists; and
* Use a jQuery plug-in like [Superfish](http://users.tpg.com.au/j_birch/plugins/superfish/) to turn that list into a menu.
You build something like this:
```
$menu = array(
array(
'name' => 'Home',
'url' => '/home',
),
array(
'name' => 'Account',
'url' => '/account',
'children' => array(
'name' => 'Profile',
'url' => '/account/profile',
),
),
// etc
);
```
and convert it into this:
```
<ul class="menu">;
<li><a href="/">Home</a></li>
<li><a href="/account">Account Services</a>
<ul>
<li><a href="/account/profile">Profile</a></li>
...
```
The PHP for generating the menu array from is reasonably straightforward but a bit finnicky to solve. You use a recursive tree-walking function that builds the HTML nested list markup but will leave it's implementation as an exercise for the reader. :) | PHP/MySQL - building a nav menu hierarchy | [
"",
"php",
"mysql",
"arrays",
"menu",
"hierarchy",
""
] |
Does anybody know of a method to trigger an event in Prototype, as you can with jQuery's trigger function?
I have bound an event listener using the observe method, but I would also like to be able to fire the event programatically. | [`event.simulate.js`](http://github.com/kangax/protolicious/blob/5b56fdafcd7d7662c9d648534225039b2e78e371/event.simulate.js) fits your needs.
I've used this several times and it works like a charm. It allows you to **manually trigger native events**, such as click or hover like so:
```
$('foo').simulate('click');
```
The great thing about this is that all attached event handlers will still be executed, just as if you would have clicked the element yourself.
For **custom events** you can use the standard prototype method [`Event.fire()`](http://www.prototypejs.org/api/element/fire). | I don't think there is one built in to Prototype, but you can use this (not tested but should at least get you in the right direction):
```
Element.prototype.triggerEvent = function(eventName)
{
if (document.createEvent)
{
var evt = document.createEvent('HTMLEvents');
evt.initEvent(eventName, true, true);
return this.dispatchEvent(evt);
}
if (this.fireEvent)
return this.fireEvent('on' + eventName);
}
$('foo').triggerEvent('mouseover');
``` | Trigger an event with Prototype | [
"",
"javascript",
"events",
"prototypejs",
""
] |
Is the window object onclose() or closing() event exposed in HTML/Javascript? | You have both onunload() and onbeforeunload() javascript events for that. | There is no event that lets you determine the difference between a page refresh, form submission, link clicked, or browser closed.
I am guessing that is what you are really after. | HTML window object onclose or closing event | [
"",
"javascript",
"html",
""
] |
I'm looking at the AdventureWorks sample database for SQL Server 2008, and I see in their creation scripts that they tend to use the following:
```
ALTER TABLE [Production].[ProductCostHistory] WITH CHECK ADD
CONSTRAINT [FK_ProductCostHistory_Product_ProductID] FOREIGN KEY([ProductID])
REFERENCES [Production].[Product] ([ProductID])
GO
```
followed immediately by :
```
ALTER TABLE [Production].[ProductCostHistory] CHECK CONSTRAINT
[FK_ProductCostHistory_Product_ProductID]
GO
```
I see this for foreign keys (as here), unique constraints and regular `CHECK` constraints; `DEFAULT` constraints use the regular format I am more familiar with such as:
```
ALTER TABLE [Production].[ProductCostHistory] ADD CONSTRAINT
[DF_ProductCostHistory_ModifiedDate] DEFAULT (getdate()) FOR [ModifiedDate]
GO
```
What is the difference, if any, between doing it the first way versus the second? | The first syntax is redundant - the `WITH CHECK` is default for new constraints, and the constraint is turned on by default as well.
This syntax is generated by the SQL management studio when generating sql scripts -- I'm assuming it's some sort of extra redundancy, possibly to ensure the constraint is enabled even if the default constraint behavior for a table is changed. | To demonstrate how this works--
```
CREATE TABLE T1 (ID INT NOT NULL, SomeVal CHAR(1));
ALTER TABLE T1 ADD CONSTRAINT [PK_ID] PRIMARY KEY CLUSTERED (ID);
CREATE TABLE T2 (FKID INT, SomeOtherVal CHAR(2));
INSERT T1 (ID, SomeVal) SELECT 1, 'A';
INSERT T1 (ID, SomeVal) SELECT 2, 'B';
INSERT T2 (FKID, SomeOtherVal) SELECT 1, 'A1';
INSERT T2 (FKID, SomeOtherVal) SELECT 1, 'A2';
INSERT T2 (FKID, SomeOtherVal) SELECT 2, 'B1';
INSERT T2 (FKID, SomeOtherVal) SELECT 2, 'B2';
INSERT T2 (FKID, SomeOtherVal) SELECT 3, 'C1'; --orphan
INSERT T2 (FKID, SomeOtherVal) SELECT 3, 'C2'; --orphan
--Add the FK CONSTRAINT will fail because of existing orphaned records
ALTER TABLE T2 ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID); --fails
--Same as ADD above, but explicitly states the intent to CHECK the FK values before creating the CONSTRAINT
ALTER TABLE T2 WITH CHECK ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID); --fails
--Add the CONSTRAINT without checking existing values
ALTER TABLE T2 WITH NOCHECK ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID); --succeeds
ALTER TABLE T2 CHECK CONSTRAINT FK_T2_T1; --succeeds since the CONSTRAINT is attributed as NOCHECK
--Attempt to enable CONSTRAINT fails due to orphans
ALTER TABLE T2 WITH CHECK CHECK CONSTRAINT FK_T2_T1; --fails
--Remove orphans
DELETE FROM T2 WHERE FKID NOT IN (SELECT ID FROM T1);
--Enabling the CONSTRAINT succeeds
ALTER TABLE T2 WITH CHECK CHECK CONSTRAINT FK_T2_T1; --succeeds; orphans removed
--Clean up
DROP TABLE T2;
DROP TABLE T1;
``` | WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT | [
"",
"sql",
"sql-server",
"t-sql",
"check-constraints",
""
] |
This works just fine:
```
protected void txtTest_Load(object sender, EventArgs e)
{
if (sender is TextBox) {...}
}
```
Is there a way to check if sender is NOT a TextBox, some kind of an equivalent of != for "is"?
Please, don't suggest moving the logic to ELSE{} :) | This is one way:
```
if (!(sender is TextBox)) {...}
``` | C# 9 allows using the [not](https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#logical-patterns) operator. You can just use
```
if (sender is not TextBox) {...}
```
instead of
```
if (!(sender is TextBox)) {...}
``` | Check if object is NOT of type (!= equivalent for "IS") - C# | [
"",
"c#",
"asp.net",
".net-2.0",
""
] |
I'm trying to make a crossplatform C# application using C#, mono/GTK# on Linux and .NET/GTK# on Windows, however the startup sequence seems to need to be slightly different under the two platforms:
Under Linux:
```
public static void Main (string[] args)
{
Gdk.Threads.Init ();
// etc...
```
Under Windows:
```
public static void Main (string[] args)
{
Glib.Thread.Init ();
Gdk.Threads.Init ();
// etc...
```
Both require it to be done that way: Windows complains about g\_thread\_init() not being called with the linux code, and linux complains about it already being called with the Windows code. Other than this, it all works wonderfully.
My first attempt at a "solution" looked like:
```
public static void Main (string[] args)
{
try {
Gdk.Threads.Init ();
} catch (Exception) {
GLib.Thread.Init ();
Gdk.Threads.Init ();
}
// etc...
```
But even this messy solution doesn't work; the error is coming from GTK+, unmanaged code, so it can't be caught. Does anyone have any bright ideas about the cause of the problem, and how to fix it? Or, failing that, have bright ideas on how to detect which one should be called at runtime? | Gtk+ on Win32 does not properly support threading. You need to do all your GUI calls from the same thread as you did called Gtk.Main().
It's not actually as bad as it sounds. There's a trick you can use to dispatch functions to the main thread. Just use GLib.Idle.Add() from any thread and the function will be called shortly in the same thread as the main loop is running in. Just remember to return false in the idle handler function, or it will go on running forever.
If you follow and use the above techniques you don't even need to call Gdk.Threads.Init() at all. | I'm not sure if this works on Mono, but you can use the Environment class to determine which OS the program is running on.
```
public static void Main (string[] args)
{
PlatformID platform = Environment.OSVersion.Platform;
if (platform == PlatformID.Win32NT ||
platform == PlatformID.Win32S ||
platform == PlatformID.Win32Windows)
Glib.Thread.Init();
else if (platform != PlatformID.Unix)
throw new NotSupportedException("The program is not supported on this platform");
Gdk.Threads.Init();
// etc...
```
The [PlatformID](http://msdn.microsoft.com/en-us/library/3a8hyw88.aspx) enum contains more than just Windows and Unix however, so you should check for other values. | Crossplatform threading and GTK#, not working (properly)? | [
"",
"c#",
"cross-platform",
"gtk#",
""
] |
When using ADO.Net Data Services client to refresh an entity by calling the `LoadProperty`:
```
ctx.BeginLoadProperty(this, "Owner", (IAsyncResult ar) => ...
```
It throws an error on the server if the property is `null`
> Error: Exception Thrown: System.Data.Services.DataServiceException:
> Resource not found for the segment 'Owner'. at
> System.Data.Services.RequestDescription.GetSingleResultFromEnumerable(SegmentInfo
> segmentInfo) at
> System.Data.Services.DataService1.CompareETagAndWriteResponse(RequestDescription
> description, ContentFormat responseFormat, IDataService dataService)
> at
> System.Data.Services.DataService1.SerializeResponseBody(RequestDescription
> description, IDataService dataService) at
> System.Data.Services.DataService1.HandleNonBatchRequest(RequestDescription
> description) at System.Data.Services.DataService`1.HandleRequest()
Problem is that the client does not know whether the property is `null` or just hasn't been populated yet. The property Owner is a link from a `Vehicle` to a `Customer`.
Any ideas what's wrong?
Thanks | Querying on primary keys generate an exception when the key does not exist. The workaround is to add a dummy true expression in the condition (eg : 1==1 && item.Id == XXX).
Without the dummy expression the ADO.NET request is:
> http: //localhost//test.svc/Role(XXX)
With the dummy condition, the request is:
> http: //localhost//test.svc/Role()?$filter=true and (Id eq 1)
The expected behaviour (null returned) is correct in the second case. | Set [IgnoreResourceNotFoundException](http://msdn.microsoft.com/en-us/library/system.data.services.client.dataservicecontext.ignoreresourcenotfoundexception.aspx) property of the service context to true:
```
svc.IgnoreResourceNotFoundException = true;
``` | Resource not found for segment 'Property' | [
"",
"c#",
"wcf-data-services",
""
] |
I'm detecting `@replies` in a Twitter stream with the following PHP code using regexes. In the first pattern, I replace @replies at the beginning of the string; in the second, I replace the @replies which follow a space.
```
$text = preg_replace('!^@([A-Za-z0-9_]+)!', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $text);
$text = preg_replace('! @([A-Za-z0-9_]+)!', ' <a href="http://twitter.com/$1" target="_blank">@$1</a>', $text);
```
How can I best combine these two rules without false flagging `email@domain.com` as a reply? | OK, on a second thought, not flagging whatever@email means that the previous element has to be a "non-word" item, because any other element that could be contained in a word could be signaled as an email, so it would lead:
```
!(^|\W)@([A-Za-z0-9_]+)!
```
but then you have to use $2 instead of $1. | Since the `^` does not have to stand at the beginning of the RE, you can use grouping and `|` to combine those REs.
If you don't want re-insert the whitespace you captured, you have to use "positive lookbehind":
```
$text = preg_replace('/(?<=^|\s)@(\w+)/',
'<a href="http://twitter.com/$1" target="_blank">@$1</a>', $text);
```
or "negative lookbehind":
```
$text = preg_replace('/(?<!\S)@(\w+)/',
'<a href="http://twitter.com/$1" target="_blank">@$1</a>', $text);
```
...whichever you find easier to understand. | Replace @replies in tweet text with HTML hyperlinks without replacing email addresses | [
"",
"php",
"regex",
"twitter",
"hyperlink",
"preg-replace",
""
] |
I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool.
Can anyone tell me how this is implemented? I know there's the Code module, which provides an InteractiveConsole class, but I don't know how this can be run in the context of currently loaded code. I'm quite new to Python, so gentle assistance would be appreciated! | Right, I'm ashamed to admit it's actually in the documentation for InteractiveConsole after all. You can make it run in the local context by passing in the result of the locals() function to the InteractiveConsole constructor. I couldn't find a way to close the InteractiveConsole without killing the application, so I've extended it to just close the console when it catches the SystemExit exception. I don't like it, but I haven't yet found a better way.
Here's some (fairly trivial) sample code that demonstrates the debug console.
```
import code
class EmbeddedConsole(code.InteractiveConsole):
def start(self):
try:
self.interact("Debug console starting...")
except:
print("Debug console closing...")
def print_names():
print(adam)
print(bob)
adam = "I am Adam"
bob = "I am Bob"
print_names()
console = EmbeddedConsole(locals())
console.start()
print_names()
``` | You could try looking at the python debugger pdb. It's like gdb in how you use it, but implemented in pure python. Have a look for pdb.py in your python install directory. | How are debug consoles implemented in Python? | [
"",
"python",
"debugging",
"interactive",
""
] |
I am writing a program that needs to search a LARGE text document for a large collection of words. The words are all file names, with underscores in them (eg, this\_file\_name). I know how to open and iterate through a text document, but I'm curious whether I should use Regex to search for these names, and if so, what kind of reg. ex. sequence should I use? I've tried
```
Regex r = new Regex("?this\_file\_name");
```
but I get an invalid argument error every time. | It would be helpful to see a sample of the source text. but maybe this helps
```
var doc = @"asdfsdafjkj;lkjsadf asddf jsadf asdfj;lksdajf
sdafjkl;sjdfaas sadfj;lksadf sadf jsdaf jf sda sdaf asdf sad
jasfd sdf sadf sadf sdajlk;asdf
this_file_name asdfsadf asdf asdf asdf
asdf sadf asdfj asdf sdaf sadfsadf
sadf asdf this_file_name asdf asdf ";
var reg = new Regex("this_file_name", RegexOptions.IgnoreCase | RegexOptions.Multiline);
var matches = reg.Matches(doc);
``` | Perhaps break your document into tokens by splitting on space or non word characters first?
After, I think a regex that might work for you would look something like this:
`Regex r = new Regex(@"([\w_]+)");` | C# regular expressions - matching whole words? | [
"",
"c#",
"regex",
""
] |
I'm looking to run some un-verified scripts (written in a yet-to-be-determined language, but needs to be Java-based, so JRuby, Groovy, Jython, BeanShell, etc are all candidates). I want these scripts to be able to do some things and restricted from doing other things.
Normally, I'd just go use Java's SecurityManager and be done with it. That's pretty simple and lets me restrict file and network access, the ability to shutdown the JVM, etc. And that will work well for the high level stuff I want to block off.
But there is some stuff I want to allow, but only via my custom API/library that I've providing. For example, I don't want to allow direct network access to open up a URLConnection to yahoo.com, but I am OK if it is done with MyURLConnection. That is - there is a set of methods/classes that I want to allow and then everything else I want to be off limits.
I don't believe this type of security can be done with the standard Java security model, but perhaps it can. I don't have a specific requirement for performance or flexibility in the scripting language itself (the scripts will be simple procedural calls to my API with basic looping/branching). So even a "large" overhead that checks a security check on every reflection call is fine by me.
Suggestions? | Disclaimer: I am not an expert on Java Security APIs, so there may be a better way to do this.
I work for [Alfresco](http://www.alfresco.com), Java-based Open Source Enterprise CMS, and we implemented something similar to what you describe. We wanted to allow scripting, but only to expose a subset of our Java APIs to the scripting engine.
We chose Rhino Engine for JavaScript scripting. It allows you to control which APIs are exposed to JavaScript, which allows us to choose which classes are available, and which are not. The overhead, according to our engineers, is on the order of 10%- not too bad.
In addition to this, and this may be relevant to you as well, on the Java side, we use Acegi (now Spring Security), and use AOP to give role-based control over which methods a certain user can call. That works pretty well for authorization. So in effect, a user accessing our app through JavaScript first has a restricted API available to him in the first place, and then that API can be restricted even further based on authorization. So you could use the AOP techniques to further restrict which methods can be called, thus allowing to expose this in other scripting languages, such as Groovy, etc. We are in the process of adding those as well, having the confidence that our underlying Java APIs protect users from unauthorized access. | You may be able to use a custom class loader that does vets linking to classes before delegating to its parent.
You can create your own permissions, check for those in your security sensitive APIs and then use `AccessController.doPrivileged` to restore appropriate privileges whilst calling the underlying API.
You need to make sure that the scripting engine itself is secure. The version of Rhino in the Sun JDK should be okay, but no guarantees. Obviously you need to make sure everything available to the script is secure. | Security with Java Scripting (JRuby, Jython, Groovy, BeanShell, etc) | [
"",
"java",
"security",
"groovy",
"jruby",
"jython",
""
] |
So I'm going to be working on a home made blog system in PHP and I was wondering which way of storing data is the fastest. I could go in the MySQL direction, or I could go with my own little way of doing it which is storing all of the information (encoded in JSON) in files.
Which way would be the fastest, MySQL or JSON files? | I would choose a MySQL database - simply because it's easier to manage.
JSON is not really a format for storage, it's for sending data to JavaScripts. If you want to store data in files look into [XML](http://www.php.net/manual/en/function.simplexml-element-construct.php) or [Serialized PHP](http://www.php.net/serialize) (which I suspect is what you are after, rather than JSON). | For a small, single user 'database', a file system would likely be quicker - as the size and complexity grows, a database server like MySQL or SQL Server is hard to beat. | MySQL vs File Databases | [
"",
"php",
"mysql",
"json",
""
] |
What are the suggested methods for using javascript files with MOSS 2007 ? in the 12 Hive somewhere or directly in the site's virtual directory in a scripts directory ? Or possibly as a embedded resource in a webpart ? | Personally, it all depends on what purpose the JavaScript files are going to serve. If they're going to be shared amongst multiple components then I would suggest placing them in the 12-hive. If however, they're going to be isolated to a single component - a web part for instance - then embedding them as a resource will work as well.
[This article](http://www.synergyonline.com/blog/blog-moss/Lists/Posts/Post.aspx?ID=42) has a discussion about best practices for the deployment of web part resources which you may find useful, in concludes:
> In this post, you have seen how to
> both link to and embed Web Part
> resources. Each has its own
> advantages and disadvantages, mostly
> boiling down to whether you need to
> maintain the resource separately from
> the Web Part. In both cases, the
> resource file can be cached, so there
> is little performance difference from
> each option. Feel free to use one of
> these two approaches for your next web
> part. | I suggest you deploy these scripts in the 12-hive.
* Having them in the 12-hive ensures fast access, which is important for scripts. You risk page rendering lag otherwise. More admin overhead as you must deploy them on *all* frontend webservers in your farm.
* Having them in the content DB makes them more centrally manageble at the const of performance. | Best practice - MOSS 07 and Javascript Files? | [
"",
"asp.net",
"javascript",
"web-parts",
"sharepoint-2007",
""
] |
On my C# asp.net webform I have a search page that has roughly 20 elements that "could" be used as part of the search. There will be more added later.
What I have done is extend the textbox and dropdown listbox to include a few variables:
fieldname: Tablename.columnname
dbtype: DbType.Int32
Joinparam: LEFT Join on otherTable ON x.y = a.b
These are all stored in the viewstate and loaded back in. The reason I do this is so that I can iterate through all the controls and pull out all the controls that are of my type. I can then validate them to make sure they have input and are of the right type. If so I can then pass them off to the database access layer and let the code dynamically generate the SQL statement.
I do not let anything but SELECT statements happen from this. The fields selected and returned can not be changed and I use the dbparameter to try and avoid sql injection.
My worry is that I put the table and field names that will be used in the search criteria and the JOINS required all in the viewstate. Is this a real bad idea?
I could obscurify this by just having some int index's into tables that hold this info in the DB but this would still need to be put into the viewstate and just mean they would have an extra layer to figure out.
The reason I went for this approach was that I did not want to have to put tons of IF statements in the DB layer to build the statement there. It would be ugly as hell and a pain to maintain.
Thanks for any and all advice about this.
Jon
**EDIT**
Thanks all for the advice. Thankfully this app is an internal thing only so the damage would be limited. But I will never use this technique again and will work on the search template idea instead.
Cheers :) | I think it's a real design mistake to encode parts of your data access layer in your view logic. Putting aside the security concerns, this is going to be really hard to maintain and understand for anyone coming after you. I think a factory class to produce your specific queries from the various selected inputs is probably going to be easier to work with in the long run. Or perhaps, you could populate a "search template" from the inputs and have the search template function as the factory for producing the query, much like the way the UserPrincipal interacts with a PrincipalSearcher in the System.DirectoryServices.AccountManagement namespace. | Viewstate is not encrypted, it is base64 encoded. There are utilities readily available that will allow you to decode a page's viewstate.
It is possible to encrypt viewstate for a page or all of your pages however:
<http://msdn.microsoft.com/en-us/library/aa479501.aspx>
That said, I would not recommend this approach. The best approach for application design is to decouple your UI from your business and data access logic. In this case, you would be closely coupling them for no apparent benefit.
If you did build a more robust ad-hoc query feature into your data access layer, you might be adding value to the back end of your application. You could provide search capabilities via web services, windows forms apps etc. Even if this type of functionality is not something you envision happening in the near future, it can be a huge time (and $$$) saver when you take this approach.
The logic you have built into the UI could easily be built into some type of query engine. Instead of the IFs that you wanted to avoid, you can build a method to assemble a query by dynamically adding criteria to it. | C# asp.net build SQL Query dynamically from viewstate | [
"",
"c#",
"asp.net",
"security",
"viewstate",
""
] |
I have a database with event information, including date (in MMDDYYYY format). is it possible to write an SQL Server statement to only get rows that fall within a certain time frame?
something like this pseudo-statement:
```
SELECT * FROM events WHERE [current_date minus date <= 31] ORDER BY date ASC
```
where `date` is the date in the SQL Server row and `current_date` is today's date. The `31` is days, so basically a month's time.
I can easily process the data after a generic statement (read: `SELECT * FROM events ORDER BY date ASC`), but it would be "cool" (as in me learning something new :P) to know if this is possible. | SELECT \* FROM events WHERE date > getdate() - 31 ORDER BY date ASC | Use DateDiff:
SELECT \* FROM events WHERE DATEDIFF(day, date, getdate()) < 31 ORDER BY date ASC
<http://msdn.microsoft.com/en-us/library/ms189794.aspx> | How to do conditional SQL Server statements? | [
"",
"sql",
"sql-server",
"t-sql",
"datetime",
"query-help",
""
] |
Does anyone know of a PDF file parser that I could use to pull out sections of text from the plaintext pdf file? Specifially I want a way to be able to reliably pull out the section of text specific to annotations?
Delphi, C# RegEx I dont mind. | The [PDF File Parser](http://www.xtractpro.com/articles/PDF-File-Parser.aspx) article on xactpro seems to be exactly what you need. It explains the format of the PDF and comes with full source code for a parser (and another project for visualisation of the model).
The parser uses format-specific terms, but you could easily use the visualiser to learn what to look for. | You can also take a look at Xpdf (<http://www.foolabs.com/xpdf/download.html>) | Looking for a PDF file parser | [
"",
"c#",
"regex",
"delphi",
"pdf",
"unicode",
""
] |
I have four flags
```
Current = 0x1
Past = 0x2
Future = 0x4
All = 0x7
```
Say I receive the two flags Past and Future (`setFlags(PAST | FUTURE)`). How can I tell if `Past` is in it? Likewise how can I tell that `Current` is not in it? That way I don't have to test for every possible combination. | If you want all bits in the test mask to match:
```
if((value & mask) == mask) {...}
```
If you want any single bit in the test mask to match:
```
if((value & mask) != 0) {...}
```
The difference is most apparent when you are testing a value for multiple things.
To test for exclusion:
```
if ((value & mask) == 0) { }
``` | First of all - use enums with FlagAttribute. That's what it's for.
```
[Flags]
public enum Time
{
None = 0
Current = 1,
Past = 2,
Future = 4
All = 7
}
```
Testing then is done like this:
```
if ( (x & Time.Past) != 0 )
```
Or this:
```
if ( (x & Time.Past) == Time.Past )
```
The latter will work better if "Past" was a combination of flags and you wanted to test them all.
Setting is like this:
```
x |= Time.Past;
```
Unsetting is like this:
```
x &= ~Time.Past;
``` | Using Bitwise operators on flags | [
"",
"c#",
".net",
"bit-manipulation",
"bit-fields",
""
] |
Is there an easy way to read an application's already embedded manifest file?
I was thinking along the lines of an alternate data stream? | Windows manifest files are Win32 resources. In other words, they're embedded towards the end of the EXE or DLL. You can use LoadLibraryEx, FindResource, LoadResource and LockResource to load the embedded resource.
Here's a simple example that extracts its own manifest...
```
BOOL CALLBACK EnumResourceNameCallback(HMODULE hModule, LPCTSTR lpType,
LPWSTR lpName, LONG_PTR lParam)
{
HRSRC hResInfo = FindResource(hModule, lpName, lpType);
DWORD cbResource = SizeofResource(hModule, hResInfo);
HGLOBAL hResData = LoadResource(hModule, hResInfo);
const BYTE *pResource = (const BYTE *)LockResource(hResData);
TCHAR filename[MAX_PATH];
if (IS_INTRESOURCE(lpName))
_stprintf_s(filename, _T("#%d.manifest"), lpName);
else
_stprintf_s(filename, _T("%s.manifest"), lpName);
FILE *f = _tfopen(filename, _T("wb"));
fwrite(pResource, cbResource, 1, f);
fclose(f);
UnlockResource(hResData);
FreeResource(hResData);
return TRUE; // Keep going
}
int _tmain(int argc, _TCHAR* argv[])
{
const TCHAR *pszFileName = argv[0];
HMODULE hModule = LoadLibraryEx(pszFileName, NULL, LOAD_LIBRARY_AS_DATAFILE);
EnumResourceNames(hModule, RT_MANIFEST, EnumResourceNameCallback, NULL);
FreeLibrary(hModule);
return 0;
}
```
Alternatively, you can use MT.EXE from the Windows SDK:
```
>mt -inputresource:dll_with_manifest.dll;#1 -out:extracted.manifest
``` | You can extract/replace/merge/validate manifests using the command line manifest tool, `mt.exe`, which is part of the Windows SDK:
```
C:\Program Files\Microsoft SDKs\Windows\v6.1>mt /?
Microsoft (R) Manifest Tool version 5.2.3790.2075
...
> To extract manifest out of a dll:
mt.exe -inputresource:dll_with_manifest.dll;#1 -out:extracted.manifest
```
Different locations:
* C:\Program Files\Microsoft SDKs\Windows\v6.1\bin
* C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x86 | reading an application's manifest file? | [
"",
"c++",
"windows",
"visual-c++",
"manifest",
""
] |
I have an updatepanel which doesn't work. My whole code:
```
<%@ Page Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="AlgemeenDocument.aspx.cs" Inherits="PCK_Web_new.WebForm7" Title="Untitled Page" %>
```
```
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<script language="javascript" type="text/javascript">
function showOverlay(panel)
{
var pageHeight;
// Get viewport height
if (typeof window.innerWidth != 'undefined')
// Get viewport height - FF
vpHeight = window.innerHeight;
else
// Get viewport height - IE
vpHeight = document.documentElement.clientHeight;
// Get site height (div)
var treeview = document.getElementById("Treeview");
var siteHeight = 0;
if(treeview != null)
{
siteHeight = document.getElementById("Treeview").offsetHeight;
}
siteHeight += document.getElementById("HeaderContainer").offsetHeight;
siteHeight += document.getElementById("divMainMenu").offsetHeight;
// Compare heights and set the overlay height
if(vpHeight < siteHeight)
pageHeight = siteHeight + "px";
else
pageHeight = vpHeight + "px";
var div = document.getElementById(panel);
div.className = "DocOverlayShow";
div.style.height = pageHeight;
document.getElementById('<%= pnlAddComment.ClientID %>').className="DocAddCommentBox";
}
function hideOverlay()
{
//document.getElementById(commentID).style.visibility = "hidden";
//document.getElementById(titelID).style.visibility = "hidden";
var inputs = new Array();
inputs = document.getElementsByTagName('input');
for ( i = 0; i < inputs.length; i++ )
{
if ( inputs[i].type == 'text' )
{
inputs[i].value = '';
}
}
document.getElementById('<%= txtTitel.ClientID %>').value = "";
document.getElementById('<%= txtComment.ClientID %>').value = "";
document.getElementById('<%= pnlOverlay.ClientID %>').className = "DocOverlayHide";
}
</script>
<asp:Panel ID="pnlOverlay" runat="server" CssClass="DocOverlayHide">
<!-- <div id="DocAddCommentBox"> -->
<asp:Panel ID="pnlAddComment" runat="server" CssClass="DocAddCommentBox">
<div id="DocACTitleBox">
Opmerking plaatsen
</div>
<div id="DocACContentBox">
<div class="DocACLabel">
Titel:
</div>
<div class="DocACInput">
<asp:TextBox ID="txtTitel" runat="server"></asp:TextBox>
</div>
<div class="ClearFloat">
</div>
<div class="DocACLabel">
Opmerking:
</div>
<div class="DocACInput">
<asp:TextBox ID="txtComment" runat="server" TextMode="MultiLine" Rows="15"
Columns="40">
</asp:TextBox>
</div>
<div class="ClearFloat">
</div>
<div id="DocBtnBox">
<input id="btnCancel" type="button" onclick="hideOverlay()" value="Annuleren"/>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" EnableViewState="False" UpdateMode="Always" RenderMode="Block">
<ContentTemplate>
<asp:Button ID="btnSave" runat="server" CssClass="btnSave" onclick="btnSave_Click" Text="Opslaan" />
<asp:Label ID="lblTitleError" runat="server" Text="ertroro"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="ClearFloat"> </div>
</div>
</asp:Panel>
<!-- </div> -->
<asp:Panel ID="pnlResult" runat="server" CssClass="DocOverlayHide">
<div id="DocResultBox">
<div id="Div1">
Opmerking plaatsen
</div>
<div id="Div2">
<div class="DocACLabel">
<asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label>
</div>
<div id="Div1">
<input id="btnClose" type="button" onclick="hideOverlay()" value="Sluiten"/>
</div>
<div class="ClearFloat"> </div>
</div>
</div>
</asp:Panel>
</asp:Panel>
<div class="DocContainer">
<div class="DocTitleBox">
<div class="DocLogo">
Het logo
</div>
<div class="DocTitle">
<asp:Label ID="lblTitle" runat="server"></asp:Label>
</div>
<div class="DocType">
Document soort
<asp:Label ID="lblDocType" runat="server"></asp:Label>
</div>
<div class="DocBtn">
<input type="button" value="Opmerking" onclick="showOverlay('<%=pnlOverlay.ClientID %>')" />
</div>
</div>
<div class="DocContentBox">
<asp:Label ID="lblID" runat="server"></asp:Label>
<p>Algemeen Document Geen vaste opmaak.</p>
</div>
</div>
```
I have tried triggers, but they didn't work..
When i press btnSave this is the code that's executed:
```
protected void btnSave_Click(object sender, EventArgs e)
{
lblTitleError.Text = "BUTTON PRESSED";
}
```
When i set a breakpoint, it runs the code. But the label text isn't set :S
Hope someone can help?
Thnx!
EDIT:
I also tried this:
```
<div id="DocBtnBox">
<input id="btnCancel" type="button" onclick="hideOverlay()" value="Annuleren"/>
<asp:Button ID="btnSave" runat="server" CssClass="btnSave" onclick="btnSave_Click" Text="Opslaan" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server" EnableViewState="False" UpdateMode="Always">
<ContentTemplate>
<asp:Label ID="lblTitleError" runat="server" Text="ertroro"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
``` | I think the best tutor on the web is Joe Stagner. His material for .NET is awesome.
Here is a [link](http://www.asp.net/LEARN/ajax-videos/video-159.aspx) where he shows you exactly, step-by-step how to do what you are trying.
Addendum:
If I were you I'd create a clean page from the sample code Joe has provided. Go to <http://www.asp.net/LEARN/ajax-videos/> and figure out which tutorial you want to base your solution on. After you get the tutorial working on a sample page, I'd slowly, piece-by-piece add in the logic you need for your application. | Try removing EnableViewState="False" from the UpdatePanel. | C# Ajax updatepanel doesn't work | [
"",
"c#",
"updatepanel",
"overlay",
""
] |
We constantly run into this problem...
Example:
if I have a file that I want to copy it into an another directory or UNC share and if the length of the path exceeds 248 (if I am not mistaken), then it throws PathTooLongException. Is there any workaround to this problem?
PS: Is there any registry setting to set this path to a longer char set? | As described in Jeremy Kuhne's [blog](https://blogs.msdn.microsoft.com/jeremykuhne/2016/07/30/net-4-6-2-and-long-paths-on-windows-10/), .NET Framework [4.6.2](https://blogs.msdn.microsoft.com/dotnet/2016/08/02/announcing-net-framework-4-6-2/#bcl) removes the `MAX_PATH` limitation where possible, without breaking backwards compatibility. | Try This : **Delimon.Win32.IO Library (V4.0)** *This library is written on .NET Framework 4.0*
`Delimon.Win32.IO` replaces basic file functions of `System.IO` and supports File & Folder names up to up to **32,767** Characters.
<https://gallery.technet.microsoft.com/DelimonWin32IO-Library-V40-7ff6b16c>
This library is written specifically to overcome the limitation of the .NET Framework to use long Path & File Names. With this library you can programmatically browse, access, write, delete, etc files and folders that are not accessible by the `System.IO` namespace.Library
**Usage**
1. First add a reference to the Delimon.Win32.IO.dll to your project
(Browse to the Delimon.Win32.IO.dll file)
2. In your Code File add "using Delimon.Win32.IO"
3. Use normal File & Directory Objects as if you are working with
System.IO | How to avoid System.IO.PathTooLongException? | [
"",
"c#",
".net",
""
] |
In python, what does the 2nd % signifies?
```
print "%s" % ( i )
``` | As others have said, this is the Python string formatting/interpolation operator. It's basically the equivalent of sprintf in C, for example:
`a = "%d bottles of %s on the wall" % (10, "beer")`
is equivalent to something like
`a = sprintf("%d bottles of %s on the wall", 10, "beer");`
in C. Each of these has the result of `a` being set to `"10 bottles of beer on the wall"`
Note however that this syntax is deprecated in Python 3.0; its replacement looks something like
`a = "{0} bottles of {1} on the wall".format(10, "beer")`
This works because any string literal is automatically turned into a str object by Python. | The second % is the string interpolation operator.
[Link to documentation](http://docs.python.org/library/stdtypes.html#string-formatting-operations). | Print method question Python | [
"",
"python",
"string",
""
] |
I'm writing a Python program with a lot of file access. It's running surprisingly slowly, so I used cProfile to find out what was taking the time.
It seems there's a *lot* of time spent in what Python is reporting as "{built-in method acquire}". I have no idea what this method is. What is it, and how can I speed up my program? | Without seeing your code, it is hard to guess. But to guess I would say that it is the [threading.Lock.acquire](http://docs.python.org/library/threading.html#threading.Lock.acquire) method. Part of your code is trying to get a threading lock, and it is waiting until it has got it.
There may be simple ways of fixing it by
* restructuring your file access,
* not locking,
* using blocking=False,
* or even not using threads at all.
But again, without seeing your code, it is hard to guess. | Using threads for IO is a bad idea. Threading won't make your program wait faster. You can achieve better results by using asynchronous I/O and an event loop; Post more information about your program, and why you are using threads. | What is Python's "built-in method acquire"? How can I speed it up? | [
"",
"python",
"optimization",
"profiling",
"performance",
""
] |
I have a datagrid which is populated with CSV data when the user drag/drops a file onto it. Is it possible to display a message in the blank grid for example "Please drag a file here" or "This grid is currently empty". The grid currently displays as a dark grey box as I wait until the file is dragged to setup the columns etc. | We subclassed the DataGridView control and added this. We didnt need the drag/drop functionality - we just needed to tell the user when there was no data returned from their query.
We have an emptyText property declared like this:
```
private string cvstrEmptyText = "";
[Category("Custom")]
[Description("Displays a message in the DataGridView when no records are displayed in it.")]
[DefaultValue(typeof(string), "")]
public string EmptyText
{
get
{
return this.cvstrEmptyText;
}
set
{
this.cvstrEmptyText = value;
}
}
```
and overloaded the PaintBackground function:
```
protected override void PaintBackground(Graphics graphics, Rectangle clipBounds, Rectangle gridBounds)
{
RectangleF ef;
base.PaintBackground(graphics, clipBounds, gridBounds);
if ((this.Enabled && (this.RowCount == 0)) && (this.EmptyText.Length > 0))
{
string emptyText = this.EmptyText;
ef = new RectangleF(4f, (float)(this.ColumnHeadersHeight + 4), (float)(this.Width - 8), (float)((this.Height - this.ColumnHeadersHeight) - 8));
graphics.DrawString(emptyText, this.Font, Brushes.LightGray, ef);
}
}
``` | I think the easiest thing to do here is to make a giant label control to do the "Drag Here" and handle the label's drag/drop event. Once the drag/drop is complete, hide the label and show the grid. | Is it possible to display a message in an empty datagrid | [
"",
"c#",
"winforms",
"datagrid",
".net-2.0",
""
] |
I'm trying to use the jQuery alerts dialog library from <http://abeautifulsite.net/notebook/87> instead of the default alerts (which look pretty awful in my opinion). This seems to be a great library, but there is not an example of how to use the jConfirm library.
I need to do something like this:
```
function confirm() {
var result = false;
var response = false;
jConfirm('are you sure?', 'Confirmation Dialog',
function(r) {
result = r;
response = true;
return r;
});
if (response == true) {
alert(result);
return result;
}
else {
//wait for response
alert('hi');
}
}
```
and my call from my .net button:
I've posted a comment on the plugin's website (just this morning) and did Google searches for javascript and waiting for a callback to complete with no results.
Any ideas on how to use the callback correctly to get the result, before the rest of the javascript executes?
Thanks. | ```
jConfirm('are you sure?', 'Confirmation Dialog',
function(r) {
result = r;
response = true;
return r;
}
);
if (response == true) {
```
This betrays a misunderstanding of the sequence of events that occurs using asynchronous code. Just because you've written it inline doesn't mean it's going to execute strictly top-to-bottom.
1. jConfirm is called, receiving a function as one of its parameters, which it remembers.
2. jConfirm displays its UI on the page and returns immediately.
3. The 'if (response==true)' line executes. Really this should just read 'if (response)', the boolean comparison is superfluous. But in any case response is of course false. Your function gives up and exits, giving control back to the browser.
4. The user clicks jConfirm's UI.
5. jConfirm only now jumps into action and calls back the function you gave it and it remembered earlier.
6. Your nested function sets response true, far too late for the 'if (response==true)' condition to do anything with it.
You have written "//wait for response" as an alternative, but there is no JavaScript code you can write that will actually do that. Your function must return to give control back to the browser, before the browser can fire the click events on the jConfirm UI that make processing proceed.
Ways to make asynchronous code work in a synchronous context (and vice versa) exist - in particular threads and coroutines (and their limited relation generators). But JavaScript has none of these features, so you must write your code to fit the synchronous-or-asynchronous model your library is using. | You've just hit a big limitation in JavaScript. Once your code enters the asynchronous world, there is no way to get back to a classic procedural execution flow.
In your example, the solution would be to make a loop waiting for the response to be filled. The problem is that JavaScript does not provide any instruction that will allow you to loop indefinitely without taking 100% of the processing power. So you will end up blocking the browser, sometimes to the point where your user won't be able to answer the actual question.
The only solution here is to stick to the asynchronous model and keep it. My advice is that you should add a callback to any function that must do some asynchronous work, so that the caller can execute something at the end of your function.
```
function confirm(fnCallback)
{
jConfirm('are you sure?', 'Confirmation Dialog', function(r)
{
// Do something with r
fnCallback && fnCallback(r); // call the callback if provided
});
}
// in the caller
alert('begin');
confirm(function(r)
{
alert(r);
alert('end');
})
``` | Can you wait for javascript callback? | [
"",
"javascript",
"jquery",
"dialog",
"callback",
"confirm",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.