Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have an app that has a ConcurrentQueue of items that have an ID property and a ConcurrentQueue of tasks for each item, the queue items look like: ``` class QueueItem { public int ID { get; set; } public ConcurrentQueue<WorkItem> workItemQueue { get; set; } } ``` and the queue itself looks like: ``` ConcurrentQueue<QueueItem> itemQueue; ``` I have one thread doing a foreach over the itemQueue, deQueueing an item from each queue and doing work on it: ``` foreach(var queueItem in itemQueue) { WorkItem workItem; if (queueItem.workItemQueue.TryDequeue(out workItem)) doWork(workItem); else // no more workItems for this queueItem } ``` I'm using ConcurrentQueues because I have a separate thread potentially adding queueItems to the itemQueue, and adding workItems to each workItemQueue. My problem comes when I have no more workItems in a queueItem - I'd like to remove that queueItem from the itemQueue - something like... ``` if (queueItem.workItemQueue.TryDequeue(out workItem)) doWork(workItem); else itemQueue.TryRemove(queueItem); ``` ...but I can't find a way to do that easily. The way i've come up with is to dequeue each QueueItem and then Enqueue it if there's still WorkItems in the workItemQueue: ``` for (int i = 0; i < itemQueue.Count; i++) { QueueItem item; itemQueue.TryDequeue(out queueItem); if (queueItem.workItemQueue.TryDequeue(out workItem)) { itemQueue.Enqueue(queueItem); doWork(workItem); } else break; } ``` Is there a better way to accomplish what I want using the PFX ConcurrentQueue, or is this a reasonable way to do this, should I use a custom concurrent queue/list implementation or am I missing something?
In general, there is no efficient ways to remove specific items from queues. They generally have O(1) queue and dequeues, but O(n) removes, which is what your implementation does. One alternative structure is something called a LinkedHashMap. Have a look at the [Java implementation](http://java.sun.com/javase/6/docs/api/java/util/LinkedHashMap.html) if you are interested. It is essentially a Hash table *and* a linked list, which allows O(1) queue, dequeue and remove. This isn't implemented in .Net yet, but there are a few implementations floating around the web. Now, the question is, why is itemQueue a queue? From your code samples, you never enqueue or dequeue anything from it (except to navigate around the Remove problem). I have a suspicion that your problem could be simplified if a more suitable data structure is used. Could you give examples on what other pieces of code access itemQueue?
This may not work for everyone, but the following is the solution I came up with for removing an item from a concurrent queue, since this is the first google result, I thought I would leave my solution behind. What I did was temporarily replace the working queue with an empty, convert the original to a list and remove the item(s), then create a new queue from the modified list and put it back. In code (sorry this is VB.net rather C#): ``` Dim found As Boolean = False //'Steal the queue for a second, wrap the rest in a try-finally block to make sure we give it back Dim theCommandQueue = Interlocked.Exchange(_commandQueue, New ConcurrentQueue(Of Command)) Try Dim cmdList = theCommandQueue.ToList() For Each item In cmdList If item Is whateverYouAreLookingFor Then cmdList.Remove(item) found = True End If Next //'If we found the item(s) we were looking for, create a new queue from the modified list. If found Then theCommandQueue = New ConcurrentQueue(Of Command)(cmdList) End If Finally //'always put the queue back where we found it Interlocked.Exchange(_commandQueue, theCommandQueue) End Try ``` Aside: This is my first answer, so feel free to put up some editing advice and/or edit my answer.
PFX ConcurrentQueue - is there a way to remove a specific item from the queue
[ "", "c#", ".net", "concurrency", "pfx", "" ]
I created a generic base class for a WinForm UserControl: ``` public partial class BaseUserControl<T> : UserControl { public virtual void MyMethod<T>() { // some base stuff here } } ``` And a UserControl based on that: ``` public partial class MyControl : BaseUserControl<SomeClass> { public override void MyMethod<SomeClass>() { // some specific stuff here base.MyMethod<SomeClass>(); } } ``` It works fine, but MyControl cannot be edited in the VisualStudio Designer, because it says it cannot load the base class. I tried to define another class BaseUserControl, non generic, hoping it would load it, but the trick doesn't seem to work. I already have a workaround: define an interface, IMyInterface<T>, and then create my control as ``` public partial class MyControl : UserControl, IMyInterface<SomeClass> ``` But I lose my base virtual methods (not a big deal, but still...). Is there a way to create a base generic class for a UserControl, with the possiblity to edit it in the VisualStudio Designer?
We're doing the same thing and we work around by specializing a class first and derive from the specialized class. Using the code from your example this means something like: ``` public partial class UserControl : UserControlDesignable { ... } public class UserControlDesignable : BaseUserControl<Someclass> { } ``` The designer is still acting flaky sometimes - but most of the time it works.
You'll have to trick the designer by adding a 'regular' class that inherits from your generic base form. Your designable form should then inherit from this class. The following 2 class definitions are thus in the same file. You'll have to make sure that the class that inherits from the generic base user-control, is the last class in the file. ``` public MyForm : EditableCustomerForm {} public EditableCustomerForm : GenericForm<Customer> {} ``` The designer will display the first class in the code file that it encounters.
Generic base class for WinForm UserControl
[ "", "c#", ".net", "winforms", "visual-studio-2008", "windows-forms-designer", "" ]
I am trying to parse some output data from and PBX and I have found something that I can't really figure out. In the documentation it says the following > Information for type of call and feature. Eight character for ’status information 3’ with following ASCII values in hexadecimal notation. > > ``` > 1. Character > Bit7 Incoming call > Bit6 Outgoing call > Bit5 Internal call > Bit4 CN call > 2. Character > Bit3 Transferred call (transferring party inside) > Bit2 CN-transferred call (transferring party outside) > Bit1 > Bit0 > ``` Any ideas how to interpret this? I have no raw data at the time to match against but I still need to figure it out.
> Eight character for ’status information 3’ with following ASCII values in hexadecimal notation. If think this means the following. 1. You will get 8 bytes - one byte per line, I guess. 2. It is just the wrong term. They mean two hex digits per byte but call them characters. So it is just a byte with bit flags - or more precisely a array of eight such bytes. ``` Bit 7 incoming 6 outgoing 5 internal 4 CN 3 transfered 2 CN transfered 1 unused? 0 unused? ``` You could map this to a enum. ``` [BitFlags] public enum CallInformation : Byte { Incoming = 128, Outgoing = 64, Internal = 32, CN = 16 Transfered = 8, CNTransfered = 4, Undefined = 0 } ```
Probably you'll receive two characters (hex digits: 0-9, A-F) First digit represents the hex value for the most significant 4 bits, next digit for the least significant 4 bits. Example: You will probably receive something like the string "7C" as hex representation of the bitmap: 01111100.
ASCII values in hexadecimal notation
[ "", "c#", "hex", "pbx", "" ]
I really should be able to get this, but I'm just to the point where I think it'd be easier to ask. In the C# function: ``` public static T GetValue<T>(String value) where T:new() { //Magic happens here } ``` What's a good implementation for the magic? The idea behind this is that I have xml to parse and the desired values are often primitives (bool, int, string, etc.) and this is the perfect place to use generics... but a simple solution is eluding me at the moment. btw, here's a sample of the xml I'd need to parse ``` <Items> <item> <ItemType>PIANO</ItemType> <Name>A Yamaha piano</Name> <properties> <allowUpdates>false</allowUpdates> <allowCopy>true</allowCopy> </properties> </item> <item> <ItemType>PIANO_BENCH</ItemType> <Name>A black piano bench</Name> <properties> <allowUpdates>true</allowUpdates> <allowCopy>false</allowCopy> <url>www.yamaha.com</url> </properties> </item> <item> <ItemType>DESK_LAMP</ItemType> <Name>A Verilux desk lamp</Name> <properties> <allowUpdates>true</allowUpdates> <allowCopy>true</allowCopy> <quantity>2</quantity> </properties> </item> </Items> ```
I would suggest instead of trying to parse XML yourself, you try to create classes that would deserialize from the XML into the classes. I would **strongly** recommend following bendewey's answer. But if you cannot do this, there is hope. You can use [`Convert.ChangeType`](http://msdn.microsoft.com/en-us/library/dtb69x08.aspx). ``` public static T GetValue<T>(String value) { return (T)Convert.ChangeType(value, typeof(T)); } ``` And use like so ``` GetValue<int>("12"); // = 12 GetValue<DateTime>("12/12/98"); ```
You can start with something roughly like this: ``` TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); if (converter != null) { return (T)converter.ConvertFrom(value); } ``` If you have to parse attributes that are special types, like colors or culture strings or whatnot, you will of course have to build special cases into the above. But this will handle most of your primitive types.
Converting from String to <T>
[ "", "c#", "xml", "generics", "" ]
When implementing a Matrix construct using arrays, which would be more efficient? Using a 1D array, or an array of arrays (2D)? I would think a 2D is more efficient as you already have the X and Y coordinates of an element, where in a 1D implementation you have to calculate the index. Edit: it is being implemented using Java
"Efficient" is not a catch-all term. An array-of-arrays solution is more efficient in terms of storage, where the array may be sparse (i.e., you can use null pointer to represent a matrix line of all zeroes). This would be (in C): ``` int *x[9]; ``` where each `"int *"` would be allocated separately. A 2D array (which is not necessarily an array of arrays) will generally be faster (efficient in terms of speed) since it works out memory locations with math, without having to de-reference memory locations. I'm talking of the construct: ``` int x[9][9]; ``` A 1D array of the form: ``` int x[81]; ``` is unlikely to be any faster than the equivalent 2D version since you still have to do the calculations at some point to find the correct cell (manually in your code rather than letting the compiler do it). *After edit where Java was added as a requirement:* I believe Java 2D arrays are of the array of arrays variety (which will require two memory accesses as opposed to the one required for a 1D array) so the 1D array with manual index calculation may well be faster. So, instead of declaring and using: ``` int x[width][height]; x[a][b] = 2; ``` you may get more speed with: ``` int x[width*height]; x[a*height+b] = 2; ``` You just need to be careful that you don't get the formula mixed up anywhere (i.e., don't swap 4 and 7 inadvertently). This speed difference is based on how I think Java is coded under the covers so I could be wrong (but I doubt it :-). My advice is, as always for optimisation questions, *measure, don't guess!*
I'm going to break ranks with the answers to date and suggest the following reason that a 1D array is quite possibly faster. A 2D array involves 2 memory accesses. A[x][y] for instance first must lookup A[x], and then do another lookup of that array[y]. A 1D implementation traditionally would be A[x + (width \*y)]. When width is in registers (or a literal), this means 2 math ops and 1 lookup instead of 2 lookups. Lookups are orders of magnitude slower than math ops, so if width is in register even a small percent of the time, or is a literal, it will be faster. Of course the standard caveats apply. Always profile, and avoid premature optimizations.
Implementing a matrix, which is more efficient - using an Array of Arrays (2D) or a 1D array?
[ "", "java", "arrays", "performance", "multidimensional-array", "" ]
I know that cout have buffer several days ago, and when I google it, it is said that the buffer is some like a stack and get the output of cout and printf from right to left, then put them out(to the console or file)from top to bottem. Like this, ``` a = 1; b = 2; c = 3; cout<<a<<b<<c<<endl; buffer:|3|2|1|<- (take “<-” as a poniter) output:|3|2|<- (output 1) |3|<- (output 2) |<- (output 3) ``` Then I write a code below, ``` #include <iostream> using namespace std; int c = 6; int f() { c+=1; return c; } int main() { int i = 0; cout <<"i="<<i<<" i++="<<i++<<" i--="<<i--<<endl; i = 0; printf("i=%d i++=%d i--=%d\n" , i , i++ ,i-- ); cout<<f()<<" "<<f()<<" "<<f()<<endl; c = 6; printf("%d %d %d\n" , f() , f() ,f() ); system("pause"); return 0; } ``` Under VS2005, the output is ``` i=0 i++=-1 i--=0 i=0 i++=-1 i--=0 9 8 7 9 8 7 ``` It seems that the stack way is right~ However, I read C++ Primer Plus yesterday, and it is said that the cout work from left to right, every time return an object(cout), so "That’s the feature that lets you concatenate output by using insertion". But the from left to right way can not explain cout< Then [Alnitak](https://stackoverflow.com/users/6782/alnitak) tell me that, "The << operator is really ostream& operator<<(ostream& os, int), so another way of writing this is: operator<< ( operator<< ( operator<< ( cout, a ), b ), c )", If the rightest argument is first evaluated, it can be some explained. Now I'm confused about how cout's buffer work, can somebody help me?
You are mixing a lot of things. To date: * Implementation details of `cout` * Chained calls * Calling conventions Try to read up on them separately. And don't think about all of them in one go. > printf("i=%d i++=%d i--=%d\n" , i , i++ ,i-- ); The above line invokes undefined behavior. Read the FAQ [3.2](http://c-faq.com/expr/evalorder2.html). Note, what you observe is a side-effect of the function's calling convention and the way parameters are passed in the stack by a particular implementation (i.e. yours). This is not guaranteed to be the same if you were working on other machines. I think you are confusing the order of function calls with buffering. When you have a `cout` statement followed by multiple insertions `<<` you are actually invoking multiple function calls, one after the other. So, if you were to write: ``` cout << 42 << 0; ``` It really means: You call, ``` cout = operator<<(cout, 42) ``` and then use the return in another call to the same operator as: ``` cout = operator<<(cout, 0) ``` What you have tested by the above will not tell you anything `cout`'s internal representation. I suggest you take a look at the header files to know more.
Just as a general tip, never ever use i++ in the same line as another usage of i or i--. The issue is that function arguments can be evaluated in any order, so if your function arguments have any side-effects (such as the increment and decrement operations) you can't guarantee that they will operate in the order you expect. This is something to avoid. The same goes for this case, which is similar to the actual expansion of your cout usage: function1 ( function2 ( foo ), bar ); The compiler is free to evaulate bar before calling function2, or vice versa. You can guarantee that function2 will return before function1 is called, for example, but not that their arguments are evaluated in a specific order. This becomes a problem when you do something like: function1 ( function2 ( i++), i ); You have no way to specify whether the "i" is evaluated before or after the "i++", so you're likely to get results that are different than you expect, or different results with different compilers or even different versions of the same compiler. Bottom line, avoid statements with side-effects. Only use them if they're the only statement on the line or if you know you're only modifying the same variable once. (A "line" means a single statement plus semicolon.)
How the buffer of cout work?
[ "", "c++", "buffer", "cout", "" ]
I am wondering if it is possible to request more information besides email from Google and get the name of the user also? Am using JanRain OpenID PHP script. Thank you
No, it isn't possible. Google only releases the user's email address. Their server is set up to never give out any more information than that: See their OpenID page for developers to learn more: <http://code.google.com/apis/accounts/docs/OpenID.html>
Search for **OpenID Attribute Exchange** -- that's what you want. * [basic overview](http://blogs.gnome.org/jamesh/2007/11/26/openid-ax/) * [formal specification](http://openid.net/specs/openid-attribute-exchange-1_0.html) We haven't looked at it in a while (6 months?) but it was quite rough when we did. Hopefully things have improved since then. More resources: <http://www.google.com/search?q=openid+attribute+exchange>
OpenID -- getting user information?
[ "", "php", "openid", "" ]
I have the following code: ``` const string Sql = @"select distinct [name] from tblCustomers left outer join tblCustomerInfo on tblCustomers.Id = tblCustomerInfo.CustomerId where (tblCustomer.Name LIKE '%@SEARCH%' OR tblCustomerInfo.Info LIKE '%@SEARCH%');"; using (var command = new SqlCommand(Sql, Connection)) { command.Parameters.AddWithValue("@SEARCH", searchString); ... } ``` This does not work, I tried this as well: ``` const string Sql = @"select distinct [name] from tblCustomers left outer join tblCustomerInfo on tblCustomers.Id = tblCustomerInfo.CustomerId where (tblCustomer.Name LIKE @SEARCH OR tblCustomerInfo.Info LIKE @SEARCH );"; using (var command = new SqlCommand(Sql, Connection)) { command.Parameters.AddWithValue("@SEARCH", "'%" + searchString + "%'"); ... } ``` but this does not work as well. What is going wrong? Any suggestions?
What you want is: ``` tblCustomerInfo.Info LIKE '%' + @SEARCH + '%' ``` (or edit the parameter value to include the % in the first place). Otherwise, you are either (first sample) searching for the *literal* "@SEARCH" (not the arg-value), or you are embedding some extra quotes into the query (second sample). In some ways, it might be easier to have the TSQL just use `LIKE @SEARCH`, and handle it at the caller: ``` command.Parameters.AddWithValue("@SEARCH","%" + searchString + "%"); ``` Either approach should work.
Instead of using: ``` const string Sql = @"select distinct [name] from tblCustomers left outer join tblCustomerInfo on tblCustomers.Id = tblCustomerInfo.CustomerId where (tblCustomer.Name LIKE '%@SEARCH%' OR tblCustomerInfo.Info LIKE '%@SEARCH%');"; ``` Use this code: ``` const string Sql = @"select distinct [name] from tblCustomers left outer join tblCustomerInfo on tblCustomers.Id = tblCustomerInfo.CustomerId where (tblCustomer.Name LIKE '%' + @SEARCH + '%' OR tblCustomerInfo.Info LIKE '%' + @SEARCH + '%');"; ```
Use of SqlParameter in SQL LIKE clause not working
[ "", "c#", "sql-server", "t-sql", "ado.net", "sql-like", "" ]
I am writing a SQL query creator using some parameters. In Java, it's very easy to detect the last element of an array from inside the for loop by just checking the current array position with the array length. ``` for(int i=0; i< arr.length;i++){ boolean isLastElem = i== (arr.length -1) ? true : false; } ``` In PHP they have non-integer indexes to access arrays. So you must iterate over an array using a foreach loop. This becomes problematic when you need to take some decision (in my case to append or/and parameter while building query). I am sure there must be some standard way of doing this. How do you solve this in PHP?
It sounds like you want something like this: ``` $numItems = count($arr); $i = 0; foreach($arr as $key=>$value) { if(++$i === $numItems) { echo "last index!"; } } ``` That being said, you don't -have- to iterate over an "array" using `foreach` in php.
You could get the value of the last key of the array using `end(array_keys($array))` and compare it to the current key: ``` $last_key = end(array_keys($array)); foreach ($array as $key => $value) { if ($key == $last_key) { // last element } else { // not last element } } ```
Find the last element of an array while using a foreach loop in PHP
[ "", "php", "foreach", "" ]
I'm having a little problem in Java. How to do this: I want to search in a HTML file for the tags href and src, and then I want to get the URL associated with that tags. What is the best way to do it? Thanks for the help. Best regards.
This is the code I used to accomplish exactly what you'd like to do, but first let me give you a few tips. If you're in a Java Swing environment, make sure to use the methods in the javax.swing.text.html and javax.swing.text.html.parser packages. Unfortunately, they're mostly intended for use on a JEditorPane, but I'd still strongly recommend that you take a look at these. There's a class in the Java 6 API called HTML.Tag that identifies the HTML start and end tags, which you can then use in order to determine where the links are that you'd like your program to follow.[http://java.sun.com/javase/6/docs/api/javax/swing/text/html/HTML.Tag.html](http://java.sun.com/javase/6/docs/api/javax/swing/text/html/HTML.Tag.html "Link to HTML.Tag in Java API") When I wrote a program very similar to this, I used 3 main methods: ``` public void handleStartTag(HTML.Tag t, MUtableAttributeSet atts, int pos) public void handleEndTag(HTML.Tag t, int pos) public void handleText(char[] text, int pos) ``` If you need more help on how to write these methods, you can message me, but basically, you are looking for an initial tag and an end tag and then from that you will have identified the url and then you can proceed to the next step, which is following the url. To follow the url, I advise you to use the JEditorPane object. The javax.swing.event.HyperlinkListener interface defines only one method, hyperlinkUpdate(HyperlinkEvent e), which you can pass the url into and then call .setPage(evt.getURL()) on your JEditorPane object. This will then update the pane with the new page and allow you to start the process again. Msg me if you have any probs and please vote this answer!
Do you want to do this as a one-time editing task, or do you need a systematic (i.e. code) implementation? In the second case, find a Java HTML parser implementation and walk the DOM tree. <http://java-source.net/open-source/html-parsers>
How to search in a HTML file for some tags?
[ "", "java", "html", "html-parsing", "" ]
I need to downgrade Java in Ubuntu. Current version is 1.6.0, I have to use JDK 1.5.0 for my Android platform. How to do it? Remove it and reinstall?
`update-java-alternatives` is your friend: ``` $ sudo update-java-alternatives -l java-1.5.0-sun 53 /usr/lib/jvm/java-1.5.0-sun java-6-sun 63 /usr/lib/jvm/java-6-sun ``` Then select the Java version you want. E.g., to seletc Java 1.5, do ``` $ sudo update-java-alternatives -s java-1.5.0-sun ``` Make sure first that you have the correct Java packages installed. See the [Ubuntu Java page](https://help.ubuntu.com/community/Java) for more details.
Late answer but it may help someone out there: ``` sudo add-apt-repository "deb http://archive.ubuntu.com/ubuntu hardy main multiverse" sudo add-apt-repository "deb http://archive.ubuntu.com/ubuntu hardy-updates main multiverse" sudo apt-get update sudo apt-get install sun-java5-jdk ``` then you can see java5 when you ``` sudo update-java-alternatives -l ```
How do I downgrade Java from 1.6.0 to 1.5.0 in Ubuntu?
[ "", "java", "" ]
I have a ray, I need to find the closest line segment that it hits. I think it's possible to do this in O(log n) time if I sort the line segments first, but I can't remember how to sort them... I think some sort of tree would work best, but how do I sort them by both start and end point? I would also like fast insertions into this data structure if possible. There's lots of code for one ray vs one line segment, but I need something for one ray vs many line segments... I don't know what terms to google for. A link to an appropriate article is good, C++ code is even better. Thanks! :) PS: The line segments are actually the edges of a non-self-intersecting polygon, sorted in CCW order... but I think there may be some advantage to sorting them in a different fashion? This is all 2D. --- On second thought, I'm not entirely sure this *is* possible. Some sort of spatial partitioning might help, but otherwise, I can't think of any way to sort the lines so that they could be compared with an arbitrary ray.
You could take a bounding box of the polygon (min-max x,y coordinates) and build a grid inside the box. Then, for each cell, remember all lines that cross the cell. Find an intesection like this: * Find out which cell the ray hits first (O(1)) * Use [Grid traversal algorithm](http://www.devmaster.net/articles/raytracing_series/part4.php) to "draw" a ray through the grid. When you hit non-empty cell, check all its lines, check if intersection is inside the cell and pick the closest intersection. If all intersections are outside the cell, continue (this is O(grid length)). You could also make the grid hierarchical (ie. [quadtree](http://www.codeproject.com/KB/recipes/QuadTree.aspx) - a tree you were asking for), and walk it using the same algorithm. [This is done in raytracing in 3D](http://www.devmaster.net/articles/raytracing_series/part4.php) and the time complexity is O(sqrt(N)). --- Or, use the approach I did in my raytracer: * Build a [quadtree](http://www.codeproject.com/KB/recipes/QuadTree.aspx) containing the lines (building quadtree is desribed in the article) - you split nodes (=areas) if they contain too many objects into 4 sub-nodes (sub-areas) * Collect all *leaf nodes* of the quadtree that are hit by the ray: Compute ray-rectangle intersection (not hard) for the root. If the root is hit by the ray, proceed with its children recursively. The cool thing about this is that when a tree node is *not* hit, you've skipped processing whole subtree (potentially a large rectangular area). In the end, this is equivalent to traversing the grid - you collect the smallest cells on the ray's path, and then test all objects in them for intersection. You just have to test all of them and pick the closest intersection (so you explore all lines on ray's path). This is O(sqrt(N)). In grid traversal, when you find an intersection, you can stop searching. To achieve this with quadtree traversal, you would have to seach the children in the right order - either sort the 4 rect intersections by distance or cleverly traverse the 4-cell grid (an we are back to traversal). This is just a different approach, comparatively same difficult to implement I think, and works well (I tested it on real data - O(sqrt(N))). Again, you would only benefit from this approach if you have at least a couple of lines, when the polygon has 10 edges the benefit compared to just testing all of them would be little I think.
How are you certain that you'll hit any of them? If they're lines, it's unlikely. If it's really a polygon (i.e. planar) that you're trying to test, the usual way to do this sort of thing is intersect with the plane first, then test that point (in the 2d coordinates) for inside/outside polygon. Maybe I misunderstood what you're actually doing. In general accelerating intersections with complex figures is done with spatial partitioning (and then techniques like mailboxing, if your tests are expensive). [Update: I misread the original intent] You can still use (2d) spatial partitioning but the overhead may not be worth it. Individual test are cheap, if your polys aren't complicated it might be cheaper to just walk them. Hard to say from description.
Line Segment container for fast Ray intersection? (2D)
[ "", "c++", "geometry", "intersection", "line-segment", "" ]
How do i avoid using hardcoded table and field names in entity framework? For example: ``` Contact contact = contactQuery.Include("SalesOrderHeader.SalesOrderDetail") .FirstOrDefault(); ``` Is there a way to get that info from the context or metadata? I'd love to be able say SalesOrderHeader.TableName or SalesOrderHeaderFields.SalesOrderDetails.FieldName
If you want to use the Entity Frameworks metadata, you need to go looking through the `MetadataWorkspace` which hangs off the `ObjectContext`. The starting point is to get the EntityType for your base type, in your case Contact. I have an [EF tips series](http://blogs.msdn.com/alexj/archive/2009/03/26/index-of-tips.aspx) and in [Tip 13](http://blogs.msdn.com/alexj/archive/2009/04/15/tip-13-how-to-attach-an-entity-the-easy-way.aspx) I show an extension method on `MetadataWorkspace` that gets the `EntityType` for a particular CLR Type: ``` public static EntityType GetCSpaceEntityType<T>( this MetadataWorkspace workspace); ``` You can use this like this: ``` var contactEntity = ctx.MetadataWorkspace.GetCSpaceEntityType<Contact>(); ``` Once you have this you can look at it's NavigationProperties to find the relationship's and the names you are interested in including: i.e. ``` foreach(var np in contactEntity.NavigationProperties) { Console.WriteLine("Include: {0}", np.Name); Console.WriteLine("... Recursively include "); EntityType relatedType = (np.ToEndMember.TypeUsage.EdmType as RefType).ElementType; //TODO: go repeat the same process... i.e. look at the relatedTypes // navProps too until you decide to stop. } ``` Of course how you decide what you want to Include is up to you. Hope this helps Alex
Read [Say goodbye to the hardcoded ObjectQuery(T).Include calls](http://blogs.microsoft.co.il/blogs/shimmy/archive/2010/08/06/say-goodbye-to-the-hard-coded-objectquery-t-include-calls.aspx), and you will be able to do it like the following, using lambda & linq expression trees: ``` Dim c = GetObjectContext() Dim query = c.Vendors.Include(Function(v) v.Contact.Addresses.Single.State) ``` There is a C# samle as well. HTH
How to avoid hardcoded field names in entity framework?
[ "", "c#", ".net", "entity-framework", "" ]
I'm looking for an IDE with use with the [Symfony Framework](http://www.symfony-project.org). I have a bit of experience using the [NetBeans 6.5 IDE](http://www.netbeans.org) but it does not always seem to complete the class methods, plus it doesn't seem to have any PHP code snippets built in. Here are the features I would ideally like to have, in order of importance, from an IDE: * Code completion of all the Symfony and Propel class methods (I can never remember them) * Code templates,(class skeletons, HTML structures, Symfony templates?) * Straight-forward code debugging * Source Control
If you could wait, Symfony support is coming to Netbeans soon: <http://www.netbeans.org/issues/show_bug.cgi?id=145913>. I'll go with Zend Studio 5.5's debugging and inspection features for the time being.
[Komodo IDE](https://www.activestate.com/blog/activestate-komodo-ide-now-open-source/) (or, without debugging and Source Control, the free [Komodo Edit](https://github.com/Komodo/KomodoEdit)) + [a set of commands for Komodo to use symfony tasks](https://web.archive.org/web/20160116140524/https://code.google.com/p/ksf/). does all your 4 points, and also works for Perl, Python, Ruby and Tcl.
What IDE has the strongest support for Symfony framework?
[ "", "php", "ide", "symfony1", "" ]
i am using this code to take a jpg image and save it as a thumbnail but it seems very slow .. ``` Image thumbNail = image.GetThumbnailImage(width, height, null, new IntPtr()); ``` is there any faster way to generate a large amount of thumbnails from a directory of images?
Try Draw Image - **Re Edited** ``` public Image ResizeImage(Image openImage, int NewWidth, int NewHeight) { var openBitmap = new Bitmap(openImage); var newBitmap = new Bitmap(NewWidth, NewHeight); using (Graphics g = Graphics.FromImage(openBitmap)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(newBitmap, new Rectangle(0, 0, NewWidth, NewHeight)); } openBitmap.Dispose(); //Clear The Old Large Bitmap From Memory return (Image)newBitmap; } ``` Typical 3-4mb Image Takes Between 4-8ms
1) By far the fastest and most reliable way to create .Jpg thumbnails is to use partial decompression. Jpg's have a unique aspect in that it's possible to extract a 1/8 size or 1/16 size (or any power of 2 size) copy of the original **without decompressing or sampling** the entire original image. Ever notice how programs like Picassa or Windows Explorer seem to create thumbnails super fast? This is how they do it (when they are not already cached). This functionality is easily available in any library based on the Independent JPEG Group library code, and most of them are. For example ImageMagick which has a .NET layer available. 2) You can further increase speed by using a hardware accelerated library like [libjpeg turbo](http://sourceforge.net/projects/libjpeg-turbo/), although it may require interop. 3) Some explanation of this special .jpg feature is [here](http://jpegclub.org/djpeg/).
generating jpg thumbnails in dotnet
[ "", "c#", "image", "" ]
I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python: ``` function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i<($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } ``` Is there a function that can do this?
You can use the `zfill()` method to pad a string with zeros: ``` In [3]: str(1).zfill(2) Out[3]: '01' ```
The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about. To output a string of length 5: --- **... in Python 3.5 and above: f-strings.** ``` i = random.randint(0, 99999) print(f'{i:05d}') ``` Search for f-strings [here](https://docs.python.org/3/tutorial/inputoutput.html) for more details. --- ... Python 2.6 and above: ``` print '{0:05d}'.format(i) ``` ... before Python 2.6: ``` print "%05d" % i ``` See: <https://docs.python.org/3/library/string.html>
Best way to format integer as string with leading zeros?
[ "", "python", "string-formatting", "" ]
I have an array ($form) which retreives some information from $\_POST: ``` $form = $_POST['game']; ``` Now I want to work with the values in this array, but I somehow fail. For debugging I used these commands (in the exact same order, with no extra lines inbetween): ``` print_r($form); echo '#' . $form['System_ID'] . "#"; ``` and as returned output I get: ``` Array ( ['Title'] => Empire: Total War - Special Forces ['Genre_ID'] => 1 ['Type'] => Spiel ['System_ID'] => 1 ) ## ``` Any ideas where my System\_ID went? It's there in print\_r, but not in the next line for echo?!?
Alright, I found the solution myself (a.k.a. d'oh!) I added another ``` var_dump($form); ``` for further analysis and this is what I got: ``` array(4) { ["'Title'"]=> string(34) "Empire: Total War - Special Forces" ["'Genre_ID'"]=> string(1) "1" ["'Type'"]=> string(5) "Spiel" ["'System_ID'"]=> string(1) "1" } ``` Notice the single quote inside the double quote? Looks as if you're not allowed to use the single quote in html forms or they will be included in the array key: ``` Wrong: <input type="text" name="game['Title']" /> Correct: <input type="text" name="game[Title]" /> ```
print\_r() doesn't put quotes around keys - for debugging i'd recommend ditching print\_r altogether. var\_export or var\_dump are better. even better: use [firephp](http://www.firephp.org/). it sends the debug info via headers, so it doesn't mess up your output and thus is even usable with ajax. output is displayed nicely with firebug including syntax coloring for data structures. and it's even easier to use: just `fb($myvar);`
PHP: Strange Array Problem - Where is my value?
[ "", "php", "arrays", "http-post-vars", "" ]
When overriding a class in C++ (with a virtual destructor) I am implementing the destructor again as virtual on the inheriting class, but do I need to call the base destructor? If so I imagine it's something like this... ``` MyChildClass::~MyChildClass() // virtual in header { // Call to base destructor... this->MyBaseClass::~MyBaseClass(); // Some destructing specific to MyChildClass } ``` Am I right?
No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.
No you don't need to call the base destructor, a base destructor is always called for you by the derived destructor. [Please see my related answer here for order of destruction](https://stackoverflow.com/questions/654428/what-is-the-order-in-which-the-destructors-and-the-constructors-are-called-in-c/654432#654432). To understand why you want a virtual destructor in the base class, please see the code below: ``` class B { public: virtual ~B() { cout<<"B destructor"<<endl; } }; class D : public B { public: virtual ~D() { cout<<"D destructor"<<endl; } }; ``` When you do: ``` B *pD = new D(); delete pD; ``` Then if you did not have a virtual destructor in B, only ~B() would be called. But since you have a virtual destructor, first ~D() will be called, then ~B().
Do I need to explicitly call the base virtual destructor?
[ "", "c++", "destructor", "" ]
I am writing editing front ends in Python since several years now, and I am fed up with micromanaging every UI detail of a window or dialog every single time. Is there a technology that allows me to, say, specify the relations between a GTK+ Glade-designed interface and the tables and records of an SQLite database to do all the middle man work? It should spare me the work of manually writing event handlers, input evaluators and view updates. The technologies in question are just examples, but I want to stick with Python as far as possible.
Besides the ones already mentioned I can add: * [Kiwi](http://www.async.com.br/projects/kiwi/api/kiwi.html) * [uxpython](http://www.uxpython.com/) * [pygtk](http://www.pygtk.org/) * [treethon](http://code.google.com/p/treethon/) I've never used any of them so have no recommendations but, for what it's worth, I have used at least 2 complex programs built directly on pygtk that worked in both Windows and Linux. I think Kiwi is the only one of these with baked in support for db (through interface with SQLAlchemy, SQLObject, or Storm) but I would be surprised if you couldn't use one of those ORM's inside any of the other frameworks.
[Dabo](http://dabodev.com/) is built on top of wxPython, so you may not prefer it, but it's designed to make it easy to tie a GUI to a database, so I'd recommend you check it out if you haven't already. In particular, it's got good facilities for tying widgets to data, and handling a lot of the common cases of GUI development.
Is there a Python library that allows to build user interfaces without writing much code?
[ "", "python", "user-interface", "sqlite", "gtk", "glade", "" ]
I have this value in a mysql database: "A+" it's the name of a magazine. I can see it sitting in the database, however i cannot manage to have it display via php. When i fetch the sql data, it outputs "A " I tried utfencode() utfdecode() htmlentities() ... to no avail. I fail to diagnose the problem. In case it matters, i fetch this data via ajax (jquery load() function) UPDATE: It turns out the + sign is removed while parsing the data through a regular expression. can't seem to find a fix for that either. preg\_quote() is of no use.
It is possible that jquery is interpreting it as the url encoded '+' sign, which can be interpreted as a space. Post some code and I'm sure somebody can give you a full answer.
The `+` character is interpreted as space when the data is declared as [`application/x-www-form-urlencoded`](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1): > This is the default content type. Forms submitted with this content type must be encoded as follows: > > 1. Control names and values are escaped. **Space characters are replaced by '`+`'**, and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by '`%HH`', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., '`%0D%0A`'). > 2. The control names/values are listed in the order they appear in the document. The name is separated from the value by '`=`' and name/value pairs are separated from each other by '`&`'. So you have to encode it properly. In JavaScript, use the `encodeURIComponent` function if you want to use `+` character in an URI: ``` "http://www.example.com/?q=" + encodeURIComponent("A+") ```
Cannot get the "+" sign to display
[ "", "php", "special-characters", "" ]
The other day, I asked [how to create a message box in your class](https://stackoverflow.com/questions/715206/show-a-message-box-from-a-class-in-c), but one of the answers stated that was it wasn't the correct approach. I understand that this is because it really defeats the point of a class. My program reads word by word from a string file, and checks if each word is in the database. I want to put every word not found into a ListBox on the form, which can have multiple selections. How do I send that data back to the form each time a new word is found?
I suggest you make a method something like this: ``` /* ... */ public IEnumerable<string> FindMissingWords( string fileName, IEnumerable<string> toSearch) { List<string> missingWords = new List<string>(); // todo: the appropriate code for looking up strings in the file, using // the filename and the strings that we passed into the function. // if you find one, add it to missingWords return missingWords; } ``` Then call that method from your form, and add each string it returns to your box. (If you're not familiar with `IEnumerable`, don't worry -- it's just a interface that defines a sequence of things, like an array or a list. You could pass an array of strings instead, but it would be a little less precise.)
If the class has a reference to the form, the it can just update the form directly. ``` someForm.SomeListBox.Items.Add(someWord); ``` If the form has a reference to the class, you can have the class raise an event like ``` public delegate string WordNotFoundHandler(string word); public WordNotFoundHandler event WordNotFound ; ``` and have the form handle that event ``` theClass.WordNotFound += AddItemToListBox void AddItemToListBox(string word) { someListBox.Items.Add(word); } ``` the advantage of doing it this way instead of one huge call that returns all the words is that it provide a faster ui response time, especially when done by a separate thread
Send data between class and form?
[ "", "c#", "forms", "class", "" ]
I'm working on a project which injects JS+CSS+HTML over web pages which I do not have control over. I am concerned about the host page styling my injected code -- I want my injected code to only obey **my** styling, and not theirs. At the moment the only method to do this I can think of involves explicitly specifying every possible tag for the container `<div>`'s class (using pre-defined, known browser defaults) and relying on inheritance for those rules to propagate down to the rest of my injected HTML. This CSS would need to appear at the bottom of the page's `<head>` tag. I don't think that's the best solution, though, and I don't look forward to implementing it. Surely there are better ways.
Others have suggested very good ways to prevent your CSS from affecting the page's, as well as making sure that your CSS takes precedence, but you seem most concerned with the page's CSS affecting you - that is, adding a funky, unexpected style (like making all divs have a pink background). The only way I can think for you to prevent their styling from affecting your injected code would be for you to sandbox what you've injected, like in an `iframe`. Otherwise there's simply too many things that you'd have to define - you'd have to define every single style (`padding`, `border`, `margin`, `background`... the list goes on and on) on the "`*`" selector (or better yet, "`#yourid *`", so you just override your own content), just so that you can guarantee absolute control over your CSS. Edit: I realize that the latter solution wouldn't necessarily be too painful, if you're using the omni-selector to reset everything to a baseline: ``` #myid * { somestyle1: default; somestyle2: default; ... } ``` I've found [someone who has written up such a solution](http://www.webmasterworld.com/css/3605017.htm). If you scroll down far enough on the page, you'll see it (from SuzyUK). It doesn't look complete, but is a good start for sure. (I, too, would be interested to know if there's a good way to prevent this. I've written Greasemonkey scripts before that injects code onto the page, and have had to write CSS to override the page's CSS, but in those cases I knew who my target was and could tailor my CSS directly towards the page.)
Wrap your injected HTML with a specifically-classed `<div>`, such as ``` <div class="my-super-specialized-unique-wrapper"><!--contents--></div> ``` Then in your CSS, prefix all rules with `.my-super-specialized-unique-wrapper` and use **[!important](http://www.w3.org/TR/CSS2/cascade.html#important-rules)** on every rule. That will instruct the client browser to treat your rule as supreme for any elements which match, regardless of any other styles that might target them - even if other rules outside your control are more-specific.
Prevent existing CSS from styling injected HTML/CSS
[ "", "javascript", "html", "css", "internet-explorer", "code-injection", "" ]
I'm writing a web-based game that involves clicking links on various sites on the internet. I know it sounds strange but the basic premise is that you start on my page where you click a link to some page on another site. You continue to follow links until you get to the page you are trying to reach. Think WikipediaGame.org. The difference being that I don't have control over the actual pages with the links. What I need to be able to do is track all the links that they clicked, and when they get to the final page, I want to send them back to my site (or something along those lines). What I was thinking was that perhaps I could somehow intercept the page requests and inject some Javascript to track which links they clicked. Is this possible? Has anyone done anything like this? Obviously this could pose a security risk. Do I have any other options? I want to avoid making the user collect a list of all the links and then post them into a textbox on my site.
So i figured out what to do. I'm using an iframe like this: `<iframe src="Puzzle/ContinuePuzzle" />` It points the source to my Mvc Controller. In my controller I do a WebRequest for the actual url that I want and then parse the Html and stick my own javascript in the page. The page acts and looks like the other site, but it's actually coming from my site.
Maybe a bookmarklet to send the current page to your site? That way the user would have complete control over the list of links shared with a minimal amount of work.
Injecting Javascript into a page
[ "", "javascript", "asp.net-mvc", "" ]
how do i apply the the distinct keyword in mysql so that it is only checking that one column field is unique, while still returning other columns from my table?
For being able to do that, mysql must know what to do with the other columns. You GROUP BY the column that should be unique and use a function that will tell it what to do with the others (a so-called [*aggregate function*](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html)). `MAX()` and `COUNT()` are common examples: ``` SELECT studentId, COUNT(courseId) AS AmountEnrolledCourses FROM student_enrollment GROUP BY studentId SELECT athlete, MAX(distance) AS PersonalRecord FROM longjump GROUP BY athlete ```
You'll need to use group by instead. SELECT SUM(A), MIN(B), C FROM TABLE WHERE A > 1 GROUP BY C; Note that if you're grouping on one column and returning others you have to provide some sort of way to cram all those values in the other fields into one. That way is called an aggregate function, and you'll have to check the manual for your database version to know exactly what your options are. See <http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html> for mysql.
limit distinct keyword to one column
[ "", "sql", "mysql", "" ]
In some C# code I have seen staments like this: ``` float someFloat = 57f; ``` I want to know why we should use literals like `f` in the above case?.
The "f" above is a type suffix. This tells the compiler the exact type of the literal provided. This is used so the compiler can allocate the appropriate amount of storage (precision) for the literal. By default, floating point literals are given storage for a "double." If you add "f" as a suffix, the literal will only get the storage for a float, which will have less accuracy. ``` double d = 50.1234; // given double storage double d = 50.1234f; // given float storage, which might lose precision compared to double ```
Mainly so the compiler knows exactly what we mean - in particular for overload resolution: ``` Foo(57f); ``` should that call `Foo(int)` / `Foo(float)` / `Foo(decimal)` ? Actually, I don't like remembering things - an alternative is: ``` float someFloat = (float)57; ``` this is **not** a runtime cast - it is identical (at the IL level) to `57f`. The only time it is subtly different is with `decimal`s with extra precision: ``` decimal someDecimal = (decimal)57.0; // same as 57M, not 57.0M (scale is different) ```
Why should we use literals in C#?
[ "", "c#", "" ]
Does anyone know how to detect in a `OnBeforeUnload` event that the server side code sent a `Response.Redirect`? I want to prompt a user to keep them from moving away from a page before it's time, but when the server redirects I it shouldn't prompt the user. I'm working with legacy code that extensively uses `Response.Redirect` and I'm not interested in changing the way the redirect occurs. Please don't suggest I use X redirect method. It **should** be possible to do this based on the response code in the XMLHttpRequest object as a response redirect should send back a 302. **Edit:** The Response.Redirect sends back a 200, with a redirect code in the body which then does a `window.location.href = new page` in the ASP.Net code. Is there any way to get to the server response to determine that this has happened?
I worked out a solution to it. When the PageRequestManager is processing the response from the server, it will set the \_processingRequest flag. In order to allow response.redirect to pass through, I changed my javascript to check for that. The event now looks like this: ``` window.onbeforeunload = function() { var prm = Sys.WebForms.PageRequestManager.getInstance(); if (!prm._processingRequest){ return "Are you sure you want to leave?"; } }; ```
For non-ajax pages, you're out of luck since the page is never sent to the browser, just the 302 header. So there's no opportunity for javascript processing of OnBeforeUnload. With ASP.NET AJAX a Response.Redirect really isn't doing a 302. It's sending back a message via the XMLHttpRequest and ASP.NET AJAX is simulating a 302. In theory you could intercept this and perform your own processing...
Can Response.Redirect and OnBeforeUnload play nice together?
[ "", "javascript", "asp.net", "ajax", "dom-events", "asp.net-ajax", "" ]
I have some text like "item number - item description" eg "13-40 - Computer Keyboard" that I want to split into item number and item description. Is this possible with 1 regular expression, or would I need 2 (one for item and one for description)? I can't work out how to "group" it - like the item number can be this and the description can be this, without it thinking that everything is the item number. Eg: ``` (\w(\w|-|/)*\w)-.* ``` matches everything as 1 match. This is the code I'm using: ``` Regex rx = new Regex(RegExString, RegexOptions.Compiled | RegexOptions.IgnoreCase); MatchCollection matches = rx.Matches("13-40 - Computer Keyboard"); Assert.AreEqual("13-40", matches[0].Value); Assert.AreEqual("Computer Keyboard", matches[1].Value); ```
From the code you posted, you are using regex wrong. You should be having one regex pattern to match the whole product and using the captures within the match to extract the number and description. ``` string RegExString = @"(?<number>[\d-]+)\s-\s(?<description>.*)"; Regex rx = new Regex(RegExString, RegexOptions.Compiled | RegexOptions.IgnoreCase); Match match = rx.Match("13-40 - Computer Keyboard"); Debug.Assert("13-40" == match.Groups["number"].Value); Debug.Assert("Computer Keyboard" == match.Groups["description"].Value); ```
Here is a regexp that works in Ruby - not sure if there are any differences in c# regexp: ``` /^([\d\-]+) \- (.+)$/ ```
Regular Expressions and "groups"
[ "", "c#", "" ]
I was looking at the [YUI Compressor](http://yuicompressor.codeplex.com/SourceControl/ListDownloadableCommits.aspx) and came across this piece of code in the ECMA.NET project (Continuation file if you are interested). ``` protected internal override int FindPrototypeId (string s) { int id; #region Generated PrototypeId Switch L0: { id = 0; string X = null; if (s.Length == 11) { X = "constructor"; id = Id_constructor; } if (X != null && X != s && !X.Equals (s)) id = 0; } EL0: #endregion return id; } ``` I have no idea what L0: and EL0: are doing here and have never seen this before. The term seems too rudimentary for google as well. Anyone know anything about this?
They look like lables for use as goto targets. See <http://msdn.microsoft.com/en-us/library/13940fs2.aspx> for more information.
They look like labels to me. The label is not used in this example (because it is generated code?), but can be used to jump another place. You could use `goto L0;` to jump the the first label. As an example, the following code writes just "Hello, World" because it skips the middle `Write()`: ``` Console.Write("Hello, "); goto Last; Console.Write("Cruel "); Last: Console.WriteLine("World"); ```
Code Curiosity in C#
[ "", "c#", "label", "goto", "" ]
ok, I'm back. I totally simplified my problem to just three simple fields and I'm still stuck on the same line using the addJSONData method. I've been stuck on this for days and no matter how I rework the ajax call, the json string, blah blah blah...I can NOT get this to work! I can't even get it to work as a function when adding one row of data manually. Can anyone PLEASE post a working sample of jqGrid that works with ASP.NET and JSON? Would you please include 2-3 fields (string, integer and date preferably?) I would be happy to see a working sample of jqGrid and just the manual addition of a JSON object using the addJSONData method. Thanks SO MUCH!! If I ever get this working, I will post a full code sample for all the other posting for help from ASP.NET, JSON users stuck on this as well. Again. THANKS!! tbl.addJSONData(objGridData); //err: tbl.addJSONData is not a function!! Here is what Firebug is showing when I receive this message: • objGridData Object total=1 page=1 records=5 rows=[5] ○ Page "1" Records "5" Total "1" Rows [Object ID=1 PartnerID=BCN, Object ID=2 PartnerID=BCN, Object ID=3 PartnerID=BCN, 2 more... 0=Object 1=Object 2=Object 3=Object 4=Object] (index) 0 (prop) ID (value) 1 (prop) PartnerID (value) "BCN" (prop) DateTimeInserted (value) Thu May 29 2008 12:08:45 GMT-0700 (Pacific Daylight Time) \* There are three more rows Here is the value of the variable tbl (value) 'Table.scroll' ``` <TABLE cellspacing="0" cellpadding="0" border="0" style="width: 245px;" class="scroll grid_htable"><THEAD><TR><TH class="grid_sort grid_resize" style="width: 55px;"><SPAN> </SPAN><DIV id="jqgh_ID" style="cursor: pointer;">ID <IMG src="http://localhost/DNN5/js/jQuery/jqGrid-3.4.3/themes/sand/images/sort_desc.gif"/></DIV></TH><TH class="grid_resize" style="width: 90px;"><SPAN> </SPAN><DIV id="jqgh_PartnerID" style="cursor: pointer;">PartnerID </DIV></TH><TH class="grid_resize" style="width: 100px;"><SPAN> </SPAN><DIV id="jqgh_DateTimeInserted" style="cursor: pointer;">DateTimeInserted </DIV></TH></TR></THEAD></TABLE> ``` Here is the complete function: ``` $('table.scroll').jqGrid({ datatype: function(postdata) { mtype: "POST", $.ajax({ url: 'EDI.asmx/GetTestJSONString', type: "POST", contentType: "application/json; charset=utf-8", data: "{}", dataType: "text", //not json . let me try to parse success: function(msg, st) { if (st == "success") { var gridData; //strip of "d:" notation var result = JSON.parse(msg); for (var property in result) { gridData = result[property]; break; } var objGridData = eval("(" + gridData + ")"); //creates an object with visible data and structure var tbl = jQuery('table.scroll')[0]; alert(objGridData.rows[0].PartnerID); //displays the correct data //tbl.addJSONData(objGridData); //error received: addJSONData not a function //error received: addJSONData not a function (This uses eval as shown in the documentation) //tbl.addJSONData(eval("(" + objGridData + ")")); //the line below evaluates fine, creating an object and visible data and structure //var objGridData = eval("(" + gridData + ")"); //BUT, the same thing will not work here //tbl.addJSONData(eval("(" + gridData + ")")); //FIREBUG SHOWS THIS AS THE VALUE OF gridData: // "{"total":"1","page":"1","records":"5","rows":[{"ID":1,"PartnerID":"BCN","DateTimeInserted":new Date(1214412777787)},{"ID":2,"PartnerID":"BCN","DateTimeInserted":new Date(1212088125000)},{"ID":3,"PartnerID":"BCN","DateTimeInserted":new Date(1212088125547)},{"ID":4,"PartnerID":"EHG","DateTimeInserted":new Date(1235603192033)},{"ID":5,"PartnerID":"EMDEON","DateTimeInserted":new Date(1235603192000)}]}" } } }); }, jsonReader: { root: "rows", //arry containing actual data page: "page", //current page total: "total", //total pages for the query records: "records", //total number of records repeatitems: false, id: "ID" //index of the column with the PK in it }, colNames: [ 'ID', 'PartnerID', 'DateTimeInserted' ], colModel: [ { name: 'ID', index: 'ID', width: 55 }, { name: 'PartnerID', index: 'PartnerID', width: 90 }, { name: 'DateTimeInserted', index: 'DateTimeInserted', width: 100}], rowNum: 10, rowList: [10, 20, 30], imgpath: 'http://localhost/DNN5/js/jQuery/jqGrid-3.4.3/themes/sand/images', pager: jQuery('#pager'), sortname: 'ID', viewrecords: true, sortorder: "desc", caption: "TEST Example")}; ```
Here is a simple example... You will need <https://github.com/douglascrockford/JSON-js/blob/master/json2.js> for this to work... and of course the usual jquery files. Paste this to a webservice ``` // The lower case properties here are required to be lower case // I cant find a way to rename them when they are serialized to JSON // XmlElement("yournamehere") does not work for JSON :( public class JQGrid { public class Row { public int id { get; set; } public List<string> cell { get; set; } public Row() { cell = new List<string>(); } } public int page { get; set; } public int total { get; set; } public int records { get; set; } public List<Row> rows { get; set; } public JQGrid() { rows = new List<Row>(); } } [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService] public class MyWebService : System.Web.Services.WebService { [WebMethod(EnableSession = true)] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public JQGrid GetJQGrid(int page, int pageSize, string sortIndex, string sortDirection) { DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.CONN_STRING, "udsp_GetMyData",pageIndex, pageSize); if (ds == null || ds.Tables.Count < 1) throw new Exception("Unable to retrieve data."); JQGrid jqGrid = new JQGrid(); int i = 1; foreach (DataRow dataRow in ds.Tables[0].Rows) { JQGrid.Row row = new JQGrid.Row(); row.id = Convert.ToInt32(dataRow["MyIdColumn"]); row.cell.Add(dataRow["MyIdColumn"].ToString()); row.cell.Add(dataRow["MyColumn"].ToString()); projectGrid.rows.Add(row); } jqGrid.page = 1; // Set this when you are actually doing paging... this is just a sample jqGrid.records = jqGrid.rows.Count; jqGrid.total = jqGrid.rows.Count; // Set this to total pages in your result... return jqGrid; } } ``` Paste this to your aspx page ``` <script type="text/javascript"> function getData(pdata) { var params = new Object(); params.page = pdata.page; params.pageSize = pdata.rows; params.sortIndex = pdata.sidx; params.sortDirection = pdata.sord; $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "/CLM/CLM.asmx/GetProjectGrid2", data: JSON.stringify(params), dataType: "json", success: function(data, textStatus) { if (textStatus == "success") { var thegrid = $("#testGrid")[0]; thegrid.addJSONData(data.d); } }, error: function(data, textStatus) { alert('An error has occured retrieving data!'); } }); } var gridimgpath = '/clm/css/ui-lightness/images'; $(document).ready(function() { $("#testGrid").jqGrid({ datatype: function(pdata) { getData(pdata); }, colNames: ['My Id Column', 'My Column'], colModel: [ { name: 'MyIdColumn', index: 'MyIdColumn', width: 150 }, { name: 'My Column', index: 'MyColumn', width: 250 } ], rowNum: 10, rowList: [10, 20, 30], imgpath: gridimgpath, pager: jQuery('#pagerdt'), sortname: 'id', viewrecords: false, sortorder: "desc", caption: "Projects", cellEdit: false }); }); </script> ```
Usually when you get the 'blah not a function' error with jqGrid it's because the correct module has not been loaded. The addJSONData function is defined in the grid.base.js file. Can you check your jqGridInclude() function in the jquery.jqGrid.js file and make sure that grid.base.js is being included as part of the initialization of your modules variable?
How do I get jqGrid to work using ASP.NET + JSON on the backend?
[ "", "asp.net", "javascript", "jquery", "json", "jqgrid", "" ]
I have this: ``` >>> print 'example' example >>> print 'exámple' exámple >>> print 'exámple'.upper() EXáMPLE ``` What I need to do to print: ``` EXÁMPLE ``` *(Where the 'a' gets its accute accent, but in uppercase.)* I'm using Python 2.6.
I think it's as simple as **not** converting to ASCII first. ``` >>> print u'exámple'.upper() EXÁMPLE ```
In python 2.x, just convert the string to unicode before calling upper(). Using your code, which is in utf-8 format on this webpage: ``` >>> s = 'exámple' >>> s 'ex\xc3\xa1mple' # my terminal is not utf8. c3a1 is the UTF-8 hex for á >>> s.decode('utf-8').upper() u'EX\xc1MPLE' # c1 is the utf-16 aka unicode for á ``` The call to `decode` takes it from its current format to unicode. You can then convert it to some other format, like utf-8, by using encode. If the character was in, say, iso-8859-2 (Czech, etc, in this case), you would instead use `s.decode('iso-8859-2').upper()`. As in my case, if your terminal is not unicode/utf-8 compliant, the best you can hope for is either a hex representation of the characters (like mine) or to convert it lossily using `s.decode('utf-8').upper().encode('ascii', 'replace')`, which results in 'EX?MPLE'. If you can't make your terminal show unicode, write the output to a file in utf-8 format and open that in your favourite editor.
How can I convert Unicode to uppercase to print it?
[ "", "python", "unicode", "python-2.x", "case-sensitive", "uppercase", "" ]
I need to disable an image which I am using in `<a "href">` until the page completely loads. I cannot use `document.ready()` because I need to disable the the BEFORE the document is ready. Can someone please help me with this?
Define it in your HTML as disabled: ``` <button disabled="disabled">My Button</button> ``` And then on page load re-enable it. This has the downside of breaking functionality for users without Javascript. The other way to do it is to add a small line of code directly after the button: ``` <button id="myButton">My Button</button> <script type="text/javascript"> document.getElementById('myButton').disabled = true; </script> ``` ...and then re-enable on document.load() **Edit with new info**: Is it an `input` with type "image"? If so, the above will still work. If not, and it's an `<a>` tag with an image inside it, I wouldn't recommend doing what the accepted answer suggests, sorry. Having an image suddenly appear at the end could get quite frustrating or distracting, considering that the page takes so long to load that you need to disable the link. What I'd suggest instead is this: ``` <a href="whatever" onclick="return myLinkHandler();"><img src="..." /></a> <script type="text/javascript"> var myLinkHandler = function() { alert('Page not loaded.'); // or something nicer return false; }; </script> ``` and then in your document.ready function, change the definition of the function: ``` myLinkHandler = function() { alert("Yay, page loaded."); return true; }; ``` Alternatively, you could put a check inside the function to see if the page has loaded or not. ``` var documentReady = false; function myLinkHandler() { alert (documentReady ? "Ready!" : "Not ready!"); return documentReady; } document.onload = function () { // or use jQuery or whatever documentReady = true; }; ```
In the case of the image, just set the style to display:none in the `<img>` tag and then use the other suggestions to remove the CSS attribute Or change it: `$(document).ready(function(){ $("#myImage").css("display","block"); });` This way, the image won't even appear until the document is ready and then the user can click on it. If you need to go the extra mile, do as the other suggested and hide/disable the link also in the tag and use jQuery to show/enable it.
How to verify if a webpage is completely loaded using JavaScript
[ "", "javascript", "dom-events", "" ]
If I have a wmf or emf image in System.Drawing.Image, is there a way to save the metafile data with c# without rendering it as a bitmap? Calling Image.Save will render it to a bitmap and I want to keep the original data so that it would still be a valid .wmf or .emf format file.
It seems you can not. On [this MSDN page](http://msdn.microsoft.com/en-us/library/system.drawing.imaging.metafile.aspx), it is stated: **Remarks** When you use the Save method to save a graphic image as a Windows Metafile Format (WMF) or Enhanced Metafile Format (EMF) file, the resulting file is saved as a Portable Network Graphics (PNG) file instead. This behavior occurs because the GDI+ component of the .NET Framework does not have an encoder that you can use to save files as .wmf or .emf files.
Despite this MSDN page, it is possible to save a true EMF file. See this question: [gdi-c-how-to-save-an-image-as-emf](https://stackoverflow.com/questions/152729/gdi-c-how-to-save-an-image-as-emf/895204#895204)
Save metafile in C#
[ "", "c#", "wmf", ".emf", "" ]
I need to transform bitmap images with their 4 corner points moved from one location to another. Any code that can run on Windows, C#/VB.NET preferably, even help how to use scriptable programs like [Paint.NET](http://www.getpaint.net/index.html) or [Photoshop](http://www.adobe.com/products/photoshop/) would be accepted. The Java Advanced Imaging API sounds hopeful. I need it for a screenshot manipulation system, which allows you to get such effects: [![alt text](https://i.stack.imgur.com/DSapn.gif)](https://i.stack.imgur.com/DSapn.gif) (source: [wholetomato.com](http://www.wholetomato.com/images/tour/mondoPerspectiveTrans.gif))
Check out the [Perspective warping](http://www.imagemagick.org/Usage/distorts/#perspective) examples from [ImageMagick](http://www.imagemagick.org/). It is available for most mainstream platforms.
Disclaimer: I work at Atalasoft If you are willing to go commercial, DotImage Photo can do this with the QuadrilateralWarpCommand. Sample C# Code ``` // Load an image. AtalaImage image = new AtalaImage("test-image.jpg"); // Prepare the warp positions. Point bottomLeft = new Point(100, image.Height - 80); Point topLeft = new Point(130, 45); Point topRight = new Point(image.Width - 60, 140); Point bottomRight = new Point(image.Width - 20, image.Height); // Warp the image. QuadrilateralWarpCommand cmd = new QuadrilateralWarpCommand(bottomLeft, topLeft, topRight, bottomRight, InterpolationMode.BiLinear, Color.White); AtalaImage result = cmd.Apply(image).Image; ``` <http://www.atalasoft.com/products/dotimage>
4-point transform images
[ "", "c#", "vb.net", "image-manipulation", "homography", "" ]
I need a function to get only the empty href query parameter names so I can replace them later with values from another array. After hours of failing at regular expressions, here is what i resorted to: ``` /** * getEmptyQueryParams(URL) * Input: URL with href params * Returns an array containing all empty href query parameters. */ function getEmptyQueryParams(URL) { var params = new Array( ); var non_empty_params = new Array( ); var regex = /[\?&]([^=]+)=/g; // gets all query params var regex2 = /[\?&]([a-zA-Z_]+)=[\w]/g; // gets non empty query params while( ( results = regex.exec( URL ) ) != null ) { params.push( results[1] ); } while( ( results = regex2.exec( URL ) ) != null ) { non_empty_params.push( results[1] ); } while(non_empty_params.length > 0) { for(y=0;y < params.length;y++) { if(params[y] == non_empty_params[0]) { params.splice(y,1); } } non_empty_params.shift(); } return params; } ``` It works, but looks ugly as hell... Is there any better way to do it? Any help is appreciated.
I just tested that this works in Opera and Chrom, the two browsers I have open right now: ``` function getEmptyQueryParams(URL) { var params = new Array(); var regex = /[\?&]([^=]+)=(?=$|&)/g; // gets non empty query params while( ( results = regex.exec( URL ) ) != null ) { params.push( results[1] ); } return params; } ```
I guess you could do that with one regex that would match empty and filled params. ``` var regex = /[\?&]([a-zA-Z_]+)=([\w]*)/g; while( ( results = regex.exec( URL ) ) != null ) { if (results[2] == '') params.push( results[1] ); } ``` To be tested, of course.
How to get empty href query parameters?
[ "", "javascript", "regex", "" ]
Is there something I can use to see if a number starts with the same digit as another? Ex. 5643 and 5377 both start with five. Is there a way to do this with numbers or do they have to be strings? (startsWith?)
Ich n1 and n2 are your numbers: ``` return (n1.toString().charAt(0) == n2.toString().charAt(0)); ``` You will have to use Integer not int, since int has no .toString() method. If n1 is an int you could use new Integer(n1).toString(). Or even better (suggested by Bombe): ``` String.valueOf(n1).charAt(0) == String.valueOf(n2).charAt(0) ```
Recurse dividing by ten until the whole division is less than ten, then that number is the first one and you can compare numbers.
Java Number comparisons
[ "", "java", "startswith", "" ]
I have a listView on my form. I want to add stuff to it durring the program is running. This is the code I use ``` public void FillList(string[] Name,int[] empty,int[] Population,int[] Max,int[] Check,int size) { if (this.InvokeRequired) { this.Invoke((MethodInvoker)delegate { for (int i = 0; i < size; i++) { ListViewItem item = new ListViewItem(Name[i]); item.SubItems.Add(empty[i].ToString); //error item.SubItems.Add(Population[i].ToString); //error item.SubItems.Add(Max[i].ToString); //error if (Check != 1) item.SubItems.Add("No"); else item.SubItems.Add("Yes"); listView1.Items.Add(item); } }); } } ``` the parameter must be string and I tried `.ToString`, but I get this: > Argument '1': cannot convert from 'method group' to 'string'
You are missing the parentheses of the method call: ``` ToString() ``` Without the parentheses, the expression is a [method group](https://stackoverflow.com/q/886822/1968) — that is, a reference to one or more overloaded methods.
You forgot the parentheses. It should be `.ToString()`
Int to string: cannot convert from 'method group' to 'string'
[ "", "c#", "winforms", "string", "listview", "int", "" ]
How do you print all variables available in the context of a Smarty template? Something like the Django debug trace that lists everything being passed. Thanks
Use `{debug}` [From the manual](http://www.smarty.net/docs/en/language.function.debug.tpl): > `{debug}` dumps the debug console to the > page. This works regardless of the > debug settings in the php script. > Since this gets executed at runtime, > this is only able to show the assigned > variables; not the templates that are > in use. However, you can see all the > currently available variables within > the scope of a template. `$debugging = true` must be enabled in your settings or class, and site popups must be unblocked to see the window
``` var_dump($Smarty->_tpl_vars); ``` From the Smarty code :)
Print all variables available in a Smarty template
[ "", "php", "smarty", "" ]
I am creating a class library with many different options for possible customizations. For example, you can design your class so that it can perform FeatureX(), or you can design your class so that it can perform FeatureY(). Under normal circumstances, you would simply create an interface IFeatureX with a pure virtual method called FeatureX, and another interface IFeatureY with a pure virtual method called FeatureY. If a class has both FeatureX and FeatureY, it can inherit from both, no problem. My problem is, what if a function/method requires an object that can perform both FeatureX() and FeatureY()? How do I express a type, in C++ preferably, but an answer in Java could help as well, to ensure that both FeatureX and FeatureY are available? Do I create another interface IFeatureXY that inherits from IFeatureX and IFeatureY? Okay... if there are only two features I could get away with this. But if there are say... 10 features, the number of possible interfaces becomes massive. Is there a simple way to do this? I tried solving the problem using C++ templates and delegation but didn't get too far. I'm hoping there is a simple solution to this, and there probably is one that I just overlooked. I appreciate any help and advice you guys have. Thanks.
If you're not afraid of using templates, you can make your function a template and use SFINAE to check for the two interfaces: ``` template <class T> void my_function(const T& data, typename enable_if_c< is_convertible<T*, IFeatureX*>::value && is_convertible<T*, IFeatureY*>::value>::type*=0) { ... } ``` This will create a method for every type that extends both feature interfaces (note that the SFINAE trick is not needed for it to work; an unconstrained template would work, but just fail to compile when you pass a type that doesn't meet the requirements). Another possibility is to create an interface IFeatureXY extending both, and use this in the function parameters; this has the drawback that types that **do** implement both interfaces, but not this joint interface would not be usable with this method. Also, you can pass two arguments to the function, one per interface, and require they are pointers to the same object; this is fragile, but could be hardened by making some template class to hold the two pointers - eg. `product_type<IFeatureX*, IFeatureY*>`, which would be initialized by the single object in question and which would hold the two types. In Java, you could probably do the same thing with bounded type variables (if they allow multiple bounds; I'm not sure now).
First thing to do is ask if you're trying to do something that can't be expressed simply, and if so, ask yourself if it is really worth doing? Given that you can't find a simpler model of what you want, you're going to need to think about dependencies among the options. If you can use Feature X independently of Feature Y, then make them independent interfaces or pure virtual classes (as appropriate to the language.) If you can't use them independently, make a class that includes both; ask yourself why you want FeatureX and FeatureY as separate interfaces, because that pattern of usage suggests they're not independent after all.
C++/Java Inheritance vs. Delegation vs. etc
[ "", "c++", "inheritance", "delegation", "" ]
I'm trying to make a little tag list doohickey for adding and removing tags. I have a textbox where the user can enter the tags, separated by commas. and an add button. I would like it for when the user clicks the add button to add a small div to the inside of a div below the box. the small div should contain the tag and a little x for which to remove the tag later. heres what I have: ``` <script type='text/javascript'> function tagsremove(tag) { document.getElementByName('tags').value.replace('/'+tag+'\,\s/', ''); } $('#tagbutton').click(function(){ var tags = $('#tagsbox').text().split(", "); for (var tag in tags) { document.getElementByName('tags').value += tag +", "; $('#curtags').append("<div class='tag'>" + tag + " <a href='#' onlclick='tagsremove(\'" + tag + "\');$(this).hide();'>x</a></div>") } }); </script> <div class='statbox'> <form method='post' action='post.php' id='writeform'> <p class='subtitle'>Title</p> <input type='text' name='title' id='titlebox' /><br /> <p class='subtitle'>Body</p> <textarea id='postbox' name='body' rows='10'></textarea><br /> <p class='subtitle'>Tags</p> <input type='text' id='tagsbox' /><input type='button' id='tagbutton' value='Add' /> <p class='subsubtitle'>Seperate by commas (eg. "programming, work, job")</p> <div class='subsubtitle' id='curtags'>Current Tags:</div> <input type='hidden' value='' name='tags' /> </form> </div> ``` The problem i'm having is that when I click the add button, nothing happens. I would like to fix this.
You have some issues in your code: 1 ) document.getElementByName('tags') That such function doesn't exists, the function you're trying to use is getElementsByName (notice the 's'), but since you're using jQuery, you could use a selector like: ``` var hiddenTags = $('input[name=tags]'); ``` 2) You're using text(), instead val() as [@Blair](https://stackoverflow.com/questions/732840/troublesome-javascript/732880#732880) point's out 3) In the foreach, you access the element indexes only, to access the actual element value, you have to do something like this: ``` for (var i in tags) { var tag = tags[i]; } ``` There will be more work to do, but for start, check my corrections [here](http://jsbin.com/urinu).
Your first problem is that ``` $('#tagsbox').text() ``` should be ``` $('#tagsbox').val() ``` because #tagsbox is an input field. There are other issues, like splitting on "," and then trimming rather than splitting on ", " but I think your main problem is the .text() vs .val()
troublesome javascript
[ "", "javascript", "jquery", "html", "" ]
I was reading [this article](http://swtch.com/~rsc/regexp/regexp1.html) today on two different regular expression algorithms. According to [the article](http://swtch.com/~rsc/regexp/regexp1.html) old Unix tools like ed, sed, grep, egrep, awk, and lex, all use what's called the Thompson NFA algorithm in their regular expresssions... However newer tools like Java, Perl, PHP, and Python all use a different algorithm for their regular expressions that are much, much slower. [This article](http://swtch.com/~rsc/regexp/regexp1.html) makes no mention at all of Javascript's regex algorthim, (and yes I know there are various JS engines out there) but I was wondering if anybody knew which of those algorithms they use, and if maybe those algorithms should be swapped out for Thompson NFA.
The Javascript ECMA language description doesn't impose a requirement for the particular implementation of regular expressions, so that part of the question isn't well-formed. You're really wondering about the particular implementation in a particular browser. The reason Perl/Python etc use a slower algorithm, though, is that the regex language defined isn't *really* regular expressions. A real regular expression can be expressed as a finite state machine, but the language of regex is context free. That's why the fashion is to just call it "regex" instead of talking about regular expressions. ### Update Yes, in fact javascript regex isn't ~~content free~~ regular. Consider the syntax using `{n,m}', that is, matches from *n* to *m* accepted regexs. Let *d* the difference *d*=|*n-m*|. The syntax means there exists a string *uxdw* that is acceptable, but a string *uxk>dw* that is not. It follows via the pumping lemma for regular languages that this is not a regular language. (augh. Thinko corrected.)
Though the ECMA standard does not specify the algorithm an ECMAScript implementation should use, the fact that the standard mandates that ECMAScript regular expressions must support backreferences (\1, \2, etc.) rules out the DFA and "Thompson NFA" implementations.
Which Regular Expression Algorithm does Javascript use for Regex?
[ "", "javascript", "regex", "algorithm", "language-agnostic", "unix", "" ]
In .NET is it possible to generate class diagrams (.cd) programmatically (C#)? If so how? PD: Obviously I'm not asking for directions of how to generate this using the IDE. I know that I can drag and drop the classes to a ClassDiagram item.
I just opened a .cd file using notepad, it's [plain XML](http://blogs.msdn.com/classdesigner/archive/2005/07/29/444501.aspx)... I shouldn't be that hard to generate it programmatically.
Select the .cs files you want a class diagram for, and select View Class diagram, and a .cd file will be generated and displayed.
.NET Class Diagrams without using the designer
[ "", "c#", ".net", "visual-studio", "class-diagram", "" ]
I am trying to understand the technical limits to the usability of web-based productivity applications that use only open, cross-platform technologies such as Javascript, HTML, and CSS on the client. [1] Let's assume for a moment that in the next few years the capabilities of web browsers continue to improve (e.g. with HTML 5 and faster JS engines), and significant progress is made in increasing bandwidth and reducing latency. **What technological barriers (e.g. performance, graphics, modes of user interaction) will remain that limit the usability of web productivity apps when compared to conventional client-side applications?** (Apart from offline access and issues that have significant non-technological aspects, such as privacy concerns.) [1] By "productivity applications", I mean things like office suites, email, calendars, and diagramming programs.
> and significant progress is made in increasing bandwidth and reducing latency. This **IS** the limitation, and latency is not something that is going to improve significantly in the future (there are real physical limits here). The roundtrip is the bottleneck. As for improvements, I see as javascript getting faster there being less AJAX and more client-side work. Right now, alot of AJAX is used to get display HTML form the server for rendering in the browser. In the future, AJAX will be used strictly for data, with javascript handing all the display. SO the barrier I see is javascript performance.
The real issue is that html+css does not provide 2d or 3d rendering primitives or any sort of real-time sound interface. Without those, a lot of the stuff we expect out of desktop apps aren't possible. I'm thinking of games, 2d/3d image and video editting, real time communications, that sort of thing. Obviously, you can do these things now, just not with open standards. With a little luck, more and more of the rich functionality available with Flash, Silverlight, and JavaFX will get pushed into "standards" and the barriers will be completely gone. I don't see any reason 99% of "productivity" apps couldn't run in a browser in a few years.
What are the technological limits to the usability of AJAX web apps?
[ "", "javascript", "html", "ajax", "web-applications", "" ]
Why do some people use the `Finalize` method over the `Dispose` method? In what situations would you use the `Finalize` method over the `Dispose` method and vice versa?
Others have already covered the difference between `Dispose` and `Finalize` (btw the `Finalize` method is still called a destructor in the language specification), so I'll just add a little about the scenarios where the `Finalize` method comes in handy. Some types encapsulate disposable resources in a manner where it is easy to use and dispose of them in a single action. The general usage is often like this: open, read or write, close (Dispose). It fits very well with the `using` construct. Others are a bit more difficult. `WaitEventHandles` for instances are not used like this as they are used to signal from one thread to another. The question then becomes who should call `Dispose` on these? As a safeguard types like these implement a `Finalize` method, which makes sure resources are disposed when the instance is no longer referenced by the application.
The finalizer method is called when your object is garbage collected and you have no guarantee when this will happen (you can force it, but it will hurt performance). The `Dispose` method on the other hand is meant to be called by the code that created your class so that you can clean up and release any resources you have acquired (unmanaged data, database connections, file handles, etc) the moment the code is done with your object. The standard practice is to implement `IDisposable` and `Dispose` so that you can use your object in a `using` statment. Such as `using(var foo = new MyObject()) { }`. And in your finalizer, you call `Dispose`, just in case the calling code forgot to dispose of you.
Finalize vs Dispose
[ "", "c#", "dispose", "" ]
How can I have one window move with another? i.e., I'd like a JDialog to follow a JFrame when the JFrame is being dragged. If the JFrame moves by (+5, +20), the JDialog needs to move the same. I've tried using ComponentListeners, but I only receive drag events in chunks which causes the JDialog window to be jumpy while dragging the main JFrame. I've tried using MouseListeners, but I can't figure out how to detect events on the actual frame of the JFrame.
AFAIK here is no move multiple windows in AWT. To get the moves to be called at a similar time, I guess you want the `JFrame` decorations to be PL&F rendered. Put in a PL&F-specific hack to do the moves yourself, moving both windows at almost the same time. You may still have a problem with exposing bits of windows only to cover them up causing some performance degradation.
Try using the ComponentListener.componentMoved event instead of monitoring drag events on the JFrame.
Java (Swing) - Drag two windows at once
[ "", "java", "swing", "drag", "" ]
If you have an instance of a Collection, say something like: ``` Collection<String> addresses = new ArrayList<String>(); ``` Which were to then be populated with a bunch of values, which is the "best" way, if any, to make use of the toArray() method without requiring a type cast? ``` String[] addressesArray = addresses.toArray(new String[] {}); String[] addressesArray = addresses.toArray(new String[0]); String[] addressesArray = addresses.toArray(new String[addresses.size()]); String[] addressesArray = addresses.toArray(new String[addresses.size() + 5]); ``` Is there any semantic difference between the first two? Is the third most efficient? Is the fourth less efficient than the third?
According to [a findbugs report](http://findbugs.sourceforge.net/bugDescriptions.html#ITA_INEFFICIENT_TO_ARRAY), this is the most efficient: ``` String[] addressesArray = addresses.toArray(new String[addresses.size()]); ``` I believe them ;)
For my money ``` String[] addressesArray = addresses.toArray(new String[0]); ``` is simplest, least error-prone and therefore "best". It also has the advantage that the same code works for concurrent/synchronized collections. You would have to be in some really low-level, heavily used code for the negligible performance difference to make any difference. Often you see an empty array assigned to a `static final` to avoid the allocation on every execution. Apparently, it turns out that the performance can drop due to that "optimisation" (allocation really are very fast). **Update:** Turn out this is faster than using a sized array. <http://shipilev.net/blog/2016/arrays-wisdom-ancients/> **tl;dr:** The reflection is of the trivial kind not involving slow method lookup, and zeroing of the array can be dropped if it can be determined that all of the elements will be written (or array becomes unreachable).
What to pass to the Arrays instance method toArray(T[] a) method?
[ "", "java", "arrays", "collections", "casting", "" ]
I'd like to create a routine that does some logging, takes some other actions, and then throws an Exception. I'd like this routine to be called from many different locations. However, creating Exceptions in this routine means they will have this routine in their stack trace. I would rather the stack trace not report this utility routine. Is there a way to do this without creating the Exception in the caller and passing it to the utility routine? ``` public static void die(String message) throws MyException { log(message); ... throw new MyException(); } ``` For programmers who are Perl/Java bilingual: how do I **carp** in Java?
You can set the stack trace of any exception you want to throw: ``` import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CarpTest { public static void main(String[] args) { new CarpTest().run(); } public void run() { methodThatCarps(); } private void methodThatCarps() { carp("Message"); } private void carp(String message) { RuntimeException e = new RuntimeException(message); e.fillInStackTrace(); List<StackTraceElement> stack = new ArrayList<StackTraceElement>(Arrays.asList(e.getStackTrace())); stack.remove(0); e.setStackTrace(stack.toArray(new StackTraceElement[stack.size()])); throw e; } } ``` This will print the following stacktrace at runtime: ``` Exception in thread "main" java.lang.RuntimeException: Message at CarpTest.methodThatCarps(CarpTest.java:18) at CarpTest.run(CarpTest.java:14) at CarpTest.main(CarpTest.java:10) ``` Note that as you want the method "carp" does not appear in the stacktrace. However the manipulation of stacktraces shoud only be done with greates care.
If you want to use an Exception to control the flow and what happens afterwards, a good advice it to override the fillInStackTrace() method: ``` public Throwable fillInStackTrace() { return this; } ``` As a result you'll have an Exception without the stacktrace and with a reduced overhead (filling in the stack trace takes time).
How do I throw an Exception from the caller's scope?
[ "", "java", "exception", "stack-trace", "" ]
I have the below stored procedure to check the user name availability ``` DELIMITER $$; DROP PROCEDURE IF EXISTS tv_check_email$$ CREATE PROCEDURE tv_check_email (IN username varchar(50)) BEGIN select USER_ID from tv_user_master where EMAIL=username; END$$ DELIMITER ;$$ ``` When I run this from my MySQL front end tool, it is works just fine: ``` call tv_check_email('shyju@techies.com') ``` But when trying to execute from the PHP page, I get an error like ``` "PROCEDURE mydatabase.tv_check_email can't return a result set in the given context" ``` I am sure that my PHP version is 5.2.6.
Cody is not 100% right. You can bind your resulting return columns and return select data from within a stored procedure. ``` $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); $stmt = $mysqli->prepare("call tv_check_email(?)"); $stmt->bind_param('s', "shyju@techies.com"); $stmt->execute(); $stmt->bind_result($userid); while ($stmt->fetch()) { printf("User ID: %d\n", $userid); } $stmt->close(); $mysqli->close(); ```
You need to bind your result into an OUT parameter. See the mysql docs on [stored procedures](http://dev.mysql.com/doc/refman/5.1/en/create-procedure.html) ``` mysql> delimiter // mysql> CREATE PROCEDURE simpleproc (OUT param1 INT) -> BEGIN -> SELECT COUNT(*) INTO param1 FROM t; -> END; -> // Query OK, 0 rows affected (0.00 sec) mysql> delimiter ; mysql> CALL simpleproc(@a); Query OK, 0 rows affected (0.00 sec) mysql> SELECT @a; +------+ | @a | +------+ | 3 | ``` +------+
MySQL stored procedure: can't run from PHP code
[ "", "php", "mysql", "stored-procedures", "" ]
I might have messed up on a design decision. Instead of using a strongly typed collection of custom objects, I have used a generic List. Essentially, what i have is: ``` public class AreaFields { [XmlArray("Items")] [XmlArrayItem("Item")] public List<Fields> Fields { set; get; } [XmlAttribute] int id { set; get; } } public class Fields { [XmlAttribute] public string Name { set; get; } } ``` Throughout the application, I have used `List<AreaFields>` Now, I am in need of serializing the list into XML. What I am hoping to get is: ``` <SomeXMLTag> <AreaFields id='1000'> <Items> <Item Name="Test1" /> <Item Name="Test2" /> </Items> </AreaFields> <AreaFields id='1001'> <Items> <Item Name="Test1" /> <Item Name="Test2" /> </Items> </AreaFields> </SomeXMLTag> ``` Since I cannot serialize List<> (or can I?), I will have to serialize every item of the list. ``` Ex: List<AreaFields> list = new List<AreaFields>(); // more code to add to list list[0].GetRawXML(); //A method i have to serialize ```
You'll need a wrapper class; then serialize the instance of `MyWrapper` to get the xml as per your example. ``` [XmlRoot("SomeXMLTag")] public class MyWrapper { [XmlElement("AreaFields")] public List<AreaFields> AreaFields { get; set; } } public class AreaFields { [XmlArray("Items")] [XmlArrayItem("Item")] public List<Fields> Fields { set; get; } [XmlAttribute] public int id { set; get; } } public class Fields { [XmlAttribute] public string Name { set; get; } } ```
You can serialize List<>. Read [here](https://stackoverflow.com/questions/664267/serializing-an-arraylist-in-c/664504#664504) for the attributes I've used.
Serializing a list of strongly typed objects
[ "", "c#", "asp.net", "xml", "" ]
Hi I'm using Struts 1.2 and I installed TinyMCE. The problem is that struts is converting all HTML tags into entities. How do I disable or configure this to allow only selected tags?
Use the filter parameter ([taglib](http://struts.apache.org/1.x/struts-taglib/tagreference.html#bean:write)). ``` <bean:write name="someField" filter="false"/> ```
Thanks, I was looking for this but in Struts 2, and this helped, it's similar: ``` <s:property value="variable" escape="false" /> ```
Disable Struts converting HTML tags into entities
[ "", "java", "jakarta-ee", "struts", "" ]
What are the best libraries available right now for client side pagination?
[jQuery Tablesorter](http://tablesorter.com/docs/) is a good choice because you usually want a table with sorting when you're displaying data, and it also has pagination built in, so you get the whole shebang.
YUI also has a very easy to use [client-side pagination control](http://developer.yahoo.com/yui/examples/datatable/dt_clientpagination.html).
Client Side Pagination
[ "", "javascript", "search", "pagination", "" ]
I have a chicken-egg problem. I would like too implement a system in PHP in a OOP way, in which two classes would play important roles: Database and Log. My idea was to build up the connection by the Database class, which would have public methods eg. runQuery(sUpdateQuery), doInsert(sInsert), etc. The Log class would writing logs through common methods just as like logMessage(message), logDatabaseQuery(sQuery) TO THE DATABASE. The problem comes now. 1: Inside the methods of the Database's class I would like to be able to use the Log class's logDatabaseQuery(sQuery) 2: This still would not be a big challenge if I would not like to use the Database class's doInsert(sInsert) method inside the logDatabaseQuery method. I would like to keep it simple - and just use one instance of the database connection object, and from the loggeras well, if it is possible. For many people Singleton model would be the first idea to choose, but I definitely would like to use different solution. So there would be two classes which would use each-other's methods: Database doInsert logDatabaseQuery Log logDatabaseQuery doInsert I would like to keep the Log methods separately (in the Log class), since later on it would have other methods for logging not just to the database, but to files or e-mails as well. Any ideas, how this should / could be done in the nicest, OOP friendly way? I was thinking about a common parent abstract class, or about using interfaces as well, but finally could not figure out the proper way :( What I would like to know is a suggestion for a correct class hierarchy
You have combined too many things together. The database can't really depend on a logger which depends on the database. It isn't good design. What you really have are two kinds of database access. Low-level access does "raw" SQL. The logger can depend on this lower-level class. It doesn't -- itself -- have raw SQL in it. It depends on a lower-level class. High-level access does application queries, it uses low-level access **and** the logger.
It sounds like you have two different database accesses - logged (normal case) and unlogged (for the logging functions). Split the database class into two, a higher-level version for logged requests, and a lower-level version for unlogged requests. Implement the higher level database class using references to the logging and lower level database classes.
Egg-chicken problem in OOP way
[ "", "php", "design-patterns", "oop", "" ]
I have a query that looks like this: ``` SELECT OrganizationName, OrganizationID, ReceivableStatus, InvoiceFee FROM v_InvoicesFreelanceOutstanding ORDER BY OrganizationID ``` The data from that might look like this: ``` OrganizationName OrganizationID ReceivableStatus InvoiceFee ----------------------------------------------------------------------------- Company A 139 60-90 days 672.00 Company A 139 60-90 days 1800.00 Company A 139 over 90 days 1440.00 Company B 264 Current 3559.38 Company B 264 60-90 days 3785.50 Company C 271 60-90 days 446.25 Company C 271 over 90 days 637.50 Company C 271 over 90 days 1126.25 ``` What I want to eventually display is something like this (for the data above): ``` Company Current 30-60 days 60-90 days over 90 days Total ----------------------------------------------------------------------------- Company A 0 0 2472.00 0 2472.00 Company B 3559.38 0 3785.50 0 7344.88 Company C 0 0 446.25 1763.75 2210.00 ``` My SQL-fu is not enough to get me past this: ``` SELECT MAX(OrganizationName) as OrganizationName, OrganizationID, ReceivableStatus, SUM(InvoiceFee) as TotalDue FROM v_InvoicesFreelanceOutstanding GROUP BY OrganizationID, ReceivableStatus ``` Which shows something like this (again, from the data above): ``` OrganizationName OrganizationID ReceivableStatus TotalDue ----------------------------------------------------------------------------- Company A 139 60-90 days 2472.00 Company A 139 over 90 days 1440.00 Company B 264 Current 3559.38 Company B 264 60-90 days 3785.50 Company C 271 60-90 days 446.25 Company C 271 over 90 days 1763.75 ``` What then? Any help would be appreciated. Note that the statuses shown in the 2nd table (`Current`, `30-60 days`, `60-90 days`, `over 90 days`) are the only ones I'm expecting to come up under `ReceivableStatus`. **EDIT**: Sorry for not including this. I am aware of `PIVOT` but I couldn't get it to do what I want.
This looks like a job for [`pivot`](http://msdn.microsoft.com/en-us/library/ms177410.aspx) if you're using SQL Server 2005 or later. EDIT: Since you already know about `pivot`, you know it does almost what you need. You already have the following query: ``` SELECT MAX(OrganizationName) as OrganizationName, OrganizationID, ReceivableStatus, SUM(InvoiceFee) as TotalDue FROM v_InvoicesFreelanceOutstanding GROUP BY OrganizationID, ReceivableStatus ``` Which gives you the current, 30-60, 60-90 and 90+ parts that you need. If you pivot that, you get everything you need except for your total. So just throw in the total: ``` (SELECT MAX(OrganizationName) as OrganizationName, OrganizationID, ReceivableStatus, SUM(InvoiceFee) as TotalDue FROM v_InvoicesFreelanceOutstanding GROUP BY OrganizationID, ReceivableStatus) UNION (SELECT MAX(OrganizationName) as OrganizationName, OrganizationID, 'Total' AS ReceivableStatus, SUM(InvoiceFee) as TotalDue FROM v_InvoicesFreelanceOutstanding GROUP BY OrganizationID) ``` Pivot on this result and you should get the output you want: ``` SELECT * FROM [the query above] PIVOT ( SUM(TotalDue) FOR ReceivableStatus IN ([Current],[30-60 days],[60-90 days],[over 90 days],[Total]) ) ```
PIVOT sucks. It has horrible syntax and isn't a PIVOT in the pivot table sense i.e. you have to know exactly how many columns will result in advance. It's probably easier to do a cross-tab report. ``` SELECT OrganizationName, OrganizationID, SUM(CASE WHEN ReceivableStatus = '30-60 days' THEN InvoiceFee ELSE 0 END) AS [30 - 60 Days], SUM(CASE WHEN ReceivableStatus = '60-90 days' THEN InvoiceFee ELSE 0 END) AS [60 - 90 Days], SUM(CASE WHEN ReceivableStatus = '90-120 days' THEN InvoiceFee ELSE 0 END) AS [90 - 120 Days] FROM v_InvoicesFreelanceOutstanding GROUP BY OrganizationID ```
Rows Into Columns and Grouping
[ "", "sql", "sql-server", "" ]
When should we override the **GetHashCode**() method provided by '**Object**' class in '**System**' namespace?
When you override `Equals`, basically. When you want to provide a different idea of equality than simple reference equality. String is a good example of this - two strings are equal (under a simple Equals call) if they represent the same sequence of characters. The hash code reflects this, such that if two strings are equal they will have the same hash code. (The reverse isn't necessarily true - two unequal strings *can* have the same hash code, but it's unlikely.) (Strings are tricky in other ways, mind you - there are lots of different ideas of equality based on culture and casing, but `String.Equals` just looks at the UTF-16 code points which make up the string, and compares them in the simplest conceivable fashion.)
If your type should follow value semantics (comparing contents) instead of reference semantics (comparing object identity) , you should write you own override of instance object.Equals().
When to override GetHashCode()?
[ "", "c#", ".net", "" ]
What is the difference between this: ``` Myclass *object = new Myclass(); ``` and ``` Myclass object = new Myclass(); ``` I have seen that a lot of C++ libraries like wxWidgets, OGRE etc use the first method... Why?
The second is wrong ! You may use ``` MyClass object; ``` That will work. Now, concerning how to choose between these two possibilities, it mainly depends on how long your object should live. See [there](https://stackoverflow.com/questions/408670/stack-static-and-heap-in-c) for a thorough answer.
``` Myclass *object = new Myclass(); //object has dynamic storage duration (usually is on the heap) Myclass object; //object has automatic storage duration (usually is on the stack) ``` You create objects with dynamic storage duration (usually on the heap) if you plan on using them throughout a long period of time and you create objects with automatic storage duration (usually on the stack) for a short lifetime (or scope).
Different methods for instantiating an object in C++
[ "", "c++", "object", "initialization", "" ]
I have: ``` ComboBox.DataSource = System.Enum.GetValues(typeof(ImageLayout)); ``` but how do I set the `ComboBox.SelectedItem` to an `ImageLayout` value? I tried.. ``` LayOutCB.SelectedItem = (int)ImageLayout.Center; ``` but I get an exception --- ### Update: originally I was trying to set the `SelectedItem` in the constructor of the `UserControl`. I added the event Handler ``` this.Load += new EventHandler(PageSettings_Load); ``` and then set the combobox.SelectedItem in there. ``` void PageSettings_Load(object sender, EventArgs e) { LayOutCB.SelectedItem = ImageLayout.Center; } ``` Works real good now. so what was that about? can someone explain please.
Have you not tried this? ``` ComboBox.SelectedItem = ImageLayout.Center ``` It works perfectly fine for me. --- ### Edit: With regards to your update, I believe you are setting the `SelectedItem` before calling `InitializeComponent()` and the combo box was not created yet give you the object reference exception (the box was defined but not assigned.)
Try something like this: ``` ComboBox.SelectedItem = (int)ImageLayout.Foo; ``` replacing `int` with the underlying type of your enumeration. Honestly it may just work without the cast but I am not anywhere near `csc.exe` right now.
How do I set a comboBox.selecteditem
[ "", "c#", "" ]
I've discovered that the following code: ``` public static class MimeHelper { public static string GetMimeType(string strFileName) { string retval; switch (System.IO.Path.GetExtension(strFileName).ToLower()) { case ".3dm": retval = "x-world/x-3dmf"; break; case ".3dmf": retval = "x-world/x-3dmf"; break; case ".a": retval = "application/octet-stream"; break; // etc... default: retval = "application/octet-stream"; break; } return retval; } } ``` causes the compiler to create this namespaceless, internal class (copied from Reflector): ``` <PrivateImplementationDetails>{621DEE27-4B15-4773-9203-D6658527CF2B} - $$method0x60000b0-1 : Dictionary<String, Int32> - Used By: MimeHelper.GetMimeType(String) : String ``` Why is that? How would I change the above code so it doesn't happen (just out of interest) Thanks Andrew
It's creating the dictionary to handle the lookups of the various cases in the switch statement instead of making several branching ifs out of it to set the return value. Trust me -- you don't want to change how it's doing it -- unless you want to make the map explicit. **ASIDE**: I had originally assumed that the dictionary stored a map from each case to the an index into another map for the return values. According to @Scott (see comments), it actually stores an index to a label for the code that should be executed for that case. This makes absolute sense when you consider that the code that would be executed for each case may differ and may be much longer than in the given example. **EDIT**: Based on your comment, I think I might be tempted to store the mappings in an external configuration file, read them in during start up, and construct the actual map -- either a single level map from key to value or a similar multilevel map from key to index and index to value. I think it would be easier to maintain these mappings in a configuration file than to update the code every time you needed to add or remove a particular case.
What is happening is compiler is creating an internal class that it emits at compile time. This class is called `<PrivateImplementationDetails>{99999999-9999-9999-9999-999999999999}`, the GUID component of this class is generated at compile time so it changes with every build. Internally in this class there is a dictionary that contains the different case variables, and an int corresponding to each value. It then replaces the switch statement with a lookup in the dictionary to get the corresponding int, and does a switch on the int value (much more efficient than doing a bunch of sting compares).
Why does the c# compiler create a PrivateImplementationDetails from this code?
[ "", "c#", "" ]
> **Possible Duplicate:** > [Fixing the PHP empty function](https://stackoverflow.com/questions/410002/fixing-the-php-empty-function) In PHP, empty() is a great shortcut because it allows you to check whether a variable is defined AND not empty at the same time. What would you use when you don't want "0" (as a string) to be considered empty, but you still want false, null, 0 and "" treated as empty? That is, I'm just wondering if you have your own shortcut for this: ``` if (isset($myvariable) && $myvariable != "") ;// do something if (isset($othervar ) && $othervar != "") ;// do something if (isset($anothervar) && $anothervar != "") ;// do something // and so on, and so on ``` I don't think I can define a helper function for this, since the variable could be undefined (and therefore couldn't be passed as parameter).
The answer to this is that it isn't possible to shorten what I already have. Suppressing notices or warnings is not something I want to have to do, so I will always need to check if empty() or isset() before checking the value, and you can't check if something is empty() or isset() within a function.
This should do what you want: ``` function notempty($var) { return ($var==="0"||$var); } ``` Edit: I guess tables only work in the preview, not in actual answer submissions. So please refer to the [PHP type comparison tables](https://www.php.net/manual/en/types.comparisons.php) for more info. ``` notempty("") : false notempty(null) : false notempty(undefined): false notempty(array()) : false notempty(false) : false notempty(true) : true notempty(1) : true notempty(0) : false notempty(-1) : true notempty("1") : true notempty("0") : true notempty("php") : true ``` Basically, notempty() is the same as !empty() for all values except for "0", for which it returns **true**. --- Edit: If you are using **error\\_reporting(E\\_ALL)**, you will not be able to pass an undefined variable to custom functions by value. And as mercator points out, you should \_always\_ use **E\\_ALL** to conform to best practices. [This link](http://www.smashingmagazine.com/2009/03/24/10-useful-php-tips-revisited/) (comment #11) he provides discusses why you shouldn't use any form of error suppression for performance and maintainability/debugging reasons. **See orlandu63's answer for how to have arguments passed to a custom function [by reference](http://us.php.net/manual/en/functions.arguments.php).**
PHP: what's an alternative to empty(), where string "0" is not treated as empty?
[ "", "php", "" ]
I'm looking for a C# code snippet to give me a notification for when a USB drive is plugged into my PC in Windows Vista (or win7)
There's a class called [DriveDetector](http://www.codeproject.com/KB/system/DriveDetector.aspx) over at Codeproject that sounds like it does what you want.
Look at [WM\_DEVICECHANGE](http://msdn.microsoft.com/en-us/library/aa363480(VS.85).aspx). This message should be sent when a drive is inserted.
Looking for C# code for detecting removable drive (usb flash)
[ "", "c#", "windows-vista", "usb-drive", "" ]
There is a table with values like this: ``` Sets | Reps -----+------ 2 | 10 3 | 15 3 | 12 4 | 8 ``` I need to combine those two values into one in my SELECT statement, so I could get ``` SELECT ... AS Reps FROM Table Reps ------------ 10,10 15,15,15 12,12,12 8,8,8,8 ``` Any ideas how to do this? Testing script: ``` DECLARE @Test TABLE ([Sets] INT, [Reps] INT); INSERT INTO @Test VALUES (2, 10); INSERT INTO @Test VALUES (3, 15); INSERT INTO @Test VALUES (3, 12); INSERT INTO @Test VALUES (4, 8); SELECT [Sets], [Reps] FROM @Test; // Here is an answer by tpdi: SELECT CAST([Reps] AS VARCHAR) + REPLICATE(',' + CAST([Reps] AS VARCHAR), [Sets] - 1) AS [Reps] FROM @Test; ```
Like this: ``` select substring(replicate(','+cast(Reps as varchar),Sets),2,8000) as Reps from Table ```
select cast(reps as varchar) + replicate( ',' + cast(reps as varchar), sets - 1) from table
T-SQL for combining 2 columns' values into one with "replicate"
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm sure this is a dumb question, but.. We have the same Java source files and we want to use a different version of a Java API (jar file) depending on the client we are building our app for. The newer version of the API has the methods setAAA() and setBBB() which we reference in our Java source: ``` if (...) { api.setAAA(a); api.setBBB(b); } ``` This code will fail if compiled with the old API has the old API doesn't have these setters. Is there any way to conditionalize this code to only compile the setter lines if we are using the new API? Thanks.
Java really wasn't meant for this conditional compilation (unlike C++), and it honestly sounds like a recipe for ending up in "classpath hell". While you could manually start dealing with functions that return the version of your API, you then have a classfile that fits a specific version, but with no indications that it may be incompatible. I've encountered this situation before (e.g., working with different versions of Eclipse) and it's not pretty. What I ended up doing is having an interface with two different implementations, one for each API, put each of them in a separate project (a plug-in in my case), and then tried to load them with a factory or an injection. Isolate them as well as you can.
The safest approach is to fall back to the lowest version you need to support. That assumes all versions are backwards compatible which isn't necessarily the case. If that solution isn't appropriate or desirable then I fall back to [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection). The [Spring framework](http://www.springsource.org/) is by far the most popular and common DI framework but no means the only one. [Guice](http://code.google.com/p/google-guice/) is another one. You can even roll your own if it's undesirable to add a complete framework for this. But I have problems envisioning a Java application--particularly a Web/J2EE application--that I do without using Spring. It's simply too useful. Let's say there are 4 versions of a relevant jar. The API has changed twice in that time so you have 3 different API versions. You need to abstract use of that jar to an API of your own that is consistent across all these versions and then create three implementations of it: one for each different API version. In Spring you create an application context, which defines all your beans and how they're injected into other beans. There is no reason you can't choose or build and application context as part of a build process. Often properties are used for this but you could also include part of the application context this way too. The key point here is that even though the APIs are different you need to abstract away those differences as far as your code is concerned. If you don't you're just asking for trouble and it just gets messier.
Handling different API versions in same Java source
[ "", "java", "build-process", "configuration-management", "" ]
I have a small problem with a define. I want to assign it to an integer variable but the compiler says it's undeclared. Here's what the code looks like: defines.h ``` #ifndef DEFINES_H #define DEFINES_H #define MYDEFINE 2 #endif ``` myclass.h ``` namespace mynamespace { class myClass { int someFunction(); }; } ``` myclass.cxx ``` #include "defines.h" #include "myclass.h" namespace mynamespace { int myClass::someFunction() { int var = MYDEFINE; return 0; } } ``` In the line with the int assignment the compiler error takes place. I also tried to use another define, defined in the same header file as above, as a function parameter with the same effect. Any ideas? Thanks in advance. I know using defines is a bad habit, but I only extend an existing project and I try to stay in their design ways. EDIT: The error message simply is: `Fehler 1 error C2065: 'MYDEFINE': nichtdeklarierter Bezeichner ...` As you might see this is not the real source code, but I think I was very careful while putting together the question. EDIT2: Thanks for the hint with the #warning. There were 2 files with the same name in different folders. I've no idea why the compiler didn't bring this up. Anyway, it works now.
You should check whether the symbol MYDEFINE is really defined. Check whether the header file where it is declared is really included (and compiled). Use #warning near the define to make sure it is compiled for myclass.cxx: ``` #ifndef DEFINES_H #define DEFINES_H #define MYDEFINE 2 #warning My define is defined #endif ``` If it is not compiling (you'll not find the warning message in compilation log), make a search for DEFINES\_H. It might be already defined somewhere else.
Let's put it all together: ``` #ifndef DEFINES_H #define DEFINES_H #define MYDEFINE 2 #endif namespace mynamespace { class myClass { int someFunction(); }; // note ; missing in your code } namespace mynamespace { int myClass::someFunction() { int var = MYDEFINE; return 0; } ``` This compiles with no errors, so there is something wrong in your #includes.
C2065 undeclared identifier while assigning a define to an int
[ "", "c++", "compiler-errors", "c-preprocessor", "" ]
Have the following string i need to split. ``` $string = "This is string sample - $2565"; $split_point = " - "; ``` One: I need to be able to split the string into two parts using a regex or any other match and specify where is going to split. Second: Also want to do a preg\_match for $ and then only grab number on the right of $. Any suggestions?
``` $split_string = explode($split_point, $string); ``` and ``` preg_match('/\$(\d*)/', $split_string[1], $matches); $amount = $matches[1]; ``` If you want, this could all be done in one regex with: ``` $pattern = '/^(.*)'.preg_quote($split_point).'\$(\d*)$/' preg_match($pattern, $string, $matches); $description = $matches[1]; $amount = $matches[2]; ```
``` $parts = explode ($split_point, $string); /* $parts[0] = 'This is string sample' $parts[1] = '$2565' */ ```
Split String into Parts PHP
[ "", "php", "regex", "string", "" ]
What is the difference between those three code samples here below? Is one better than the others and why? ``` 1.Page.ClientScript.RegisterClientScriptInclude(typeof(demo), "jQuery", ResolveUrl("~/js/jquery.js")); 2. <asp:ScriptManager runat="server"> <Scripts> <asp:ScriptReference Path="~/jquery-1.2.6.min.js" /> <asp:ScriptReference Path="~/jquery.blockUI.js" /> </Scripts> </asp:ScriptManager> 3. <script type="text/javascript" src="/js/jquery.latest.js"></script> ``` I've seen people using jQuery in their examples, and each one of them brings jQuery into ASP.NET in a different way. What is the best way?
**The first one is** > used on server side for adding client script **The second one is** > used with managing of asp.net [AJAX scripts](http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.aspx).If jQuery detects an ASP.Net AJAX ScriptManager, it will use this to register the scripts instead of Page.ClientScript **The third one is** > the plain way to register the jquery plugin I typically prefer the last one over the second one, but I never use Ajax anyway, and the first it only needed when you want to add in script after a postback to the server is done
It depends what you are trying to achieve. The first one adds the script tag to your page during rendering, from the server side. This can be useful for adding dynamically generated JavaScript and things like that. The second option is only interesting if you're using ASP.NET AJAX for managing your JavaScript, because it registers a whole lot of other JavaScript on the page. So if you want to keep everything clean and only plan on using jQuery, go with option 3.
Proper way of bringing in jQuery into ASP.NET (or any other external JavaScript)
[ "", "asp.net", "javascript", "jquery", "" ]
I often have large arrays, or large amounts of dynamic data in PHP that I need to run MySQL queries to handle. Is there a better way to run many processes like INSERT or UPDATE without looping through the information to be INSERT-ed or UPDATE-ed? Example (I didn't use prepared statement for brevity sake): ``` $myArray = array('apple','orange','grape'); foreach($myArray as $arrayFruit) { $query = "INSERT INTO `Fruits` (`FruitName`) VALUES ('" . $arrayFruit . "')"; mysql_query($query, $connection); } ```
OPTION 1 You can actually run multiple queries at once. ``` $queries = ''; foreach(){ $queries .= "INSERT....;"; //notice the semi colon } mysql_query($queries, $connection); ``` This would save on your processing. OPTION 2 If your insert is that simple for the same table, you can do multiple inserts in ONE query ``` $fruits = "('".implode("'), ('", $fruitsArray)."')"; mysql_query("INSERT INTO Fruits (Fruit) VALUES $fruits", $connection); ``` The query ends up looking something like this: ``` $query = "INSERT INTO Fruits (Fruit) VALUES ('Apple'), ('Pear'), ('Banana')"; ``` This is probably the way you want to go.
If you have the mysqli class, you can iterate over the values to insert using a prepared statement. ``` $sth = $dbh->prepare("INSERT INTO Fruits (Fruit) VALUES (?)"); foreach($fruits as $fruit) { $sth->reset(); // make sure we are fresh from the previous iteration $sth->bind_param('s', $fruit); // bind one or more variables to the query $sth->execute(); // execute the query } ```
Is it bad to put a MySQL query in a PHP loop?
[ "", "php", "mysql", "" ]
Is there a way - using jQuery or otherwise - to monitor the DOM for insertions, deletions, updates to styles, etc?
See "MutationEvent" elements in here: <https://developer.mozilla.org/en/DOM/DOM_event_reference> but those are deprecated. jQuery now features a way to attach events to existing AND future elements corresponding to a selector: <http://docs.jquery.com/Events/live#typefn> It may be a trick you could use for lack of proper DOM Node modification info.
See the [mutation-summary](http://code.google.com/p/mutation-summary/) library. It's built on top of a new browser API called DOM Mutation Observers.
How do I monitor the DOM for changes?
[ "", "javascript", "jquery", "dom", "" ]
I ran into this supposed interview of Bjarne Stroustrup, the inventor of C++. <http://artlung.com/smorgasborg/Invention_of_Cplusplus.shtml> > **Stroustrup**: Well, it's been long enough, now, and I believe most people have figured out for themselves that C++ is a waste of time but, I must say, it's taken them a lot longer than I thought it would... > > **Interviewer**: Yes, but C++ is basically a sound language. > > **Stroustrup**: You really believe that, don't you? Have you ever sat down and worked on a C++ project? Here's what happens: First, I've put in enough pitfalls to make sure that only the most trivial projects will work first time. Take operator overloading. At the end of the project, almost every module has it, usually, because guys feel they really should do it, as it was in their training course. The same operator then means something totally different in every module. Try pulling that lot together, when you have a hundred or so modules. And as for data hiding, God, I sometimes can't help laughing when I hear about the problems companies have making their modules talk to each other. Is this a hoax? Do any of these points seem true for any of the veteran C++ programmers out there?
You just have to check the [Stroustrup's website (the FAQ part)](http://www.stroustrup.com/bs_faq.html#IEEE) to find that it's wrong - a well known hoax as Judah Himango already pointed : > **Did you really give an interview to IEEE?** > > in which you confessed that C++ was > deliberately created as an awful > language for writing unmaintainable > code to increase programmers' > salaries? Of course not. [Read the > real IEEE interview.](http://www.stroustrup.com/ieee_interview.html)
It's a [well-known hoax](http://jimmod.blogspot.com/2007/01/interview-with-bjarne-stroustrup-hoax.html). And no, learning C++ isn't a waste of your time, something that's been discussed on StackOverflow many times.
Is C++ a "waste of time"?
[ "", "c++", "" ]
I have a problem where I need to synchronize processing for multiple threads across multiple different servers for a Java service on Windows. In this application, I have multiple consumer threads pullings messages off the same JMS queue. Messages come in in groups of 3 or 4, and I need to make sure the messages in each group are processed completely in serial. I need some sort of synch mechanism to make sure if thread1 pulls a message off, then thread2 pulls the next message from that group, thread2 waits for thread1 to finish processing before starting to process it's message. Any suggestions on distributed synching mechanisms for threads? Any type of solution would be good (JMS solutions, distributed caching, etc.) Note: the JMS provider we're using is ActiveMQ.
ActiveMQ has support for [message groups](http://activemq.apache.org/message-groups.html) which, quite literally, should be exactly what you need.
you might want to consider using [Hazelcast](http://www.hazelcast.com) distributed locks. Super lite, easy and open source. ``` java.util.concurrent.locks.Lock lock = Hazelcast.getLock ("mymonitor"); lock.lock (); try { // do your stuff }finally { lock.unlock(); } ``` Regards, -talip [Hazelcast](http://www.hazelcast.com) - Open Source Distributed Queue, Map, Set, List, Lock
Java: synchronizing threads across multiple servers
[ "", "java", "multithreading", "synchronization", "jms", "distributed", "" ]
I need to capture the first frame of a video uploaded on an asp.net website. I really would like to do this with WPF (if it's even possible), but if anyone knows an easier way, I am open to that too. I have seen examples of this using MediaPlayer and RenderTargetBitmap in WPF, but each example assumes the video is accessible via a URI. In my scenario, I only have the file bytes and I do not want to store the video directly on the FS. <http://blogs.msdn.com/delay/archive/2008/09/03/video-frame-grabbing-made-easy-how-to-quickly-capture-multiple-video-frames-with-wpf.aspx> Any help is greatly appreciated!
I ended up using [FFMpeg.exe](http://ffmpeg.org) ([Downloaded from here](http://ffdshow.faireal.net/mirror/ffmpeg)) to capture the first frame of videos uploaded to my site. This probably isn't the most ideal solution, but I don't have any DirectShow experience and, in my opinion, this solution is much simpler than other suggestions mentioned. I was not able to get around saving the file to the file system, so I simply wrote the uploaded bytes out to a temporary file on disk performed the work using FFMpeg and then removed each of the files generated during the process. The processing for this is done on a separate thread from the request thread. If I find this to be an issue, I have a separate Windows service that I can offload the work to with no problem. The syntax for obtaining a single frame is as follows: ``` FFMpeg.exe -i "c:\MyPath\MyVideo" -vframes 1 "c:\MyOutputPath\MyImage%d.jpg" ``` The %d is very important. If you do not include this, FFMpeg will throw an error. The %d will substitute a serial number when writing out the file. I hope this helps!
I don't know that this is advisable at all, as it will more than likely require that you run a message pump of some kind, which is a really bad idea in an ASP.NET site. Rather, I would use the DirectShow API to try and process the video. You *should* be able to stream the content as bytes using it, and you won't need a message loop to process the video. You can access it through .NET using the DirectShow .NET wrapper, located here: <http://directshownet.sourceforge.net/> And you will want to look at the Sample Grabber Example on MSDN: <http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx> Mind you that you might not necessarily want the first frame, as with a number of videos, they can be black and not really be a good candidate for a thumbnail. Rather you might want to do what Vista does and look for the first non-black frame.
Capturing the first frame of a video with WPF
[ "", "c#", "asp.net", "wpf", "" ]
Instead of passing many arguments to a method, I was encapsulating it into an argument object. *note*: simplied for demo ![alt text](https://farm4.static.flickr.com/3461/3390095308_6f5dccc4cd_o.png) For such a case, what would be a better practice? > • Create a class and **name** it as `InventorySaveArgs`? > -- or -- > • Create a nested class and **name** it as `SaveArgs`? And would you also explain why one would choose one or the other? **[EDIT]**: That argument type will be used in another assemblies, as well. *side question*: Just curious, if there is a pattern name for encapsulating multiple parameters to a single object by chance. **[UPDATE]**: [Found Nested Type Usage Guidelines](http://msdn.microsoft.com/en-us/library/tdz1bea9(VS.71).aspx) on MSDN `InventorySaveArgs` should be available from another assemblies, so I am going with a regular class.
IIRC .NET Design Guidelines are pretty clear on this - there should be no public nested types.
I would name it `InventorySaveArgs` just in case you ever want to make the type available to other types to use. If you name it `InventorySaveArgs` from the beginning then you will have a name that is meaningful in all contexts if you ever need to refactor.
Create a regular class or an Inner class for a Parameter Object?
[ "", "c#", ".net", "naming-conventions", "inner-classes", "parameter-object", "" ]
I have a class, C. C has a member variable declared as: bool markerStart; From within C a call to sizeof(\*this) gives a value of 0x216 bytes. Elsewhere within C, I do: markerStart = false; Rather than setting markerStart to false, this call is actually clobbering the start of the next class in memory! Looking at the disassembled code, I find: ``` markerStart = false; 06FB6B7F mov eax, dword ptr [this] 06FB6B78 mov byte ptr [eax+218h], 0 ``` The second move instruction is setting a byte at this + 0x218 to zero, but since the class is only 0x216 bytes long, this is clobbering memory! In response to a comment, it definitely is the markerStart = false instruction. I can watch it happening in the disassembler view and in the memory view (and using Windbg, by using a data breakpoint). The first byte of the next class gets set to zero, which messes up its vftbl pointer. Note: taking the address of markerStart and subtracting it from this, yields 0x211! Can anyone give me a clue on where to start looking to resolve this problem? Update: Thanks for all the help. Without code, it was next to impossible for any of you to solve the problem. What I was looking for were hints as to where to start looking. Most of you provided excellent hints, so thank you! I finally found the problem. In this case alignment had been set in one class, and not been correctly reset following the critical block of code. The class with the faulty alignment happened to get compiled immediately before the declaration of class C - hence that's where the problem showed up.
As pointed out by Pontus, you probably broken the one definition rule somehow. You've probably included the header file with the definition of class C in two translation units where other code, often in a preceding header file, changes the way the definition of class C is interpreted so that it has a different size in the two translation units. One possibility, is that you've accidently changed the default member alignment (either through a command line argument to the compiler or via a #pragma in the source) so that two different translation units think the structure has a different size because of differing amounts of padding (most x86 compilers default to alignment on 4-byte boundaries, but allow you to request alignment on 1-byte boundaries as needed). Look in the other header files for a #pragma changing the default alignment that is missing a following #prama to restore it back to the previous value (you don't specify what compiler, so I can't give specifics).
You need to post more code -- even better would be if you could prune it down to the minimum class definition where your anomaly occurs. That in itself will probably help you identify what's happening. Some possibilities that occur to me: 1. You are referencing another markerStart variable which shadows the member variable you are interested in. 2. You calculate the sizeof in the method of a base class of C. sizeof() only measures the static type, not the dynamic type. 3. You have broken the [One Definition Rule](http://en.wikipedia.org/wiki/One_Definition_Rule) somewhere, and have two different versions of the class C (perhaps through some #ifdef in a header file which is interpreted differently in two translation units). Without more information, I'd go for the ODR violation. Those can be insidious, and impossible to detect when compiling or linking.
sizeof(*this) gives wrong value
[ "", "c++", "assembly", "sizeof", "" ]
I have the following code: ``` @BeforeClass public static void setUpOnce() throws InterruptedException { fail("LOL"); } ``` And various other methods that are either @Before, @After, @Test or @AfterClass methods. The test doesn't fail on start up as it seems it should. Can someone help me please? I have JUnit 4.5 The method is failing in an immediate call to setUp() which is annotated as @before. Class def is : ``` public class myTests extends TestCase { ```
do NOT extend TestCase AND use annotations at the same time! If you need to create a test suite with annotations, use the RunWith annotation like: ``` @RunWith(Suite.class) @Suite.SuiteClasses({ MyTests.class, OtherTest.class }) public class AllTests { // empty } public class MyTests { // no extends here @BeforeClass public static void setUpOnce() throws InterruptedException { ... @Test ... ``` *(by convention: class names with uppercase letter)*
Make sure you imported @Test from the correct package. * Correct package: org.junit.Test * Incorrect pacakge: org.junit.jupiter.api.Test Please note that this is a solution for: If your @Before, @Atter, etc did not get called at all.
Why isn't my @BeforeClass method running?
[ "", "java", "junit", "annotations", "" ]
What is the difference between a coroutine and a continuation and a generator ?
I'll start with generators, seeing as they're the simplest case. As @zvolkov mentioned, they're functions/objects that can be repeatedly called without returning, but when called will return (yield) a value and then suspend their execution. When they're called again, they will start up from where they last suspended execution and do their thing again. A generator is essentially a cut down (asymmetric) coroutine. The difference between a coroutine and generator is that a coroutine can accept arguments after it's been initially called, whereas a generator can't. It's a bit difficult to come up with a trivial example of where you'd use coroutines, but here's my best try. Take this (made up) Python code as an example. ``` def my_coroutine_body(*args): while True: # Do some funky stuff *args = yield value_im_returning # Do some more funky stuff my_coro = make_coroutine(my_coroutine_body) x = 0 while True: # The coroutine does some funky stuff to x, and returns a new value. x = my_coro(x) print x ``` An example of where coroutines are used is lexers and parsers. Without coroutines in the language or emulated somehow, lexing and parsing code needs to be mixed together even though they're really two separate concerns. But using a coroutine, you can separate out the lexing and parsing code. (I'm going to brush over the difference between symmetric and asymmetric coroutines. Suffice it to say that they're equivalent, you can convert from one to the other, and asymmetric coroutines--which are the most like generators--are the easier to understand. I was outlining how one might implement asymmetric coroutines in Python.) Continuations are actually quite simple beasts. All they are, are functions representing another point in the program which, if you call it, will cause execution to automatically switch to the point that function represents. You use very restricted versions of them every day without even realising it. Exceptions, for instance, can be thought of as a kind of inside-out continuation. I'll give you a Python based pseudocode example of a continuation. Say Python had a function called `callcc()`, and this function took two arguments, the first being a function, and the second being a list of arguments to call it with. The only restriction on that function would be that the last argument it takes will be a function (which will be our current continuation). ``` def foo(x, y, cc): cc(max(x, y)) biggest = callcc(foo, [23, 42]) print biggest ``` What would happen is that `callcc()` would in turn call `foo()` with the current continuation (`cc`), that is, a reference to the point in the program at which `callcc()` was called. When `foo()` calls the current continuation, it's essentially the same as telling `callcc()` to return with the value you're calling the current continuation with, and when it does that, it rolls back the stack to where the current continuation was created, i.e., when you called `callcc()`. The result of all of this would be that our hypothetical Python variant would print `'42'`.
Coroutine is one of several procedures that take turns doing their job and then pause to give control to the other coroutines in the group. Continuation is a "pointer to a function" you pass to some procedure, to be executed ("continued with") when that procedure is done. Generator (in .NET) is a language construct that can spit out a value, "pause" execution of the method and then proceed from the same point when asked for the next value.
Coroutine vs Continuation vs Generator
[ "", "python", "generator", "coroutine", "continuations", "" ]
Is YUI3 ready mature enough? What are its advantages and disadvantages compared to YUI?
@Corwin is incorrect about files changing on the yui.yahooapis.com servers -- if you use the YUI 3 PR 2 release from our servers, those files will remain there even when subsequent releases come out. It's true that the API will change some as we move toward beta 1 (scheduled for June) and then to GA. We will undoubtedly make changes that will require your attention and time as you upgrade. That -- and the fact that YUI 3 doesn't contain all of the functionality of YUI 2.7.0 (the current release in the 2.x codeline) -- is the primary reason to hold off right now. You can learn more about YUI 3 and how it's different from 2.7.0 here: <http://video.yahoo.com/watch/3711767/10207432> We're using YUI 3 on the next version of Yahoo's homepage. You can read about that here: <http://yuiblog.com/blog/2008/11/11/frontpage-and-yui3/>
I've been using YUI3 exclusively since the PR2 release. There has been a lot that has changed since then, but my specific application code didn't have to change too much. I have also been tracking all the major changes in YUI3 during the past months. It's now June, and things appear to be coming close to beta 1 as I'm seeing a ton of documentation related commits. I would recommend using YUI3 over 2 if you're looking for very nice, feature-rich base JavaScript library. If you need a bunch of generic widgets, it is possible to have both YUI2 and YUI3 running together, although things will be complicated and your code will be using mixed APIs; but you may want to stick with YUI2. YUI3 is becoming a pretty great library and framework, it has matured greatly in functionality, performance, and cohesiveness since PR2.
Comparison of yui and yui3
[ "", "javascript", "ajax", "yui", "yui3", "" ]
I am trying to do a request that accepts a compressed response ``` var request = (HttpWebRequest)HttpWebRequest.Create(requestUri); request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); ``` I wonder if when I add the second line I will have to handle the decompression manually.
I found the answer. You can change the code to: ``` var request = (HttpWebRequest)HttpWebRequest.Create(requestUri); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; ``` And you will have automatic decompression. No need to change the rest of the code.
For .NET Core things are a little more involved. A `GZipStream` is needed as there isn't a property (as of writing) for `AutomaticCompression` Consider the following `GET` example: ``` var req = WebRequest.CreateHttp(uri); /* * Headers */ req.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate"; /* * Execute */ try { using (var resp = await req.GetResponseAsync()) { using (var str = resp.GetResponseStream()) using (var gsr = new GZipStream(str, CompressionMode.Decompress)) using (var sr = new StreamReader(gsr)) { string s = await sr.ReadToEndAsync(); } } } catch (WebException ex) { using (HttpWebResponse response = (HttpWebResponse)ex.Response) { using (StreamReader sr = new StreamReader(response.GetResponseStream())) { string respStr = sr.ReadToEnd(); int statusCode = (int)response.StatusCode; string errorMsh = $"Request ({url}) failed ({statusCode}) on, with error: {respStr}"; } } } ```
Does .NET's HttpWebResponse uncompress automatically GZiped and Deflated responses?
[ "", "c#", ".net", "httpwebrequest", "gzip", "deflate", "" ]
I have in my database a coloumn say agent which can have enum values ('G','Y','M') where G= google Y= yahoo M= msn how should i map the output coming from my function i.e google as G in my code so that database recognise it and saves it??
I think the easiest way is to **get the int representation of the enum value**. Enums are numbers in the background, so it's usually easy to cast an enum member to a number and vice versa. You can write a **converter class** for the best flexibility. You can process the enum value and generate a string, or get a string and return an enum member. You can do this in a simple if-then-else or switch-case structure. If you are using .NET (C#), be aware that you can pass any number as a parameter even you specify an enum, so an else or a default branch is a must in case of conversion. If you are using **PHP**, here is an example: ``` $myEnum = array ("red" => 1,"blue" => 2,"yellow" => 3); $d = $myEnum["red"]; ``` You will get 1 for red, 3 for yellow. If you want to use a string: ``` $myEnum = array ("Google" => "G","Yahoo" => "Y","MSN" => "M"); $d = $myEnum["Google"]; ```
You're already using ENUM data types, which are just an integer. Why not (in your DB schema, where you define ENUM), just define ENUM('Google','Yahoo','MSN', ...)? That's what I do -- then, when you're pulling/pushing data, you can just use the literal enum value (PHP will treat it like a string when you grab data from the db, and MySQL will treat the string passed from PHP as the enum type, assuming it's the same). There's really no reason to use 'G' over 'Google', unless you're really that lazy of a typist. And if you're that lazy, why would you want to put another layer of indirection into your code, unnecessarily? Edit: Sorry for the tone of the post -- it came off as far more harsh than intended. I just happen to feel pretty strongly against unnecessary indirection.
How to map enum with the string or viceversa in order to save into database?
[ "", "php", "cakephp", "" ]
In C# what is the best way to tell if a particular file is an image?
Most picture formats specify the file type in the first few bytes of the image. You can read in a few bytes and look for the correct headers. File extensions technically don't hold any important data about the image. It just helps the OS figure out what program to use to open it. (But, checking the extn is probably the easiest way, and usually correct.)
This isn't tested, but it's something like this: ``` private string MimeType (string Filename) { string mime = "[default]"; string ext = GetExtension(Filename).ToLower(); Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); if (rk != null && rk.GetValue("Content Type") != null) mime = rk.GetValue("Content Type").ToString(); return mime; } ``` (Sorry, it's been a while since I've done registry stuff.)
Is a file an image?
[ "", "c#", "image", "" ]
I want to implement a function tracer, which would trace how much time a function is taking to execute. I have following class for the same:- ``` class FuncTracer { public: FuncTracer(LPCTSTR strFuncName_in) { m_strFuncName[0] = _T('\0'); if( strFuncName_in || _T('\0') != strFuncName_in[0]) { _tcscpy(m_strFuncName,strFuncName_in); TCHAR strLog[MAX_PATH]; _stprintf(strLog,_T("Entering Func:- <%s>"),m_strFuncName); LOG(strLog) m_dwEnterTime = GetTickCount(); } } ~FuncTracer() { TCHAR strLog[MAX_PATH]; _stprintf(strLog,_T("Leaving Func:- <%s>, Time inside the func <%d> ms"),m_strFuncName, GetTickCount()-m_dwEnterTime); LOG(strLog) } private: TCHAR m_strFuncName[MAX_PATH]; DWORD m_dwEnterTime; }; void TestClass::TestFunction() { // I want to avoid writing the function name maually.. // Is there any macro (__LINE__)or some other way to // get the function name inside a function ?? FuncTracer(_T("TestClass::TestFunction")); /* * Rest of the function code. */ } ``` I want to know if there is any way to get the name of the function from inside of a function? Basically I want the users of my class to simply create an object the same. They may not pass the function name.
VC++ has ``` __FUNCTION__ for undecorated names ``` and ``` __FUNCDNAME__ for decorated names ``` And you can write a macro that will itself allocate an object and pass the name-yelding macro inside the constructor. Smth like ``` #define ALLOC_LOGGER FuncTracer ____tracer( __FUNCTION__ ); ```
C99 has `__func__`, but for C++ this will be compiler specific. On the plus side, some of the compiler-specific versions provide additional type information, which is particularly nice when you're tracing inside a templatized function/class. * [MSVC](http://msdn.microsoft.com/en-us/library/b0084kay.aspx): `__FUNCTION__`, `__FUNCDNAME__`, `__FUNCSIG__` * [GCC](http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html): `__func__`, `__FUNCTION__`, `__PRETTY_FUNCTION__` Boost library has defined macro `BOOST_CURRENT_FUNCTION` for most C++ compilers in header [boost/current\_function.hpp](http://www.boost.org/doc/libs/1_62_0/boost/current_function.hpp). If the compiler is too old to support this, the result will be "(unknown)".
Is there a way to get function name inside a C++ function?
[ "", "c++", "macros", "profiling", "" ]
I have an application that supplies long list of parameters to a web page, so I have to use POST instead of GET. The problem is that when page gets displayed and user clicks the Back button, Firefox shows up a warning: > To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier. Since application is built in such way that going Back is a quite common operation, this is really annoying to end users. Basically, I would like to do it the way this page does: [<http://www.pikanya.net/testcache/>](http://www.pikanya.net/testcache/) Enter something, submit, and click Back button. No warning, it just goes back. Googling I found out that this might be a bug in Firefox 3, but I'd like to somehow get this behavior even after they "fix" it. I guess it could be doable with some HTTP headers, but which exactly?
One way round it is to redirect the POST to a page which redirects to a GET - see [Post/Redirect/Get on wikipedia](http://en.wikipedia.org/wiki/Post/Redirect/Get). Say your POST is 4K of form data. Presumably your server does something with that data rather than just displaying it once and throwing it away, such as saving it in a database. Keep doing that, or if it's a huge search form create a temporary copy of it in a database that gets purged after a few days or on a LRU basis when a space limit is used. Now create a representation of the data which can be accessed using GET. If it's temporary, generate an ID for it and use that as the URL; if it's a permanent set of data it probably has an ID or something that can be used for the URL. At the worst case, an algorithm like tiny url uses can collapse a big URL to a much smaller one. Redirect the POST to GET the representation of the data. --- As a historical note, this technique was [established practice in 1995](https://lists.w3.org/Archives/Public/ietf-http-wg-old/1995JanApr/0195.html).
See my golden rule of web programming here: [Stop data inserting into a database twice](https://stackoverflow.com/questions/638494/stop-data-inserting-into-a-database-twice/638506#638506) It says: “Never ever respond with a body to a POST-request. Always do the work, and then respond with a Location: header to redirect to the updated page so that browser requests it with GET” If browser ever asks user about re-POST, your web app is broken. User should not ever see this question.
Prevent Back button from showing POST confirmation alert
[ "", "php", "forms", "post", "http-headers", "" ]
Where can I find good Java web services practicals and tutorials (I'm a newbe to JWS so I prefer from the scratch). Thanks.
Try the [Sun Tutorial](http://java.sun.com/webservices/docs/1.6/tutorial/doc/). These are usually very good
I've always read (though I've never followed) the [Sun tutorials](http://java.sun.com/javaee/5/docs/tutorial/doc/bnayl.html). Well written enough for me. Though, I would suggest to use a framework like [CXF](http://cxf.apache.org/) or [spring web services](http://static.springsource.org/spring-ws/sites/1.5/) to avoid the boilerplate.
Java Web Services
[ "", "java", "web-services", "" ]
Is it possible to put ASp.NET tags in my javascript which is in a seperate script file. For example, I have the following ``` $.getJSON("/Postcode/GetAddressResults/" + $get("SearchPostcode").value, null, function(data) { ``` which I want to turn into but it does not like the ASP tags! ``` var action = "<%=Url.Content('~/Postcode/GetAddressResults/')%>" + $get("SearchPostcode").value $.getJSON(action, null, function(data) { ``` However this does not seem to work, what am I doing wrong?
Add to your master page(s) a meta tag to hold the value of the current applications path from the host (the bit the ~ represents). In your Javascript create a function which will resolve a ~ prefixed path using the meta tag content. **Edit** Example as requested:- Place this code in the head section your master pages:- ``` <meta id="meta.AppDomainAppVirtualPath" name="AppDomainAppVirtualPath" value="<%=HttpRuntime.AppDomainAppVirtualPath%>" /> ``` In your javascript include this function:- ``` function resolveUrl(url) { if (url.charAt(0) == "~") { if (!resolveUrl.appPath) { var meta = document.getElementById('meta.AppDomainAppVirtualPath'); resolveUrl.appPath = meta ? meta .getAttribute("content") : '/'; } if (resolveUrl.appPath == '/') return url.slice(1, url.length; else return resolveUrl.appPath + url.slice(1, url.length); } else { return url; } } ``` Now your line of code is:- ``` $.getJSON(resolveUrl("~/Postcode/GetAddressResults/") + $get("SearchPostcode").value, null, function(data) { ```
If your JavaScript is in a separate script file, then it won't be processed by ASP.NET, so these tags won't be processed. You'll need them inline in an ASP.NET page for this to work.
ASP.NET MVC including ASP in Javascript
[ "", "javascript", "asp.net-mvc", "" ]
Yesterday a colleague asked me how to display data in a grid where the built in data binding doesn't support what he wants to do for some of the columns. Pleased to be able to help I explained all about the OnRowDataBound event and how you can hook into it and dynamically manipulate the cells in the row object to do pretty much what you want. Great. If you're working with asp.net. Only problem it he's writing a winforms app and the DataGridView doesn't support OnRowDataBound! I couldn't believe it, but it's just not there. So how the hell do the winforms guys manage this?
The [RowsAdded](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowsadded.aspx) event is roughly equivalent, but you can run into performance issues using this event to access rows because of the [shared memory state](http://msdn.microsoft.com/en-us/library/ha5xt0d9.aspx) it uses. This is essentially a scheme where the DataGridView tries to minimize its memory footprint by sharing some state when possible between rows *until* you access one of the shared rows, which causes it to unshare state (memory and possible performance hit). A lot has been optimized away, but I've run into issues with using this event for one reason or another. So if RowsAdded works for you with no degradation of performance, great. If not, you still have lots of options. You can derive from the DataGridViewCell and DataGridView to add custom cell (column) types to the grid. This is probably the most complicated way to customize the DataGridView... but it would allow pretty much any kind of cell manipulation you'd want. The [CellPainting](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellpainting.aspx) event gives you a hook into the painting of a particular cell if you wish you paint something with GDI+ (System.Drawing) before display. There's also a [CellFormatting](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx) event which gives you special event args, as well - but I've never used that one, so I'm not sure if the shared memory state issue applies (normally for the painting event it does not). HTH, Richard
I'm not exactly sure, since I'm an ASP.NET guy too, but in winforms you work in a true stateful environment, rather than a "pseudo-stateful" (through viewstate) environment. So because there's no need to to do everything (such as change cell styles etc) before everything is flushed to a Response, you can wait until the data has finished binding and then change each row as you see fit, you've still got your datasource as well, so just use it if you need to do anything more with it.
Forms DataGridView missing OnRowDataBound?
[ "", "c#", ".net", "asp.net", "winforms", "" ]
we have a data structure ``` struct MyData { int length ; char package[MAX_SIZE]; }; ``` where MAX\_SIZE is a fixed value . Now we want to change it so as to support "unlimited" package length greater than MAX\_SIZE . one of the proposed solution is to replace the static array with a pointer and then dynamically allocating the size as we require For EX ``` struct MyData { int length ; char* package; }; ``` and then ``` package = (char*)malloc(SOME_RUNTIME_SIZE) ; ``` Now my question is that is this the most efficient way to cater to the requirement OR is there any other method .. maybe using STL data structures like growable arrays etc etc . we want a solution where most of the code that works for the static char array should work for the new structure too ..
I would also wrap a vector: ``` // wraps a vector. provides convenience conversion constructors // and assign functions. struct bytebuf { explicit bytebuf(size_t size):c(size) { } template<size_t size> bytebuf(char const(&v)[size]) { assign(v); } template<size_t size> void assign(char const(&v)[size]) { c.assign(v, v+size); } // provide access to wrapped vector std::vector<char> & buf() { return c; } private: std::vector<char> c; }; int main() { bytebuf b("data"); process(&b.buf()[0], b.buf().size()); // process 5 byte std::string str(&b.buf()[0]); std::cout << str; // outputs "data" bytebuf c(100); read(&c.buf()[0], c.buf().size()); // read 100 byte // ... } ``` There is no need to add many more functions to it, i think. You can always get the vector using `buf()` and operate on it directly. Since a vectors' storage is contiguous, you can use it like a C array, but it is still resizable: ``` c.buf().resize(42) ``` The template conversion constructor and `assign` function allows you to initialize or assign from a C array directly. If you like, you can add more constructors that can initialize from a set of two iterators or a pointer and a length. But i would try keeping the amount of added functionality low, so it keeps being a tight, transparent vector wrapping struct.
Much, much better/safer: ``` struct my_struct { std::vector<char>package; }; ``` To resize it: ``` my_struct s; s.package.resize(100); ``` To look at how big it is: ``` my_struct s; int size = s.package.size(); ``` You can even put the functions in the struct to make it nicer: ``` struct my_struct { std::vector<char>package; void resize(int n) { package.resize(n); } int size() const { return package.size(); } }; my_struct s; s.resize(100); int z = s.size(); ``` And before you know it, you're writing good code...
Best Replacement for a Character Array
[ "", "c++", "data-structures", "" ]
This came up while talking to a friend and I thought I'd ask here since it's an interesting problem and would like to see other people's solutions. The task is to write a function Brackets(int n) that prints all combinations of **well-formed** brackets from 1...n. For Brackets(3) the output would be ``` () (()) ()() ((())) (()()) (())() ()(()) ()()() ```
Took a crack at it.. C# also. ``` public void Brackets(int n) { for (int i = 1; i <= n; i++) { Brackets("", 0, 0, i); } } private void Brackets(string output, int open, int close, int pairs) { if((open==pairs)&&(close==pairs)) { Console.WriteLine(output); } else { if(open<pairs) Brackets(output + "(", open+1, close, pairs); if(close<open) Brackets(output + ")", open, close+1, pairs); } } ``` The recursion is taking advantage of the fact that you can never add more opening brackets than the desired number of pairs, and you can never add more closing brackets than opening brackets..
Python version of the first voted answer. ``` def foo(output, open, close, pairs): if open == pairs and close == pairs: print output else: if open<pairs: foo(output+'(', open+1, close, pairs) if close<open: foo(output+')', open, close+1, pairs) foo('', 0, 0, 3) ```
Finding all combinations of well-formed brackets
[ "", "c#", "algorithm", "f#", "catalan", "" ]
I'm pretty new to databases, so forgive me if this is a silly question. In modern databases, if I use an index to access a row, I believe this will be O(1) complexity. But if I do a query to select another column, will it be O(1) or O(n)? Does the database have to iterate through all the rows, or does it build a sorted list for each column?
Actually, I think access based on an index will be O(log(n)), because you'll still be searching down through a B-Tree-esque organization to get to your record.
To answer your literal question, yes if there is no index on a column, the database engine will have to look at all rows. In the more interesting case of selecting by multiple columns, both with and without index, the situation becomes more complex: If the Query Optimizer chooses to use the index, then it'll first select rows based on the index and then apply a filter with the remaining constraints. Thus reducing the second filtering operation from O(number of rows) to O(number of selected rows by index). The ratio between these two number is called **selectivity** and an important statistic when choosing which index to use.
Database query time complexity
[ "", "sql", "database", "language-agnostic", "big-o", "" ]
I have a web App running and I want to access the sql db with a another app to update one of the tables with new calculations. Will my users notice anything during the updates? WIll I get an error if they access at the same time I do updates, or is there auto locking ? tia
Generally the rows would be locked while you do the updates and any SQL query that might use those rows will "hang" until your update completes, then return the correct data. There are some edge-case exceptions to this, but generally speaking I wouldn't worry about it unless you are doing some really fancy long-running updates that will cause the data to be locked for a long period of time.
If your RDBMS is any good, it should take care of it for you. You probably want to make sure "autocommit" is off, and only commit when you're finished your update, though.
Do I need to "lock" a Sql Table during update job?
[ "", "sql", "" ]
I have a ShareThis (<http://www.sharethis.com>) link in the footer of my Masterpage. The code they provide generates the link via Javascript. My site is very simple so far (<http://www.quotidianword.com>), just a place to put your email. But when the email is entered, there is an AJAX postback and the link disappears! Is there any way to prevent this? How do I get the link to reload? Thanks!
Without code sample, I'm not sure--but I would guess you're not running the code after the postback. Remember, `UpdatePanel`s still run the whole page lifecycle--`Init`, `Load`, `PreRender`, etc. They only send back the rendered HTML for the particular block of code in the `UpdatePanel`. Other than that, it acts just as a complete postback does.
Ok, so I think I figured it out... It was included in the same UpdatePanel. I took it out of that UpdatePanel and now it works fine. But shouldn't it reload it anyways?
Javascript ShareThis Link Disappearing On Postback
[ "", "asp.net", "javascript", "ajax", "" ]
How can I replace the scrollbar's images using HTML/CSS? I have: ``` scrollbar-base-color: #00acee; scrollbar-dark-shadow-color: #00acee; scrollbar-track-color: #ffffff; scrollbar-face-color: #00acee; scrollbar-shadow-color: #00acee; scrollbar-highlight-color: #00acee; scrollbar-3d-light-color: #00acee; ``` Can I use an image to accomplish the same idea?
It is not possible to put an image inside the scrollbar. Customizing the scrollbar is not a W3C spec (IE only CSS), but details on what is possible can be found here: <http://www.quirksmode.org/css/scrollbars.html>
No you can't use images in place of the scroll bar. I'll also just mention that changing the colours is very annoying to users and it only works in IE anyway, so just stick with the standard GUI elements.
How can one use scroll bar images?
[ "", "javascript", "html", "css", "" ]
I have a large number of strings to process in php. I want to "fix" them to be title case (using `ucwords(strtolower($str))`) but only if they are all upper or all lower case already. If they are already mixed case, I'd just rather just leave them as they are. What is the fastest way to check for this? It seems like `for`ing through the string would be a rather slow way to go about it. Here's what I have, which I think will be too slow: ``` function fixCase($str) { $uc = 0; $lc = 0; for($i=0;$i<strlen($str);$i++) { if ($str[$i] >= 'a' && $str[$i] <= 'z') $lc++; else if ($str[$i] >= 'A' && $str[$i] <= 'Z') $uc++; } if ($uc == 0 || $lc == 0) { return ucwords(strtolower($str)); } } ```
just use a string compare (case sensitive) ``` function fixCase($str) { if ( (strcmp($str, strtolower($str)) === 0) || (strcmp($str, strtoupper($str)) === 0) ) { $str = ucwords(strtolower($str)); } return $str; } ```
You could try the string case test function I posted [here](https://stackoverflow.com/questions/371116/how-to-check-case-of-a-string-in-php/371832#371832) ``` function getStringCase($subject) { if (!empty($subject)) { if (preg_match('/^[^A-Za-z]+$/', $subject)) return 0; // no alphabetic characters else if (preg_match('/^[^A-Z]+$/', $subject)) return 1; // lowercase else if (preg_match('/^[^a-z]+$/', $subject)) return 2; // uppercase else return 3; // mixed-case } else { return 0; // empty } } ```
Fast case counting
[ "", "php", "optimization", "" ]
I'm wondering if it's possible for .Net's String.Format() to split an integer apart into two sub strings. For example I have a number 3234 and I want to format it as 32X34. My integer will always have 4 or 6 digits. Is this possible using String.Format()? If so what format string would work? P.S. I know there is other ways to do this, but i'm specifically interested to know if String.Format() can handle this.
You can specify your own format when calling `String.Format` ``` String.Format("{0:00x00}", 2398) // = "23x93" ```
James, I'm not sure you've completely specified the problem. If your goal is to put the 'x' in the *center* of the string, [Samuel's answer](https://stackoverflow.com/questions/727727/string-format-split-integer-value/727741#727741) won't work for 6 digit numbers. `String.Format("{0:00x00}", 239851)` returns "2398x51" instead of "239x851" Instead, try: ``` String.Format(val<10000 ? "{0:00x00}" : "{0:000x000}", val) ``` In either case, the method is called [Composite Formatting](http://msdn.microsoft.com/en-us/library/txafckwd.aspx). (I'm assuming the numbers will be between 1000 and 999999 inclusive. Even then, numbers between 1000 and 1009 inclusive will report the number after the 'x' with an unnecessary leading '0'. So maybe this approach is valid for values between 1010 and 999999 inclusive.)
String.Format() split integer value
[ "", "c#", ".net", "string", "formatting", "" ]
I have a php web page with 15 fields. The user will use it to upload images. I tested this by uploading 15 jpg images, each about 2 M, without any problems. On the day I launch, I will be moving this web page to another Linux shared hosting environment (still not sure which). Are there some web hosting environments that limit the size of total uploads in one http request?
Yes. There are (as far as I can remember) three or so configuration settings which will affect upload size restrictions: * [`upload_max_filesize`](http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize), which sets an upper limit on the size of uploaded files * [`post_max_size`](http://www.php.net/manual/en/ini.core.php#ini.post-max-size), which limits the total size of posted data, including file data * [`max_input_time`](http://www.php.net/manual/en/info.configuration.php#ini.max-input-time), which restricts the length of time the script is allowed to process input data, including posted values `upload_max_filesize` is a limit on each individual file; however, `post_max_size` is an upper limit on the entire request, which includes all the uploaded files. Different hosting environments will have these values set differently, which may affect your abilities upon deployment.
The upload limits are set through php ini. You can try get them like so: ``` $post_max_size = ini_get('post_max_size'); $upload_max_filesize = ini_get('upload_max_filesize'); ```
PHP - Maximum Total Upload Size?
[ "", "php", "upload", "limit", "" ]
I need to write a tree search method which takes a type parameter T and returns all items of type T that exist in the tree. Is there any way to do this? I would prefer elegance over efficiency at this point...
Something like this: ``` internal static IEnumerable<T> AllDescendantNodes<T>( this TreeNode input ) where T class; { T current = null; foreach ( TreeNode node in input.Nodes ) if( (current = node as T) != null ) { yield return current; foreach ( var subnode in node.AllDescendantNodes<T>() ) yield return subnode; } } ``` You would then call this against the root node as an extension method: ``` foreach( MyCustomNodeClass item in rootNode.AllDescendantNodes<MyCustomNodeClass>() ) { ... } ```
Well, internally the method would have to iterate over all the elements of the tree, so the skip to just enumerating over it, and using the OfType LINQ method isn't that far: ``` var onlyTs = yourTree.OfType<SomeT>(); ```
Finding all objects of type T in a tree structure C#
[ "", "c#", "generics", "search", "tree", "" ]
How can I copy a part of an array to another array? Consider I'm having ``` int[] a = {1,2,3,4,5}; ``` Now if I give the start index and end index of the array `a` it should get copied to another array. Like if I give start index as 1 and end index as 3, the elements 2, 3, 4 should get copied in the new array.
``` int[] b = new int[3]; Array.Copy(a, 1, b, 0, 3); ``` * a = source array * 1 = start index in source array * b = destination array * 0 = start index in destination array * 3 = elements to copy
See [this question](https://stackoverflow.com/questions/406485/array-slices-in-c). LINQ Take() and Skip() are the most popular answers, as well as Array.CopyTo(). A purportedly faster [extension method is described here](http://www.dotnetperls.com/array-slice).
How to copy part of an array to another array in C#?
[ "", "c#", "arrays", "" ]
I'm trying to create an flexible update query. I have now something like this: ``` $lsQuery = "UPDATE `"; $lsQuery .= $psTableName; $lsQuery .= " SET "; foreach($psValues as $lsKey => $lsValue) { $lsQuery .= $lsKey; $lsQuery .= " = '"; $lsQuery .= $lsValue; $lsQuery .= "' AND "; } $lsQuery .= "` "; $lsQuery .= "WHERE "; if(isset($psWhere)){ foreach($psWhere as $lsKey => $lsValue) { $lsQuery .= $lsKey; $lsQuery .= " = '"; $lsQuery .= $lsValue; $lsQuery .= "' AND "; } } $lsQuery = substr($lsQuery,0,(strlen($lsQuery)-5)); ``` But when I print my query on the screen I get something like: UPDATE `persons SET per_password = '2a6445462a09d0743d945ef270b9485b' AND` WHERE per\_email = 'bla@gmail.com' How can I get rid of this extra 'AND'?
If you want to keep your existing code. ``` $lsWhere = array(); foreach($psWhere as $lsKey => $lsValue) { $lsWhere[] = $lsKey." = '".mysql_real_escape_string($lsValue)."'"; } $lsQuery .= join(" AND ", $lsWhere); ```
I'd probably start with: ``` function update($table, $set, $where) { $change = array(); foreach ($set as $k => $v) { $change[] = $k . ' = ' . escape($v); } $conditions = array(); foreach ($where as $k => $v) { $conditions[] = $k . ' = ' . escape($v); } $query = 'UPDATE ' . $table . ' SET ' . implode(', ', $change) . ' WHERE ' . implode(' AND ', $conditions); mysql_query($query); if (mysql_error()) { // deal with it how you wish } } function escape($v) { if (is_int($v)) { $v = intval($v); } else if (is_numeric($v)) { $v = floatval($v); } else if (is_null($v) || strtolower($v) == 'null') { $v = 'null'; } else { $v = "'" . mysql_real_escape_string($v) . "'"; } return $v; } ```
Creating a flexible update query
[ "", "php", "mysql", "sql-update", "" ]
In Java, if I call `List.toString()`, it will automatically call the `toString()` method on each object inside the List. For example, if my list contains objects `o1`, `o2`, and `o3`, `list.toString()` would look something like this: ``` "[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]" ``` Is there a way to get similar behavior in Python? I implemented a `__str__()` method in my class, but when I print out a list of objects, using: ``` print 'my list is %s'%(list) ``` it looks something like this: ``` [<__main__.cell instance at 0x2a955e95f0>, <__main__.cell instance at 0x2a955e9638>, <__main__.cell instance at 0x2a955e9680>] ``` how can I get python to call my `__str__()` automatically for each element inside the list (or dict for that matter)?
Calling string on a python list calls the `__repr__` method on each element inside. For some items, `__str__` and `__repr__` are the same. If you want that behavior, do: ``` def __str__(self): ... def __repr__(self): return self.__str__() ```
You can use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) to generate a new list with each item str()'d automatically: ``` print([str(item) for item in mylist]) ```
How to make print call the __str__ method of Python objects inside a list?
[ "", "python", "" ]
I have been given a header with the following declaration: ``` //The index of 1 is used to make sure this is an array. MyObject objs[1]; ``` However, I need to make this array dynamically sized one the program is started. I would think I should just declare it as MyObject \*objs;, but I figure if the original programmer declared it this way, there is some reason for it. Is there anyway I can dynamically resize this? Or should I just change it to a pointer and then malloc() it? Could I use some the new keyword somehow to do this?
You're correct. If you want to dynamically instantiate its size you need to use a pointer. (Since you're using C++ why not use the **new** operator instead of *malloc*?) ``` MyObject* objs = new MyObject[size]; ```
Use an [STL vector](http://www.sgi.com/tech/stl/Vector.html): ``` #include <vector> std::vector<MyObject> objs(size); ``` A vector is a [dynamic array](http://en.wikipedia.org/wiki/Array_list) and is a part of the [Standard Template Library](http://www.sgi.com/tech/stl/). It resizes automatically as you [push back](http://www.cplusplus.com/reference/stl/vector/push_back/) objects into the array and can be accessed like a normal C array with the [`[]` operator](http://www.cplusplus.com/reference/stl/vector/push_back/). Also, `&objs[0]` is guaranteed to point to a contiguous sequence in memory -- unlike a [list](http://www.sgi.com/tech/stl/List.html) -- if the container is not empty.
How should I change this declaration?
[ "", "c++", "arrays", "resize", "" ]
For example: "½" or ASCII DEC 189. When I read the bytes from a text file the byte[] contains the valid value, in this case 189. Converting to Unicode results in the Unicode replacement character 65533. > UnicodeEncoding.Unicode.GetString(b); Converting to ASCII results in 63 or "?" > ASCIIEncoding.ASCII.GetString(b); If this isn't possible what is the best way to handle this data? I'd like to be able to perform string functions like Replace().
Byte 189 represents a "½" in iso-8859-1 (aka "Latin-1"), so the following is maybe what you want: ``` var e = Encoding.GetEncoding("iso-8859-1"); var s = e.GetString(new byte[] { 189 }); ``` All strings and chars in .NET are UTF-16 encoded, so you need to use an encoder/decoder to convert anything else, sometimes this is defaulted (e.g. UTF-8 for FileStream instances) but good practice is to always specify. You will need some form of implicit or (better) explicit metadata to supply you with the information about which encoding.
The old PC-8 or Extended ASCII character set was around before IBM and Microsoft introduced the idea of Code Pages to the PC world. This WAS Extended ASCII - in 1982. In fact, it was the ONLY character set available on PC's at the time, up until the EGA card allowed you to load other fonts in to VRAM. This was also the default standard for ANSI terminals, and nearly every BBS I dialed up to in the 80's and early 90's used this character set for displaying menus and boxes. Here's the code to turn 8-bit Extended ASCII in to Unicode text. Note the key bit of code: the GetEncoding("437"). That used Code Page 437 to translate the 8-bit ASCII text to the Unicode equivalent. ``` string ASCII8ToString(byte[] ASCIIData) { var e = Encoding.GetEncoding("437"); return e.GetString(ASCIIData); } ```
How can I convert extended ascii to a System.String?
[ "", "c#", ".net", "extended-ascii", "" ]
As *[function overloading](http://web.archive.org/web/20090624083829/http://mail.python.org/pipermail/python-list/2003-May/206149.html)* says: Function overloading is absent in Python. As far as I feel this a big handicap since its also an object-oriented (OO) language. Initially I found that unable to differentiate between the argument types was difficult, but the dynamic nature of Python made it easy (e.g. list, tuples, strings are much similar). However, counting the number of arguments passed and then doing the job is like an overkill. Any pythonic way to do this?
As unwind noted, keyword arguments with default values can go a long way. I'll also state that in my opinion, it goes against the spirit of Python to worry a lot about what types are passed into methods. In Python, I think it's more accepted to use duck typing -- asking what an object can do, rather than what it is. Thus, if your method may accept a string or a tuple, you might do something like this: ``` def print_names(names): """Takes a space-delimited string or an iterable""" try: for name in names.split(): # string case print name except AttributeError: for name in names: print name ``` Then you could do either of these: ``` print_names("Ryan Billy") print_names(("Ryan", "Billy")) ``` Although an API like that sometimes indicates a design problem.
Now, unless you're trying to write C++ code using Python syntax, what would you need overloading for? I think it's exactly opposite. Overloading is only necessary to make strongly-typed languages act more like Python. In Python you have keyword argument, and you have `*args` and `**kwargs`. See for example: *[What is a clean, Pythonic way to have multiple constructors in Python?](https://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-way-to-have-multiple-constructors-in-python)*
Function overloading in Python: Missing
[ "", "python", "overloading", "missing-features", "" ]
The FileUpload control requires me to provide a rooted directory in the SaveAs() method. However, I would much rather the uploaded files go into a virtual directory, such as "~/UserFiles/[username]/[filename]". Is there a way for me to accomplish that?
Use the pages MapPath method:- ``` ctl.SaveAs(MapPath("~/UserFiles/[username]/[filename]")); ```
No, the keyword is requires. You can use your script to copy the file after the download.
FileUploads and rooted directories
[ "", "c#", ".net", "file-upload", "root", "" ]
I want a quick an easy way to check my ip address after reading a recent question that had been answered on SO. For future reference, is there a way to make the following alias work? ``` alias myip='python -c "from urllib import urlopen; print urlopen("http://whatismyip.appjet.net").read()[:-1]"' ```
``` alias myip="python -c 'from urllib import urlopen; print urlopen(\"http://whatismyip.appjet.net\").read()[:-1]'" ``` You need to use single quotes inside the alias to stop bash trying to interpret parts of your code inside them. The escapes on the double quotes get stripped out while processing what the alias itself is.
Quote the inside double-quotes: ``` alias myip='python -c "from urllib import urlopen; print urlopen(\"http://whatismyip.appjet.net\").read()[:-1]"' ```
How do I make this python command line an alias in bash?
[ "", "python", "bash", "alias", "" ]
I know that in most cases it`s more useful to learn more complicated technology/language and then easy one than vice versa. But, actually, time to do university tasks is limited. If I first learn LINQ, then go for SQL, would it be hard for me to use and learn sql? **EDIT** The task I need to do is to work with database and get some data from it, so the question is almost about LINQ to SQL.
It is a bad idea. And if today's universities teach you LINQ instead of giving you foundation to build your knowledge upon, I can only feel sorry and pity for their students. Time is always limited. Don't waste it on things that are subject to constant change. SQL will be there tomorrow, LINQ.... well who knows. SQL is applicable anywhere, LINQ only in .NET world. Either LINQ or something else, it will be easy to "learn" it afterwards. When you have the knowledge of SQL, it will just me a matter of hours/days/weeks, hardly longer.
Well, the 2 things are very different. LINQ (in the pure sense) isn't actually related to databases *at all* - it can be used quite happily just with in memory objects, or against web services, etc. If you are mainly interested in writing better .NET code, then learn LINQ - but learn it *properly* - perhaps pick up [C# in Depth](http://www.manning.com/skeet/), for example - which covers it very well in the last few chapters. If you want to know about databases, then sure: learn SQL (such as TSQL) - but understand the differences. Databases are good if you need to write enterprise software, but not necessarily if you just want to do simple tasks. **edit re edit to the question** If you are just getting simple data in and out of the database, then you probably don't need to know much about SQL. Just use LINQ-to-SQL (or whatever tool), and let the ORM tooling worry about it.
Is it a good idea to learn LINQ first, then SQL?
[ "", "sql", "linq", "" ]