Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've started to pick up this pattern: ``` template<typename T> struct DefaultInitialize { DefaultInitialize():m_value(T()){} // ... conversions, assignments, etc .... }; ``` So that when I have classes with primitive members, I can set them to be initialized to 0 on construction: ``` struct Class { ... DefaultInitialize<double> m_double; ... }; ``` The reason I do this is to avoid having to remember to initialize the member in each constructor (if there are multiple constructors). I'm trying to figure out if: * This is a valid pattern? * I am using the right terminology?
> This is a valid pattern? It's a known "valid" pattern, i would say. Boost has a class template called [`value_initialized`](http://www.boost.org/doc/libs/1_39_0/libs/utility/value_init.htm) that does exactly that, too. > I am using the right terminology? Well, your template can be optimized to have fewer requirements on the type parameter. As of now, your type `T` requires a copy constructor, unfortunately. Let's change the initializer to the following ``` DefaultInitialize():m_value(){} ``` Then, technically this kind of initialization is called `value initialization`, starting with C++03. It's a little bit weird, since no kind of value is provided in the first place. Well, this kind of initialization looks like default initialization, but is intended to fill things with zero, but respecting any user defined constructor and executing that instead. To summarize, what you did was to value initialize an object having type `T`, then to copy that object to `m_value`. What my version of above does it to value initialize the member directly.
Seems like a lot of work to avoid having to type `m_double(0)`. I think it's harder to understand at first glance, but it does seem fine as long as everything is implemented properly. But is it worth it? Do you really want to have to `#include "DefaultInitialize.h"` everywhere? --- To clarify, basically, you're: * Making your compile times longer because of the includes. * Your code base larger because you have to manage the deceptively simple `DefaultInitialize` class * Increase the time it takes other people to read your code. If you have a member of a class that's a `double`, that's natural to me, but when I see `DefaultInitialize`, I have to learn what that is and why it was created All that because you don't like to type out a constructor. I understand that it seems very nice to not have to do this, but most worth-while classes I've ever written tend to need to have a constructor written anyway. This is certainly only my opinion, but I think most other people will agree with it. That is: it would be handy to not have to explicitly initialize members to 0, but the alternative (your class) isn't worth it. Not to mention that in C++0x, you can do this; ``` class Foo { private: int i = 0; // will be initialized to 0 } ```
Initializing member variables
[ "", "c++", "" ]
``` from PIL import Image img = Image.open('1.png') img.save('2.png') ``` The first image has a transparent background, but when I save it, the transparency is gone (background is white) What am I doing wrong?
Probably the image is indexed (mode "P" in PIL), so the transparency is not set in PNG alpha channel, but in metadata info. You can get transparent background palette index with the following code: ``` from PIL import Image img = Image.open('1.png') png_info = img.info img.save('2.png', **png_info) ``` image info is a dictionary, so you can inspect it to see the info that it has: eg: If you print it you will get an output like the following: ``` {'transparency': 7, 'gamma': 0.45454, 'dpi': (72, 72)} ``` The information saved there will vary depending on the tool that created the original PNG, but what is important for you here is the "transparency" key. In the example it says that palette index "7" must be treated as transparent.
You can always force the the type to "RGBA", ``` img = Image.open('1.png') img = img.convert('RGBA') img.save('2.png') ```
PIL does not save transparency
[ "", "python", "png", "python-imaging-library", "" ]
I have a table that represents a list of countries. I have another table that represents a list of states. I have another table that represents a list of provinces. Because of poor data definition, some states are actually in the province table and vice-versa. Regardless, each province and state is associated with a country. I need to essentially do a double left outer join. My question is, how do I do this? Here is what I am currently trying: ``` select c.Name as 'CountryName', ISNULL(p.[Name], '') as 'ProvinceName', ISNULL(s.[Name], '') as 'StateName' from Country c left outer join [Province] p on p.[CountryID]=c.[ID] left outer join [State] s on s.[CountryID]=c.[ID] ``` Please note that I need to do something comparable to two left outer joins. This is a simplified version of the query I'm trying to do. Thank you for your help!
You can do it the way you've stated. There's nothing wrong with that. I wouldn't necessarily replace NULLs with empty strings though. Is there a reason you're doing that? What you have to be aware of when doing what are essentially two one-to-many joins is that the results are multiplicative. By this I mean that if for a country there are 3 entries in the province table and 4 in the state table you'll get back 12 rows for that country. It might be more appropriate to do a UNION in these circumstances. For example: ``` SELECT c.Name AS 'CountryName', '' AS 'ProvinceName', ISNULL(s.[Name], '') AS 'StateName' FROM Country c LEFT OUTER JOIN [Province] p ON p.[CountryID]=c.[ID] UNION ALL SELECT c.Name AS 'CountryName', ISNULL(p.[Name], '') AS 'ProvinceName', '' AS 'ProvinceName' FROM Country c LEFT OUTER JOIN [State] s ON s.[CountryID]=c.[ID] ``` as just one possibility. It really depends on what your data looks like and what you want the end result to be.
A LEFT OUTER JOIN is just a LEFT JOIN, the syntax is simply: ``` SELECT c.Name AS CountryName p.Name AS ProvinceName s.Name AS StateName FROM Country c LEFT JOIN Province p ON p.CountryID = c.ID LEFT JOIN State s ON s.CountryID = c.ID ```
SQL - Two Outer Joins
[ "", "sql", "" ]
I'm using the WebBrowser control in .Net to execute some 3rd party affiliate marketing conversions. I have a queue table in a database with all the scripts/images to execute. I loop through all these in a WinForms app with the WebBrowser control. After I've executed a script/image I Dispose the WebBrowser control, set it to null, and renews it with a new WebBrowser control instance. Consider this URL: <http://renderserver/RenderScript.aspx?id=1> RenderScript.aspx displays an Image with a URL of e.g.: <http://3rdparty/img.ashx?id=9343> I use Fiddler to see all requests and responses, and when the same URL is executed twice, it uses some kind of cache. That cache exists underneath the WebBrowser control itself. This cache means that the img.ashx is not called. I tried using Internet Explorer to request the URL: <http://renderserver/RenderScript.aspx?id=1> and hit F5. Then it is requested perfectly. But if I click the address bar and hits Enter to navigate to the same URL again - it is not requested. When I use Firefox is will request the page and image everytime no matter if I use F5 or navigate from the address bar. I found some Win32 API calls (<http://support.microsoft.com/kb/326201>) that was able to clear the cache. It worked on my local machine. Then the app was deployed to a server running Windows Server 2003 Standard x64 (my own machine is Vista x86). And now the API calls to clear the cache doesn't work. Any ideas on why the API calls doesn't work on Windows Server, but works on Vista? Both machines running IE8.
I had the same problem (quite) a while back. Microsoft has a page that was very helpful with this: <http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/q326/2/01.asp&NoWebContent=1> I created a class out of Microsoft's sample, however I also had to add a couple if statements to stop processing when there are no more items; it's been a while now, but I'm pretty sure it would throw an error (see `ERROR_NO_MORE_ITEMS` in the code below). I hope its helpful! ``` using System; using System.Runtime.InteropServices; // copied from: http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/q326/2/01.asp&NoWebContent=1 namespace PowerCode { public class IECache { // For PInvoke: Contains information about an entry in the Internet cache [StructLayout(LayoutKind.Explicit, Size = 80)] public struct INTERNET_CACHE_ENTRY_INFOA { [FieldOffset(0)] public uint dwStructSize; [FieldOffset(4)] public IntPtr lpszSourceUrlName; [FieldOffset(8)] public IntPtr lpszLocalFileName; [FieldOffset(12)] public uint CacheEntryType; [FieldOffset(16)] public uint dwUseCount; [FieldOffset(20)] public uint dwHitRate; [FieldOffset(24)] public uint dwSizeLow; [FieldOffset(28)] public uint dwSizeHigh; [FieldOffset(32)] public FILETIME LastModifiedTime; [FieldOffset(40)] public FILETIME ExpireTime; [FieldOffset(48)] public FILETIME LastAccessTime; [FieldOffset(56)] public FILETIME LastSyncTime; [FieldOffset(64)] public IntPtr lpHeaderInfo; [FieldOffset(68)] public uint dwHeaderInfoSize; [FieldOffset(72)] public IntPtr lpszFileExtension; [FieldOffset(76)] public uint dwReserved; [FieldOffset(76)] public uint dwExemptDelta; } // For PInvoke: Initiates the enumeration of the cache groups in the Internet cache [DllImport(@"wininet", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "FindFirstUrlCacheGroup", CallingConvention = CallingConvention.StdCall)] public static extern IntPtr FindFirstUrlCacheGroup( int dwFlags, int dwFilter, IntPtr lpSearchCondition, int dwSearchCondition, ref long lpGroupId, IntPtr lpReserved ); // For PInvoke: Retrieves the next cache group in a cache group enumeration [DllImport(@"wininet", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "FindNextUrlCacheGroup", CallingConvention = CallingConvention.StdCall)] public static extern bool FindNextUrlCacheGroup( IntPtr hFind, ref long lpGroupId, IntPtr lpReserved ); // For PInvoke: Releases the specified GROUPID and any associated state in the cache index file [DllImport(@"wininet", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "DeleteUrlCacheGroup", CallingConvention = CallingConvention.StdCall)] public static extern bool DeleteUrlCacheGroup( long GroupId, int dwFlags, IntPtr lpReserved ); // For PInvoke: Begins the enumeration of the Internet cache [DllImport(@"wininet", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "FindFirstUrlCacheEntryA", CallingConvention = CallingConvention.StdCall)] public static extern IntPtr FindFirstUrlCacheEntry( [MarshalAs(UnmanagedType.LPTStr)] string lpszUrlSearchPattern, IntPtr lpFirstCacheEntryInfo, ref int lpdwFirstCacheEntryInfoBufferSize ); // For PInvoke: Retrieves the next entry in the Internet cache [DllImport(@"wininet", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "FindNextUrlCacheEntryA", CallingConvention = CallingConvention.StdCall)] public static extern bool FindNextUrlCacheEntry( IntPtr hFind, IntPtr lpNextCacheEntryInfo, ref int lpdwNextCacheEntryInfoBufferSize ); // For PInvoke: Removes the file that is associated with the source name from the cache, if the file exists [DllImport(@"wininet", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "DeleteUrlCacheEntryA", CallingConvention = CallingConvention.StdCall)] public static extern bool DeleteUrlCacheEntry( IntPtr lpszUrlName ); public static void ClearCache() { // Indicates that all of the cache groups in the user's system should be enumerated const int CACHEGROUP_SEARCH_ALL = 0x0; // Indicates that all the cache entries that are associated with the cache group // should be deleted, unless the entry belongs to another cache group. const int CACHEGROUP_FLAG_FLUSHURL_ONDELETE = 0x2; // File not found. const int ERROR_FILE_NOT_FOUND = 0x2; // No more items have been found. const int ERROR_NO_MORE_ITEMS = 259; // Pointer to a GROUPID variable long groupId = 0; // Local variables int cacheEntryInfoBufferSizeInitial = 0; int cacheEntryInfoBufferSize = 0; IntPtr cacheEntryInfoBuffer = IntPtr.Zero; INTERNET_CACHE_ENTRY_INFOA internetCacheEntry; IntPtr enumHandle = IntPtr.Zero; bool returnValue = false; // Delete the groups first. // Groups may not always exist on the system. // For more information, visit the following Microsoft Web site: // http://msdn.microsoft.com/library/?url=/workshop/networking/wininet/overview/cache.asp // By default, a URL does not belong to any group. Therefore, that cache may become // empty even when the CacheGroup APIs are not used because the existing URL does not belong to any group. enumHandle = FindFirstUrlCacheGroup(0, CACHEGROUP_SEARCH_ALL, IntPtr.Zero, 0, ref groupId, IntPtr.Zero); // If there are no items in the Cache, you are finished. if (enumHandle != IntPtr.Zero && ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error()) { return; } // Loop through Cache Group, and then delete entries. while (true) { if (ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error() || ERROR_FILE_NOT_FOUND == Marshal.GetLastWin32Error()) { break; } // Delete a particular Cache Group. returnValue = DeleteUrlCacheGroup(groupId, CACHEGROUP_FLAG_FLUSHURL_ONDELETE, IntPtr.Zero); if (!returnValue && ERROR_FILE_NOT_FOUND == Marshal.GetLastWin32Error()) { returnValue = FindNextUrlCacheGroup(enumHandle, ref groupId, IntPtr.Zero); } if (!returnValue && (ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error() || ERROR_FILE_NOT_FOUND == Marshal.GetLastWin32Error())) { break; } } // Start to delete URLs that do not belong to any group. enumHandle = FindFirstUrlCacheEntry(null, IntPtr.Zero, ref cacheEntryInfoBufferSizeInitial); if (enumHandle != IntPtr.Zero && ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error()) { return; } cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial; cacheEntryInfoBuffer = Marshal.AllocHGlobal(cacheEntryInfoBufferSize); enumHandle = FindFirstUrlCacheEntry(null, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial); while (true) { internetCacheEntry = (INTERNET_CACHE_ENTRY_INFOA)Marshal.PtrToStructure(cacheEntryInfoBuffer, typeof(INTERNET_CACHE_ENTRY_INFOA)); if (ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error()) { break; } cacheEntryInfoBufferSizeInitial = cacheEntryInfoBufferSize; returnValue = DeleteUrlCacheEntry(internetCacheEntry.lpszSourceUrlName); if (!returnValue) { returnValue = FindNextUrlCacheEntry(enumHandle, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial); } if (!returnValue && ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error()) { break; } if (!returnValue && cacheEntryInfoBufferSizeInitial > cacheEntryInfoBufferSize) { cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial; cacheEntryInfoBuffer = Marshal.ReAllocHGlobal(cacheEntryInfoBuffer, (IntPtr)cacheEntryInfoBufferSize); returnValue = FindNextUrlCacheEntry(enumHandle, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial); } } Marshal.FreeHGlobal(cacheEntryInfoBuffer); } } } ``` To use it in your code, just call: ``` IECache.ClearCache() ``` before calling the navigate methods.
Fiddler uses fundamentally the same code as in the KB article to clear the WinINET cache, and I use it on Win2k3 every day. Rather than wiping the user's entire cache, the proper fix is to set the proper HTTP response header to forbid caching. You can learn more about WinINET caching here: <http://www.enhanceie.com/redir/?id=httpperf> (Alternatively, you could simply add a randomized query-string parameter; that way, each time the control encounters a request for the resource, the URL is different and the cache is thus automatically bypassed.)
Caching and the WebBrowser control in .Net
[ "", "c#", "winforms", "webbrowser-control", "" ]
What is the easiest way to code in the values in fifteen minute increments? In other words, instead of doing the following: ``` <select> <option value="">12:00 AM</option> <option value="">12:15 AM</option> <option value="">12:30 AM</option> <option value="">12:45 AM</option> ... so on ``` How could I use PHP to take up less space? Thanks!
use mktime() <https://www.php.net/manual/en/function.mktime.php> ``` for ($x = 0; $x < 10; $x++) { print "<option value=''>" . mktime(0, $x * 15) . "</option>"; } ``` Obviously your params for mktime will vary.
use the various time function there are in php: ``` $number = 10; echo '<select>'; for(i = 0; i < $number; ++$i) { echo '<option value="">', date('h:i A', mktime(12, 15*$i)), '</option>'; } echo '</select>'; ```
PHP Multiple Options
[ "", "php", "date", "time", "" ]
I am using ADO.NET Entity framework for connect db and get data. I want if there is no data in object it will write "EMPTY FIELD" if it's full than it will write to listview coloumn data from the db. I am getting 'System.NullReferenceException' error when there is a null object in objectcontext.Dont return a " EMPTY ROW" string. Here is my code: ``` using (ITSEntities arama = new ITSEntities()) { var sql = "SELECT VALUE s_tesis FROM ITSEntities.TB_SAGLIK_TESIS AS s_tesis WHERE s_tesis.TESIS_AD like @p1"; ObjectQuery<TB_SAGLIK_TESIS> sorgu = new ObjectQuery<TB_SAGLIK_TESIS>(sql, arama).Include("TB_IL").Include("TB_TESIS_TIPI").Include("TB_TESIS_TURU"); sorgu.Parameters.Add(new ObjectParameter("p1", String.Format("{0}%", btnAra.Text))); listTesis.Items.Clear(); foreach (var item in sorgu) { ListViewItem listitem = new ListViewItem { Text = item.KODU.ToString() }; listitem.SubItems.Add(item.TESIS_AD); listitem.SubItems.Add(String.IsNullOrEmpty(item.TB_IL.ADI) ? "EMPTY ROW" : item.TB_IL.ADI); listitem.SubItems.Add(String.IsNullOrEmpty(item.TB_TESIS_TIPI.TIP_AD) ? "EMPTY ROW" : item.TB_TESIS_TIPI.TIP_AD); listitem.SubItems.Add(String.IsNullOrEmpty(item.TB_TESIS_TURU.TESIS_TURU) ? "EMPTY ROW" :item.TB_TESIS_TURU.TESIS_TURU); listTesis.Items.Add(listitem); } } } catch (Exception ex) { MessageBox.Show(ex.InnerException.ToString()); } ```
I don't know EF, but you're dereferencing 2 objects in the following lines: ``` ListViewItem listitem = new ListViewItem { Text = item.KODU.ToString() }; listitem.SubItems.Add(String.IsNullOrEmpty(item.TB_IL.ADI) ? "EMPTY ROW" : item.TB_IL.ADI); listitem.SubItems.Add(String.IsNullOrEmpty(item.TB_TESIS_TIPI.TIP_AD) ? "EMPTY ROW" : item.TB_TESIS_TIPI.TIP_AD); listitem.SubItems.Add(String.IsNullOrEmpty(item.TB_TESIS_TURU.TESIS_TURU ``` If the container object (`KODU`, `TB_IL`, `TB_TESIS_TIPI`. or `TB_TESIS_TURU`) is ever null, then you'd get a NullReferenceException. My *guess* is that these are table names, and that some rows don't have a corresponding JOIN to those tables. In any case, you'd probably need to rewrite those as: ``` ListViewItem listitem = new ListViewItem { Text = (item.KODU ?? "").ToString() }; listitem.SubItems.Add( (item.TB_TL == null || String.IsNullOrEmpty(item.TB_IL.ADI)) ? "EMPTY ROW" : item.TB_IL.ADI ); ``` To make it a bit cleaner, a method: ``` string EmptyRowIfNull<T>(T o, Func<T, string> p) { string s; if (o != null) { s = p(o); } return string.IsNullOrEmpty(s) ? "EMPTY ROW" : s; } listitem.SubItems.Add(EmptyRowIfNull(item.TB_IL, t => t.ADI)); listitem.SubItems.Add(EmptyRowIfNull(item.TB_TESIS_TIPI, t => t.TIP_AD)); listitem.SubItems.Add(EmptyRowIfNull(item.TB_TESIS_TURU, t => t.TESIS_TURU)); ```
You may want to try item.attr.IsNull() -I believe that the cast to string is causing it to flag the item as null before the IsNullOrEmpty Test.
What's the problem with this C# condition code?
[ "", "c#", "entity-framework", "" ]
Right, my application occassionally kicks off a background thread that does some stuff. As its doing its stuff it also updates a progress bar on the main window. It does this by calling Invoke to get the main thread to update the interface. When the user closes the application, I want to wait until all the background threads are finished before closing the form. In the form closing event I have something like ``` while ( this._Queue.Count > 0 ) Application.DoEvents (); ``` But this does not work!! The background thread is getting stuck on the Invoke call. The main thread continues to loop around calling its DoEvents, which I thought would be all it needed to do to pick up and process its invokes. But it isnt doing this... Why not!?!
Right, I have sorted out the problem by taking it from a different angle. No more waiting for threads to finish... I have just added a variable bool KillOnThreadFinish in the worker thread. Then in the form closing of main form I check if the thread is running. If it is I set KillOnThreadFinish = true, I set e.cancel = true ( to prevent the form closing at that point ) and I set the MainForm.Enabled = false ( to prevent the user from closing the form again ). Then when the thread finishes its work it checks KillOnThreadFinish and if True calls Application.Exit() and the app exits. Seems to work beautifully! (Thanks for trying guys. :-) )
The BackgroundWorker provides a convenient way to run background threads while allowing for progress to be reported easily using .NET events. You would hook up your ProgressBar UI update to the ProgressChanged event handler, and completion is reported back to you through RunWorkerCompleted. If you only have a single background thread, this is much simpler than rolling your own thread handling code. Here's the MSDN article: <http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx> If you're stuck with using regular threads, then I'd consider using Join to wait for the thread to complete. This keeps processing normal messages and saves you polling in a tight loop. There's more information here: <http://msdn.microsoft.com/en-us/library/95hbf2ta.aspx> In addition, there are overloads that take a timeout parameter (either an Int32 for milliseconds or a TimeSpan object). If the thread has not completed after this time has elapsed, an exception is thrown. This helps catch threads which are stuck while you're trying to shutdown. More here: <http://msdn.microsoft.com/en-us/library/6b1kkss0.aspx> I hope this helps.
Main thread waiting on background threads that update the interface
[ "", "c#", ".net", "multithreading", "" ]
How do I validate XML document via compact RELAX NG schema in Python?
How about using [lxml](http://codespeak.net/lxml/validation.html#relaxng)? From the docs: ``` >>> f = StringIO('''\ ... <element name="a" xmlns="http://relaxng.org/ns/structure/1.0"> ... <zeroOrMore> ... <element name="b"> ... <text /> ... </element> ... </zeroOrMore> ... </element> ... ''') >>> relaxng_doc = etree.parse(f) >>> relaxng = etree.RelaxNG(relaxng_doc) >>> valid = StringIO('<a><b></b></a>') >>> doc = etree.parse(valid) >>> relaxng.validate(doc) True >>> invalid = StringIO('<a><c></c></a>') >>> doc2 = etree.parse(invalid) >>> relaxng.validate(doc2) False ```
If you want to check syntax vs **Compact** RelaxNG Syntax from command line, you can use `pyjing`, from the [jingtrang](https://pypi.org/project/jingtrang/) module. It supports **.rnc** files and displays more details than just `True` or `False`. For example: ``` C:\>pyjing -c root.rnc invalid.xml C:\invalid.xml:9:9: error: element "name" not allowed here; expected the element end-tag or element "bounds" ``` *NOTE: it is a Python wrapper of the Java `jingtrang` so it requires to have Java installed.* If you want to check the syntax from within Python, you can 1. Use `pytrang` (from *jingtrang* wrapper) to convert "Compact RelaxNG" (**.rnc**) to XML RelaxNG (**.rng**): `pytrang root.rnc root.rng` 2. Use `lxml` to parse converted **.rng** file like this: <https://lxml.de/validation.html#relaxng> That would be something like that: ``` >>> from lxml import etree >>> from subprocess import call >>> call("pytrang root.rnc root.rng") >>> with open("root.rng") as f: ... relaxng_doc = etree.parse(f) >>> relaxng = etree.RelaxNG(relaxng_doc) >>> valid = StringIO('<a><b></b></a>') >>> doc = etree.parse(valid) >>> relaxng.validate(doc) True >>> invalid = StringIO('<a><c></c></a>') >>> doc2 = etree.parse(invalid) >>> relaxng.validate(doc2) False ```
How do I validate XML document using compact RELAX NG schema in Python?
[ "", "python", "xml", "relaxng", "" ]
May i know how to create childClass if my childClass method getInfoFromDB() and saveToDB() need to do different logic? ``` public abstract class BaseClass { public abstract Object doTransaction(); public Object executeTrans() { //do something tx.begin(); this.doTransaction(); tx.commit(); } } public childClass extends BaseClass{ @Override public Object doTransaction(){ //overide to get something from database so can only be used for getInfoFromDB() and not for saveToDB() return something; } public List<String> getInfoFromDB(){ super.executeTrans(); } public void saveToDB(){ super.executeTrans() ; } } ```
You should use the template pattern in this case, something like this: ``` public abstract class BaseClass { public Object executeTrans(Template template) { tx.begin(); template.doTransaction(); tx.commit(); } } public interface Template { public void doTransaction(); } public childClass extends BaseClass { public List<String> getInfoFromDB() { executeTrans( new Template() { public void doTransaction() { ...do get info from DB here. } } ); } public void saveToDB() { executeTrans( new Template() { public void doTransaction() { ...do save to DB here. } } ); } } ``` Saying that, I'd advise using the Spring JDBC template classes rather than rolling your own - they've been tried and tested and have solved the problems you'll run into with nested transactions etc.
Nick, the "tx" that i going to use look like below. judging from the code, best practise, is the lifecycle is ok since it's called by both savetodb() and getinfofromdb() ``` public abstract class BaseClass { public Object executeTrans(Template template) { // PersistenceManager pm = ...; Transaction tx = pm.currentTransaction(); try { tx.begin(); template.doTransaction(); tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } } } } ```
template method pattern
[ "", "java", "spring", "template-method-pattern", "" ]
``` <?php function aum($x) { $contents = $_FILES['userfile']['tmp_name']; $contents = file("$contents"); $aum = $contents[$x][13].$contents[$x][14].$contents[$x][15].$contents[$x][16].$contents[$x][17].$contents[$x][18].$contents[$x][19].$contents[$x][20].$contents[$x][21].$contents[$x][22].$contents[$x][23]; $faum = money_format('%(#1n',$aum)."\n"; return $faum; } ?> ``` > Notice: A non well formed numeric > value encountered in > ./includes.php > on line 28 --- Hi, I'm getting the error above. Line 28 is: $faum = money\_format('%(#1n',$aum)."\n"; I have three questions: 1. Why am I getting this error notice and what should I do to fix it? 2. Is there a better way to upload a CSV text file that has non-uniform comma separation into a HTML table? By "non-uniform" comma separation I mean: **KEY DATA**,DATA,,,**$aum DATA**,,,,,,DATA,,etc. As you can see, I am deriving $aum by using the *file()* function. I then count the number of characters from the right of the beginning of each row to get the *fixed* character number that corresponds with the $aum DATA. The $x variable corresponds to the row numbers in the file. Then I can return each $aum per row $x. I am new to PHP and would like to know if there is a smarter way to do this. I appreciate any tips/advice that you might share. thx,
You need to have a look at $aum as it probably can't be formatted as a number. Pop ``` echo $aum; echo floatval($aum); ``` Before the error to see what you get. You might need to change the position you're looking at if you're picking up leading or trailing data.
for the second question, fgetcsv is your friend to get data out of CSV files <http://ee.php.net/fgetcsv>
PHP: "non well formed numeric value encountered"
[ "", "php", "" ]
In the type of embedded programming I'm getting into, determinism and transparency of the running code are highly valued. What I mean by transparency is, for instance, being able to look at arbitrary sections of memory and know what variable is stored there. So, as I'm sure embedded programmers expect, new is to be avoided if at all possible, and if it can't be avoided, then limited to initialization. I understand the need for this, but don't agree with the way my coworkers have gone about doing this, nor do I know a better alternative. What we have are several global arrays of structures, and some global classes. There is one array of structs for mutexes, one for semaphores, and one for message queues (these are initialized in main). For each thread that runs, the class that owns it is a global variable. The biggest problem I have with this is in unit testing. How can I insert a mock object when the class I want to test `#include`s global variables that I don't? Here's the situation in pseudo-code: **foo.h** ``` #include "Task.h" class Foo : Task { public: Foo(int n); ~Foo(); doStuff(); private: // copy and assignment operators here } ``` **bar.h** ``` #include <pthread.h> #include "Task.h" enum threadIndex { THREAD1 THREAD2 NUM_THREADS }; struct tThreadConfig { char *name, Task *taskptr, pthread_t threadId, ... }; void startTasks(); ``` **bar.cpp** ``` #include "Foo.h" Foo foo1(42); Foo foo2(1337); Task task(7331); tThreadConfig threadConfig[NUM_THREADS] = { { "Foo 1", &foo1, 0, ... }, { "Foo 2", &foo2, 0, ... }, { "Task", &task, 0, ... } }; void FSW_taskStart() { for (int i = 0; i < NUMBER_OF_TASKS; i++) { threadConfig[i].taskptr->createThread( ); } } ``` What if I want more or less tasks? A different set of arguments in the constructor of foo1? I think I would have to have a separate bar.h and bar.cpp, which seems like a lot more work than necessary.
If you want to unit test such code first I would recommend reading [Working Effectively With Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052) Also see [this](http://www.objectmentor.com/resources/articles/WorkingEffectivelyWithLegacyCode.pdf). Basically using the linker to insert mock/fake objects and functions should be a last resort but is still perfectly valid. However you can also use inversion of control, without a framework this can push some responsibility to the client code. But it really helps testing. For instance to test `FSW_taskStart()` ``` tThreadConfig threadConfig[NUM_THREADS] = { { "Foo 1", %foo1, 0, ... }, { "Foo 2", %foo2, 0, ... }, { "Task", %task, 0, ... } }; void FSW_taskStart(tThreadConfig configs[], size_t len) { for (int i = 0; i < len; i++) { configs[i].taskptr->createThread( ); } } void FSW_taskStart() { FSW_taskStart(tThreadConfig, NUM_THREADS); } void testFSW_taskStart() { MockTask foo1, foo2, foo3; tThreadConfig mocks[3] = { { "Foo 1", &foo1, 0, ... }, { "Foo 2", &foo2, 0, ... }, { "Task", &foo3, 0, ... } }; FSW_taskStart(mocks, 3); assert(foo1.started); assert(foo2.started); assert(foo3.started); } ``` Now you can can can pass mock version of you're threads to 'FSW\_taskStart' to ensure that the function does in fact start the threads as required. Unfortunatly you have to rely on the fact that original `FSW_taskStart` passes the correct arguments but you are now testing a lot more of your code.
Would dependency injection help in your situation? This could get rid of all global variables and allow for easy substitution of dependencies in your unit tests. Each thread main function is passed a map containing dependencies (drivers, mailboxes, etc.) and stores them in the classes that will use them (instead of accessing some global variable). For each environment (target, simulator, unit test...) you create one "configuration" function that creates all needed objects, drivers and all threads, giving threads their list of dependencies. For example, the target configuration could create a USB driver and inject it into some comms thread, while the comms unit test configuration could create a stub USB driver that the tests controls. If you absolutely need this "transparency" for important variable, create classes for them, which will hold them at a known address, and inject these classes where needed. It's quite a bit more work than static lists of objects, but the flexibility is fantastic, especially when you hit some tricky integration issues and want to swap components for testing. Roughly: ``` // Config specific to one target. void configure_for_target_blah(System_config& cfg) { // create drivers cfg.drivers.push_back("USB", new USB_driver(...)) // create threads Thread_cfg t; t.main = comms_main; // main function for that thread t.drivers += "USB"; // List of driver names to pass as dependencies cfg.threads += t; } // Main function for the comms thread. void comms_main(Thread_config& cfg) { USB_driver* usb = cfg.get_driver("USB"); // check for null, then store it and use it... } // Same main for all configs. int main() { System_config& cfg; configure_for_target_blah(cfg); //for each cfg.drivers // initialise driver //for each cfg.threads // create_thread with the given main, and pass a Thread_config with dependencies } ```
Avoiding global variables in embedded programming
[ "", "c++", "embedded", "global-variables", "" ]
I didn't realize at the time I create this particular application that I'd need to reuse some of the components - some Windows forms and a class or two. Now that I've already created the fairly complex forms inside one project, what's the easiest way to transform those forms into inheritable forms that I can reuse in other projects? Once that's done I'd like to modify the existing project to use the newly created inheritable forms. How can I accomplish this with as little pain as possible? I'm using C# in Visual Studio 2008.
You don't really have to do anything special to achieve this. Your form is already inheritable. On any new form, just make sure the first line looks like this: ``` public partial class frmMyChild : frmMyInheritableForm ``` instead of: ``` public partial class frmMyChild : Form ``` and make any methods that you need to access from the child either "public" or "protected". **Update**: one additional trick is to set the Modifiers property of each control on your original form to Protected (instead of the default Private). In the designer for your child form that inherits from this form, you will then see all of the controls on the parent form, and you can move them and resize them as you see fit (this will not affect the original form's layout). To access any parent method from the child form, you just call: ``` base.MyMethod(); ```
Just declare an empty class that inherits from System.Windows.Forms.Form and then make your "huge" class inherit from that. Once that works, start moving, a small reusable piece at a time from your "huge" class to the parent class.
Make an Existing Windows Form Inheritable
[ "", "c#", "winforms", "visual-studio-2008", "inheritance", "" ]
I'm trying to create a search engine for all literature (books, articles, etc), music, and videos relating to a particular spiritual group. When a keyword is entered, I want to display a link to all the PDF articles where the keyword appears, and also all the music files and video files which are tagged with the keyword in question. The user should be able to filter it with information such as author/artist, place, date/time, etc. When the user clicks on one of the results links (book names, for instance), they are taken to another page where snippets from that book everywhere the keyword is found are displayed. I thought of using the Lucene library (or Searcharoo) to implement my PDF search, but I also need a database to tag all the other information so that results can be filtered by author/artist information, etc. So I was thinking of having tables for Text, Music, and Videos, and a field containing the path to the file for each. When a keyword is entered, I need to search the DB for music and video files, and also need to search the PDF's, and when a filter is applied, the music and video search is easy, but limiting the text search based on the filters is getting confusing. Is my approach correct? Are there better ways to do this? Since the search content is limited only to the spiritual group, there is not an infinite number of items to search. I'd say about 100-500 books and 1000-5000 songs.
If you definitely want to go the database route then you should use SQL Server with [Full Text Search](http://msdn.microsoft.com/en-us/library/ms142571.aspx) enabled. You can use this with Express versions, too. You can then store and search the contents of PDFs very easily (so long as you install the free Adobe PDF iFilter).
Lucene is a great way to get up and running quickly without too much effort, along with several areas for extending the indexing and searching functionality to better suit your needs. It also has several built-in analyzers for common file types, such as HTML/XML, PDF, MS Word Documents, etc. It provides the ability to use a variety of Fields, and they don't necessarily have to be uniform across all Documents (in other words, music files might have different attributes than text-based content, such as artist, title, length, etc.), which is great for storing different types of content. Not knowing the exact implementation of what you're working on, this may or may not be feasible, but for tagging and other related features, you might also consider using a database, such as MySQL or SQL Server side-by-side with the Lucene index. Use the Lucene index for full-text search, then once you have a result set, go to the database to extract all the relational content. Our company has done this before, and it's actually not as big of a headache as it sounds. **NOTE:** If you decide to go this route, BE CAREFUL, as the "unique id" provided by Lucene is highly volatile (it changes everytime the index is optimized), so you will want to store the actual id (the primary key in the database) as a separate field on the Document. Another added benefit, if you are set on using C#.NET, there is a port called Lucene.Net, which is written entirely in C#. The down-side here is that you're a few months behind on all the latest features, but if you really need them, you can always check out the Java source and implement the required updates manually.
Help with Search Engine Architecture .NET C#
[ "", "c#", ".net", "search", "full-text-search", "lucene", "" ]
Is there any way to read the currently playing song title/artist (id3 tags) in walkman on sony ericsson (w series) phone?
you can get information of currently playing song by the using of player MetaDataControl class. with the help of this u can find information like title,album,total time,content type etc....
The Java ME API for playing MP3s doesn't tell you any metadata about the currently playing song. But if you know which file is playing, you can probably access the file directly, read out the first bit, and parse the ID3 info out of that. A quick Google search turns up several Java SE ID3 reading libraries. It's probably possible to do it in Java ME as well.
J2ME Read ID3 Tags From Walkman (Sony Ericsson)
[ "", "java", "java-me", "mp3", "id3", "" ]
can someone tell me how i can capture a running process in c# using the process class if i already know the handle? Id rather not have not have to enumerate the getrunning processes method either. pInvoke is ok if possible.
In plain C#, it looks like you have to loop through them all: ``` // IntPtr myHandle = ... Process myProcess = Process.GetProcesses().Single( p => p.Id != 0 && p.Handle == myHandle); ``` The above example intentionally fails if the handle isn't found. Otherwise, you could of course use `SingleOrDefault`. Apparently, it doesn't like you requesting the handle of process ID `0`, hence the extra condition. Using the WINAPI, you can use [`GetProcessId`](http://msdn.microsoft.com/en-us/library/ms683215%28VS.85%29.aspx). I couldn't find it on pinvoke.net, but this should do: ``` [DllImport("kernel32.dll")] static extern int GetProcessId(IntPtr handle); ``` (signature uses a `DWORD`, but process IDs are represented by `int`s in the .NET BCL) It seems a bit odd that you'd have a handle, but not a process ID however. Process handles are acquired by calling [`OpenProcess`](http://msdn.microsoft.com/en-us/library/ms684320%28VS.85%29.aspx), which takes a process ID.
``` using System.Diagnostics; class ProcessHandler { public static Process FindProcess( IntPtr yourHandle ) { foreach (Process p in Process.GetProcesses()) { if (p.Handle == yourHandle) { return p; } } return null; } } ```
Get running process given process handle
[ "", "c#", "process", "handle", "" ]
The JavaScript String object has two substring functions substring and substr. * `substring` takes two parameters `beginIndex` and `endIndex`. * `substr` also takes two parameters `beginIndex` and `length`. It's trivial to convert any range between the two variants but I wonder if there's any significance two how the two normally would be used (in day-to-day programming). I tend to favor the index/length variant but I have no good explanation as to why. I guess it depends on what kind of programming you do, but if you have strong opinion on the matter, I'd like to hear it. When is a (absolute, relative) range more suited than an (absolute, absolute) and vice versa? ### Update: This is not a JavaScript question per se (JavaScript just happen to implement both variants [which I think is stupid]), but what practical implication does the relative vs. absolute range have? I'm looking for solid argument for why we prefer one over the other. To broaden the debate a bit, how would you prefer to design your data structures for use with either one approach?
I prefer the `startIndex`, `endIndex` variant (`substring`) because `String.substring()` operates the same way in Java and I feel it makes me more efficient to stick to the same concepts in whatever language I use most often (when possible). If I were doing more C# work, I might use the other variant more because that is how `String.Substring()` works in C#. To answer your comment about JavaScript having both, it looks like `substr()` was added to browsers after `substring()` ([reference](http://www.bloggingdeveloper.com/post/substring-vs-substr-The-Difference-Between-JavaScript-String-Functions.aspx) - it seems that although `substr()` was part of JavaScript 1.0, most browser vendors didn't implement it until later). This suggests to me that even the implementers of the early language recognized the duplication of functionality. I'd suggest `substring()` came first in an attempt to leverage the *Java*Script trademark. Regardless, it seems that they recognized this duplication in [ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm) and took some small steps toward removing it: * [substring()](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/substring): ECMA Version: ECMA-262 * [substr()](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/substr): ECMA Version: None, although ECMA-262 ed. 3 has a non-normative section suggesting uniform semantics for substr Personally I wouldn't mind a `substring()` where the second parameter can be negative, which would return the characters between the first parameter and the length of the string minus the second parameter. Of course you can already achieve that more explicitly and I imagine the design would be confusing to many developers: ``` String s1 = "The quick brown fox jumps over the lazy dog"; String s2 = s1.substring(20, -13); // "jumps over" ```
> When is a (absolute, relative) range more suited than an (absolute, absolute) and vice versa? The former, when you know *how much*, the latter when you know *where*. I presume substring is implemented in terms of substr: ``` substring( b, e ) { return substr( b, e - b ); } ``` or substr in terms of substring: ``` substr( b, l) { return substring( b, b + l ); } ```
Substring arguments best practice
[ "", "javascript", "substring", "" ]
I'm using [PHPUnderControl](https://github.com/phpundercontrol/phpUnderControl-UNMAINTAINED) which runs on top of Cruise Control for my continuous integration and unit testing. I also have it setup to run PHPDocumentor to generate phpdoc's for me and it runs PHP Code Sniffer to enforce coding standards for me. But now I want to set up something on that same server (Ubuntu) to make deploying to a remote server easier. I already have it setup so after every successful build an SVN Export is done from trunk into a directory within the projects folder on the server. I've been thinking of writing a little custom PHP script that will SSH to a configured remote server, tarball up the latest export, copy it over, untar and run any migrations. A PHP script like this shouldn't be too hard initially, unless I need to eventually begin scaling to multiple servers. I know there are systems out there like [Phing](http://phing.info), [Fabric](http://github.com/bitprophet/fabric) and others. My question is if anyone has any experience with these and can provide some pro's and con's? I've begun setting up Phing on my server and will be trying Fabric next to play with them, but was wondering if anyone who has used them more extensively, or had to scale them, could provide some feedback.
I've used [Capistrano](http://capistranorb.com/) with PHP (even though it's more of a Rails-y thing as it's written in Ruby). It's been really straightforward to use, but that said I haven't had to scale much with it. We do deploy to various different staging/production servers though, and the multi-stage extension has been useful in those scenarios. However like most things Ruby, there's a lot of hooks and "magic" which can get confusing if you're new to Capistrano and trying to do something tricky with it. As for how it compares to other deployment tools, I can't comment. I know we used to use Phing, but I'm uncertain why we switched to Capistrano.
If you like Capistrano, but wished it was a bit more PHP'ish, check out [Fredistrano](http://code.google.com/p/fredistrano/). I wrote an automated build (SVN export, Zend Guard encoding, etc) and deployment system using Phing once and found quite the pain to use. Whenever I had to write a special task I felt I had to jump through way to many hoops just to get it to work. So, these days I just write simple bash scripts that does building with SVN checkout, encoding, creating a tag in SVN and deployment through rsync. It may be low-tech, and Phing may have some superior features, but atleast it doesn't get in my way.
PHP Build system
[ "", "php", "build-process", "build-automation", "build-tools", "" ]
After uploading my Kohana project to my Godaddy server, I noticed my standard .htaccess file wasn't working sufficiently to provide the clean URLs. After some guidance, I ended up with the following rule: ``` RewriteRule .* index.php?kohana_uri=$0 [PT,L] ``` This got my nice-URLs working again, but today I find out that it may be breaking my internal search-engine, which also uses GET-style variables: ``` /search?terms=php ``` The values aren't being found by the scripts. They are on my development-server which doesn't have the modified RewriteRule, but not on the Godaddy server which does use the RewriteRule. Am I right in assuming that rule is breaking any scripts ability to read from $\_GET, and if so how can I remedy this?
Maybe using QSA in your rewriterules, like this : ``` RewriteRule .* index.php?kohana_uri=$0 [PT,QSA,L] ``` See the [manual of mod\_rewrite](http://httpd.apache.org/docs/2.2/en/mod/mod_rewrite.html) (quoting) : > 'qsappend|QSA' (query string append) > > This flag forces the rewrite engine to append a query string part > of the substitution string to the > existing string, instead of replacing > it. Use this when you want to add more > data to the query string via a rewrite > rule. Might help (not tested in your particular case, but I remember have used this some time ago, for some kind of problem like this one)
I think you could add: `RewriteCond $1 !^(search)`, or a variation of such.
Kohana, .htaccess, and $_GET
[ "", "php", ".htaccess", "get", "kohana", "mod-rewrite", "" ]
I have a method returning an `ISomething`. I am trying to use Inversion of Control throughout my program... but I have no idea how to do it when it comes to the return value - I cannot pass it to the method, or to the object when constructing it, because this method is supposed to create the object. The only solution I see is to pass an `ISomething` factory (`Func<ISomething>`) to the object when constructing it. Is this the usual / correct solution or is something else recommended? [Edit] Weird - nobody else had this problem? I mean, there's no up- (or even down-) voting... [Edit] More details: the method is supposed to import an IExcel into an ITable. The consensus below seems to be that I should think of this method as a converter, transforming an IExcel into an ITable, thus receiving both as arguments instead of returning the ITable value. I'll leave this up for one more day and then go with one of the responses if nothing new shows up.
Is your method supposed to be constructing the ISomething, or setting it's state and returning an ISomething with state initialized? (or does this need to be one operation?) If your class has a method that is responsible for creating an ISomething, then it *is* an ISomethingFactory (unless you have mixed concerns). In that case, it has the logic to choose the correct ISomething implementation and create it, so you shouldn't worry too much about the IoC aspect. However, if this class's concern is *not* creating the appropriate ISomething, then I would probably pass a factory in. The issue is, that in most cases your DI container should be able to do this for you (call a factory to get the appropriate ISomething), so seeing a method that must create an ISomething that is not a factory makes me nervous. Trying to give architectural guidance is always tough in a forum like this though - but with the limited input there I'd say either you have a factory that you didn't know was a factory, or you have a problem.
"I have an object that needs to create an object and do something with it, but I don't want the object to know what kind of object is being created, except that it should be of a certain interface." That sounds almost like a textbook description of the Abstract Factory pattern, which would suggest that your object has a dependency on an appropriate factory. Which also neatly splits the responsibilities - one object is responsible for creating an object of the appropriate type, while the other is responsible for performing operations on it before returning it.
Inversion of control for return object
[ "", "c#", "inversion-of-control", "" ]
Looking at some example code and come across some zero-size array allocation. I created the following code snippet to clarify my question This is valid code: ``` class T { }; int main(void) { T * ptr = new T[0]; return 0; } ``` What is its use? Is ptr valid? Is this construct portable?
5.3.4 in the C++ Standard: 6 Every *constant-expression* in a *direct-new-declarator* shall be an integral constant expression (5.19) and evaluate to a strictly positive value. The *expression* in a *direct-new-declarator* shall have integral or enumeration type (3.9.1) with a non-negative value... 7 When the value of the *expression* in a *direct-new-declarator* is zero, the allocation function is called to allocate an array with no elements. So, your code allocates an array which behaves in every respect like any other array of T (can be deleted with delete[], passed as a parameter, probably other things). However, it has no accessible indexes (that is, reading or writing ptr[0] results in undefined behaviour). In this context the different between the constant-expression and the expression is not whether the actual expression is compile time constant (which obviously 0 is), but whether it specifies the "last" dimension of a multi-dimensional array. The syntax is defined in 5.3.4:1.
It is authorized (5.3.4/6). Its result is an empty array, so the value returned is the pointer past the array.
What does zero-sized array allocation do/mean?
[ "", "c++", "memory-management", "" ]
I have created a small Windows Forms test application to try out some drag/drop code. The form consists of three PictureBoxes. My intention was to grab a picture from one PictureBox, display it as a custom cursor during the drag operation, then drop it on another PictureBox target. This works fine from one PictureBox to another *as long as they are on the same form*. If I open two instances of the same application and attempt to drag/drop between them, I get the following cryptic error: > This remoting proxy has no channel > sink which means either the server has > no registered server channels that are > listening, or this application has no > suitable client channel to talk to the > server. For some reason, however, it does work to drag/drop to Wordpad (but not MS Word or Paintbrush). The three PictureBoxes get their events hooked up like this: ``` foreach (Control pbx in this.Controls) { if (pbx is PictureBox) { pbx.AllowDrop = true; pbx.MouseDown += new MouseEventHandler(pictureBox_MouseDown); pbx.GiveFeedback += new GiveFeedbackEventHandler(pictureBox_GiveFeedback); pbx.DragEnter += new DragEventHandler(pictureBox_DragEnter); pbx.DragDrop += new DragEventHandler(pictureBox_DragDrop); } } ``` Then there are the four events like this: ``` void pictureBox_MouseDown(object sender, MouseEventArgs e) { int width = (sender as PictureBox).Image.Width; int height = (sender as PictureBox).Image.Height; Bitmap bmp = new Bitmap(width, height); Graphics g = Graphics.FromImage(bmp); g.DrawImage((sender as PictureBox).Image, 0, 0, width, height); g.Dispose(); cursorCreatedFromControlBitmap = CustomCursors.CreateFormCursor(bmp, transparencyType); bmp.Dispose(); Cursor.Current = this.cursorCreatedFromControlBitmap; (sender as PictureBox).DoDragDrop((sender as PictureBox).Image, DragDropEffects.All); } ``` --- ``` void pictureBox_GiveFeedback(object sender, GiveFeedbackEventArgs gfea) { gfea.UseDefaultCursors = false; } ``` --- ``` void pictureBox_DragEnter(object sender, DragEventArgs dea) { if ((dea.KeyState & 32) == 32) { // ALT is pressed dea.Effect = DragDropEffects.Link; } else if ((dea.KeyState & 8) == 8) { // CTRL is pressed dea.Effect = DragDropEffects.Copy; } else if ((dea.KeyState & 4) == 4) { // SHIFT is pressed dea.Effect = DragDropEffects.None; } else { dea.Effect = DragDropEffects.Move; } } ``` --- ``` void pictureBox_DragDrop(object sender, DragEventArgs dea) { if (((IDataObject)dea.Data).GetDataPresent(DataFormats.Bitmap)) (sender as PictureBox).Image = (Image)((IDataObject)dea.Data).GetData(DataFormats.Bitmap); } ``` Any help would be greatly appreciated!
After much gnashing of teeth and pulling of hair, I was able to come up with a workable solution. It seems there is some undocumented strangeness going on under the covers with .NET and its OLE drag and drop support. It appears to be trying to use .NET remoting when performing drag and drop between .NET applications, but is this documented anywhere? No, I don't think it is. So the solution I came up with involves a helper class to help marshal the bitmap data between processes. First, here is the class. ``` [Serializable] public class BitmapTransfer { private byte[] buffer; private PixelFormat pixelFormat; private Size size; private float dpiX; private float dpiY; public BitmapTransfer(Bitmap source) { this.pixelFormat = source.PixelFormat; this.size = source.Size; this.dpiX = source.HorizontalResolution; this.dpiY = source.VerticalResolution; BitmapData bitmapData = source.LockBits( new Rectangle(new Point(0, 0), source.Size), ImageLockMode.ReadOnly, source.PixelFormat); IntPtr ptr = bitmapData.Scan0; int bufferSize = bitmapData.Stride * bitmapData.Height; this.buffer = new byte[bufferSize]; System.Runtime.InteropServices.Marshal.Copy(ptr, buffer, 0, bufferSize); source.UnlockBits(bitmapData); } public Bitmap ToBitmap() { Bitmap bitmap = new Bitmap( this.size.Width, this.size.Height, this.pixelFormat); bitmap.SetResolution(this.dpiX, this.dpiY); BitmapData bitmapData = bitmap.LockBits( new Rectangle(new Point(0, 0), bitmap.Size), ImageLockMode.WriteOnly, bitmap.PixelFormat); IntPtr ptr = bitmapData.Scan0; int bufferSize = bitmapData.Stride * bitmapData.Height; System.Runtime.InteropServices.Marshal.Copy(this.buffer, 0, ptr, bufferSize); bitmap.UnlockBits(bitmapData); return bitmap; } } ``` To use the class in a manner that will support both .NET and unmanaged recipients of the bitmap, a DataObject class is used for the drag and drop operation as follows. To start the drag operation: ``` DataObject dataObject = new DataObject(); dataObject.SetData(typeof(BitmapTransfer), new BitmapTransfer((sender as PictureBox).Image as Bitmap)); dataObject.SetData(DataFormats.Bitmap, (sender as PictureBox).Image as Bitmap); (sender as PictureBox).DoDragDrop(dataObject, DragDropEffects.All); ``` To complete the operation: ``` if (dea.Data.GetDataPresent(typeof(BitmapTransfer))) { BitmapTransfer bitmapTransfer = (BitmapTransfer)dea.Data.GetData(typeof(BitmapTransfer)); (sender as PictureBox).Image = bitmapTransfer.ToBitmap(); } else if(dea.Data.GetDataPresent(DataFormats.Bitmap)) { Bitmap b = (Bitmap)dea.Data.GetData(DataFormats.Bitmap); (sender as PictureBox).Image = b; } ``` The check for the customer BitmapTransfer is performed first so it takes precedence over the existence of a regular Bitmap in the data object. The BitmapTransfer class could be placed in a shared library for use with multiple applications. It must be marked serializable as shown for drag and drop between applications. I tested it with drag and drop of bitmaps within an application, between applications, and from a .NET application to Wordpad. Hope this helps you out.
I recently came across this problem, and was using a custom format in the clipboard, making Interop a bit more difficult. Anyway, with a bit of light reflection I was able to get to the original System.Windows.Forms.DataObject, and then call the GetData and get my custom item out of it like normal. ``` var oleConverterType = Type.GetType("System.Windows.DataObject+OleConverter, PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); var oleConverter = typeof(System.Windows.DataObject).GetField("_innerData", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(e.Data); var dataObject = (System.Windows.Forms.DataObject)oleConverterType.GetProperty("OleDataObject").GetValue(oleConverter, null); var item = dataObject.GetData(this.Format); ```
Drag and Drop between Instances of the same Windows Forms Application
[ "", "c#", "winforms", "drag-and-drop", "" ]
T-SQL DateTime Question. I have a set of time ranges. During those time ranges there could be a set of overlapping time ranges that I call 'blocked' out time. The blocked time wouldn't span more than one day. What I want to do is split the time to exclude the blocked out time, basically giving me the time ranges that are not 'blocked'. Its safe to assume that blocked times cant fall outside of the times ranges. Example: I work 9am to 5pm with a 30 min lunch break at 1pm. I want the result of 2 rows: 9am to 1pm and 1.30pm to 5pm. As mentioned, I have a set of time ranges so in the above example the working hours may differ on a daily basis and the number of breaks as well as their duration may differ. I guess in terms of SQL the input parameters would look like this: ``` declare @timeranges table ( StartDateTime datetime, EndDateTime datetime ) declare @blockedtimes table ( StartDateTime datetime, EndDateTime datetime ) insert into @timeranges select '01 Jan 2009 09:00:00', '01 Jan 2009 17:00:00' union select '02 Feb 2009 10:00:00', '02 Feb 2009 13:00:00' insert into @blockedtimes select '01 Jan 2009 13:00:00', '01 Jan 2009 13:30:00' union select '02 Feb 2009 10:30:00', '02 Feb 2009 11:00:00' union select '02 Feb 2009 12:00:00', '02 Feb 2009 12:30:00' ``` The result set would look like this. ``` Start End --------------------- --------------------- '01 Jan 2009 09:00:00' '01 Jan 2009 13:00:00' '01 Jan 2009 13:30:00' '01 Jan 2009 17:00:00' '02 Feb 2009 10:00:00' '02 Feb 2009 10:30:00' '02 Feb 2009 11:00:00' '02 Feb 2009 12:00:00' '02 Feb 2009 12:30:00' '02 Feb 2009 13:00:00' ``` I could do this with a cursor or while loop but if someone could suggest how to do this without iteration that would be great - thanks.
I thought I'd share the solution I finally settled on: Slight adjustment to the temp table in that I've added a StartDate field to both @timeranges and @blockedtimes ``` declare @timeranges table ( StartDate datetime, StartDateTime datetime, EndDateTime datetime ) declare @blockedtimes table ( StartDate datetime, StartDateTime datetime, EndDateTime datetime ) ``` Anyways seems simpler than some of the other answer posted - cheers for everyones help :) ``` select * from ( -- first SELECT get start boundry select t.StartDateTime s, b.StartDateTime e from @timeranges t, @blockedtimes b where -- same day and blocks overlaps timerange t.StartDate = b.StartDate and (t.StartDateTime <= b.EndDateTime and b.StartDateTime <= t.EndDateTime) and -- the following is the important bit for this SELECT not exists (select 1 from @blockedtimes b2 where b2.StartDate = b.StartDate and b2.StartDateTime < b.StartDateTime) union -- second SELECT get spikes ie middle select b1.EndDateTime s, b2.StartDateTime e from @timeranges t, @blockedtimes b1, @blockedtimes b2 where -- same day and blocks overlaps timerange t.StartDate = b1.StartDate and (t.StartDateTime <= b1.EndDateTime and b1.StartDateTime <= t.EndDateTime) and -- same day and blocks overlaps timerange t.StartDate = b2.StartDate and (t.StartDateTime <= b2.EndDateTime and b2.StartDateTime <= t.EndDateTime) and -- the following is the important bit for this SELECT b1.EndDateTime < b2.StartDateTime union -- third SELECT get end boundry select b.EndDateTime s, t.EndDateTime e from @timeranges t, @blockedtimes b where -- same day and blocks overlaps timerange t.StartDate = b.StartDate and (t.StartDateTime <= b.EndDateTime and b.StartDateTime <= t.EndDateTime) and -- the following is the important bit for this SELECT not exists (select 1 from @blockedtimes b2 where b2.StartDate = b.StartDate and b2.StartDateTime > b.StartDateTime) ) t1 ```
First cut, may have some issues, but I'll keep working on it. Works for the given data, just need to try additional scenarios ``` declare @timeranges table ( StartDateTime datetime, EndDateTime datetime ) declare @blockedtimes table ( StartDateTime datetime, EndDateTime datetime ) insert into @timeranges select '01 Jan 2009 09:00:00', '01 Jan 2009 17:00:00' union select '02 Feb 2009 10:00:00', '02 Feb 2009 13:00:00' --union select '03 Feb 2009 10:00:00', '03 Feb 2009 15:00:00' insert into @blockedtimes select '01 Jan 2009 13:00:00', '01 Jan 2009 13:30:00' union select '02 Feb 2009 10:30:00', '02 Feb 2009 11:00:00' union select '02 Feb 2009 12:00:00', '02 Feb 2009 12:30:00' --build an ordered, time range table with an indicator --to determine which ranges are timeranges 'tr' --and which are blockedtimes 'bt' -- declare @alltimes table (row int, rangetype varchar(10), StartDateTime datetime, EndDateTime datetime ) insert into @alltimes select row_number() over (order by a.startdatetime), * from ( select 'tr' as rangetype ,startdatetime, enddatetime from @timeranges union select 'bt' as rangetype ,startdatetime, enddatetime from @blockedtimes )a --what does the data look like -- select * from @alltimes -- -- build up the results select --start time is either the start time of a timerange, or the end of a blockedtime case when at1.rangetype = 'tr' then at1.startdatetime when at1.rangetype = 'bt' then at1.enddatetime end as [Start], case --a time range followed by another time range : end time from the current time range when at1.rangetype = 'tr' and (select at2.rangetype from @alltimes at2 where at2.row = at1.row+1) = 'tr' then at1.enddatetime --a time range followed by nothing (last record) : end time from the currenttime range when at1.rangetype = 'tr' and (select at2.rangetype from @alltimes at2 where at2.row = at1.row+1) is null then at1.enddatetime --a time range followed by a blockedtime : end time is start time of blocked time when at1.rangetype = 'tr' and (select at2.rangetype from @alltimes at2 where at2.row = at1.row+1) = 'bt' then (select top 1 at2.startdatetime from @alltimes at2 where at2.row > at1.row and at2.rangetype = 'bt' order by row) --a blocked time followed by a blockedtime : end time is start time of next blocked time when at1.rangetype = 'bt' and (select at2.rangetype from @alltimes at2 where at2.row = at1.row+1) = 'bt' then (select top 1 at2.startdatetime from @alltimes at2 where at2.row > at1.row and at2.rangetype = 'bt' order by row) --a blocked time followed by a time range : end time is end time of previous time range when at1.rangetype = 'bt' and (select at2.rangetype from @alltimes at2 where at2.row = at1.row+1) = 'tr' then (select top 1 at2.enddatetime from @alltimes at2 where at2.row < at1.row and at2.rangetype = 'tr' order by row desc) --a blocked time followed by nothing (last record) : end time is end time of previous time range when at1.rangetype = 'bt' and (select at2.rangetype from @alltimes at2 where at2.row = at1.row+1) is null then (select top 1 at2.enddatetime from @alltimes at2 where at2.row < at1.row and at2.rangetype = 'tr' order by row desc) end as [End] from @alltimes at1 ```
Selecting overlapping time ranges
[ "", "sql", "sql-server", "datetime", "" ]
Does anyone know of a good resource that will show me how to load an image with C++ and spin it? What I mean by spin is to do an actual animation of the image rotating and not physically rotating the image and saving it. If I am not clear on what I am asking, please ask for clarification before downvoting. Thanks
You could use [SDL](http://www.libsdl.org) and the extension [sdl\_image](http://www.libsdl.org/projects/SDL_image) and/or [sdl\_gfx](http://www.ferzkopp.net/joomla/content/view/19/14/)
I would definitely default to OpenGL for this type of task, you can load the image into a Texture, then either redraw the image at different angles, or better yet you can just spin the 'camera' in the OpenGL engine. There are loads of OpenGL tutorials around, a quick google search will get you everything you need.
C++ Spin Image Resources
[ "", "c++", "image", "" ]
As I prepare to tackle the issue of input data filtering and sanitization, I'm curious whether there's a best (or most used) practice? Is it better to filter/sanitize the data (of HTML, JavaScript, etc.) before inserting the data into the database, or should it be done when the data is being prepared for display in HTML? A few notes: * I'm doing this in PHP, but I suspect the answer to this is language agnostic. But if you have any recommendations specific to PHP, please share! * This is not an issue of escaping the data for database insertion. I already have PDO handling that quite well. Thanks!
When it comes to displaying user submitted data, the generally accepted mantra is to "Filter input, escape output." I would recommend against escaping things like html entities, etc, before going into the database, because you never know when HTML will not be your display medium. Also, different types of situations require different types of output escaping. For example, embedding a string in Javascript requires different escaping than in HTML. Doing this before may lull yourself into a false sense of security. So, the basic rule of thumb is, sanitize before use and specifically for that use; not pre-emptively. (Please note, I am not talking about escaping output for SQL, just for display. Please still do escape data bound for an SQL string).
i like to have/store the data in original form. i only escape/filter the data depending on the location where i'm using it. * on a webpage - encode all html * on sql - kill quotes * on url - urlencoding * on printers - encode escape commands * on what ever - encode it for that job
When to filter/sanitize data: before database insertion or before display?
[ "", "php", "html", "filter", "sanitize", "" ]
Consider the following code: ``` public abstract class Test1 { public object Data { get; set; } } public abstract class Test2<T> : Test1 { public T Data { get; set; } } ``` This will generate the following warning: > 'Test2.Data' hides inherited member 'Test1.Data'. Use the new keyword if hiding was intended. Why is this only a warning and what effect will adding the "new" keyword have? According to my testing I cannot find any difference once the "new" keyword is added. Don't get me wrong, I'm all for being explicit, but I was curious as to the benefit of adding "new". My only thoughts on what it might be are: * Improved human readability * Some saving at run-time when the compiler isn't left to figure the inevitable out the long way around
The only effect the `new` keyword has is to remove the warning. The purpose of getting the warning when not using the `new` keyword is to prevent you from accidentally shadowing the method when you really meant to override it.
`new` is used to hide a method or property of the base class. This is **not** like overriding it : the member doesn't need to have the same signature as the hidden base class member, and is not involved in polymorphism. An example : ``` class A { public virtual void Test() { Console.WriteLine("A.Test"); } } class B : A { public new void Test() { Console.WriteLine("B.Test"); } } class B : A { public override void Test() { Console.WriteLine("C.Test"); } } public static void Main(string[] args) { A aa = new A(); aa.Test(); // Prints "A.Test" A ab = new B(); ab.Test(); // Prints "A.Test" because B.Test doesn't overrides A.Test, it hides it A ac = new C(); ac.Test(); // Prints "C.Test" because C.Test overrides A.Test B b = new B(); b.Test(); // Prints "B.Test", because the actual type of b is known at compile to be B } ```
What effect does the "new" keyword have in C# and why is it only a warning when not employed?
[ "", "c#", "new-operator", "warnings", "keyword", "" ]
Sometimes i extract boolean checks into local variables to achief better readability. What do you think? Any disadvantages? Does the compiler a line-in or something if the variable isn't used anywhere else? I also thought about reducing the scope with an additional block "{}". ``` if (person.getAge() > MINIMUM_AGE && person.getTall() > MAXIMUM_SIZE && person.getWeight < MAXIMUM_WEIGHT) { // do something } ``` --- ``` final boolean isOldEnough = person.getAge() > MINIMUM_AGE; final boolean isTallEnough = person.getTall() > MAXIMUM_SIZE; final boolean isNotToHeavy = person.getWeight < MAXIMUM_WEIGHT; if (isOldEnough && isTallEnough && isNotToHeavy) { // do something } ```
I do this all the time. The code is much more readable that way. The only reason for not doing this is that it inhibits the runtime from doing shortcut optimisation, although a smart VM might figure that out.
The real risk in this approach is that it loses responsiveness to changing values. Yes, people's age, weight, and height don't change very often, relative to the runtime of most programs, but they do change, and if, for example, age changes while the object from which your snippet is still alive, your final isOldEnough could now yield a wrong answer. And yet I don't believe putting `isEligible` into Person is appropriate either, since the knowledge of what constitutes eligibility seems to be of a larger scope. One must ask: eligible for what? All in all, in a code review, I'd probably recommend that you add methods in Person instead. ``` boolean isOldEnough (int minimumAge) { return (this.getAge() > minimumAge); } ``` And so on.
extract boolean checks to local variables
[ "", "java", "" ]
I need to store up to tens or even hundreds of millions of pieces of data on-disk. Each piece of data contains information like: ``` id=23425 browser=firefox ip-address=10.1.1.1 outcome=1.0 ``` New pieces of data may be added at the rate of up-to 1 per millisecond. So its a relatively simple set of key-value pairs, where the values can be strings, integers, or floats. Occasionally I may need to update the piece of data with a particular id, changing the flag field from 0 to 1. In other words, I need to be able to do random key lookups by id, and modify the data (actually only the floating point "outcome" field - so I'll never need to modify the size of the value). The other requirement is that I need to be able to stream this data off disk (the order isn't particularly important) efficiently. This means that the hard disk head should not need to jump around the disk to read the data, rather it should be read in consecutive disk blocks. I'm writing this in Java. I've thought about using an embedded database, but DB4O is not an option as it is GPL and the rest of my code is not. I also worry about the efficiency of using an embedded SQL database, given the overhead of translating to and from SQL queries. Does anyone have any ideas? Might I have to build a custom solution to this (where I'm dealing directly with ByteBuffers, and handling the id lookup)?
In the end I decided to log the data to disk as it comes in, and also keep it in memory where I can update it. After a period of time I write the data out to disk and delete the log.
How about [H2](http://www.h2database.com/)? The [License](http://www.h2database.com/html/license.html) should work for you. * You can use H2 for free. You can integrate it into your application (including commercial applications), and you can distribute it. * Files containing only your code are not covered by this license (it is 'commercial friendly'). * Modifications to the H2 source code must be published. * You don't need to provide the source code of H2 if you did not modify anything. I get *1000000 insert in 22492ms (44460.252534234394 row/sec)* *100000 updates in 9565ms (10454.783063251438 row/sec)* from ``` import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Random; /** * @author clint * */ public class H2Test { static int testrounds = 1000000; public static void main(String[] args) { try { Class.forName("org.h2.Driver"); Connection conn = DriverManager. getConnection("jdbc:h2:/tmp/test.h2", "sa", ""); // add application code here conn.createStatement().execute("DROP TABLE IF EXISTS TEST"); conn.createStatement().execute("CREATE TABLE IF NOT EXISTS TEST(id INT PRIMARY KEY, browser VARCHAR(64),ip varchar(16), outcome real)"); //conn.createStatement().execute("CREATE INDEX IDXall ON TEST(id,browser,ip,outcome"); PreparedStatement ps = conn.prepareStatement("insert into TEST (id, browser, ip, outcome) values (?,?,?,?)"); long time = System.currentTimeMillis(); for ( int i = 0; i < testrounds; i++ ) { ps.setInt(1,i); ps.setString(2,"firefox"); ps.setString(3,"000.000.000.000"); ps.setFloat(4,0); ps.execute(); } long last = System.currentTimeMillis() ; System.out.println( testrounds + " insert in " + (last - time) + "ms (" + ((testrounds)/((last - time)/1000d)) + " row/sec)" ); ps.close(); ps = conn.prepareStatement("update TEST set outcome = 1 where id=?"); Random random = new Random(); time = System.currentTimeMillis(); /// randomly updadte 10% of the entries for ( int i = 0; i < testrounds/10; i++ ) { ps.setInt(1,random.nextInt(testrounds)); ps.execute(); } last = System.currentTimeMillis(); System.out.println( (testrounds/10) + " updates in " + (last - time) + "ms (" + ((testrounds/10)/((last - time)/1000d)) + " row/sec)" ); conn.close(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ```
How do I persist data to disk, and both randomly update it, and stream it efficiently back into RAM?
[ "", "java", "persistence", "embedded-database", "" ]
I am getting this error when i am trying to access mail file(mail/usermail.nsf) of user ( on different machine) using C#. I am using "Interop.Domino.dll". Is this happening because of same user name and organization name? But i am able to access local User NSF file (user configured on same machine where Domino server installed) where lotus notes client name is same as that of domain name.
Some things to check would be: * Are you opening the database using a server name and path (not just a mapped, remote file path)? * Does the ID file being used have access to the server (in Server document in NAB, as mentioned by another response)? * Does the ID file have access to the NSF (from a Notes client, use the "Effective Access" tool, from within the ACL dialog to verify)? * If the file path you're using have the correct delimitters - you should be using a backslah () in your GetDatabase method call. * Are you able to access and read content from any other NSF on the remote server? For example, a simple test would be to have your code open names.nsf in the root data folder. * Finally, is it possible for you to post a snippet of your code?
Are you sure the user has access to that mail file? Also make sure the user ID has access to the server.
"User CN={user's name}/O={organisation name } cannot open database {path to databasename.nsf}"
[ "", "c#", "lotus-notes", "lotus-domino", "interop-domino", "" ]
I wrote a windows service and a gui for it. Of course gui mainly depends on the service. Is there a way for gui to wait for the service? Sometimes I need to reload service config from the gui and restart the service. I was thinking about 2 solutions: 1. using while and sleep to wait for service controller status to change (of course the simplest solution :P) 2. implementin INotifiPropertyChanged interface somewhere (this looks to complicated for this trivial problem). I was wondering is there more elegant way of doing it? Is there an event that I am missing somewhere?
ServiceController has a method WaitForStatus where you pass it an argument of type ServiceControllerStatus. You can use it like this: ``` controller.WaitForStatus(ServiceControllerStatus.Running); ```
Use a [kernel Event object](http://msdn.microsoft.com/en-us/library/ms682396%28VS.85%29.aspx). When you start both apps, have them create or open a named Event object, then wait on it. The other can signal it, flipping the state thus allowing the other app to stop waiting and run.
How to make GUI wait for windows service?
[ "", "c#", "windows-services", "" ]
I have a table with several account fields like this: ``` MAIN_ACCT GROUP_ACCT SUB_ACCT ``` I often need to combine them like this: ``` SELECT MAIN_ACCT+'-'+GROUP_ACCT+'-'+SUB_ACCT FROM ACCOUNT_TABLE ``` I'd like a calculated field that automatically does this, so I can just say: ``` SELECT ACCT_NUMBER FROM ACCOUNT_TABLE ``` What is the best way to do this? I'm using SQL Server 2005.
``` ALTER TABLE ACCOUNT_TABLE ADD ACCT_NUMBER AS MAIN_ACCT+'-'+GROUP_ACCT+'-'+SUB_ACCT PERSISTED ``` This will persist a calculated column and may perform better in selects than a calculation in view or UDF if you have a large number of records (once the intial creation of the column has happened which can be painfully slow and should probably happen during low usage times). It will slow down inserts and updates. Usually I find a slow insert or update is tolerated better by users than a delay in a select unless you get locking issues. The best method for doing this will depend a great deal on your usage and what kind of performance you need. If you don't have a lot of records or if the computed column won't be called that frequently, you may not want a persisted column, but if you are frequently running reports with all the records for the year or other large sets of data, you may find the persisted calculated column works better for you. As with any task of this nature, the only way to know what works best in your situation is to test.
This is a great candidate for a View. ``` CREATE VIEW vwACCOUNT_TABLE AS SELECT MAIN_ACCT+'-'+GROUP_ACCT+'-'+SUB_ACCT AS ACCT_NUMBER FROM ACCOUNT_TABLE GO --now select from the View SELECT ACCT_NUMBER FROM vwACCOUNT_TABLE ```
How can I set up a simple calculated field in SQL Server?
[ "", "sql", "sql-server-2005", "calculated-field", "" ]
I'm new to Mac OS X Dashboard developement. Now, I have a button with id b\_start. When that button is clicked, I want the label of the button to change to "Round". Now I have tried these, but none of them work: ``` document.getElementById("b_start").label = "Round"; document.getElementById("b_start").text = "Round"; document.getElementById("b_start").innerText = "Round"; document.getElementById("b_start").object.setValue("Round"); document.getElementById("b_start").value = "Round"; ``` Does anyone how I can change the button's label?
I solved the question my own. Just use this: ``` document.getElementById("b_start").object.textElement.innerText = "Round"; ```
document.getElementById("b\_start").object.setText("Round");
Dashcode newbie: Change a button's label programmatically
[ "", "javascript", "button", "dashcode", "" ]
Are there any good C# Silverlight Graphics or Game engines currently? I am planning to create a game with it (either 2d or 3d) but are there already usable frameworks or should I expect to have to build everything myself?
At the moment, probably the most well known graphics engine is: [Balder](http://www.codeplex.com/Balder) > Managed GameEngine with both 2D and 3D > support targetting Silverlight 2/3, > Xna and OpenGL. There is also: [Kit3D](http://www.codeplex.com/Kit3D) > Kit3D is a 3D graphics engine for > Microsoft Silverlight. As far as *Game Engines* go, there is: [PlayBits Engine](http://www.envygames.com/content/index.php/playbits-engine) Although PlayBits is not yet available, and will not be free.
If you're targeting both XNA and Silverlight for 2D games you can use the SilverSprite library at <http://silversprite.codeplex.com> and it may also be useful if you're used to a traditional game loop and draw calls.
Silverlight C# Game or Graphics Engine?
[ "", "c#", "silverlight", "" ]
I have a table with 2 columns: ``` nid realm 1 domain_id 1 domain_site 2 domain_id 3 domain_id ``` I want every entry to have 1 entry for domain id, and 1 for domain site. So I want to end up with: ``` nid realm 1 domain_id 1 domain_site 2 domain_id 2 domain_site 3 domain_id 3 domain_site ``` If I was doing this in PHP, I'd just foreach through the whole list and insert the extra line whenever it didn't exist. Unfortunately I only have PHPmyAdmin access to this DB. Is there a way to do this in straight SQL? (If it makes a difference: The table has about 3000 rows currently, of which I think about 2000 will need the extra line inserted. Also, this is a one-time thing so it does not need to be optimized/uber-slick.)
``` INSERT IGNORE INTO `table` SELECT `alt1`.`nid`, `alt2`.`realm` FROM `table` AS `alt1`, `table` AS `alt2` ```
I think this will do it, but I don't have a place to test it right now and I'm used to Sql Server rather than MySQL: ``` INSERT INTO `table` SELECT id.nid, r.realm FROM (SELECT nid FROM `table` GROUP BY nid) id CROSS JOIN (SELECT realm FROM `table` GROUP BY realm) r LEFT JOIN `table` t ON t.nid=id.nid AND t.realm=r.realm WHERE t.realm IS NULL ```
SQL - Is there a query that will do "foreach A in table, if !B, insert B"?
[ "", "sql", "mysql", "" ]
I want the api of my module to only throw MyPackageSpecificException whenever anything goes wrong and the module unable to perform its task. (The original exception will be given as the cause of the MyPackageSpecificException). Now, for one constructor I needed an URL as a parameter to locate a resource. I would also like to make an alternative constructor to which a String representation of the URL can be given: ``` public MyClass(String urlString) throws MalformedURLException{ this(new URL(urlString)); } ``` As the URL constructor throws MalformedURLException, I want to wrap it into a MyPackageSpecificException by doing: ``` public MyClass(String urlString) throws MyPackageSpecificException{ try{ this(new URL(urlString)); } catch (MalformedURLException e){ throw new MyPackageSpecificException(e); } } ``` But, the above is not valid, since the super() or this() constructor call must occur on the first line of the constructor. The same problem applies if the super() or this() constructor throws an exception which I want to wrap into something else. How should I solve this? Or is what I am trying to do bad practice?
Try the following: ``` public class MyClass { private URL url; public MyClass(URL url) { this.url = url; } public MyClass(String urlString) throws MyPackageSpecificException { this(toURL(urlString)); } private static URL toURL(String urlString) throws MyPackageSpecificException { try { return new URL(urlString)); } catch (MalformedURLException e) { throw new MyPackageSpecificException(e); } } } ```
If it fits your code, you can use a static creator method instead: ``` private MyClass(String urlString) { ... } public static MyClass createMyClass(String urlString) throws MyPackageSpecificException { try { new MyClass(urlString); catch (Exception e) { throw new MyPackageSpecificException(e); } } ```
Wrapping exceptions thrown in super/this constructor calls into other exceptions
[ "", "java", "exception", "constructor", "" ]
Is there any way to get the xml encoding in the toString() Function? **Example:** ``` xml.Save("myfile.xml"); ``` leads to ``` <?xml version="1.0" encoding="utf-8"?> <Cooperations> <Cooperation> <CooperationId>xxx</CooperationId> <CooperationName>Allianz Konzern</CooperationName> <LogicalCustomers> ``` But ``` tb_output.Text = xml.toString(); ``` leads to an output like this ``` <Cooperations> <Cooperation> <CooperationId>xxx</CooperationId> <CooperationName>Allianz Konzern</CooperationName> <LogicalCustomers> ... ```
Either explicitly write out the declaration, or use a `StringWriter` and call `Save()`: ``` using System; using System.IO; using System.Text; using System.Xml.Linq; class Test { static void Main() { string xml = @"<?xml version='1.0' encoding='utf-8'?> <Cooperations> <Cooperation /> </Cooperations>"; XDocument doc = XDocument.Parse(xml); StringBuilder builder = new StringBuilder(); using (TextWriter writer = new StringWriter(builder)) { doc.Save(writer); } Console.WriteLine(builder); } } ``` You could easily add that as an extension method: ``` public static string ToStringWithDeclaration(this XDocument doc) { if (doc == null) { throw new ArgumentNullException("doc"); } StringBuilder builder = new StringBuilder(); using (TextWriter writer = new StringWriter(builder)) { doc.Save(writer); } return builder.ToString(); } ``` This has the advantage that it won't go bang if there *isn't* a declaration :) Then you can use: ``` string x = doc.ToStringWithDeclaration(); ``` Note that that will use utf-16 as the encoding, because that's the implicit encoding in `StringWriter`. You can influence that yourself though by creating a subclass of `StringWriter`, e.g. [to always use UTF-8](https://stackoverflow.com/questions/955611/xmlwriter-to-write-to-a-string-instead-of-to-a-file/955698#955698).
The Declaration property will contain the XML declaration. To get the contents plus declaration, you can do the following: ``` tb_output.Text = xml.Declaration.ToString() + xml.ToString() ```
XDocument.ToString() drops XML Encoding Tag
[ "", "c#", "linq-to-xml", "" ]
I have a structure such this works : ``` import a.b.c a.b.c.foo() ``` and this also works : ``` from a.b import c c.foo() ``` but this doesn't work : ``` from a import b.c b.c.foo() ``` nor does : ``` from a import b b.c.foo() ``` How can I do the import so that `b.c.foo()` works?
Just rename it: ``` from a.b import c as BAR BAR.foo() ```
In your '`b`' package, you need to add '`import c`' so that it is always accessible as part of `b`.
Python: How to import part of a namespace
[ "", "python", "import", "namespaces", "" ]
How do I create a thread routine of a static member function ``` class Blah { static void WINAPI Start(); }; // .. // ... // .... hThread = (HANDLE)_beginthreadex(NULL, 0, CBlah::Start, NULL, NULL, NULL); ``` This gives me the following error: ``` ***error C2664: '_beginthreadex' : cannot convert parameter 3 from 'void (void)' to 'unsigned int (__stdcall *)(void *)'*** ``` What am I doing wrong?
Sometimes, it is useful to read the error you're getting. ``` cannot convert parameter 3 from 'void (void)' to 'unsigned int (__stdcall *)(void *)' ``` Let's look at what it says. For parameter three, you give it a function with the signature `void(void)`, that is, a function which takes no arguments, and returns nothing. It fails to convert this to `unsigned int (__stdcall *)(void *)`, which is what `_beginthreadex` *expects*: It expects a function which: * Returns an `unsigned int`: * Uses the `stdcall` calling convention * Takes a `void*` argument. So my suggestion would be "give it a function with the signature it's asking for". ``` class Blah { static unsigned int __stdcall Start(void*); }; ```
``` class Blah { static unsigned int __stdcall Start(void*); // void* should be here, because _beginthreadex requires it. }; ``` The routine passed to `_beginthreadex` must use the `__stdcall` calling convention and **must return a thread exit code**. Implementation of Blah::Start: ``` unsigned int __stdcall Blah::Start(void*) { // ... some code return 0; // some exit code. 0 will be OK. } ``` Later in your code you could write any of the following: ``` hThread = (HANDLE)_beginthreadex(NULL, 0, CBlah::Start, NULL, NULL, NULL); // or hThread = (HANDLE)_beginthreadex(NULL, 0, &CBlah::Start, NULL, NULL, NULL); ``` In first case `Function-to-pointer conversion` will be applied according to C++ Standard 4.3/1. In second case you'll pass pointer to function implicitly.
_beginthreadex static member function
[ "", "c++", "function", "static", "multithreading", "member", "" ]
I want something like this in javascript. ``` for (i = 0; i < 10; i++) { alert(i); // now sleep 1 sec sleep(1000); } ``` is there a built in Javascript or Jquery for this? Thank you!
There's no such thing, directly. You would have to tell javascript to wake 'something' up after some time using `setTimeout`. This 'something' would be the code that you plan to execute *after* the sleep, of course. From an example I found on [the internet](http://juixe.com/techknow/index.php/2005/10/28/put-javascript-to-sleep/): ``` function dothingswithsleep( part ) { if( part == 0 ) { alert( "before sleep" ); setTimeout( function() { dothingswithsleep( 1 ); }, 1000 ); } else if( part == 1 ) { alert( "after sleep" ); } } ``` But that's fragile design. You better rethink your business logic to really *do something* after a second: call a different function instead of using these contrived helper variables.
use [setTimeout](http://www.w3schools.com/htmldom/met_win_settimeout.asp) method
Is there an equivalent Javascript or Jquery sleep function?
[ "", "javascript", "jquery", "sleep", "" ]
I was just wondering how the PHP is behaving in the background. Say I have a PHP which creates an array and populates it with names. ``` $names = Array("Anna", "Jackson" .... "Owen"); ``` Then I have a input field which will send the value on every keypress to the PHP, to check for names containing the value. Will the array be created on every call? I also sort the array before looping through it, so the output will be alphabetical. Will this take up time in the AJAX call? If the answer is yes, is there some way to go around that, so the array is ready to be looped through on every call?
There's no difference between an AJAX request and a "normal" http request. So yes, a new php instance will be created for each request. If the time it takes to parse the script(s) is a problem you can use something like [APC](http://uk.php.net/apc). If those arrays are created at runtime and the time this takes is a problem you might store and share the values between requests in something like [memcache](http://uk.php.net/memcache)
No matter what method you use to create the array, if it's in the code, if you pull it out of a database, a text file or any other source, when the web server gets an http request, ( whether it be Ajax or not ) it will start the execution of the PHP script, create its space in memory, and the array will be created. There's only one entry point for a PHP script and it's the first line of it, when an http rquest points to it. (or when another script is included, which is the same)
Is the PHP file instantiated on every AJAX call?
[ "", "php", "ajax", "" ]
I can start a new hidden Visual Studio process from VBScript, and drive it programmatically, by doing this: ``` Set DTE = CreateObject("VisualStudio.DTE.8.0") DTE.DoStuff() ``` How do I do that in C#? (**Edit:** using the correct types, not generic COM objects as used by that VBScript code.) I've tried this: ``` using EnvDTE; ... DTE dte = new DTE(); ``` but I get "Retrieving the COM class factory for component with CLSID {3C9CFE1E-389F-4118-9FAD-365385190329} failed".
I found the answer (thanks to Sebastiaan Megens for putting me on the right track): ``` [STAThread] static void Main(string[] args) { System.Type t = System.Type.GetTypeFromProgID("VisualStudio.DTE.8.0", true); DTE2 dte = (EnvDTE80.DTE2)System.Activator.CreateInstance(t, true); // See http://msdn.microsoft.com/en-us/library/ms228772.aspx for the // code for MessageFilter - just paste it in. MessageFilter.Register(); dte.DoStuff(); dte.Quit(); } public class MessageFilter : IOleMessageFilter { ... Continues at http://msdn.microsoft.com/en-us/library/ms228772.aspx ``` (The nonsense with STAThread and MessageFilter is "due to threading contention issues between external multi-threaded applications and Visual Studio", whatever that means. Pasting in the code from <http://msdn.microsoft.com/en-us/library/ms228772.aspx> makes it work.)
I don't know how start a new instance of Visual Studio, but I use an existing instance by calling: ``` EnvDTE.DTE dte = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.8.0"); ``` Maybe creating a new instance is something similar? Hope this helps a bit. Regards, Sebastiaan
Start Visual Studio programmatically; C# equivalent of VB's CreateObject("VisualStudio.DTE.8.0")
[ "", "c#", "visual-studio", "com", "createobject", "" ]
This works, but i would like to remove the redundancy. Is there a way to merge the update with a single select statement so i don't have to use vars? ``` DECLARE @OrgAddress1 varchar, @OrgAddress2 varchar, @OrgCity varchar, @OrgState varchar, @OrgZip varchar, @DestAddress1 varchar, @DestAddress2 varchar, @DestCity varchar, @DestState varchar, @DestZip varchar SELECT @OrgAddress1 = OrgAddress, @OrgAddress2 = OrgAddress2, @OrgCity = OrgCity, @OrgState = OrgState, @OrgZip = OrgZip, @DestAddress1 = DestAddress, @DestAddress2 = DestAddress2, @DestCity = DestCity, @DestState = DestState, @DestZip = DestZip FROM ProfilerTest.dbo.BookingDetails WHERE MyID=@MyID UPDATE SHIPMENT SET OrgAddress1 = @OrgAddress1, OrgAddress2 = @OrgAddress2, OrgCity = @OrgCity, OrgState = @OrgState, OrgZip = @OrgZip, DestAddress1 = @DestAddress1, DestAddress2 = @DestAddress2, DestCity = @DestCity, DestState = @DestState, DestZip = @DestZip WHERE MyID2=@ MyID2 ```
Something like this should work (can't test it right now - from memory): ``` UPDATE SHIPMENT SET OrgAddress1 = BD.OrgAddress1, OrgAddress2 = BD.OrgAddress2, OrgCity = BD.OrgCity, OrgState = BD.OrgState, OrgZip = BD.OrgZip, DestAddress1 = BD.DestAddress1, DestAddress2 = BD.DestAddress2, DestCity = BD.DestCity, DestState = BD.DestState, DestZip = BD.DestZip FROM BookingDetails BD WHERE SHIPMENT.MyID2 = @MyID2 AND BD.MyID = @MyID ``` Does that help?
You can use: ``` UPDATE s SET s.Field1 = q.Field1, s.Field2 = q.Field2, (list of fields...) FROM ( SELECT Field1, Field2, (list of fields...) FROM ProfilerTest.dbo.BookingDetails WHERE MyID=@MyID ) q WHERE s.MyID2=@ MyID2 ```
SQL Update Multiple Fields FROM via a SELECT Statement
[ "", "sql", "sql-server", "stored-procedures", "sql-update", "" ]
From what I understand, the key in a value pair in an std::map cannot be changed once inserted. Does this mean that creating a map with the key template argument as const has no effect? ``` std::map<int, int> map1; std::map<const int, int> map2; ```
The answer to your title question is yes. There is a difference. You cannot pass a `std::map<int, int>` to a function that takes a `std::map<const int, int>`. However, the functional behavior of the maps is identical, even though they're different types. This is not unusual. In many contexts, int and long behave the same, even though they're formally different types.
since int is copied by value this declaration of const has no sense. On other hand ``` std::map<const char*, int> map2; ``` dramatically changes a picture
Is there a difference between std::map<int, int> and std::map<const int, int>?
[ "", "c++", "stl", "std", "stdmap", "" ]
I have a form on a website which has a lot of different fields. Some of the fields are optional while some are mandatory. In my DB I have a table which holds all these values, is it better practice to insert a NULL value or an empty string into the DB columns where the user didn't put any data?
By using `NULL` you can distinguish between "put no data" and "put empty data". Some more differences: * A `LENGTH` of `NULL` is `NULL`, a `LENGTH` of an empty string is `0`. * `NULL`s are sorted before the empty strings. * `COUNT(message)` will count empty strings but not `NULL`s * You can search for an empty string using a bound variable but not for a `NULL`. This query: ``` SELECT * FROM mytable WHERE mytext = ? ``` will never match a `NULL` in `mytext`, whatever value you pass from the client. To match `NULL`s, you'll have to use other query: ``` SELECT * FROM mytable WHERE mytext IS NULL ```
One thing to consider, if you **ever** plan on switching databases, is that [Oracle does not support empty strings](http://www.techonthenet.com/oracle/questions/empty_null.php). They are converted to NULL automatically and you can't query for them using clauses like `WHERE somefield = ''` .
MySQL, better to insert NULL or empty string?
[ "", "mysql", "sql", "sql-null", "" ]
I'm trying to "reset" the formatting in my RichTextBox (WinForms, not WPF). I was previously using ``` richTextBox.Text = richTextBox.Text; ``` However, that seems to have suddenly failed me. Now no matter what I set `richTextBox.Text` to, it retains some of the rtf formatting. I've tried ``` richTextBox.Rtf = richTextBox.Text; ``` However, that complains about an incorrect format. There's gotta be a better way to do this. (Of course, selecting the entire thing, then resetting the back color, fore color, and font works, but that results in a flicker as the entire thing is selected then deselected, plus it's slower and requires a lot more code.) Anyone have any idea? Edit: I've gotten this to work: ``` string tempTxt = richTextBox.Text; richTextBox.Clear(); richTextBox.Text = tempTxt; ``` But there has to be a better way, right? Edit 2: To be clear, I wish to remove all formatting while retaining the text. It looks like the code in the first edit will ship, unless anyone else has a more efficient/better coding way. Edit 3: ``` richTextBox.Text = richTextBox.Text.ToString(); ``` doesn't seem to work because it still doesn't clear all the formatting. The reason I don't like the method in the first Edit above is it makes the text box "flash" when it clears it then re-inputs the text. It seems like there should simply be a richTextBox.ResetFormatting() method, or some way to access the same functionality, as the Clear() method clearly (no pun intended) does some sort of formatting reset in addition to simply clearing all the text. To summarize: **Is there a way (and if so, what is it) to reset the formatting of the text in a RichTextBox without clearing the text as in the example above (because that produces undesirable flashing)?**
Saddly I've done my VERY best effort to slim this down to only the required code. It's still big, but it will work. The RichTextBox api in .Net is very limited, to do anything you almost have to thunk into the Win32 library. I've built a entire library around this thing just so I can toggle bold and determine if bold is actually set across the selection. **Usage:** ``` RichTextBox te = ...; te.ClearAllFormatting(new Font("Microsoft Sans Serif", 8.25f)); ``` **Tons of code:** ``` static class RichTextExtensions { public static void ClearAllFormatting(this RichTextBox te, Font font) { CHARFORMAT2 fmt = new CHARFORMAT2(); fmt.cbSize = Marshal.SizeOf(fmt); fmt.dwMask = CFM_ALL2; fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR; fmt.szFaceName = font.FontFamily.Name; double size = font.Size; size /= 72;//logical dpi (pixels per inch) size *= 1440.0;//twips per inch fmt.yHeight = (int)size;//165 fmt.yOffset = 0; fmt.crTextColor = 0; fmt.bCharSet = 1;// DEFAULT_CHARSET; fmt.bPitchAndFamily = 0;// DEFAULT_PITCH; fmt.wWeight = 400;// FW_NORMAL; fmt.sSpacing = 0; fmt.crBackColor = 0; //fmt.lcid = ??? fmt.dwMask &= ~CFM_LCID;//don't know how to get this... fmt.dwReserved = 0; fmt.sStyle = 0; fmt.wKerning = 0; fmt.bUnderlineType = 0; fmt.bAnimation = 0; fmt.bRevAuthor = 0; fmt.bReserved1 = 0; SendMessage(te.Handle, EM_SETCHARFORMAT, SCF_ALL, ref fmt); } private const UInt32 WM_USER = 0x0400; private const UInt32 EM_GETCHARFORMAT = (WM_USER + 58); private const UInt32 EM_SETCHARFORMAT = (WM_USER + 68); private const UInt32 SCF_ALL = 0x0004; private const UInt32 SCF_SELECTION = 0x0001; [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, UInt32 wParam, ref CHARFORMAT2 lParam); [StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Auto)] struct CHARFORMAT2 { public int cbSize; public uint dwMask; public uint dwEffects; public int yHeight; public int yOffset; public int crTextColor; public byte bCharSet; public byte bPitchAndFamily; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szFaceName; public short wWeight; public short sSpacing; public int crBackColor; public int lcid; public int dwReserved; public short sStyle; public short wKerning; public byte bUnderlineType; public byte bAnimation; public byte bRevAuthor; public byte bReserved1; } #region CFE_ // CHARFORMAT effects const UInt32 CFE_BOLD = 0x0001; const UInt32 CFE_ITALIC = 0x0002; const UInt32 CFE_UNDERLINE = 0x0004; const UInt32 CFE_STRIKEOUT = 0x0008; const UInt32 CFE_PROTECTED = 0x0010; const UInt32 CFE_LINK = 0x0020; const UInt32 CFE_AUTOCOLOR = 0x40000000; // NOTE: this corresponds to // CFM_COLOR, which controls it // Masks and effects defined for CHARFORMAT2 -- an (*) indicates // that the data is stored by RichEdit 2.0/3.0, but not displayed const UInt32 CFE_SMALLCAPS = CFM_SMALLCAPS; const UInt32 CFE_ALLCAPS = CFM_ALLCAPS; const UInt32 CFE_HIDDEN = CFM_HIDDEN; const UInt32 CFE_OUTLINE = CFM_OUTLINE; const UInt32 CFE_SHADOW = CFM_SHADOW; const UInt32 CFE_EMBOSS = CFM_EMBOSS; const UInt32 CFE_IMPRINT = CFM_IMPRINT; const UInt32 CFE_DISABLED = CFM_DISABLED; const UInt32 CFE_REVISED = CFM_REVISED; // CFE_AUTOCOLOR and CFE_AUTOBACKCOLOR correspond to CFM_COLOR and // CFM_BACKCOLOR, respectively, which control them const UInt32 CFE_AUTOBACKCOLOR = CFM_BACKCOLOR; #endregion #region CFM_ // CHARFORMAT masks const UInt32 CFM_BOLD = 0x00000001; const UInt32 CFM_ITALIC = 0x00000002; const UInt32 CFM_UNDERLINE = 0x00000004; const UInt32 CFM_STRIKEOUT = 0x00000008; const UInt32 CFM_PROTECTED = 0x00000010; const UInt32 CFM_LINK = 0x00000020; // Exchange hyperlink extension const UInt32 CFM_SIZE = 0x80000000; const UInt32 CFM_COLOR = 0x40000000; const UInt32 CFM_FACE = 0x20000000; const UInt32 CFM_OFFSET = 0x10000000; const UInt32 CFM_CHARSET = 0x08000000; const UInt32 CFM_SMALLCAPS = 0x0040; // (*) const UInt32 CFM_ALLCAPS = 0x0080; // Displayed by 3.0 const UInt32 CFM_HIDDEN = 0x0100; // Hidden by 3.0 const UInt32 CFM_OUTLINE = 0x0200; // (*) const UInt32 CFM_SHADOW = 0x0400; // (*) const UInt32 CFM_EMBOSS = 0x0800; // (*) const UInt32 CFM_IMPRINT = 0x1000; // (*) const UInt32 CFM_DISABLED = 0x2000; const UInt32 CFM_REVISED = 0x4000; const UInt32 CFM_BACKCOLOR = 0x04000000; const UInt32 CFM_LCID = 0x02000000; const UInt32 CFM_UNDERLINETYPE = 0x00800000; // Many displayed by 3.0 const UInt32 CFM_WEIGHT = 0x00400000; const UInt32 CFM_SPACING = 0x00200000; // Displayed by 3.0 const UInt32 CFM_KERNING = 0x00100000; // (*) const UInt32 CFM_STYLE = 0x00080000; // (*) const UInt32 CFM_ANIMATION = 0x00040000; // (*) const UInt32 CFM_REVAUTHOR = 0x00008000; const UInt32 CFE_SUBSCRIPT = 0x00010000; // Superscript and subscript are const UInt32 CFE_SUPERSCRIPT = 0x00020000; // mutually exclusive const UInt32 CFM_SUBSCRIPT = (CFE_SUBSCRIPT | CFE_SUPERSCRIPT); const UInt32 CFM_SUPERSCRIPT = CFM_SUBSCRIPT; // CHARFORMAT "ALL" masks const UInt32 CFM_EFFECTS = (CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_COLOR | CFM_STRIKEOUT | CFE_PROTECTED | CFM_LINK); const UInt32 CFM_ALL = (CFM_EFFECTS | CFM_SIZE | CFM_FACE | CFM_OFFSET | CFM_CHARSET); const UInt32 CFM_EFFECTS2 = (CFM_EFFECTS | CFM_DISABLED | CFM_SMALLCAPS | CFM_ALLCAPS | CFM_HIDDEN | CFM_OUTLINE | CFM_SHADOW | CFM_EMBOSS | CFM_IMPRINT | CFM_DISABLED | CFM_REVISED | CFM_SUBSCRIPT | CFM_SUPERSCRIPT | CFM_BACKCOLOR); const UInt32 CFM_ALL2 = (CFM_ALL | CFM_EFFECTS2 | CFM_BACKCOLOR | CFM_LCID | CFM_UNDERLINETYPE | CFM_WEIGHT | CFM_REVAUTHOR | CFM_SPACING | CFM_KERNING | CFM_STYLE | CFM_ANIMATION); #endregion } ``` **More you ask?** I use most of this via a small utility class that wraps this for all the styles and font changes. This way you can change font-size and not change font name, etc. ``` class RichTextStyle { private readonly Control _textEdit; private readonly CHARFORMAT2 _charFormat; public RichTextStyle(RichTextBox te) { _textEdit = te; _charFormat = new CHARFORMAT2(); _charFormat.cbSize = Marshal.SizeOf(_charFormat); SendMessage(te.Handle, EM_GETCHARFORMAT, SCF_SELECTION, ref _charFormat); } private void SetEffect(UInt32 mask, UInt32 effect, bool valid) { CHARFORMAT2 fmt = new CHARFORMAT2(); fmt.cbSize = Marshal.SizeOf(fmt); fmt.dwMask = mask; fmt.dwEffects = valid ? effect : 0; SendMessage(_textEdit.Handle, EM_SETCHARFORMAT, SCF_SELECTION, ref fmt); } private bool GetEffect(UInt32 mask, UInt32 effect) { return (0 != (_charFormat.dwMask & mask)) && (0 != (_charFormat.dwEffects & effect)); } public bool Bold { get { return GetEffect(CFM_BOLD, CFE_BOLD); } set { SetEffect(CFM_BOLD, CFE_BOLD, value); } } public bool Italic { get { return GetEffect(CFM_ITALIC, CFE_ITALIC); } set { SetEffect(CFM_ITALIC, CFE_ITALIC, value); } } // ... etc ... etc ... you get the idea. ```
What about ``` richTextBox.Text = richTextBox.Text.ToString(); ```
Reset RTF formatting in a WinForms RichTextBox without discarding its text?
[ "", "c#", "winforms", "richtextbox", "rtf", "richtext", "" ]
In an attempt to make the best index choices for my database, I've noticed some particular behaviour which I'd like to address. Observe the following table and corresponding index (SQL Server 2005): ``` CREATE TABLE demo ( id INT PRIMARY KEY IDENTITY, name NVARCHAR(50) NOT NULL, password BINARY(20) NOT NULL ); CREATE NONCLUSTERED INDEX idx_demo_foo ON demo ( name, password ); ``` In this case, if I perform the following query... ``` SELECT id FROM demo WHERE name = @0 AND password = @1; ``` ... only a nonclustered index seek occurs. This strikes me as odd because I didn't explicitly add id to the nonclustered index.
A NCIX must include the Clustered Index keys, so that the system knows how to reach the underlying rows in the table itself. So if your Primary Key has a Clustered Index behind it (which by default it would), then you're in luck. Of course, if you change the Clustered Index, or make your table into a heap, then you'll need lookups to get to the Primary Key. Edit: I would recommend taking the password field out of the index keys, and making it an included column. Surely you just look up the entry by username and then check that the password matches, rather than having a number of passwords for each username. ``` create index ixBlah on demo (name) include (password); ``` Rob
The clustered index key is always included in a nonclustered index. The clustered index key is the row locator for the table, and every index must contain the row locator in order to match the index rows with table rows.
Are primary keys available in nonclustered indices?
[ "", "sql", "sql-server-2005", "t-sql", "" ]
I am building a website which allows people to send out emails to people with a choice of different templates. When they have set-up their email and chosen a template the user can preview it. At present this loads up the corresponding aspx page to the template selected. I currently have 3 templates but expect this to grow substantially. The aspx pages all have the same controls, with the same names and even the codebehind(cs) page is the same. So it would be far simpler and efficient if i could somehow tie this pages together and minimise repetition, perhaps even just using one page but loading up the HTML corresponding to the selected template. I cant think of an appropriate way to do this, or even work out if its possible. Ive probably got to the point where i cant think straight on the matter since its giving me such a headache. So..... Please please please give me some solutions or even just suggestions. ;-) Thanks. --- **ADDITIONAL INFO** As an additional problem, i have to recreate the templates programatically when the emails are created and sent out to recipients as HTML emails. This is done via a different page and thus results in more duplication that id like to minimise.
create a Page class, let say, TemplateViewerPage TemplateViewerPage.cs ``` using System; using System.Web.UI; public partial class TemplateViewerPage : Page { protected override void OnLoad(EventArgs e) { // load your properties _subject = "test"; _messageBody = "body"; base.OnLoad(e); } // your property private string _subject; public string Subject { get { return _subject; } set { _subject = value; } } private string _messageBody; public string MessageBody { get { return _messageBody; } set { _messageBody = value; } } } ``` then you can create viewer for template A : ViewerA.aspx ``` <%@ Page Language="C#" AutoEventWireup="false" Inherits="TemplateViewerPage" CodeFile="TemplateViewerPage.cs" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <td>Subject</td> <td> <%= Subject %> </td> </tr> <tr> <td>Message</td> <td> <%= MessageBody %> </td> </tr> </table> </div> </form> </body> </html> ``` and ViewerB, with same code behind (codefile=TemplateViewerPage.cs) ViewerB.aspx: ``` <%@ Page Language="C#" AutoEventWireup="false" Inherits="TemplateViewerPage" CodeFile="TemplateViewerPage.cs" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <div class="subject"> <%= Subject %> </div> <div class="message"> <%= MessageBody %> </td> </div> </div> </form> </body> </html> ```
How about MasterPages for the templates? The select the appropriate master page at PageLoad. If it's content then using CSS for the formatting (you can obviously change the CSS being loaded at Pageload) also Placeholders and populating them from your data store for the mails is another option. It think there are probably as many solutions as there are users on StackOverflow ;)
Different HTML, Same Codebehind & Same Controls
[ "", "c#", ".net", "asp.net", "c#-3.0", "" ]
Does someone know if it's even possible (in PHP) to take a frame/thumbnail from a quicktime movie on the server? Something like the usual GD thumbnail generation, but for .mov files. note: I'm using dreamhost, so I don't have more than web-panel access to the server.
Dreamhost provides a [shared ffmpeg binary](http://wiki.dreamhost.com/FFmpeg) in /usr/bin/ffmpeg, so you should definitely be able to call ffmpeg from php by using the system() or shell\_exec() functions. The Dreamhost wiki has also an entry providing directions on how to install and configure ffmpeg-php..
This looks promising: <http://ffmpeg-php.sourceforge.net/index.php>
Take a thumbnail from a quicktime (movie) file
[ "", "php", "gd", "thumbnails", "quicktime", "movie", "" ]
I've run across multiple situations in the last few months where legacy sql SP's are returning a single table made up mostly of redundant information. Example: Select CustomerID, CustomerEmail, CustomerAddress, InventoryLineItem, ShipQty from ... Returns: ``` 55 a@b.com 723 StreetName InvLineItem#1 45 55 a@b.com 723 StreetName InvLineItem#2 42 55 a@b.com 723 StreetName InvLineItem#3 1 55 a@b.com 723 StreetName InvLineItem#4 5 55 a@b.com 723 StreetName InvLineItem#5 200 55 a@b.com 723 StreetName InvLineItem#6 7045 ``` (first 3 fields never change) Since I'm the only developer on the project, I've started breaking this into two select statements. (I work on the receiving .NET code as well) select CustomerID, CustomerEmail, CustomerAddress from .... ``` Returns: 55 a@b.com 723 Streetname <-- 1 record ``` select InventoryLineItem, ShipQty from .... Returns: ``` LineItem#1 45 LineItem#2 42 LineItem#3 1 ``` etc. Obviously the resulting Dataset in .NET is smaller, but it really bugs me to have sometimes 10 fields in a select statement that are always under all circumstances exactly the same. Some of the queries may even return 10's of thousands of records. I feel like I'm doing the right thing here, but then again I'm no SQL pro. Are there any reasons for me to avoid this practice? Thanks in advance for your time.
If your client consuming the data coming back from the stored procedure can properly handle multiple result sets, then no, there's absolutely no reason not to use them. They have several advantages, as you've already pointed out yourself: - reduce the amount of data transferred - keep the normalization, no unnecessary duplication of data - save you a roundtrip to the server compared to have to call two separate stored procs (one for header, one for details data) So all in all - go for it! :-) Seems like an excellent idea to me. Marc
Well, my big answer here is that if you're feeding the output to a reporting framework such as SSRS, multiple tables are going to make your life difficult -- reporting frameworks are pretty good at taking denormalized results and processing them into pretty reports. As far as performance goes, no, you don't have a reason to avoid multiple resultsets coming off the sproc. As long as you're using a DataReader and .NextResult() on the client end, IMO you're golden.
SQL Server 2005 - Are there any major negative implications to returning multiple tables w/ stored procedures?
[ "", "sql", "sql-server", "sql-server-2005", "sql-server-2008", "" ]
I'm using Tamir's SharpPCap to try to send data to my msn. Currently, for testing purposes, my idea is to wait for any msg received by mymsn@msn.com and then send the packet itself again, that is, make any message appear repeated forever on my msn. I thought this had to work, as I am simply getting the packet itself I receive, and resending it again. For some reason nothing appears on my msn, although I will see printed in the console a lot of "caught data, resending it". Any ideas? Thanks ``` class Program { static PcapDevice device; static void Main(string[] args) { device = SharpPcap.GetAllDevices()[0]; device.PcapOnPacketArrival += new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival2); device.PcapOpen(true, 1000); device.PcapStartCapture(); Console.ReadKey(); } static void device_PcapOnPacketArrival2(object sender, Packet packet) { TCPPacket tcpPacket = packet as TCPPacket; if (tcpPacket == null) { return; } string data = Encoding.Default.GetString(tcpPacket.Data); if (!data.StartsWith("MSG mymsn@msn.com")) { return; } Console.WriteLine("caught data, resending it"); device.PcapSendPacket(tcpPacket); } } ```
One key feature of [TCP](http://en.wikipedia.org/wiki/Transmission_Control_Protocol) is "discarding duplicate packets" So to solve your problem with WinPcap you'll have to capture of all packets of one MSN message and resend it in new packets. Hopefully MSN won't accept that. In that case learning how to deal with the MSN protocol could bring a solution to this problem. CodeProject Howto: [Connect\_To\_MSN\_Messenger](http://www.codeproject.com/KB/cs/Connect_To_MSN_Messenger.aspx) Maybe this C# lib [MSNP-Sharp](http://en.wikipedia.org/wiki/MSNP-Sharp) somehow solves your problem or at least gives you a better understanding of [Microsoft Notification Protocol](http://en.wikipedia.org/wiki/Microsoft_Notification_Protocol)
Here's my suspicion... You're resending the packet, which I believe will make the network driver think it's received the same packet twice. That can happen in various cases, such as the first occurrence taking a while to arrive, so the sender resending in case it's got lost. The network driver (or MSN) will then spot the duplicate and discard it - after all, it's already seen that data, so it doesn't need the redundant copy. So explicitly sending the same packet again basically has no purpose. You've also got to consider that you're seeing one packet in a *stream* of data. There's no guarantee that that packet contains *exactly* a single command saying "here's a single message". It may end with the first bit of the next message, for example. Just inserting extra data into the stream would not only be hard, but you'd also need to understand the protocol in order to do it properly. --- Now when you say "nothing appears on my MSN" do you mean no *extra* messages, or that the first message doesn't appear? If it's that you're just not getting repetition, then the above explains it. If you're effectively *blocking* MSN by running this program, then that's clearly somewhat different.
Winpcap - Having troubles sending data
[ "", "c#", ".net", "packet-capture", "winpcap", "packet-sniffers", "" ]
Assume I have a webpage where people submit java source code (a simple class). I want to compile and run the code on my server, but naturally I want to prevent people from harming my server, so how do I disable `java.io.*` and other functions/libraries of my choice? A regexp on the source code would be one way, but it would be "nicer" if one could pass some argument to `javac` or `java`. (This could be useful when creating an AI competition or something where one implements a single class, but I want to prevent tampering with the java environment.)
If you are in complete control of the JVM, then you can use security policies to do this. It's the same approach taken by web browsers when they host applets. <http://java.sun.com/j2se/1.5.0/docs/guide/security/permissions.html> Hope this helps.
Depending on your intent, you might be able to speak with Nick Parlante, who runs javabat.com - it does pretty much exactly what you're describing. I don't know whether he's willing to share his solution, but he might be able to give you some specific help.
Disable libraries in Java?
[ "", "java", "security", "" ]
I am trying to implement a password reset functionality on my company website where if a user needs to reset her password, she can click on a link and a new, randomly generated password will be sent to her inbox. I am using the PHP `mail()` function. Now, I am running PHP5 on an Ubuntu machine. In php.ini I have declared SMTP as the IP of the machine running the mail server and smtp\_port as 25. Further, I have tried to telnet into the mailserver on port 25 and send a mail - it works (my work terminal is Windows). The problem is that the mail is not being sent / received - the PHP script calling `mail()` hangs for about 1 minute at the end of which `mail()` returns `true`. The worst part is that I am out of ideas on how to even find out where the problem lies - with PHP, with Ubuntu, with the mailserver or with the code! Can somebody please help?
I haven't looked in php.ini recently, but doesn't it say: ``` [mail function] ; For Win32 only. ;SMTP = ``` Emphasis on the **For Win32 only**. You may want to look at [PEAR::Mail](http://pear.php.net/package/Mail) instead. When pear.php.net is actually responding, that is.
Can you check your mail.err and mail.log files ?
PHP mail problem
[ "", "php", "smtp", "" ]
Posts and comments are stored in the same table. So to get each post and its comments we do this: ``` $posts = $this->select()->setIntegrityCheck(false) ->from(array('post' => 'Posts'), array('*')) ->where('post.idGroup = ' . $idGroup) ->where('post.idTopic IS NULL') ->order('post.date DESC') ->limit($resultsPerPage, $resultsPerPage * ($page - 1)) ->joinLeft(array('user' => 'Users'), 'post.idUser = user.idUser', array('idUser', 'fname', 'lname', 'profileUrl', 'photoUrl')) ->joinLeft(array('comment' => 'Posts'), 'comment.idTopic = post.idPost') ->query()->fetchAll(); ``` The problem is that the resulting array is flat and the comment data overwrites the post data, this is an example of what is returned: ``` [1] => Array ( [idPost] => 13 [idTopic] => 11 [idGroup] => 1 [idUser] => 84 [postContent] => Hello my name is Mud. [postUrl] => 13/hello-my-name-is-mud [postVotes] => [postScore] => [date] => 2009-07-21 16:39:09 [fname] => John [lname] => Doe [profileUrl] => john-doe [photoUrl] => uploads/userprofiles/0/84/pic84_14 ) ``` What we would like the result to be is something more like this: ``` [1] => array( [post] => array( [0] => array( idPost => 12, postContent => This is a post..., idGroup => 1 ... ) ), [user] => array( [0] => array( userName => JohnDoe ... ) ), [comments] => array( [0] => array( idPost => 15, postContent => This is a comment..., idGroup => 1 ... ), [1] => array( idPost => 17, postContent => This is another comment..., idGroup => 1 ... ) ) ) ``` Any hints to other solutions is also very welcome. Thanks.
If you alias all the columns in the second join to posts (like idPost as child\_idPost... etc), you'll get many rows that are the parent row with the columns of the second row. Thats about the closest you'll get. You can then grab the parent data from the first row, and then loop through the subsequent rows to get your one-to-many data. Otherwise, just do two queries, one for the parent, one for the children. It may be faster than creating that large result table anyway.
Zend does not make your preferred form easy, but it might be possible. Note, however, that you are asking the database server to do far more work than you actually want, because the post and user information are duplicated for each comment. Justin is correct that a second query is easier and probably faster. However, I can provide some pointers toward a solution. To start, consider what you would get by using the `Zend_Db::FETCH_NUM` fetch mode: ``` Array( [0] => Array( [0] => 12 [1] => [2] => 1 [3] => 84 [4] => This is a post..., [5] => 12/this-is-a-post [6] => [7] => [8] => 2009-07-21 16:39:09 [9] => 84 [10] => John [11] => Doe [12] => john-doe [13] => uploads/userprofiles/0/84/pic84_14 [14] => 15 [15] => 12 [16] => 1 [17] => 79 [18] => This is a comment..., [19] => [20] => [21] => [22] => 2009-07-21 17:40:10 ), [1] => Array( [0] => 12 [1] => [2] => 1 [3] => 84 [4] => This is a post..., [5] => 12/this-is-a-post [6] => [7] => [8] => 2009-07-21 16:39:09 [9] => 84 [10] => John [11] => Doe [12] => john-doe [13] => uploads/userprofiles/0/84/pic84_14 [14] => 17 [15] => 12 [16] => 1 [17] => 127 [18] => This is another comment..., [19] => [20] => [21] => [22] => 2009-07-20 10:31:26 ) ) ``` Then somehow you have to come up with the mapping of column numbers to table and column names: ``` Array( [0] => post.idPost [1] => post.idTopic [2] => post.idGroup [3] => post.idUser [4] => post.postContent [5] => post.postUrl [6] => post.postVotes [7] => post.postScore [8] => post.date [9] => user.idUser [10] => user.fname [11] => user.lname [12] => user.profileUrl [13] => user.photoUrl [14] => comment.idPost [15] => comment.idTopic [16] => comment.idGroup [17] => comment.idUser [18] => comment.postContent [19] => comment.postUrl [20] => comment.postVotes [21] => comment.postScore [22] => comment.date ) ``` This is the part where it gets tricky, because the table part of that is strongly specific to the database interface, and not always possible. Because it is tied to the result set, the adapter will also be the best place to obtain it; that means hacking Zend classes, possibly by providing your own adapter class. Depending on your database, the information might come from: * PDO: [`PDOStatement->getColumnMeta`](https://www.php.net/manual/en/pdostatement.getcolumnmeta.php) * Mysqli: [`mysqli_fetch_field_direct`](https://www.php.net/manual/en/mysqli-result.fetch-field-direct.php) Other adapters might not have a way to obtain the table name, unfortunately.
Zend Select with self join overwriting fields
[ "", "sql", "zend-framework", "select", "self-join", "" ]
A little background: I'm in the process of learning Python through O'Reilly's, "Learning Python" book, I've had some experience in Java. Anyway, upon reading Chapter 5 (I'm still in the middle of it, actually) I have come across a question with the way Python treats results of Mixed Numeric expressions. In the book, they use an example of mixing an integer and a floating-point number (40 + 3.14) and proceed to explain that the result of this expression would be a floating-point number because Python converts operands *up* to the type of the most complicated operand. My question is this: Instead of programmers having to remember which Numeric operand is the highest and remember that the that the result will be "upped" to that format, wouldn't it be simpler to create a special Numeric Literal for result types? My logic is this: If you have a decimal place in your expression, you know it's going to be a floating point number, if you have something like 3+4j, you know it's going to be a complex number. Why should you have to remember the hierarchy of Numeric Literals just to know what your result is going to be treated as? In my opinion, it seems like it would be a much simpler process to assign results to a single, uninformed Literal to know that regardless of whether or not the expression has Mixed Numerics, it will be treated as a specific Data Type. Follow up question: Is there a language where this kind of thing is currently being preformed? Again, my knowledge of Python is limited, so this may be a silly question, but I would like to know why programmers have to put themselves through this process. The only reason why I could imagine that there isn't a system of some kind in place already is that perhaps the specific Numeric Type of a result isn't as important as it is in some other languages (Java).
> "If you have a decimal place in your expression, you know it's going to be a floating point number, if you have something like 3+4j, you know it's going to be a complex number." That *is* the "hierarchy of Numeric Literals". I'm not really sure what more you want. Furthermore, the result will always be a subclass of numbers.Number, so you actually do have some guarantee about what type the resulting object will be.
Suppose you had a unified numeric type and you typed the following statements: ``` a = 42 b = 42.24 c = 4 + 2j ``` How would this be any different from what you get today? This is already valid Python. The only difference is that `type(a)`, `type(b)`, `type(c)` return `int`, `float` and `complex`, and I guess you want them all to return something like `number`. But you never really deal with that unless you want/have to. There are reasons for having something like a scheme-like [numerical tower](http://en.wikipedia.org/wiki/Numerical_tower). You may take advantage of the hardware for integer calculations if you know you're only dealing with itnegers. Or you may derive from the `int` type when you know you want to restrict some kind of user input to an integer. I'm sure you can find a language with a type system that has some kind of unified number. But I'm not sure I've understood your argument. Perhaps I've missed something in your question?
About Python's Mixed Numeric Data Types converting results up to the most complicated operand
[ "", "python", "numeric", "" ]
What is wrong with this function? It works in Opera and Firefox, but doens't work on Safari under the Windows ``` function getImage(url) { var image = document.createElement('img'); // new Image(1, 1); image.src = url; image.onload = function() {}; } ``` when I try getImage('<http://site.com/someservlet.gif>') This image is not loaded (because someservlet.gif logs all requests) It works in Opera and Firefox, but not in Safari. I tried "new Image()" and "document.createElement('img')" -- the same result. ========== UPDATE: Function works well when it's called directly, problem start when it's called from event listener ``` <a href="http://google.com/" onclick="getImage('http://127.0.0.1/pic/img.gif?rnd=' + Math.random());">google</a> <a href="#" onclick="getImage('http://127.0.0.1/pic/img.gif?rnd=' + Math.random());">local</a> <script type="text/javascript"> function getImage(url) { var image = document.createElement('img'); alert('1'); image.onload = function() {alert(image.src);}; image.src = url; alert('2'); } </script> ``` "local" link works well in Firefox, Opera and Safari (but Safari shows alert1, alert2 and then alert with "src" for some reason, while other browsers show alert1, alertSrc, alert2) "google" link Opera, Firefox - works well (alert1, alertSrc, alert2), but Safari doesn't - show alertSrc. In Safari you see alert1, alert2 and thats all. Servlet "/pic/img.gif" doesn't get request when someone clicks "google" link from Safari. What is the problem, how to solve it? Thanks.
My first impression is that you stumbled upon some optimization code in browsers that defers loading of images that aren't displayed. So far: Safari 4.0.2 (530.19.1): * works for me, as described (both local, google, and when I changed the event to mouseover) * ordering of the alerts is alert1, alertsrc, alert2 Firefox Nightly (3.5.3pre, 20090805): * works as described. Funny, since it didn't work at first. Try loading the image into your cache, see if it affects the test. * ordering of the alerts is alert1, and then alertsrc and alert2 at the same time (move the dialog to see both) Google Chrome (2.0.172.39): * works as in Safari, although mouseover seems to fire too many events * ordering of the alerts is alert1, alert2, alertsrc Internet Explorer (7.0.6001.18000) * works as described (both local, google, and when changed to mouseover) * ordering of the alerts is alert1, alertsrc, alert2 Keep in mind that I changed the image location to <http://www.google.com.ar/images/nav_logo6.png> since I don't have a random image script running right now. Based on this, I would suggest running a test yourself with different images, and trying non-existent images, images in your cache, images not in your cache. The reason the alerts aren't necessarily in order is that different browsers load images in different orders, and the alertsrc only happens after the image is loaded. A good check if an image is loaded or not is if the width is 0.
I think it's a cache problem. When you say `image.src = url;` javascript immediately goes to fetch the image, and if the image is cached, then the browser will just used the cached one and fires the onload, and now you say `image.onload = function() {};` but onload has already fired, so `function()` is never called. Anyway, this is all just my speculation, I'm not sure if I'm right. However, If I am right, you should be able to fix it by moving `image.src = url;` under `image.onload = function() {};`
javascript crossbrowser new Image()
[ "", "javascript", "" ]
I am trying to create a program to copy all the files from one directory to another. But I am running in a basic issue. It says indentifier expected when I try to compile on line 52. ``` public bool RecursiveCopy() { string origDir = @"D:\Documents and Settings\Dub\My Documents\HoN Updates\test"; string destDir = @"C:\Games\HoN"; bool status = false; //get all the info about the original directory var dirInfo = new DirectoryInfo(origDir); //retrieve all the _fileNames in the original directory var files = dirInfo.GetFiles(origDir); //always use a try...catch to deal //with any exceptions that may occur try { //loop through all the file names and copy them foreach (string file in Directory.GetFiles(origDir)) { var origFile = new FileInfo(file); var destFile = new FileInfo(file.Replace(origDir, destDir)); //copy the file, use the OverWrite overload to overwrite //destination file if it exists System.IO.File.Copy(origFile.FullName, destFile.FullName, true); //TODO: If you dont want to remove the original //_fileNames comment this line out File.Delete(origFile.FullName); status = true; } Console.WriteLine("All files in " + origDir + " copied successfully!"); } catch (Exception ex) { status = false; //handle any errors that may have occurred Console.WriteLine(ex.Message); } return status; } public string origDir = @"D:\Documents and Settings\Dub\My Documents\HoN Updates\test"; // ERROR HERE public string destDir = @"C:\Games\HoN"; // ERROR HERE private static void RecursiveCopy(origDir, destDir) { Console.WriteLine("done"); Console.ReadLine(); } ```
You did not give type identifiers to your argument list here ``` static void RecursiveCopy(origDir, destDir) ``` should be ``` static void RecursiveCopy(string origDir, string destDir) ```
Your method `RecursiveCopy` has two parameters listed without their types. It should be this: ``` static void RecursiveCopy(string origDir, string destDir) ```
c# identifier expected?
[ "", "c#", "" ]
i have two datasets and i need to compare these two datasets such that if ID does not exist in one table then i need to write insert Query else update query. For Ex: ``` Id in One dataset ID in second Dataset 1 1 2 2 3 4 ``` I need to insert ID 3 to second dataset. Here is my code for your reference: ``` if (ds.Tables[0].Rows.Count > 0 || clientDS.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { for (int j = 0; j < clientDS.Tables[0].Rows.Count; j++) { if (ds.Tables[0].Rows[i]["Id"].ToString() == clientDS.Tables[0].Rows[j]["Id"].ToString()) { client.GetSingleValue("update customers set Name='" + ds.Tables[0].Rows[i]["Name"].ToString() + "',ContactPerson= '" + ds.Tables[0].Rows[i]["ContactPerson"].ToString() + "',Address='" + ds.Tables[0].Rows[i]["Address"].ToString() + "',TinNo='" + ds.Tables[0].Rows[i]["TinNo"].ToString() + "',ContactNo='" + ds.Tables[0].Rows[i]["Contactno"].ToString() + "',Report= '" + ds.Tables[0].Rows[i]["Report"].ToString() + "',Sync=0,Ids='" + ds.Tables[0].Rows[i]["Id"].ToString() + "' where id='" + ds.Tables[0].Rows[i]["Id"].ToString() + "' "); } else { client.GetSingleValue("insert into customers(id,Name,ContactPerson,Address,TinNo,ContactNo,Report,Sync,Ids) values('" + ds.Tables[0].Rows[i]["Id"].ToString() + "', '" + ds.Tables[0].Rows[i]["Name"].ToString() + "','" + ds.Tables[0].Rows[i]["ContactPerson"].ToString() + "', '" + ds.Tables[0].Rows[i]["Address"].ToString() + "', '" + ds.Tables[0].Rows[i]["TinNo"].ToString() + "', '" + ds.Tables[0].Rows[i]["Contactno"].ToString() + "', '" + ds.Tables[0].Rows[i]["Report"].ToString() + "',0,'" + ds.Tables[0].Rows[i]["Id"].ToString() + "')"); } } } } ``` Above code does not work. Pls rectify my issue. Thanks
I think your error is compaing the Id string using `==`. Try using `Equals`. I'd just use a foreach and select instead: ``` foreach (DataRow row in ds.Tables[0].Rows) { string filter = string.Format("Id = '{0}'", row["Id"]); DataRow[] rows = clientDS.Tables[0].Select(filter); if (rows.length == 0) { // insert here } else { // update here } } ```
Use the Merge method: ``` Dataset2.Merge(Dataset1); ``` This will insert into Dataset2 any records that are in Dataset1 but not already in Dataset2. Note: your original question suggests that you need to insert records or update matching records from Dataset1, but your comments appear to suggest that you don't actually need to do an update. The Merge method will only insert new records from Dataset1.
Compare two datasets in C#
[ "", "c#", ".net-2.0", "dataset", "" ]
I am new to PHP, but have a decent grasp of things (have not learned classes yet). **The question:** Which to choose? PHPMailer or mail() for my new contact form. The form is simple: ``` Your name: Your email: Subject: Body: ``` I have around 2,000 visitors per day and receive about 10 submissions per day, so I don't need anything too fancy. =) **Miscellaneous questions in my head:** * Is PHPMailer going to better protect my Contact Form from CC: injection (major concern)? I already know the `anti-spambot display:none CSS` trick. * Will PHPMailer save me the step of having to write an `email_validator()` function? * Will PHPMailer save me any other time of having to write any custom functions? Thanks! With any luck, I'll be answering questions soon. Lol
Here is all I could think of in one sitting, forgive me if there are any glaring omissions. Advantages to using PHP's built-in mail function, no external library/wrapper: * You don't need anything outside of PHP. * You don't need to learn a new API. * You don't have to worry about a PHP upgrade or such breaking the script. * You don't have to worry about an updated version not working on your PHP installation. * You don't have to worry about potential security vulnerabilities as a result of using that script. * If it's a simple task, you'll be done in a few minutes. Advantages to using an external library/wrapper: * If you need to introduce more complexity into your emailing, you can do so quite easily. Adding attachments, inline images and such are not much fun using PHP plain mail function. External libraries (at least the good ones) have a more OOPish API. Adding an attachment can be as easy as `$message->addAttachment($file);` without having to play around with headers, etc. * External libraries better hide the ugly complexities of tasks such as adding attachments, character encodings and inline images. * Using a library now will save you the hassle of having to learn it in the future when you *do* need the additional complexity/functionality. * External libraries *probably* (I'm really not sure which ones, and to what extent) address certain vulnerabilities that PHP's mail does not. If I can think of anything else, I'll be sure to add it.
This will maybe not really answer all your questions, but it won't hurt either, I guess... Whatever you want to do, **I would not go with `mail()`** : sending a mail is not such an easy task, and using an existing library/framework will always be a good idea : it will solve many problems you probably have not even thought about -- even if you don't need to send lots of mails. About your specific questions, maybe other answers will say something else and/or get your more informations, but any "good" library created to send mails should deal with those kind of problems... Else, you should probably search for another library ^^ Still, testing a couple of dumb non-addresses will allow you to be 100% sure ;-) Another solution to be quite sure is to check the source of the library ;-) In the source of version 2.2.1, you'll find stuff like this : `class.phpmailer.php`, function `AddAnAddress`, line 413, you'll see this : ``` if (!self::ValidateAddress($address)) { $this->SetError($this->Lang('invalid_address').': '. $address); if ($this->exceptions) { throw new phpmailerException($this->Lang('invalid_address').': '.$address); } echo $this->Lang('invalid_address').': '.$address; return false; } ``` And it seems this function is used by the other functions that add an address... So, I suppose there's some kind of email-addresses validation ;-) That'll answer at least one of your questions ^^ PHPMailer is not the only solution that exists, btw ; there are plenty of others, like, for instance : * [Zend\_Mail](http://framework.zend.com/manual/en/zend.mail.html) * [Rmail for PHP](http://www.phpguru.org/static/mime.mail.html) *(Formerly known as HTML Mime Mail)* * [Swift Mailer](http://swiftmailer.org/)
PHPMailer v. mail() for a simple Contact Form
[ "", "php", "" ]
Every Java enumeration has a static values() method can be used like this ``` for (MyEnum enum : MyEnum.values()) { // Do something with enum } ``` However, I cannot figure out where this method is defined. There's no mention of it in the [Javadoc](http://java.sun.com/javase/6/docs/api/java/lang/Enum.html) and it doesn't appear anywhere in the source file.
This is required by the [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9): `values` and `valueOf` will be implicitly declared for all Enums: ``` /** * Returns an array containing the constants of this enum * type, in the order they're declared. This method may be * used to iterate over the constants as follows: * * for(E c : E.values()) * System.out.println(c); * * @return an array containing the constants of this enum * type, in the order they're declared */ public static E[] values(); /** * Returns the enum constant of this type with the specified * name. * The string must match exactly an identifier used to declare * an enum constant in this type. (Extraneous whitespace * characters are not permitted.) * * @return the enum constant with the specified name * @throws IllegalArgumentException if this enum type has no * constant with the specified name */ public static E valueOf(String name); ``` These methods are added during compile time, so if you use `javap` to disassemble the code, you can actually look at their body.
It's defined in the [JLS, section 8.9.3 "Enum Members"](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.3)
where is Enum.values() defined?
[ "", "java", "enums", "" ]
What is the usage of `synchronized` statements?
It is a java built in form of mutual exclusion. This is used for multithreaded applications. [Sun concurrency tutorial](http://java.sun.com/docs/books/tutorial/essential/concurrency/) This has a section about synchronized, but you should read the whole thing if you are trying to use multithreaded applications. [Wiki mutex](http://en.wikipedia.org/wiki/Mutex)
These are used for when you are building a program with many "threads". When main starts, it starts with one thread, which executes the steps in a sequence. You can start many more threads, which can then execute code at the same time. If you're executing the same code at the same time, things might behave in ways you don't want: ``` y = x+20; // at this moment, before the next instruction starts, some other thread performs // the above step, which sets 'y' (an object property) to something different. int b = y+10; // this would not be x+20, as you might expect. ``` What you want to do is put a 'lock' over this block of code, to make sure that no other thread can start executing any code that is "synchronized on" the variable y. ``` synchronized (y) { y = x+20; int b = y+10; } // lock gets released here ``` Now, all other threads have to wait for whichever thread got there first to exit the block and release the lock, at which point another thread grabs the lock, enters the block of code, executes it, and releases the lock. Note that `y` has to be an object (Integer), not a primitive type. You can also add 'synchronized' to methods, which synchronizes on 'this' (the instance object), or the class in the case of a static method. Writing multi-threaded code is hard, because of problems like this. Synchronization is one tool, though it has one major problem - deadlocks. There is a lot of information online about deadlocks.
What is synchronized statement used for?
[ "", "java", "synchronization", "" ]
I am writing an application that runs on Windows logon but I want it to wait until the desktop is fully functional/loaded before it actually starts doing anything. Is there any way of working out when Windows has completely finished loading the desktop?
On vista you could use a service in Automatic (Delayed) mode, this would start before log on if no one logged on fast enough though but if you wished to avoid running until much of the system had become ready this would work. If you are heavily user centric in your desire to wait till they are ready then you will likely have to use user centric triggers. Several metrics exist which would give you a good idea of whether the user considered the session ready for use: * CPU load of processes associated with the System account were no longer taking a significant proportion of the CPU time. * The user has begun interacting with the UI (so significant mouse movement or keyboard activity) * network connectivity is established Since these are heuristics you should have some time based constraints for the minimum and maximum possible wait in case they misfire.
Very old question but I needed the same. The following code seems to work: ``` [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); // wait until desktop ready IntPtr lHwnd = IntPtr.Zero; do { lHwnd = FindWindow("Shell_TrayWnd", null); Thread.Sleep(100); } while (lHwnd == IntPtr.Zero); ```
How to tell if Windows desktop is fully functional (loaded) c#
[ "", "c#", "window", "desktop", "" ]
How can I get the number of times a program has previously run in C# without keeping a file and tallying. If it is not possible that way, can it be gotten from the Scheduled Task Manager? *To C. Ross: how would this be done in a registry setting? forgive me. . . what is a registry setting?*
To the best of my knowledge Windows does not keep this information for you. You would have to tally the value somewhere (file, database, registry setting). The Windows Task Scheduler is very low functionality.
I do this in a registry setting. ``` static string AppRegyPath = "Software\\Cheeso\\ApplicationName"; static string rvn_Runs = "Runs"; private Microsoft.Win32.RegistryKey _appCuKey; public Microsoft.Win32.RegistryKey AppCuKey { get { if (_appCuKey == null) { _appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegyPath, true); if (_appCuKey == null) _appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegyPath); } return _appCuKey; } set { _appCuKey = null; } } public int UpdateRunCount() { int x = (Int32)AppCuKey.GetValue(rvn_Runs, 0); x++; AppCuKey.SetValue(rvn_Runs, x); return x; } ``` If it's a WinForms app, you can hook the Form's OnClosing event to run `UpdateCount`.
How many times program has run? C#
[ "", "c#", "count", "scheduled-tasks", "execution", "" ]
For checking code in python mode I use flymake with [pyflakes](http://www.emacswiki.org/cgi-bin/wiki/PythonMode#toc8) Also I want check code style (pep8) with pylint (description on the same page with pyflakes) This solutions work. But I can't configure flymake for work with pyflakes and pylint together. How can I do it?
Well, flymake is just looking for a executable command thats output lines in a predefined format. You can make a shell script for example that will call successively all the checkers you want... You must also make sure that your script ends by returning errorlevel 0. So this is an example: This is what I've done in a "pycheckers" script: ``` #!/bin/bash epylint "$1" 2>/dev/null pyflakes "$1" pep8 --ignore=E221,E701,E202 --repeat "$1" true ``` For the emacs lisp part: ``` (when (load "flymake" t) (defun flymake-pyflakes-init () (let* ((temp-file (flymake-init-create-temp-buffer-copy 'flymake-create-temp-inplace)) (local-file (file-relative-name temp-file (file-name-directory buffer-file-name)))) (list "pycheckers" (list local-file)))) (add-to-list 'flymake-allowed-file-name-masks '("\\.py\\'" flymake-pyflakes-init))) ```
Usually one can enable flymake mode in the python-mode-hook. Unfortunately that causes issues with things like py-execute-buffer which create temporary buffers which invoke the hook and then cause flymake mode to hiccup because of the lack of "real file". The solution is to modify the conditions where you add the hook:- e.g mine is: ``` (add-hook 'python-mode-hook (lambda () (unless (eq buffer-file-name nil) (flymake-mode 1)) ;dont invoke flymake on temporary buffers for the interpreter (local-set-key [f2] 'flymake-goto-prev-error) (local-set-key [f3] 'flymake-goto-next-error) )) ```
How can I use Emacs Flymake mode for python with pyflakes and pylint checking code?
[ "", "python", "emacs", "pylint", "pep8", "pyflakes", "" ]
Hi Fellow StackOverflowers, I am receiving a string in one of my .NET function. The string when viewed from the XML Visualizer looks like this: ``` - <root> - <Table> <ID>ABC-123</ID> <CAT>Housekeeping</CAT> <DATE>21-JUN-2009</DATE> <REP_BY>John</REP_BY> <LOCATION>Head Office</LOCATION> </Table> - <Table> <ID>ABC-124</ID> <CAT>Environment</CAT> <DATE>23-JUN-2009</DATE> <REP_BY>Michelle</REP_BY> <LOCATION>Block C</LOCATION> </Table> - <Table> <ID>ABC-125</ID> <CAT>Staging</CAT> <DATE>21-JUN-2009</DATE> <REP_BY>George</REP_BY> <LOCATION>Head Office</LOCATION> </Table> - <Table> <ID>ABC-123</ID> <CAT>Housekeeping</CAT> <DATE>21-JUN-2009</DATE> <REP_BY>John</REP_BY> <LOCATION space="preserve" xmlns="http://www.w3.org/XML/1998/namespace" /> </Table> </root> ``` I need to parse this string so that I could write the data into a datatable whose columns are the xml tags for each data. In the above text, I would then have a datatable that wil have 5 columns, named ID, CAT, DATE, REP\_BY and LOCATION which will then contain 4 rows of data. In the fourth tag, notice that the does not have any data, but rather it is marked space="preserve". This would mean that the data I am placing in my datatable would be blank for the LOCATION column of the fourth row. How can I achieve this? Sample codes would be highly appreciated. Thanks.
This is probably the simplest solution to get the XML into table form. Throwing the attributes out using regular expressions is not that smart (and safe), but I don't like the `System.Xml` API and LINQ to XML is no option in .NET 2.0. ``` using System; using System.Data; using System.IO; using System.Text.RegularExpressions; namespace GeneralTestApplication { class Program { private static void Main() { String input = @"<root><Table> [...] </root>"; input = Regex.Replace(input, @" [a-zA-Z]+=""[^""]*""", String.Empty); DataSet dataSet = new DataSet(); dataSet.ReadXml(new StringReader(input)); foreach (DataRow row in dataSet.Tables[0].Rows) { foreach (DataColumn column in dataSet.Tables[0].Columns) { Console.Write(row[column] + " | "); } Console.WriteLine(); } Console.ReadLine(); } } } ``` **UPDATE** Or get rid of the attribute using `System.Xml`. ``` XmlDocument doc = new XmlDocument(); doc.Load(new StringReader(input)); foreach (XmlNode node in doc.SelectNodes("descendant-or-self::*")) { node.Attributes.RemoveAll(); } input = doc.OuterXml; ``` But this doesn't work because the XML namespace on the last `LOCATION` element remains and the `DataSet.LoadXml()` complains that there connot be two columns named `LOCATION`.
Using the XmlReader class. This class is fast and does not use a lot of memory but reading the xml can be difficult. ``` using (StringReader strReader = new StringReader(yourXMLString)) { using (XmlReader reader = XmlReader.Create(strReader)) { while (reader.Read()) { if(reader.Name == "Table" && reader.NodeType == reader.NodeType == XmlNodeType.Element) { using(XmlReader tableReader = reader.ReadSubtree()) { ReadTableNode(tableReader); } } } } } private void ReadTableNode(XmlReader reader) { while (reader.Read()) { if(reader.Name == "ID" && reader.NodeType == reader.NodeType == XmlNodeType.Element) //do something else if(reader.Name == "CAT" && reader.NodeType == reader.NodeType == XmlNodeType.Element) //do something //and continue.... } } ``` To get an attribute of the current node you use: ``` string value = reader.GetAttribute(name_of_attribute); ``` To get the inner text of an element: ``` string innerText = reader.ReadString(); ``` Using the XmlDocument class. This class is slow but manipulating and reading the xml is very easy because the entire xml is loaded. ``` XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(yourXMLString); //do something ``` Using the XDocument class. The advantage of using XDocument is elements can be accessed directly and simultaneously. This class also use the power of LINQ to query the xml document. ``` using(StringReader tr = new StringReader(yourXMLString)) { XDocument doc = XDocument.Load(tr); //do something } ```
How to parse XML in a string in .NET?
[ "", "c#", ".net", "xml", "string", "" ]
How to convert a string 0E-11 to 0.00000000000 in Java? I want to display the number in non scientific notations. I've tried looking at the number formatter in Java, however I need to specific the exact number of decimals I want but I will not always know. I simply want the number of decimal places as specificed by my original number.
I would use BigDecimal.Pass your string into it as a parameter and then use String.format to represent your newly created BigDecimal without scientific notation. Float or Double classes can be used too.
Apparently the correct answer is to user BigDecimal and retrieve the precision and scale numbers. Then use those numbers in the Formatter. Something similar like this: ``` BigDecimal bg = new BigDecimal(rs.getString(i)); Formatter fmt = new Formatter(); fmt.format("%." + bg.scale() + "f", bg); buf.append( fmt); ```
How to convert a string 3.0103E-7 to 0.00000030103 in Java?
[ "", "java", "formatting", "numbers", "" ]
I'm using JavaScript to set the value of an input with text that may contain HTML specific chars such a `&amp;` `&nbsp;` etc. So, I'm trying to find one regex that will match these values and replace them with the appropriate value ("&", " ") respectively, only I can't figure out the regex to do it. Here's my attempt: Make an object that contains the matches and reference to the replacement value: ``` var specialChars = { "&amp;nbsp;" : " ", "&amp;amp;" : "&", "&amp;gt;" : ">", "&amp;lt;" : "<" } ``` Then, I want to match my string ``` var stringToMatch = "This string has special chars &amp;amp; and &amp;nbsp;" ``` I tried something like ``` stringToMatch.replace(/(&amp;nbsp;|&amp;)/g,specialChars["$1"]); ``` but it doesn't work. I don't really understand how to capture the special tag and replace it. Any help is greatly appreciated.
I think you can use the functions from a question on a slightly different subject ([Efficiently replace all accented characters in a string?](https://stackoverflow.com/questions/286921)). Jason Bunting's answer has some nice ideas + the necessary explanation, here is his solution with some modifications to get you started (*if you find this helpful, upvote his original answer as well, as this is his code, essentially*). ``` var replaceHtmlEntites = (function() { var translate_re = /&(nbsp|amp|quot|lt|gt);/g, translate = { 'nbsp': String.fromCharCode(160), 'amp' : '&', 'quot': '"', 'lt' : '<', 'gt' : '>' }, translator = function($0, $1) { return translate[$1]; }; return function(s) { return s.replace(translate_re, translator); }; })(); ``` callable as ``` var stringToMatch = "This string has special chars &amp; and &amp;nbsp;"; var stringOutput = replaceHtmlEntites(stringToMatch); ``` Numbered entites are even easier, you can replace them much more generically using a little math and [`String.fromCharCode()`](http://www.w3schools.com/jsref/jsref_fromCharCode.asp). --- Another, much simpler possibility would be like this (works in any browser) ``` function replaceHtmlEntites(string) { var div = document.createElement("div"); div.innerHTML = string; return div.textContent || div.innerText; } replaceHtmlEntites("This string has special chars &lt; &amp; &gt;"); // -> "This string has special chars < & >" ```
Another way would be creating a div object ``` var tmp = document.createElement("div"); ``` Then assigning the text to its innerHTML ``` tmp.innerHTML = mySpecialString; ``` And finally reading the element's text content ``` var output = tmp.textContent || tmp.innerText //for IE compatibility ``` And there you go...
javascript regex replace html chars
[ "", "javascript", "regex", "" ]
I'm currently using an IFrame to sandbox user generated content on a website. This eliminates any styling issues with our main stylesheets. However, when a user generates a link using our rich text editor, we would like the link to open in the parent and not just open the link in the IFrame. I realize you can set a target to the parent, but we do not have control of the user and what they enter in their content. Is there any way to hijack the HREFs inside the IFrame so they all target parent without modifying them? Or use a bit of Javascript that could be injected universally so I do not need to scrape through all of the content and replace the target programatically? Ideally a simple script in one spot would be the best solution. Thoughts? **END SOLUTION** I used a variation of the answer I selected... It got me in the right direction. ``` <script> Event.observe(window, 'load', function() { $$('a').each(function(e) { e.writeAttribute('target', '_parent'); }); }); </script> ``` That's inside the IFrame with the content. It ended up being the most simple solution for the task.
Use this to create it and you'll have access to any parts with the $body variable: ``` $(function() { var $frame = $('<iframe style="width:200px; height:100px;">'); $('body').html( $frame ); setTimeout( function() { var doc = $frame[0].contentWindow.document; var $body = $('body',doc); $body.html('<h1>Test</h1>'); }, 1 ); }); ``` So you can then do something like this ``` $('a', $body).attr('target', '_parent'); ``` Found here: <http://groups.google.com/group/jquery-en/browse_thread/thread/fb646741a6192540>
Same domain in the iframe? Yes. ``` <script type="text/javascript"> function hijacklinks(iframe){ var as = iframe.contentDocument.getElementsByTagName('a'); for(i=0;i<as.length;i++){ as[i].setAttribute('target','_parent'); } } </script> <iframe src="http://example.com/test.html" onload="hijacklinks(this)"></iframe> ``` Different domain in the iframe? No. ``` <iframe src="http://www.google.com/search?q=google+happy" onload="hijacklinks(this)"></iframe> ``` yields a "Permission denied to get property HTMLDocument.getElementsByTagName". There may be ways around, but at least with simple JavaScript their are some protections against iframes mucking with sites (imagine a malicious frame around a bank's website and you can understand why).
Force any HREF in an IFrame to use its parent as the target
[ "", "javascript", "jquery", "iframe", "href", "target", "" ]
Scenario: I have a blog that I want to make a post to. I have a form set up where I can write out a blog post and submit it to a seperate php page that then stores it in a database (after it confirms it is me posting) where it will be read from and displayed on the home page. How can I easily escape any quotes or anything that will interfere with it being stored in the database but still allow it to be displayed properly (with all formatting intact)? Thanks
[Prepared statements](http://us.php.net/pdo.prepared-statements) in PHP will do a good job of taking care of sanitizing data as it goes into the database.
The only things that will interfere with it being stored in a MySQL database can be easily escaped by [mysql\_real\_escape\_string()](http://php.net/mysql_real_escape_string). When you pull it out of the database, everything will look the same as before it was escaped and put in. Before you display it on a web page, you'll want to run [htmlspecialchars()](http://php.net/htmlspecialchars) on the text to prevent any malicious scripting from having an effect. An optional command would be [strip\_tags()](http://php.net/strip_tags) if you don't want the text to contain any HTML at all.
What is the best way to "clean" information to be stored in a SQL database?
[ "", "php", "mysql", "sanitization", "" ]
This is probably an oldie-but-goodie. I am using System.Data.Common for an interchangeable Oracle/SQL Server/SQLite data access library. During the constructor I take the connection string name and use that to determine the underlying provider type. The reason I do this is to handle the different IDbParameter naming conventions for each provider. For example, Oracle likes :parameter whereas SQL Server and SQLite like @parameter. The default is ? to cover Oledb. Question: Is this all unnecessary and is there some simple thing I'm missing that should simply take care of this? If my IDbCommand.CommandText = "select id, name from my.table where id = :id" am I covered? For now I'm just adopting ? as the default and then RegEx'ing my way to the right parameter identifier before executing the command. Thanks. ``` /// <summary> /// Initializes a new instance of the <see cref="RelationalGateway"/> class. /// </summary> /// <remarks>You must pass in the name of the connection string from the application configuration /// file rather than the connection string itself so that the class can determine /// which data provider to use, e.g., SqlClient vs. OracleClient.</remarks> public RelationalGateway(string connectionStringName) { if (string.IsNullOrEmpty(connectionStringName)) throw new ArgumentNullException("connectionStringName"); if (ConfigurationManager.ConnectionStrings[connectionStringName] == null || ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString.Length == 0 || ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName.Length == 0) { throw new InvalidOperationException(string.Format( "The configuration file does not contain the {0} connection ", connectionStringName) + "string configuration section or the section contains empty values. Please ensure the " + "configuration file has the appropriate values and try again."); } _connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; _providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName; _theProvider = DbProviderFactories.GetFactory(_providerName); _adapter = _theProvider.CreateDataAdapter(); //GetConnection(); DetermineProviderSpecificParameters(); } ``` The DetermineProviderSpecificParameters bit basically figures out "?" or ":" or "@" or something else. UPDATE Here's how I'm handling the details thus far: 1. Get the right parameter string: private void DetermineProviderSpecificParameters() { // Check for supported providers. This is so that parametized queries to limit // by spatial extent are correctly created. string shortName = \_providerName.Substring(\_providerName.LastIndexOf(".") + 1); ``` switch (shortName) { case "SqlClient": _param = "@"; _ql = "["; _qr = "]"; break; case "SQLite": _param = "@"; _ql = string.Empty; _qr = string.Empty; break; case "OracleClient": _param = ":"; _ql = string.Empty; _qr = string.Empty; break; default: _param = "?"; _ql = string.Empty; _qr = string.Empty; break; } } ``` 2. call a little helper before I execute each command to "cleanify" or "parameterific" it or however we call this half-assed hack: ``` private void MakeProviderSpecific(IDbCommand command) { foreach (IDataParameter param in command.Parameters) { param.ParameterName = GetProviderSpecificCommandText(param.ParameterName); } command.CommandText = GetProviderSpecificCommandText(command.CommandText); } ``` 3. And this calls a little regex to do to do: ``` public string GetProviderSpecificCommandText(string rawCommandText) { return Regex.Replace(rawCommandText, @"\B\?\w+", new MatchEvaluator(SpecificParam)); } ``` Yuck. Still searching for a relatively simple solution but the advice thus far is certainly appreciated.
I have done something like this for [Salamanca](http://salamanca.codeplex.com/) : see [ParameterBuilder.cs](http://salamanca.codeplex.com/sourcecontrol/changeset/view/24649?projectName=salamanca#183762). This code uses : * protected methods on [`DbCommandBuilder`](http://msdn.microsoft.com/en-us/library/system.data.common.dbcommandbuilder.aspx), called via reflection (will only work in full trust mode, I assume) : [`GetParameterPlaceholder`](http://msdn.microsoft.com/en-us/library/system.data.common.dbcommandbuilder.getparameterplaceholder.aspx) and [`GetParameterName`](http://msdn.microsoft.com/en-us/library/system.data.common.dbcommandbuilder.getparametername.aspx). * the information returned by [`DbConnection.GetSchema`](http://msdn.microsoft.com/en-us/library/system.data.common.dbconnection.getschema.aspx). In a perfect world, I could only use this, but I failed to see how so far... The thing is that you need a valid name for your parameter (`"@name"` in Sql Server, `"name"` in Oracle), and a valid placeholder in your SQL query (`"@name"` in Sql Server, `":name"` in Oracle). 1. With a proper connection, [`GetParameterName`](http://msdn.microsoft.com/en-us/library/system.data.common.dbcommandbuilder.getparametername.aspx) will give you a valid name for your parameter. 2. Create your placeholder : * Either via [`GetParameterPlaceholder`](http://msdn.microsoft.com/en-us/library/system.data.common.dbcommandbuilder.getparameterplaceholder.aspx). * Or query the [`DbMetaDataColumnNames.ParameterMarkerFormat`](http://msdn.microsoft.com/en-us/library/system.data.common.dbmetadatacolumnnames.parametermarkerformat.aspx) value contained in [the schema for your connection](http://msdn.microsoft.com/en-us/library/ms254501.aspx) . You should be able to create your placeholder by using this string as a format string, taking the previous parameter name as input (implying that the format string is `"{0}"` for Sql Server and `":{0}"` for Oracle) : ``` // DbConnection connection; // string parameterName DataRow schema=connection.GetSchema(DbMetaDataCollectionNames.DataSourceInformation).Rows[0]; string placeholder=string.Format( CultureInfo.InvariantCulture, (string)schema[DbMetaDataColumnNames.ParameterMarkerFormat], name.Substring(0, Math.Min(parameterName.Length, (int)schema[DbMetaDataColumnNames.ParameterNameMaxLength])) ); ``` This has been tested with Sql Server, Access, Sqlite and Oracle (but note that, quite unsurprisingly, [this will not work as is with ODP .NET](http://forums.oracle.com/forums/thread.jspa?forumID=146&threadID=423300)...).
Seems there's no convention or API for this. ORMs such as nhibernate also implements their own mapping of the placeholder prefix for each driver.
Parameter naming using System.Data.Common
[ "", "c#", "database", "" ]
I'm sure this is a Noob question, but I've never worked with WPF before. Is MVVM an alternative to Expression Blend?
No. They are completely different concepts. Expression Blend is software for creating interfaces - it's a designer's tool for working with WPF. MVVM is a design pattern - it's an architecture you can use to make your WPF application clean and easily maintainable. You are perfectly capable of using Blend together with MVVM - in fact, this is one of the benefits MVVM provides (it makes it very easy to keep the UI design separate from the programming).
No; MVVM is a design pattern while Expression Blend is a program. See: <http://en.wikipedia.org/wiki/MVVM> <http://en.wikipedia.org/wiki/Expression_Blend> <http://www.google.com/> Blend actually creates code that can be used as MVVM
Is MVVM an alternative to Expression Blend?
[ "", "c#", "wpf", "mvvm", "expression-blend", "" ]
How can I set ini settings within a PHP script? php.ini isn't being read and ini\_set doesn't work. Test File: ``` #!usr/local/bin/php -q <?php // display_errors is set to false in /etc/php.ini // This shouldn't display any errors $test = $foo; // We can also try ini_set('display_errors', false); // This definitely shouldn't display an error $test = $fum; ?> ``` Output: ``` PHP Notice: Undefined variable: foo in /data/home/___/test.php on line 7 PHP Notice: Undefined variable: fum in /data/home/___/test.php on line 13 ```
The [`-c` option](http://www.php.net/manual/en/features.commandline.php) allows to specify the php.ini file that should be used.
Try setting error reporting using `error_reporing()` function ``` error_reporting(0); ```
How can I change PHP ini settings from within a shell script?
[ "", "php", "linux", "configuration", "" ]
I need to use a function's/functor's returned value without knowing what type it is (that is, as a template). While I could pass it over to a second function without a problem: ``` template <typename T> void DoSomething(T value); ... DoSomething(FunctionWhoseReturnedTypeIsUnknown(...)); ``` I want to use the returned value inline (without the need to call a second function): ``` WhatGoesHere? x=FunctionWhoseReturnedTypeIsUnknown(...); ``` The two methods seem conceptually identical to me (generic-programming-wize), but can the latter be achived in C++?
Not yet. In C++0X you'll be able to use `auto` as `WhatGoesHere`. There is already experimental support for this in some compilers (gcc 4.4 for instance).
Until the auto keyword makes it really trivial, one can rely on the convention that function objects provide certain typedef's, including result\_type. One just needs to wrap a plain function into a function object. The standard "functional" header provides some (pointer\_to\_unary\_function/pointer\_to\_binary\_function in addition to a couple of member function wrappers). When these are not enough, boost library provides more powerful wrappers. ``` #include <iostream> #include <boost/function.hpp> #include <boost/bind.hpp> int answer() { return 42; } template <class T> T unknown() { return T(); } template <class Function> void foobar(Function unknown) { typename Function::result_type x = unknown(); std::cout << x << '\n'; } int main() { foobar(boost::function<int()>(answer)); foobar(boost::bind(unknown<int>)); } ``` And below's an example, how you might add a pointer\_to\_zeronary\_function. (I suppose the helper function that helps you create one, ptr\_fun, might be added to the standard namespace as well as an overload(?) ``` template <class T> class pointer_to_zeronary_function { typedef T(*zeronary_func)(); zeronary_func func; public: typedef T result_type; pointer_to_zeronary_function(zeronary_func f): func(f) {} T operator()() const { return func(); } }; template <class T> pointer_to_zeronary_function<T> ptr_fun(T(*f)()) { return pointer_to_zeronary_function<T>(f); } ... //usage: foobar(ptr_fun(answer)); ```
Inferring the return type of a function or functor in C++
[ "", "c++", "generic-programming", "" ]
In .NET what is the difference between: * `Environment.CurrentDirectory` * `Directory.GetCurrentDirectory()`? Of course, `Environment.CurrentDirectory` is a property which can be set and obtained. Are there any other differences?
As David says: they do the same thing. Internally, when getting `Environment.CurrentDirectory` it will call `Directory.GetCurrentDirectory` and when setting `Environment.CurrentDirectory` it will call `Directory.SetCurrentDirectory`. Just pick a favorite and go with it.
As per other answers, there is no difference - the implemenetation of `Environment.CurrentDirectory` delegates to the `Get` and `Set` methods in `Directory`. There's an interesting stylistic API-design question that raises - why did the designers of `Environment` feel that a regular property was appropriate, whereas the designers of `Directory` preferred explicit `Get` and `Set` methods? The Framework Design Guidelines book has a fair amount to say about choosing properties versus methods, some of which is [available online](http://msdn.microsoft.com/en-us/library/ms229054(v=vs.100).aspx). The most relevant parts seem to me to be (with my emphases): > A rule of thumb is that methods should > represent actions and properties > should represent data. *Properties are > preferred over methods **if everything > else is equal*** > > ... > > * CONSIDER using a property, if the member represents a logical attribute > of the type > > ... > > * DO use a method, rather than a property, in the following situations: > + The operation is orders of magnitude slower than a field access > would be All things considered my opinion is that explicit `Get` and `Set` **methods** better represent what is going on here.
What is the difference between Environment.CurrentDirectory and Directory.GetCurrentDirectory?
[ "", "c#", ".net", "" ]
`ArrayList` declares that it implements the `IList`, `ICollection`, and `IEnumeralbe` interfaces. Why not only implement `IList`, because `IList` is also derived from `ICollection`, and `ICollection` is derived from `IEnumerable`. What's the purpose of this kind of declaration? There are many cases like this in .NET BCL.
With the following code: ``` interface I1 { } interface I2 : I1 { } class Foo: I2 { } ``` If you look at Foo through reflection you will find ``` class Foo: I2, I1 { } ``` Which is also valid to compile and gives the same result. So the difference is moot, and in documenting Foo you might as well write it with both interfaces. Also see the SO question: [Why collections classes in C# (like ArrayList) inherit from multiple interfaces if one of these interfaces inherits from the remaining?](https://stackoverflow.com/questions/1023375/why-collections-classes-in-c-like-arraylist-inherit-from-multiple-interfaces-i)
There is no effective difference. I believe the extra declarations are there for clarity. When checked in Reflector, classes which in code implement `IList` have the same interface declaration list as classes which in code declare implementing all of `Ilist`, `ICollection` and `IEnumerable`.
Why ArrayList implement IList, ICollection, IEnumerable?
[ "", "c#", "interface", "" ]
Was wondering if anyone knows a good alternative to tinymce? I find that it sometimes has problems with AJAX infused content. And I've noticed that it seems a little slow when loading - I first see the textarea with the HTML-Markup and then it flashes and then I see the tiny interface. wmd and markitup are not exactly what I am looking for - they are too rudimentary. Is there any other good lightweight Javascript WYSIWYG Editor out there? Thanks Casper
peirix's comment was helpful. Tried a couple of the suggested ones and apparently Tiny or FCK are the best of the crop. --EDIT-- I found and liked: <http://markitup.jaysalvat.com/> --EDIT 2012-- I have now moved back to a minimal/light weight tinyMCE installation using jQuery.
What about [FCKeditor](http://www.fckeditor.net/)?
Alternative to Tiny MCE
[ "", "javascript", "tinymce", "wysiwyg", "" ]
I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works? Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.
Thanks to @jessenoller on Twitter I have an answer that fits my needs - you can compile lxml with static dependencies, hence avoiding messing with the libxml2 that ships with OS X. Here's what worked for me: ``` cd /tmp curl -O http://lxml.de/files/lxml-3.6.0.tgz tar -xzvf lxml-3.6.0.tgz cd lxml-3.6.0 python setup.py build --static-deps --libxml2-version=2.7.3 --libxslt-version=1.1.24 sudo python setup.py install ```
This worked for me (10.6.8): ``` sudo env ARCHFLAGS="-arch i386 -arch x86_64" easy_install lxml ```
How do you install lxml on OS X Leopard without using MacPorts or Fink?
[ "", "python", "macos", "shell", "lxml", "osx-leopard", "" ]
The Java Swing GUI that I'm developing needs to plot a 2D graph based on the x and y coordinates generated in the program. Is there a Swing component for that? Or is there any other open source package for the purpose?
You should check out [JFreeChart](http://www.jfree.org/jfreechart/) which has Swing support. Here are some samples: <http://www.jfree.org/jfreechart/samples.html>
You should look at [JFreeChart](http://www.jfree.org/jfreechart).
Plot Graphs in Java
[ "", "java", "user-interface", "swing", "graph", "plot", "" ]
I'm making a form (html & php) which is part of an admin section used to edit content for a website. I want to allow users to include some basic html. This works fine. I want to retain line breaks. This also works. My problem is that when someone writes something like this: ``` <ul> <li>item one</li> <li>item two</li> </ul> ``` the line breaks between the lines of code are retained and turned into BRs when written out. This means that there's double spacing between each LI element. Now this can be fixed by writing the whole list section on one line but a) that makes it confusing to read and b) it's hard enough teaching people to use the codes let alone explaining extraineous line breaks. What I want is some way to strip all /n out but ONLY between UL and /UL tags.
This regular expression removes all linebreaks/whitespaces between `<ul>` and `</ul>` that are not part of the text between `<li>` and `</li>` ``` /(?<=<ul>|<\/li>)\s*?(?=<\/ul>|<li>)/is ``` php example: ``` $output = preg_replace('/(?<=<ul>|<\/li>)\s*?(?=<\/ul>|<li>)/is', '', $input); ``` input: ``` <ul> <li>item one</li> <li>item two</li> </ul> ``` output: ``` <ul><li>item one</li><li>item two</li></ul> ``` **EDIT: fixed**
You might be able to get away with using a regular expression, although this will fail if the HTML is not well formed. This should match everything within HTML tags, because the regex is greedy by default. ``` <?php $str = "Hello <ul> <li>item one</li> <li>item two</li> </ul>"; $str = preg_replace_callback('~\<[^>]+\>.*\</[^>]+\>~ms','stripNewLines', $str); function stripNewLines($match) { return str_replace(array("\r", "\n"), '', $match[0]); } echo nl2br($str); ``` **Edit** Actually, this won't work. If there are two blocks of HTML with normal text in between, the text in the middle will also be stripped.
Remove line breaks from between html tags
[ "", "php", "html", "" ]
I am using accordion menu on an e-commerce site. The menu stays open with the options until the product page. On that page I am trying to use the breadcrumbs to match text in the menu and then apply a class to open the menu to the correct category for the page. Here is my code: ``` $(document).ready(function(){ var bctext = $('#ProductBreadcrumb ul li:last-child').prev('li').children().text(); $('ul#accordion a:contains(bctext)').parent().parent().addClass('special'); }); ``` The variable returns the correct text, and if I put a matching string ("Tomato Sauces") in the `:contains` it works just like I want it to and applies the class. However when I use bctext variable it wont work. I also tried `a:contains($(bctext))` and it didn't work. Is it my syntax? Thanks
Try: ``` $('ul#accordion a:contains(' + bctext + ')') ```
You could use [Traversing/contains](http://docs.jquery.com/Traversing/contains) also: ``` $('ul#accordion a').contains(bctext); ```
using a variable in :contains - how to
[ "", "javascript", "jquery", "jquery-plugins", "" ]
**Which of the following ways is the right one in using the characters " and ' inside PHP's sub-arrays?** ## #1 Way in debugging PHP code ``` $_POST["login['username']"]; ``` ## #2 My original way in PHP ``` $_POST['login[username]']; ``` My code is now broken after changing all my variables to arrays. --- The following is the HTML to which the variables refer. ``` <p>Username: <input name="login['username']" type="text" cols="92" /> </p> <p>Email: <input name="login['email']" type="text" cols="92" /> </p> <p>Password: <input name="login['password']" type="password" cols="92" /> </p> <input type="submit" value="OK" /> </form> ``` **Which one is the right way of the following ways in using arrays in HTML.** ## #11 ``` <input name="login['password']" type="password" cols="92" /> ``` ## #22 ``` <input name="login[password]" type="password" cols="92" /> ``` **I am at the moment using the ways #1 and #11 unsuccessfully?**
First of all, the correct form in html is what you have for #22 (no quotes). Secondly, the entire point of doing this is because it will convert it into an array. When this form is posted, an array is created INSIDE of $\_POST called login. To access it, try this: ``` echo $_POST['login']['username']; //echos username echo $_POST['login']['password']; //echos password ``` Here's a quick overview of how the nesting looks: ``` '_POST' => array 'login' => array 'username' => string 'myusername' (length=10) 'password' => string 'mysecretpassword' (length=16) ``` Try doing this to get a good idea of what's going on and get output like above: ``` echo "<pre>"; var_dump($_POST); echo "</pre>"; ``` You'll be able to see all the nesting.
You don't need to quote the array keys in HTML, this is correct: ``` <input name="login[password]" type="password" cols="92" /> ``` This will create in $\_POST a key 'login' whose value is another array having the key 'password', so you can access it like: ``` $_POST['login']['password'] ```
What is the right way of usig " and ' inside sub-arrays in PHP and HTML?
[ "", "php", "html", "arrays", "" ]
Hi I am a newbie in SQL and require help I have a parameterized stored procedure which contains a Update query like... ``` UPDATE sometable SET price1 = @param1, price2 = @param2, price3 = @param3, price4 = @param4, WHERE ID = @param5 ``` Now when I execute this SP by setting any of the parameters value as NULL it gets updated in DB, what I want to know is if one of the parameters value is NULL then can we retain that columns original value in DB instead of updating it with NULL.
In SQLServer the tidy way is to use [ISNULL(@param1, price1)](http://msdn.microsoft.com/en-us/library/ms184325.aspx). This takes @param1 and checks if it is NULL. If it is NULL it is replaced with the value from price1. I like [ISNULL](http://msdn.microsoft.com/en-us/library/ms184325.aspx) as it's very readable, does what it says on the tin. It's not ANSI SQL though, with a more flexible command existing there: [COALESCE](http://msdn.microsoft.com/en-us/library/ms190349.aspx). It's just like [ISNULL](http://msdn.microsoft.com/en-us/library/ms184325.aspx), but takes any number of parameters. It searches through them in order for the first non-NULL value. If none are found, NULL is returned... ``` UPDATE sometable SET price1 = ISNULL(@param1, price1), price2 = ISNULL(@param2, price2), price3 = ISNULL(@param3, price3), price4 = ISNULL(@param4, price4) WHERE ID = @param5 ``` ``` UPDATE sometable SET price1 = COALESCE(@param1, price1), price2 = COALESCE(@param2, price2), price3 = COALESCE(@param3, price3), price4 = COALESCE(@param4, price4) WHERE ID = @param5 ``` Also see: "[COALESCE vs ISNULL](http://databases.aspfaq.com/database/coalesce-vs-isnull-sql.html)"
Try wrapping the @paramx with a CASE statement: CASE @paramx WHEN NULL THEN pricex ELSE @paramx END
Retain original value in DataBase when NULL value is passed to Stored Procedure
[ "", "sql", "" ]
I have some large files (from several gigabytes to hundreds of gigabytes) that I'm searching and trying to find every occurrence of a given string. I've been looking into making this operate in parallel and have some questions. 1. How should I be doing this? I can't copy the entire file into memory since its too big. Will multiple FILE\* pointers work? 2. How many threads can I put on the file before the disk bandwidth becomes a limiting factor, rather than the CPU? How can I work around this? Currently, what I was thinking is I would use 4 threads, task each with a FILE\* at either 0%, 25%, 50%, and 75% way through the file, and have each save its results to a file or memory, and then collect the results as a final step. Though with this approach, depending on bandwidth, I could easily add more threads and possibly get a bigger speedup. What do you think? EDIT: When I said memory bandwidth, I actually meant disk I/O. Sorry about that.
With this new revised version of the question, the answer is "almost immediately". Hard disks aren't very good at reading from two places on the disk at the same time. :) If you had multiple hard drives and split your file across them, you could probably take advantage of some threading. To be fair, though, I would say that the disk speed is *already* the limiting factor. I highly doubt that your disk can read data faster than the processor can handle it.
I doubt memory bandwidth will be as big of a problem as disk IO limitations. With most hardware, you're going to be very restricted on how each thread can read from disk - If you want to maximize throughput, you may need to do something like have one thread who's job is to handle disk IO (most hardware can only stream one chunk from disk at a time, so that'll be a limiting factor). It can then take this and push off chunks of memory to individual threads in some type of thread pool to process. My guess is that your processing will be fast - probably much faster than the disk IO - but if it's slow, having multiple processing threads could speed up your entire operation. Multiple FILE\* pointers will work - but may actually be slower than just having a single one, since they'll end up time slicing to read the file, and you'll be jumping around on your disk more.
When doing a parallel search, when will memory bandwidth become the limiting factor?
[ "", "c++", "c", "file-io", "" ]
Could any one please give me pointers as to how one can add text to images dynamically. For example a person fills up text form and selects an image . Then after clicking the submit button the text input by the visitor gets added to the image. To understand it better please check : <http://www.vistaprint.com/> . In this site this has been achieved without using flash. Any pointers on how to achieve this would be greatly appreciated. THanks PS: Another site which does something similar eyebuydirect.com/eyetry.php
There are plenty of options, depending on which technology you have available, and what you want to do with the image once it has been generated. My recommendation is to generate the image using server-side technology. For example, if you have .NET available you could use the System.Drawing classes to create the image. Other solutions include CSS positioning, Flash, or SVG, none of which would required server-side technology, but may limit the subsequent use of the image.
in <http://www.vistaprint.com/> they just submit Ajax request on <http://www.vistaprint.com/vp/ns/studiotext.aspx> and it returns compiled image. This image just a rendered text they position absolutely inside card. Depending on what do you want SVG/VML([raphael](http://raphaeljs.com/) for cross browser) could be taken in consideration. This will allow render image without server requests.
How to add custom text input to images dynamically
[ "", "javascript", "html", "ajax", "image", "" ]
I have a large, growing OSGi application with a number of bundles. I am curious to know the best way to manage this type of application. Currently, I am using Eclipse and Maven, but although this is great for building bundles (via maven-bundle-plugin), as of now it has not been easy to manage the entire application. What I would like to do is either have ONE run configuration or ONE pom.xml that can be launched and the entire application/project be built and launched. Also, I would like to have something that would be good for debugging. I have heard of PAX Construct and have it installed in Eclipse, but so far it has been of little help (maybe I'm not using it correctly). I am sure there are people out there with large OSGi applications that are being managed correctly. Any advice that could be shared would help tremendously. Thank you, Stephen
A run configuration is possible via [Pax Runner](http://paxrunner.ops4j.org/space/Pax+Runner). It lets you choose OSGi platform implementation, specify profiles (pre-packaged sets of bundles for some role, e.g. `web`, `log`, `ds`, etc.) and has good provisioning support, for instance it can load bundles from Maven repository. As a result, you can have a run configuration like ``` --platform=felix --log=INFO --profiles=scalamodules,ds,config,log mvn:com.my/bundle/1.0.1-SNAPSHOT@update # other bundles ``` In case your application is very large or you have different applications, there a way to create own profiles as well.
Well... It all deopends on what do You mean by "managing" the application. For dev time launching, building and debugging - Eclipse IDE should fit the bill just perfectly. Maven... I can't speak for it, as I've never used it myself. We have a pretty large eclipse based application (several, actually) and on the dev side of things we are not using anything special besides the Eclipse and it's integrated SCM. In the cc build server, we also use headless eclipse to do the building and packaging. Now the setup of the workspace has gone a bit out of hand of late with all the dependencies and intermediate build steps, so we are investigating [Buckminster](http://www.eclipse.org/buckminster/) for managing the materialization of target platform and workspace resources. If that works out, we'll probably move to building with Bucky as well - it sure looks promising. (I do not have any experience with PAX, but at a glance, it looks promising as well...)
Managing a Large OSGi Application
[ "", "java", "eclipse", "maven-2", "osgi", "" ]
I am new to c#. I need to write a method that takes a log file created by a compilation output and figures out the number of errors and warnings. I need to scan each line of the log and find the following match: x error(s), y warning(s) Examples of this patterns are: ``` Compile complete -- 1 errors, 213 warnings 6>Process_Math - 3 error(s), 1 warning(s) 24>Process_Math - 1 error(s), 0 warning(s) ``` How can I write the algorithm that finds that pattern and extract x and y from the line? Thanks Tony
``` int errors = 0; int warnings = 0; Regex regexObj = new Regex(@"(?<errors>\d+) error\(s\), (?<warnings>\d+) warning\(s\)", RegexOptions.Multiline); Match matchResults = regexObj.Match(input); while (matchResults.Success) { errors = errors + Convert.ToInt16(matchResults.Groups["errors"].Value); warnings = warnings + Convert.ToInt16(matchResults.Groups["warnings"].Value); matchResults = matchResults.NextMatch; } ```
Here is a small example: ``` using System; using System.Text.RegularExpressions; class Program { static void Main() { String input = @"Compile complete -- 1 errors, 213 warnings 6>Process_Math - 3 error(s), 1 warning(s) 24>Process_Math - 1 error(s), 0 warning(s)"; Regex regex = new Regex(@"(\d+)\serrors?,\s(\d+)\swarnings?", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Multiline); Match match = regex.Match(input); if (match.Success) { Console.WriteLine("errors: " + match.Groups[1].Value); Console.WriteLine("warnings: " + match.Groups[2].Value); } } } ``` This will grab the errors and warnings from the *first* line, not the subsequent ones. Here is a commented version of the regular expression to help explain how it works: ``` (\d+) # capture any digit, one or more times \s # match a single whitespace character errors?, # match the string "error" or "errors" followed by a comma \s # match a single whitespace character (\d+) # capture any digit, one or more times \s # match a single whitespace character warnings? # match the string "warning" or "warnings" ```
Regular expression to find warnings and errors in compiler output
[ "", "c#", "regex", "" ]
I want to check the current color depth of the OS to warn users if they try to run my application with a "wrong" color depth (using c++ & Qt). I guess there's a win api call to get this information, but I couldn't find anything.
On Windows you could use `GetDeviceCaps` with the `BITSPIXEL` flag but you'll need a screen DC first (`GetDC` could fetch you one). ``` HDC dc = GetDC(NULL); int bitsPerPixel = GetDeviceCaps(dc, BITSPIXEL); ReleaseDC(NULL, dc); ```
You can do it using WMI. ``` int bitDepth = -1; hr = CoInitializeEx( NULL, COINIT_MULTITHREADED ); if ( SUCCEEDED( hr ) ) { // hr = CoInitializeSecurity( NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL ); if ( SUCCEEDED( hr ) ) { IWbemLocator* pLoc = NULL; hr = CoCreateInstance( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (void**)&pLoc ); if ( SUCCEEDED( hr ) ) { IWbemServices* pSvc = NULL; hr = pLoc->ConnectServer( BSTR( L"ROOT\\CIMV2" ), NULL, NULL, 0, NULL, 0, 0, &pSvc ); if ( SUCCEEDED( hr ) ) { hr = CoSetProxyBlanket( pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE ); if ( SUCCEEDED( hr ) ) { IEnumWbemClassObject* pEnumerator = NULL; hr = pSvc->ExecQuery( L"WQL", L"SELECT * FROM Win32_DisplayConfiguration", WBEM_FLAG_FORWARD_ONLY/* | WBEM_FLAG_RETURN_IMMEDIATELY*/, NULL, &pEnumerator ); if ( SUCCEEDED( hr ) ) { IWbemClassObject* pDisplayObject = NULL; ULONG numReturned = 0; hr = pEnumerator->Next( WBEM_INFINITE, 1, &pDisplayObject, &numReturned ); if ( numReturned != 0 ) { VARIANT vtProp; pDisplayObject->Get( L"BitsPerPel", 0, &vtProp, 0, 0 ); bitDepth = vtProp.uintVal; } } pEnumerator->Release(); } } pSvc->Release(); } pLoc->Release(); } } // bitDepth wshould now contain the bitDepth or -1 if it failed for some reason. ```
How can I find out the current color depth of a machine running vista/w7?
[ "", "c++", "windows", "colors", "settings", "" ]
For any given site "example.domain.tld" or merely "domain.tld" I need to do the following in PHP: * If the site has a favicon, get it wherever it is + If it is not already a PNG, convert it to PNG + Save it to /favicons/example.domain.tld.png * If the site has no favicon, do nothing. Any ideas? I'm being stumped by the unreliable fileformat and location of the favicons, but if at all possible I want to avoid downloading the entire source of the page with file\_get\_contents in order to find it in the headers. Also converting to png seems nontrivial. Thanks, Mala
As is typical, I found a passable solution shortly after asking the question - let google do the work for you: <http://www.google.com/s2/favicons?domain=URL> returns a 16x16 png
Found this: <http://www.controlstyle.com/articles/programming/text/php-favicon/> I'm about to try it for my project and I'll report back and tell you if it works! Cheers Iain
PHP - getting a site's favicon and converting it to png if necessary
[ "", "php", "image-processing", "png", "favicon", "" ]
Need Some Help With Regex: I want to replace ``` [url=http://youtube.com]YouTube.com[/url] ``` with ``` <a href="http://youtube.com">YouTube.com</a> ``` the regex ``` preg_replace("/[url=(.*?)](.*?)[/url]/is", '<a href="$1">$2</a>', $text); ``` why does this give me: *Warning: preg\_replace() [function.preg-replace]: Unknown modifier 'r' in C:\Programa\wamp\www\func.php on line 18*
You should escape special characters in your regular expression: ``` preg_replace('/\[url=(.*?)](.*?)\[\/url]/is', '<a href="$1">$2</a>', $text); ``` I have escaped the `[` characters (they specify the start of a character class) and the `/` character (it specifies the boundaries of the regular expression.) Alternatively (for the `/` character) you can use another boundary character: ``` preg_replace('#\[url=(.*?)](.*?)\[/url]#is', '<a href="$1">$2</a>', $text); ``` You still have to escape the `[` characters, though.
PHP is interpreting the '`/`' in `/url` as being the end of the regex and the start of the regex options. Insert a '`\`' before it to make it a literal '`/`'. You need to escape the '`[`'s in the same way (otherwise they will be interpreted as introducing a character class). ``` preg_replace("/\[url=(.*?)](.*?)\[\/url]/is", '<a href="$1">$2</a>', $text); ```
Why does this PHP regex give me error?
[ "", "php", "regex", "" ]
i think i am not going about this quite right, being very new to jquery. i have a page with 3 recipes on it hidden. when a link to recipe A is clicked it opens in a modal. i want to be able to print just the content of the recipe. so i am opening a new window (nonmodal) and trying to write the recipe to it (depending on which recipe is chosen) this is the code i am using ``` $('a.new-window').click(function(){ var recipe = window.open('','RecipeWindow','width=600,height=600'); $('#recipe1').clone().appendTo('#myprintrecipe'); var html = "<html><head><title>Print Your Recipe</title></head><body><div id="myprintrecipe"></div></body></html>"; recipe.document.open(); recipe.document.write(html); recipe.document.close(); return false; }); ``` but it returns an error. i think it is close but not quite right. the error is: missing ; before statement [Break on this error] var html = "Print...="myprintrecipe">";\n
I think what you are looking for is the following: ``` jQuery(function($) { $('a.new-window').click(function(){ var recipe = window.open('','RecipeWindow','width=600,height=600'); var html = '<html><head><title>Print Your Recipe</title></head><body><div id="myprintrecipe">' + $('<div />').append($('#recipe1').clone()).html() + '</div></body></html>'; recipe.document.open(); recipe.document.write(html); recipe.document.close(); return false; }); }); ``` Marius had a partially correct answer - you did have a javascript error in your html string, but the content wouldn't have been appended anyways even if the error didn't get thrown because you were trying to append the recipe before the #myprintrecipe div was even in the new window. Hope this helps.
The problem is in your string. Change it to this: ``` $('a.new-window').click(function(){ var recipe = window.open('','RecipeWindow','width=600,height=600'); $('#recipe1').clone().appendTo('#myprintrecipe'); var html = "<html><head><title>Print Your Recipe</title></head><body><div id=\"myprintrecipe\"></div></body></html>"; recipe.document.open(); recipe.document.write(html); recipe.document.close(); return false; }); ``` The problem is that you had a " character inside the string, which ends the string. The script engine got confused and complained with the error message.
New window with content from modal content on opener page
[ "", "javascript", "jquery", "" ]
I get some informations in a Dataset, and i would like to cast it in a strongly type object. For example my dataset have : TableName : tab\_data Rows : 1 Columns : Name, FirstName, Address So i created a class like : ``` public class Customer { public String Name; public String FirstName; public String Address; } ``` Is there a magic trick to simply cast my dataset to Customer type ? Use LiNQ ? Thanks,
You can't *cast* this, but you can translate the data... The answer is probably different for 1 table than it is for 20; on an individual bases, you should just be able to `Select` out the data (or alternatively, [just iterate](https://stackoverflow.com/questions/441023/fastest-way-to-convert-datatable-to-generic-list)) - this will be the fastest option, but is lots of maintenance if you have lots of tables. In the latter case, some kind of reflection, [perhaps like so](https://stackoverflow.com/questions/545328/datatable-to-generic-list-memory-leak/545429#545429).
Is there any reason you haven't created a strongly-typed DataSet to start with? That would probably be the easiest solution. You can certainly convert each DataTable into (say) a `List<Customer>` using the `AsEnumerable` extension to `DataTable` and a projection which creates a `Customer` from a `DataRow` if you really need to.
How to cast a Dataset into Strongly Type Object?
[ "", "c#", ".net", "asp.net", "ado.net", "dataset", "" ]
## Question The solution below is intended to slide down the ***groupDiv*** displaying ***div1*** and enough space for ***div2*** to slide in. It's all achieved by chaining the animations on the ***#Link.Click()*** element. It seems to ***bug out***, though, when the ***link is clicked rapidly***. Is there a way to prevent this? By perhaps disabling the Click function until the ***chained*** animations are complete? I currently have checks in place, but they don't seem to be doing the job :( Here's the code i'm using: ## Custom animate functions. --- ``` //Slide up or down and fade in or out jQuery.fn.fadeThenSlideToggle = function(speed, easing, callback) { if (this.is(":hidden")) { visibilityCheck("show", counter--); return this.slideDown({duration: 500, easing: "easeInOutCirc"}).animate({opacity: 1},700, "easeInOutCirc", callback); } else { visibilityCheck("hide", counter++); return this.fadeTo(450, 0, "easeInOutCirc").slideUp({duration: 500, easing: "easeInOutCirc", complete: callback}); } }; //Slide off page, or into overflow so it appears hidden. jQuery.fn.slideLeftToggle = function(speed, easing, callback) { if (this.css('marginLeft') == "-595px") { return this.animate({marginLeft: "0"}, speed, easing, callback); } else { return this.animate({marginLeft: "-595px"}, speed, easing, callback); } }; ``` --- ## In the dom ready, i have this: --- ``` $('#Link').toggle( function() { if (!$("#div2 .tab").is(':animated')) { $("#GroupDiv").fadeThenSlideToggle(700, "easeInOutCirc", function() {$('#div2 .tab').slideLeftToggle();}); } }, function(){ if (!$("#groupDiv").is(':animated')) { $('#div2 .tab').slideLeftToggle(function() {$("#groupDiv").fadeThenSlideToggle(700, "easeInOutCirc", callback);} ); } } ); ``` --- ## HTML structure is this: --- ``` <div id="groupDiv"> <div id="div1"> <div class="tab"></div> </div> <div id="div2"> <div class="tab"></div> </div> </div> ```
The issue is your first animating the div#GroupDiv so your initial check `if (!$("#div2 .tab").is(':animated'))` will be false until the groupDiv has finished animated and the callback is fired. You could maybe try ``` if (!$("#div2 .tab").is(':animated') && !$("#GroupDiv").is(':animated')) ``` however I doubt this will cover really quick clicking. The safest is to unbind the event using `$(this).unbind('toggle').unbind('click');` as the first line inside the if and you can then do away with the animated check. The downside to this is you will have to rebind using the callback you are passing through to your custom animation functions.
You can easily disable your links while animation is running ``` $('a').click(function () { if ($(':animated').length) { return false; } }); ``` You can of course replace the `$('a')` selector to match only some of the links.
jQuery - Disable Click until all chained animations are complete
[ "", "javascript", "jquery", "" ]
I would like to get all form elements that don't have a specific CSS class. Example: ``` <form> <div> <input type="text" class="good"/> <input type="text" class="good"/> <input type="text" class="bad"/> </div> </form> ``` What selector should I use to select all elements that don't have 'bad' css class? Thank you.
You can use the not() filter: ``` $("input").not(".bad") ```
You can also use the [not selector](http://docs.jquery.com/Selectors/not): ``` $('input:not(".bad")').hide(); ``` Note the quotes are not needed: ``` $('input:not(.bad)').hide(); ``` See: <http://docs.jquery.com/Selectors/not>
How to find all elements that DON'T have specific CSS class in jQuery?
[ "", "javascript", "jquery", "" ]
Hi i've got 2 data tables (bannedlist,countrylist), both contains list of country names and cods in columns cc and country. I am trying to do a query where i can select countries from countrylist table that are not in bannedlist table in order to create a 3rd table. Any ideas? I haven't got too far with this. ``` var ccList = ds.Tables[2].AsEnumerable(); var bannedCCList = ds.Tables[1].AsEnumerable(); var query = from r in ccList.... ``` .. after trying ``` var bannedCCList = ds.Tables[1].AsEnumerable(); var query = from r in ccList where !bannedCCList.Any(b => b["cc"] == r["cc"])select r; ``` i still get same country list. banned ones haven't been removed. here is more detail in order to explain more. not sure what i am doing wrong ``` protected void BindCountryBan(string subd) { DataSet ds = new DataSet(); ds = new DB().CountryBan_GetSiteSettings(); BannedCountryListBox.DataSource = ds.Tables[1]; BannedCountryListBox.DataValueField = "cc"; BannedCountryListBox.DataTextField = "country"; BannedCountryListBox.DataBind(); //bind country list var ccList = ds.Tables[2].AsEnumerable(); var bannedCCList = ds.Tables[1].AsEnumerable(); var query = from r in ccList where !bannedCCList.Any(b => b["cc"] == r["cc"])select r; //var query = ccList.Except(bannedCCList); //CountryListBox.DataSource = ds.Tables[2]; DataTable boundTable = query.CopyToDataTable<DataRow>(); CountryListBox.DataSource = boundTable; CountryListBox.DataValueField = "cc"; CountryListBox.DataTextField = "country"; CountryListBox.DataBind(); } ```
Except would work if you use it on sequences of the countries: ``` using System.Linq; ... var ccList = from c in ds.Tables[2].AsEnumerable() select c.Field<string>("Country"); var bannedCCList = from c in ds.Tables[1].AsEnumerable() select c.Field<string>("Country"); var exceptBanned = ccList.Except(bannedCCList); ``` If you need the full rows where the countries aren't banned, you could try a left outer join: ``` var ccList = ds.Tables[2].AsEnumerable(); var bannedCCList = ds.Tables[1].AsEnumerable(); var exceptBanned = from c in ccList join b in bannedCCList on c.Field<string>("Country") equals b.Field<string>("Country") into j from x in j.DefaultIfEmpty() where x == null select c; ```
You can use the Except() LINQ extension method like this: ``` var result = full.Except(banned); ``` However this will work fine with the default comparer of the contained type. Thus if you want to use a specific column like in your example, you might need another approach like: ``` from r in ccList where !bannedCCList.Any(b => b["cc"] == r["cc"]) select r; ``` Using Except() implies the references are the same in both collections, which I think is not the case with Tables, or correct me if I'm wrong.
Linq not in select on datatable
[ "", "c#", "linq", "datatable", "" ]
I need to ensure that, once the execution hits a method, the control received by this method is not changed by another thread. Basically, I thought in something like this: ``` private void doSomeWork(Control control) { lock (control) { // do some stuff with the control... } } ``` Is this a bad idea? **Edit:** Actually, what I'm trying to do, is to ensure that the control will not disposed by another thread while I execute some of the control's methods (which, by the way, will be executed via reflection).
In a well behaving application, windows forms controls are already restricted to only one thread. If any thread tries to access a control created in a different thread, an exception will be thrown. There is nothing wrong about your code, just know that right now it's *mostly* useless unless you are hacking your way through the protection (which is possible). Usually, when you have data being created or manipulated in a working thread, the working thread will send an event to the UI thread to update the UI. In no way should a working thread updates the UI itself, it will automatically fail.
Actually Fernando, it's not a bad idea but it's not the correct way to look at locking. You need to closely read what the lock statement does in .Net: <http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.80).aspx> i think that from your statement you expect the whole object to be locked, or somehow be made safe for threading, because the object iteself is used in a locked block of code. What actually happens is that block of code is locked and not allowed to be executed by two or more threads at the same time. If that block of code is the only place you're going to be operating on the control then you're ok, otherwise you'll need to do synch locks on the object itself.
Lock a winforms control
[ "", "c#", "winforms", "controls", "thread-safety", "locking", "" ]
Resource files seem great for localization of labels and messages, but are they perfect? For example: 1. Is there a better solution if there is a huge amount of resources? Like 100,000 strings in a .resx file? (Theoretically, I do not actually have this problem) 2. Is this a good method for storing the other types of data, such as images, icons, audio files, regular files, etc.? 3. Is it a best practice to store your .resx files in a stand-alone project for easier updates/compiling? 4. Are there any other issues that you have run into when using .resx files?
>  1. Is there a better solution if there is a huge amount of resources? Like 100,000 strings in a .resx file? (Theoretically, I do not actually have this problem) I've used Alfresco as an alternative content repository on Java projects. RESX files, from a maintaince standpoint (because of encoding issues I guess) can really stink. >  2. Is this a good method for storing the other types of data, such as images, icons, audio files, regular files, etc.? I've seen it work with images...but that's it. (not sure with other media/files) >  3. Is it a best practice to store your .resx files in a stand-alone project for easier updates/compiling? I don't, but you can edit a resx file on a live site and then edit will go through, I believe. Certainly that's the way it works in development (except for the global resx, I think) >  4. Are there any other issues that you have run into when using .resx files? Besides being really annoying to maintain, and the fact that visual studio doesn't provide the neatest tools for working with them...no.
I recently used a .resx file with 5 million strings (normal length, like this sentence), compiled in different DLLS about 1 GB in size. It still works fine in an Azure web project. The load time is unknown, maybe few seconds or so, since it always can heat up in stages, I never noticed it.
Are there any performance issues or caveats with resource (.resx) files?
[ "", "c#", "asp.net", "resources", "resx", "resource-files", "" ]
I use a panel in c# winforms and fill the panel with the no of picture box using loop For example, panel name is panal ``` foreach (string s in fileNames) { PictureBox pbox = new new PictureBox(); pBox.Image = Image.FromFile(s); pbox.Location = new point(10,15); . . . . this.panal.Controls.Add(pBox); } ``` now I want to change the location of picturebox in another method. The problem is that how can now I access the pictureboxes so that I change the location of them. I try to use the following but it is not the success. ``` foreach (Control p in panal.Controls) if (p.GetType == PictureBox) p.Location.X = 50; ``` But there is an error. The error is: ``` System.Windows.Forms.PictureBox' is a 'type' but is used like a 'variable' ```
There appear to be some typos in this section (and possibly a real error). ``` foreach (Control p in panal.Controls) if (p.GetType == PictureBox.) p.Location.X = 50; ``` The typos are 1. PictureBox is followed by a period (.) 2. GetType is missing the parens (so it isn't called). The error is: * You can't compare the type of *p* to PictureBox, you need to compare it to the type of PictureBox. This should be: ``` foreach (Control p in panal.Controls) if (p.GetType() == typeof(PictureBox)) p.Location = new Point(50, p.Location.Y); ``` Or simply: ``` foreach (Control p in panal.Controls) if (p is PictureBox) p.Location = new Point(50, p.Location.Y); ```
Try this: ``` foreach (Control p in panal.Controls) { if (p is PictureBox) { p.Left = 50; } } ```
How to access controls that is in the panel in c#
[ "", "c#", "winforms", "desktop-application", "" ]
I have a text area and a "add" button on a form. By default the text area is shown as shrinked and grayed out. On focus it will be highlighted by changing the style. On blur it should go back to previous state. Along with highlighting the textarea, add note should toggle as visible and hidden. The problem is when i enter the data in text area and click on the add button, the blur event is hiding the add button and the event on the add button is never triggered.. any solution?? It seems like my question is not clear... The solution is something like execute the blur event except that the next focused element is not the "add" button...
If there is text entered is it safe to assume you don't want to toggle the button because the user has the intention of entering a note? If so you could do something like: ``` $(textBox).blur(function() { if($(this).val().length == 0) { //change the style //hide the button } }) ```
You need to unhighlight your textarea and hide the "add" button **only if there is nothing entered in the textarea**: ``` $('textarea').blur(function() { if($(this).val() != '') { // unhighlight textarea // hide "add" button } }); ``` This way the user always sees the field and button if they actually entered something into it, regardless of whether it has focus or not.
JQuery blur event
[ "", "javascript", "jquery", "events", "" ]
Let's take [Wes Dyer's](http://blogs.msdn.com/wesdyer/archive/2007/01/26/function-memoization.aspx) approach to function memoization as the starting point: ``` public static Func<A, R> Memoize<A, R>(this Func<A, R> f) { var map = new Dictionary<A, R>(); return a => { R value; if (map.TryGetValue(a, out value)) return value; value = f(a); map.Add(a, value); return value; }; } ``` The problem is, when using it from multiple threads, we can get into trouble: ``` Func<int, int> f = ... var f1 = f.Memoize(); ... in thread 1: var y1 = f1(1); in thread 2: var y2 = f1(1); // We may be recalculating f(1) here! ``` Let's try to avoid this. Locking on `map`: ``` public static Func<A, R> Memoize<A, R>(this Func<A, R> f) { var map = new Dictionary<A, R>(); return a => { R value; lock(map) { if (map.TryGetValue(a, out value)) return value; value = f(a); map.Add(a, value); } return value; }; } ``` is clearly a horrible idea, because it prevents us from calculating `f1` on many *different* arguments at once. Locking on `a` won't work if `a` has a value type (and at any rate is a bad idea, since we don't control `a` and outside code may lock on it, too). Here are two options I can think of: Assuming a `Lazy<T>` class for lazy evaluation (see [here](http://msdn.microsoft.com/en-us/vcsharp/bb870976.aspx)): ``` public static Func<A, R> Memoize<A, R>(this Func<A, R> f) { var map = new Dictionary<A, Lazy<R>>(); return a => { Lazy<R> result; lock(map) { if (!map.TryGetValue(a, out result)) { result = () => f(a); map.Add(a, result); } } return result.Value; }; } ``` Or keeping an additional dictionary of objects for synchronization: ``` public static Func<A, R> Memoize<A, R>(this Func<A, R> f) { var map = new Dictionary<A, R>(); var mapSync = new Dictionary<A, object>(); return a => { R value; object sync; lock(mapSync) { if (!mapSync.TryGetValue(a, out sync)) { sync = new object(); mapSync[a] = sync; } } lock(map) { if (map.TryGetValue(a, out value)) return value; } lock(sync) { value = f(a); lock(map) { map[a] = value; } return value; } }; } ``` Any better options?
Use .net 4.0's `ConcurrentDictionary<A, R>` without the unnecessary `Lazy<R>`. The key is `GetOrAdd(A, Func<A, R>)` which renders into a beautifully trivial lambda. ``` public static Func<A, R> Memoize<A, R>(this Func<A, R> f) { var cache = new ConcurrentDictionary<A, R>(); return a => cache.GetOrAdd(a, f); }; ``` **Update** The above solution does allow multiple simultaneous readers & writers with the minimum of overhead. But, it doesn't prevent `f(a)` from being executed more than once for the same value (during the period while it is being calculated). If that is vital to you, you could wrap the value in `Lazy<R>` but you incur a cost for every read. ``` public static Func<A, R> Memoize<A, R>(this Func<A, R> f) { var cache = new ConcurrentDictionary<A, Lazy<R>>(); return a => cache.GetOrAdd(a, new Lazy<R>(() => f(a))).Value; } ``` **Update** Timing tests for a million reads of a pre-populated 1000-item cache show **19ms** for `ConcurrentDictionary` -- same as regular `Dictionary` -- but **720ms** for the `Lazy` version. If that sounds too steep, you can get the best of both worlds with a more complex solution. ``` public static Func<A, R> Memoize<A, R>(this Func<A, R> f) { var cache = new ConcurrentDictionary<A, R>(); var syncMap = new ConcurrentDictionary<A, object>(); return a => { R r; if (!cache.TryGetValue(a, out r)) { var sync = syncMap.GetOrAdd(a, new object()); lock (sync) { r = cache.GetOrAdd(a, f); } syncMap.TryRemove(a, out sync); } return r; }; } ```
If you already have that `Lazy<T>` type, I assume you're using .net 4.0, so you could also use the [`ConcurrentDictionary<A,R>`](http://msdn.microsoft.com/en-us/library/dd287191.aspx): ``` public static Func<A, R> Memoize<A, R>(this Func<A, R> f) { var map = new ConcurrentDictionary<A, Lazy<R>>(); return a => { Lazy<R> lazy = new Lazy<R>(() => f(a), LazyExecutionMode.EnsureSingleThreadSafeExecution); if(!map.TryAdd(a, lazy)) { return map[a].Value; } return lazy.Value; }; } ```
Thread-safe memoization
[ "", "c#", "multithreading", "locking", "thread-safety", "memoization", "" ]
Given a text file, how would I go about reading an arbitrary line and nothing else in the file? Say, I have a file test.txt. How would I go about reading line number 15 in the file? All I've seen is stuff involving storing the entire text file as a String array and then using the value of the line number as the number of the String to use from the array... but there are some complications: The text file is enormously huge and the machine that the application I'm coding isn't exactly a top-notch system. Speed isn't the top priority, but it is definitely a major issue. Are there any ways to **ONLY** read a specific line of a text file and store the result as a string? Thanks for your responses: The file is KINDA structured. It's got 25 lines of info and then *X* lines of numbers but line 17 of the first 25 has the value of *X*. But then, there's 1 blank line and it repeats itself all over as a second record in the file and *X* can have a different value for each record. What I want to do is read and store the first 25 lines as independent values and then store the next *X* (usually around 250) lines as an array. Then I'm going to store it in an SQL database and repeat with the NEXT record until I reach the *Y*th record (the number of records in the file is in line 3) **EDIT 2**: Alright, I think I've gotten to a solution based on a combination of your alls' responses. I'm going to read the first 25 lines and store it as an array. I'll copy the pertinent contents of the array to local variables then I'll delete the first 25 lines. Then, I can use the info to store the next *X* lines (the value of item 13 in the array) as an array, serialize it, store it in a database then delete the lines that I just read. I could then repeat the process for each subsequent record. Of course, this relies on one assumption I'm making, which to be honest, I'm not sure is true. Is it possible to delete the first *n* lines from a text file from within C# without having to read the entire thing and re-write it without the first *n* lines?
**.NET 4.0 edit** Since .NET 4.0, it is possible to access a single line of a file directly. For instance, to access line 15: ``` string line = File.ReadLines(FileName).Skip(14).Take(1).First(); ``` This will return only the line required --- Since you can't predict the location (can you?) of the i-th line in the file, you'll have to read all previous lines too. If the line number is small, this can be more efficient than the `ReadAllLines` method. ``` string GetLine(string fileName, int line) { using (var sr = new StreamReader(fileName)) { for (int i = 1; i < line; i++) sr.ReadLine(); return sr.ReadLine(); } } ```
If each line is a fixed length then you can open a Stream around it, seek (bytes per line) \* n into the file and read your line from there. ``` using( Stream stream = File.Open(fileName, FileMode.Open) ) { stream.Seek(bytesPerLine * (myLine - 1), SeekOrigin.Begin); using( StreamReader reader = new StreamReader(stream) ) { string line = reader.ReadLine(); } } ``` Alternatively you could just use the StreamReader to read lines until you found the one you wanted. That way's slower but still an improvement over reading every single line. ``` using( Stream stream = File.Open(fileName, FileMode.Open) ) { using( StreamReader reader = new StreamReader(fileStream) ) { string line = null; for( int i = 0; i < myLineNumber; ++i ) { line = reader.ReadLine(); } } } ```
How do I read a specified line in a text file?
[ "", "c#", "string", "file-io", "input", "" ]
How can I determine via javascript if a user has logged in to my site via facebook connect or not? Based on this result, I would like to show/not show a `<fb:login-button>` button on the site. If I did something like this using jquery: ``` <div id="login"></div> <script> if (notLoggedIn) { $("#login").html("<fb:login-button></fb>"); } </script> ``` Will it work?
I did It this way: **HTML:** ``` <div id="logindisplay"> <span id="login"> <fb:login-button background="dark" onlogin="facebook_onlogin_ready();"> </fb:login-button> </span> </div> ``` **js:** ``` function updateUserBox() { var user_box = document.getElementById("login"); user_box.innerHTML = "<span><fb:name uid=loggedinuser useyou='false'></fb:name><fb:profile-pic uid=loggedinuser facebook-logo='true'></fb:profile-pic></span>"; FB.XFBML.Host.parseDomTree(); } FB_RequireFeatures(["Connect"], function() { FB.init("appkey", "/Content/xd_receiver.htm", { "ifUserConnected": updateUserBox }); FB.Connect.showPermissionDialog("publish_stream,status_update"); FB.Connect.requireSession(); }); ```
I don't think jQuery will stop you from inserting non-standard HTML tags, but you'll definitely want to change your closing tag from `</fb>` to `</fb:login-button>`. Beyond that, whenever you insert XFBML tags into your DOM after page load, you'll need to request that the FB API re-parses the DOM. This should do just that: ``` FB.ensureInit(function(){ FB.XFBML.Host.parseDomTree(); }); ```
How to dynamically show/hide a facebook login button
[ "", "javascript", "jquery", "facebook", "" ]
I'm trying to use jQuery to make some AJAX calls, but because I have wild card mapping (to .NET) in IIS 6 turned on, it doesn't seem to work. Disabling the mapping makes everything magically work.
With the wildcard mapping on IIS will run the initial request via the wildcard handler first. This will be done BEFORE any URL rewriting (or URL routing) by your CMS. I think that is why you are getting 404. You can also try to disable "verify file exists" checkbox on the wildcard mapping to cater for the scenario when the actual URL will be later rewritten to something else.
This is not a complete answer but I hope it points you in the direction of a solution. Have you tried accessing the url directly in a browser and using some well placed breakpoints to track down the problem? If you're getting 404s it sounds like your rules for routing aren't working. [I'll update this if you can give a little more info about the behaviour you're seeing] # UPDATE I think what might be happening is this: You're providing a seperate mapping for your files with extensions (in these cases .aspx and .asmx): localhost/UserChecker.aspx/CheckIfUserEmailsExists localhost/UserChecker.asmx/CheckIfUserEmailsExists These mappings are being used when you turn the wild card mappings off, and the '/CheckIfUserEmailsExists' is handled used or ignored. When you turn on the wildcard mappings your routing isn't informing your app how to 'route' correctly. If you removed the extensions (with wildcard mappings turned on) does the following work? localhost/UserChecker/CheckIfUserEmailsExists
Why does IIS wild card mapping break my AJAX calls?
[ "", "c#", "asp.net", "iis-6", "webmethod", "wildcard-mapping", "" ]