Saturday, February 5, 2011

determine size of array if passed to function

Is it possible to determine the size of an array if it was passed to another function (size isn't passed)? The array is initialized like int array[] = { XXX } ..

I understand that it's not possible to do sizeof since it will return the size of the pointer .. Reason I ask is because I need to run a for loop inside the other function where the array is passed. I tried something like:

for( int i = 0; array[i] != NULL; i++) {
........
}

But I noticed that at the near end of the array, array[i] sometimes contain garbage values like 758433 which is not a value specified in the initialization of the array..

  • Nope, it's not possible.

    One workaround: place a special value at the last value of the array so you can recognize it.

    Rom : ... and get ready to debug the cases when someone places that special value in the middle of the array. In other words: don't do it. Like others said: wither use well-defined containers (e.g. STL) or pass the size of the array along with it as other parameter of the function
    From tekBlues
  • If you can't pass the size, you do need a distinguishable sentinel value at the end (and you need to put it there yourself -- as you've found, you can't trust C++ to do it automagically for you!). There's no way to just have the called function magically divine the size, if that's not passed in and there is no explicit, reliable sentinel in use.

  • Can you try appending a null character \0 to the array and then send it? That way, you can just check for \0 in the loop.

  • If it's within your control, use a STL container such as a vector or deque instead of an array.

    rlbond : Agreed. If you don't know about vector, now is a great time to learn! It will make your life much easier.
  • The other answers overlook one feature of c++. You can pass arrays by reference, and use templates:

    template <typename T, int N>
    void func(T (&a) [N]) {
        for (int i = 0; i < N; ++i) a[i] = T(); // reset all elements
    }
    

    then you can do this:

    int x[10];
    func(x);
    

    but note, this only works for arrays, not pointers.

    However, as other answers have noted, using std::vector is a better choice.

    David Rodríguez - dribeas : +1 This is a somewhat of a solution, but will create a different func() symbol for each different array size. That is, in different places the passed array has different sizes, the function will be instantiated that many times. This could be helpful though to insert the size of the array in a call to another function that has the real implementation and receives the size, probably flagging it as inline (not that the compiler must follow your rule...) template inline void wrapper( T (&a)[N] ) { return func( a, N ); } -- with func() being the real function.
    Evan Teran : sure, the goal would be to make the function which operates on it small enough that it is likely to get inlined. I also like your wrapper idea.
    From Evan Teran
  • One obvious solution is to use STL. If it's not a possibility, it's better to pass array length explicitly. I'm skeptical about use the sentinel value trick, for this particular case. It works better with arrays of pointers, because NULL is a good value for a sentinel. With array of integers, it's not that easy - you need to have a "magic" sentinel value, which is not good.

    Side note: If your array is defined and initalized as

     int array[] = { X, Y, Z };
    

    in the same scope as your loop, then

    sizeof(array) will return it's real size in bytes, not the size of the pointer. You can get the array length as

    sizeof(array) / sizeof(array[0])
    

    However, in general case, if you get array as a pointer, you can't use this trick.

jQuery to re-enable form after a file result is returned

I have an ASP.NET MVC form that returns a report as a File(...) result. This means that the browser stays on the current page after the file download is triggered. Using jQuery, I would like to disable the submit button and then re-enable it after the file returns. My code already disables the button just fine, however, I'm unable to find an event to hook into that is triggered after the file returns.

Here's what I have so far:

  $(document).ready(function() {
        $("#downloadForm").submit(function() {
            $("#cmdSubmit").attr("disabled", "disabled");
            $("#uiProgress").show();
        });
    });

What can I add to this to trigger when the form submit returns?

  • You may have to complicate the process: rather than returning the File from the post, have #downloadForm post an AJAX request that returns the URL to the file. When the response is received, you can reenable your button and set document.location to the returned URL.

SVN analysis tool

I have been searching all over the net to find something remotely usable. I tried all kinds of HTML based tools for analyzing an SVN repository (commits by users, reports etc) but none of them are user friendly.

I am interested in a desktop client (that does NOT depend on an external svn.exe to be installed on my system) that does just that. Analyze the repository and create reports.

Does anyone know of such a program?

  • TortoiseSVN can show you some, well, basic statistics.

  • you can look into statsvn which just needs a checkedout workingcopy and a connection to the repo. It will extract tons of informations out of your repository. It is a java project and will run on all architectures. It will also create heatmaps, LOC-graphs and other images to visualize the data.

  • I've used StatSVN also. It does provide useful stats (have a look at an example output for Ant), but it does require you to have already done a svnlog of the repository and have a working copy checked out to perform the analysis on.

Displaying a custom hierarchy.

I have a simple hirachey of Tasks similar to the snipet below:

public class Task
{
    public Guid TaskId { get; set; }
    public Guid ParentId { get; set; }
    public string Name { get; set; }
    public List<Task> Subtasks = new List<Task>();
}

What would be be the best way to display this data? A TreeView would be look ideal but since im not using a DataSet is this control excluded? Or how could i modify my code to enable me to use a TreeView?

Cheers Anthony

  • You do not need to make the TreeView data bound.

    You can create TreeNode instances, and add them to the TreeView.Nodes collection yourself.

    This would allow you to create a TreeView programmatically from your data.

  • Take a look at the TreeView.Nodes.Add method.

    Then use recursion to add the sub tasks. Something like this:

    public void AddTaskToTree(TreeNodeCollection nodes, Task aTask)
    {
        TreeNode taskNode = New TreeNode(aTask.Name);
        nodes.Add(taskNode);
        foreach (Task subTask in aTask.Subtasks)
        {
            AddTaskToTree(taskNode.Nodes, subTask);
        }
    }
    

asp.net iText dll implementation help

Hi,

I have a function for reading and creating a pdf file. I was told it uses iText.dll, but not sure where to find it and implement it. Can anyone point me in the right direction. Im a .net newbie. I dont need help with the code right now, so just setting up the dependancies would be a good start.

Any help would be great

Thanks

--Mark

Is there a tool to create MySQL database model from an existing MySQL database?

I am looking for a piece of software to allow me easily create the database mode for an existing MySQL database

  • If you use mysqldump with the --no-data option, you can extract the schema from the old database. There can be issues with views using this method, see this article for a workaround.

    You can copy a schema in this way with something like this:

    mysqldump --opt --no-data olddatabase | mysql newdatabase
    
    From Paul Dixon
  • You can dump the database schema to SQL using the mysqldump command.

    mysqldump {databasename} --no-data=true -u {username} -p  > database_schema.sql
    
    From Matt
  • http://dev.mysql.com/workbench/ is still in Beta (depending on your Operating System), but can be a handy tool for exploring the schema of databases - there is a free version to.

    Use mysqldump on your DB as the other answers state then import the resulting file into this program.

    From James

asp.net mvc renderaction

<%Html.RenderAction("Index", "Test", New With {.pagetmp = "test"})%>

I call the above line in my asp.net mvc view. How do i retrieve the dictionary values from the test controller?

  • You can pass information using ViewData e.g. ViewData["MyDictionary"] = myDictionary;

    From Rick
  • You can't. The point of RenderAction is to let the controller you're calling do what it normally would without you worrying about what's happening. Maybe a partial view might be better suited for you in your case, it's hard to say without seeing the big picture...

    From BFree

GWT with a Content Management System

After seeing some of the benefits of GWT, my partner and I decided that it would be a good front end for the web app we hope to build. A main part of this web app will be content management. We were hoping to use a CMS framework and put GWT on the front end, but all the open source CMS systems we find seem to be very tied to their front end.

Does anybody know of a CMS that would work well with GWT?

  • No, but I can tell you that using a Java based CMS will make your life much much easier. GWT lives on RPC calls, and while translation / JSON overlays are possible, you're much better off with a Java backend.

    You mind find this difficult, though, because when you want to use GWT you're doing a massive amount of work on the front end, leaving the backend mostly data processing and storage. Since very few CMSs are designed to do nothing more than processing and storage, you might be better off building your own.

    That said, you might find it very easy if you're open to using App Engine. The GWT + App Engine stack works really well, now has a great Eclipse plugin dedicated to it, and is free to get started with.

  • I think it all depends on how much integration you want, specifically, what you want to do with GWT. We have successfully integrated GWT with Documentum + Java on the back end.

    With that said, our integration is fairly light. The site is largely a content oriented website, but we use GWT to:

    1. Implement certain more dynamic widgets (e.g., text box with intelligent auto completion, font size changers).
    2. Enhance content in the CMS to make it more animated (for instance, instead of displaying lots of content in a single screen, we use GWT's tab panel to display chunks at a time, while still allowing content authors to manage our content).
    3. Implement "mini-apps" within the site.

    Unfortunately, since this is something I do for a client, I cannot specifically mention the site by name in public, but if you're interested, I can share some details with you via e-mail.

    KevMo : We were hoping to use GWT exclusively for the front end. All of the open source CMS systems we have seen have such an ugly and static front end, we want something very custom and very current.
    Jack Leow : I have sent you a message on your FaceBook page, let me know if it helps, or if you need further details.
    KevMo : Very helpful :)
    From Jack Leow
  • Try the Nuxeo CMS/EMS, which is implemented in Java. Search google for "nuxeo", and also search for "nuxeo gwt" for a variety of tutorials on integrating GWT with Nuxeo.

    From Lukasz
  • can you integrate a gwt application with fatwire?

    From kwast

Processor : How to get cache information about intel xeon.

I'm looking for a way to have a precise architecture information about Xeon E5420. This processor have 4 cores and 2x6Mo cache, so 2 cores shares a 6Mo cache.

I'm working on machines that have 2 processors xeon, thus have 8 cores, and looking at /proc/cpuinfo just gives me indication about which core is on which processor.

Usually odd cores are on a processor and even cores are on the other but I didn't find a way to know which two cores on the same processor shares the 6Mo cache.

Any clue?

  • /proc/cpuinfo gives you physical id, core id, and cache size per core what more info do you need?

    claferri : That should be a comment ... What I need is in my question ... which two cores shares the same L2 Cache ...
    From mog
  • By the way, I found a good library that provide a lstopo command that gives you exactly the topology of the system!

    It is called libtopology and is still in developpement, only avaliable using svn on INRIA's forge.

    If someone want it and don't find it, I will help :)

    From claferri

incremental k-core algorithm

Calculating the k-core of a graph by iteratively pruning vertices is easy enough. However, for my application, I'd like to be able to add vertices to the starting graph and get the updated core without having to recompute the entire k-core from scratch. Is there a reliable algorithm that can take advantage of the work done on previous iterations?

For the curious, the k-core is being used as a preprocessing stage in a clique finding algorithm. Any cliques of size 5 are guaranteed to be part of the 4-core of a graph. In my data set, the 4-core is much smaller than the whole graph so brute-forcing it from there might be tractable. Incrementally adding vertices lets the algorithm work with as small of a data set as possible. My set of vertices is infinite and ordered (prime numbers), but I only care about the lowest numbered clique.

Edit:

Thinking about it some more based on akappa's answer, detecting the creation of a loop is indeed critical. In the graph below, the 2-core is empty before adding F. Adding F does not change the degree of A but it still adds A to the 2-core. It's easy to extend this to see how closing a loop of any size would cause all of the vertices to simultaneously join the 2-core.

Adding a vertex can have an effect on the coreness of vertices an arbitrary distance away, but perhaps this is focusing too much on worst-case behavior.

A -- B; A -- C; A -- D -- E; B -- F; C -- F;

  • It seems to me that an algorithm for an incremental k-core computation based on local exploration of the graph, instead of a "global" iterative pruning, would need an incremental loop detection in order to see which edges could contribute to enter a vertex in the k-core, which is an hard problem.

    I think that the best you can do is to recompute the k-core algorithm at each pass, just removing from the graph the vertices that already are in the k-core and initializing, in the map vertex -> "k-core adjacent vertices" the number of adjacent vertices that already are in the k-core.

    From akappa
  • Quick idea: You could save the history in a list L, i.e., save the order in which the nodes where removed. Whenever you add a new node v, start at the first node w in L which is adjacent to v. Then just go through the remaining nodes in L from w on in linear order. (And test the node v as well and possibly add it to L.)

    From jacob

Best way to make a cross-site request with JavaScript?

Until the cross-site XHR API becomes widely supported, what is the best way to make a cross-site request through JavaScript? I've been using iFrames, but those can get a bit messy. Is there a better way? (By better, I mean easier to work with.)

Also, I'd prefer to see pure JavaScript code, not a framework such as jQuery, etc. I'm using my own mini-framework and I don't want to have to look up how they did it.

EDIT: I forgot to mention, I have no control over the target server, so I can't use the dynamic <script> tags method.

  • There are 2 common ways I know of. One is using a proxy on your server, basically a php file fetching the data for you.

    The other is using dynamic script tags. More info here:

    http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS

    Page 9 of this slideshow also has some info:

    http://bulletproofajax.com/workshop/slides/04formats.html

    musicfreak : I have no control over the target's server, so the second method wouldn't work. But +1 for the proxy method, didn't think about that.
    epascarello : Do not try some hacking thing, use a proxy. If you are afraid of someone using the proxy for no good, lock it down as tight as you can so it can only get what you need it to get.
  • If the data you are trying to grab is JSON, look into JSONP. It works by injecting a <script> tag into the DOM referencing a script on the remote server. The server on the other end returns some json/javascript style response calling a "callback" function with the data. Basically the remote script will looks something like this:

    callbackfunc({'somedata':'testing'});
    

    Where callbackfunc was a function you defined in your script.

    From gnarf
  • You could also take a look at easyxss (http://code.google.com/p/easyxss/wiki/InvokingRemoteMethods) . With only a few lines of code you can get method calls that work across the domain-boundry.

    musicfreak : Hmm, looks interesting. +1

open source alternative to create reports in classic asp?

I'm looking for some open source alternative to create reports from classic asp

they don't have to be something awfully elaborated, we rather find some simple product that allows us to generate pdf files from a data set.

we were thinking about developing some kind of service that took an xml as input and returned a pdf, probably with jasperreports or any other free tool...

we also looked for a component that could convert plain html to pdf, adding some special tags to handle pagination and layout...

any idea?

  • Report.NET is nice. Open-source and implemented in C#.

    A really slick solution for XML, HTML -> PDF is PrinceXML. Not free, but it might be worth it.

Linq dynamic arguments for IQueryable.Where()

I'll preface this with saying I'm day 8 into life as a C# developer.

For a number of DomainModels in the project I am working on, I need the ability to filter all records in a table given what a user submits in a review/search form.

Currently the 2 cent short tour is:

Form submits to FooController/review.

Review then grabs all key/value pairs from Params['filter'] into a dictionary and passes that to a helper class call FooFinder.ByProperties which looks very similar to:

public IQueryable<WorkPlan> ByProperties( IDictionary<string, string> properties)
    {            

        var result = ForSite(Convert.ToInt64(properties.DefaultVal("SiteId", "0")));

        v);

        if(properties.ContainsKeyAndIsNotNullOrEmpty("WorkPlan.Key"))
        {
            var tempVal = Convert.ToInt64(properties["WorkPlan.Key"]);
            result = result.Where(r => r.Id == tempVal);
        }
        // Multiple of these conditional checks follows
       return result;

}

I'd like to cut down on repetative code as much as possible and tried something like

result = ByProperty(properties, "WorkPlan.key", typeof (Int64), r, v => r.id == v);

But thats obviously not going to work for a lot of reasons... still the idea of what I'm trying to accomplish is there. I'd really like to simplify the code down and speed up the process of filtering by using some sort of dynamic helper/utility.

Other idea's I tried was using Reflection and that kid of works for straight comparisons, but then how to check for things like a CreatedDatime property where I want all records greater then " r => CreatedDatetime > CreatedFrom".

If none of this makes sense please comment and I'll try to clear up any issues.

  • What you are asking can be automated, but it is quite a lot of work, and requires a knowledge of the Expression API. Which is quite an advanced topic.

    I would probably keep the code "as is"... dry is fine, but "don't break working code" is another adage worth knowing...

    Alternatively, you might want to look at the Dynamic LINQ Library - this might help you automate things. But to be honest, the existing code isn't that ugly...

    David : Thats the conclusion I reached when I found the Dynamic Linq Library on my own. Its pretty cool but I can't afford to implement right now.

Modelling Collections with associated statistics, and NHibernate.

I am currently attempting to refactor an application that has a lot of places where it displays lists or tables of data, with totals or averages at the end, and percentage changes or cumulative totals with each record.

Typically the collection is modelled as a list of objects and the other data is calculated in the aspx code behind (yuck). I would like to move this logic into my model in order to make it testable and reusable.

The best I can come up with at the moment is to create a collection class that all these objects are added to. This collection can then expose properties that represent various statistics. Like this:

public class DailySales
{
    public DateTime Date { get; set; }
    public decimal Value { get; set; }
}

public class SalesCollection
{
    public List<DailySales> Sales { get; private set; }

    public decimal TotalSales
    {
        get { return Sales.Sum(x => x.Value); }
    }
}

This works well for totals. But now I need to calculate a %change for each day. I can add this to the daily sales, and then update it from the collection class which also seems to work quite well. Except it makes persisting it with Nhibernate rather difficult as there is no way to fire events from the Sales list that the SalesCollection can hook into and calculate the other statistics.

I guess what I am lookin for is a clean way of modelling this kind of data, that can be persisted to Nhibernate easily.

  • I would leave your collection alone, and expose is as something like this

    private IList<DailySales> _dailySales;
    public IEnumerable<DailySales> DailySales
    {
      get
      {
         return _dailySales;
      }
    }
    

    and then just create extension methods for IEnumerable that will do your calculations.

    public static decimal CalculateSomething (this IEnumerable<DailySales>sales)
    {
       return {your calculation here}
    }
    
    From epitka

How to define the RouteTable in VB.NET ?

[Route Table 1][1] This image shows how to define the RouteTable in C#, using the Route Class. How to define it in VB.NET?

  • I see you've asked a couple of questions about code conversion. There are free tools that help with this like:

    http://codechanger.com/

    It'll be quicker than waiting for others to help you translate. There are some language features that don't get handled well, but it works on most code.

    Also, you image link is broken, so I can't see the code to help translate.

    : This is how the code looks. Route myroute=new Route(); myroute.url="[controller]/[action]/[id]"; myroute.RouteHandle=typeof(MvcRouteHandler); myRoute.Defaults=new {action="Index", id=(string)null}; For the below line of Code, myRoute.Defaults=new {action="Index", id=(string)null}; Would it be like myroute.defaults=New With {action="Index",id=(string)null}; or myroute.defaults=New With {.action="Index",.id=(string)null}; Thanks in advance

Best way to find out if an (upcast) instance doesn't implement a particular interface

Maybe the need to do this is a 'design smell' but thinking about another question, I was wondering what the cleanest way to implement the inverse of this:

foreach(ISomethingable somethingableClass in collectionOfRelatedObjects)
{
  somethingableClass.DoSomething();
}

i.e. How to get/iterate through all the objects that don't implement a particular interface?

Presumably you'd need to start by upcasting to the highest level:

foreach(ParentType parentType in collectionOfRelatedObjects)
{
  // TODO: iterate through everything which *doesn't* implement ISomethingable 
}

Answer by solving the TODO: in the cleanest/simplest and/or most efficient way

  • Something like this?

    foreach (ParentType parentType in collectionOfRelatedObjects) {
        if (!(parentType is ISomethingable)) {
        }
    }
    
    From J D OConal
  • Probably best to go all the way and improve the variable names:

    foreach (object obj in collectionOfRelatedObjects)
    {
        if (obj is ISomethingable) continue;
    
        //do something to/with the not-ISomethingable
    }
    
  • J D OConal's is the best way to do this but as a side note, you can use the as keyword to cast an object, and it'll return null if its not of that type.

    So something like:

    foreach (ParentType parentType in collectionOfRelatedObjects) {
        var obj = (parentType as ISomethingable);
        if (obj == null)  {
        }
    }
    
    From sontek
  • this should do the trick:

    collectionOfRelatedObjects.Where(o => !(o is ISomethingable))
    
    J D OConal : Nice. I haven't done too much with these new methods.
    From Jay Bazuzi
  • With some help from the LINQ extension method OfType<>(), you can write:

    using System.Linq;
    
    ...
    
    foreach(ISomethingable s in collection.OfType<ISomethingable>())
    {
      s.DoSomething();
    }
    
    From Yacoder

Internationalizing Desktop App within a couple years... What should we do now?

So we are sure that we will be taking our product internationally and will eventually need to internationalize it. How much internationalizing would you recommend we do as we go along?

I guess in other words, is there any internationalization that is easy now but can be much worse if we let the code base mature and that won't slow us down very much if we choose to start doing it now?

Tech used: C#, WPF, WinForms

  • Prepare it now, before you write all the strings in the codebase itself.

    Everything after now will be too late. It's now or never!

    It's true that it is a bit of extra effort to prepare well now, but not doing it will end up being a lot more expensive.

    If you won't follow all the guidelines in the links below, at least heed points 1,2 and 7 of the summary which are very cheap to do now and which cause the most pain afterwards in my experience.

    Check these guidelines and see for yourself why it's better to start now and get everything prepared.

    1. Developing world ready applications

    2. Best practices for developing world ready applications

    Little extract:

    1. Move all localizable resources to separate resource-only DLLs. Localizable resources include user interface elements such as strings, error messages, dialog boxes, menus, and embedded object resources. (Moving the resources to a DLL afterwards will be a pain)
    2. Do not hardcode strings or user interface resources. (If you don't prepare, you know you will hardcode strings)
    3. Do not put nonlocalizable resources into the resource-only DLLs. This causes confusion for translators.
    4. Do not use composite strings that are built at run time from concatenated phrases. Composite strings are difficult to localize because they often assume an English grammatical order that does not apply to all languages. (After the interface design, changing phrases gets harder)
    5. Avoid ambiguous constructs such as "Empty Folder" where the strings can be translated differently depending on the grammatical roles of the strings' components. For example, "empty" can be either a verb or an adjective, and this can lead to different translations in languages such as Italian or French. (Same issue)
    6. Avoid using images and icons that contain text in your application. They are expensive to localize. (Use text rendered over the image)
    7. Allow plenty of room for the length of strings to expand in the user interface. In some languages, phrases can require 50-75 percent more space. (Same issue, if you don't plan for it now, redesign is more expensive)
    8. Use the System.Resources.ResourceManager class to retrieve resources based on culture.
    9. Use Microsoft Visual Studio .NET to create Windows Forms dialog boxes, so they can be localized using the Windows Forms Resource Editor (Winres.exe). Do not code Windows Forms dialog boxes by hand.
  • IMHO, to claim something is going to happens "in a few years" literally translates to "we hope one day" which really means "never". Although I would still skim over various tutorials to make sure you don't make any horrendous mistakes. Doing correct internationalization support now will mean less work in the future, and once you get use to it, it won't have any real affect on today's productivity. But if you can measure the goal in years, maybe it's not worth doing at all right now.

    I have worked on two projects that did internationalization: a C# ASP.NET (existed before I joined the project) app and a PHP app (homebrewed my own method using a free Internationalization control and my own management app).

    You should store all the text (labels, button text, etc etc) as data inside a database. Reference these with keys (I prefer to use the first 4 words, made uppercase, spaces converted to underscores and non alpha-numerics stripped out) and when you have a duplicate, append a number to the end. The benefit of this key method is the programmer has a pretty strong understanding of the content of the text just by looking at the key.

    Write a utility to extract the data and build .NET resource files that you add into your project for compile. Create a separate resource file for each language. In your code, use the key to point to the proper entry.

    I would skim over the MS documents on the subject: http://www.microsoft.com/globaldev/getwr/dotneti18n.mspx

    Some basic things to avoid:

    • never ever ever use translation software, hire a pro or an intern taking that language at a local college
    • never try to create text by appending two existing entries, because grammar differs greately in each language, this will never work. So if you have a string that says "Click" and want one that says "Click Now", do not try to create a setup that merges two entries, or during translation, copy the word for click and translate the word now. Treat every string as a totally new translation from scratch
    Justin Bozonier : As far as the YAGNI... yeah I think that way about a lot of stuff. This is one area where I've been bit in the butt for it though. Internationalization is a common way to grow your product's user base so you want to make sure you can do it. One project I worked on literally couldn't. That was bad.
    From TravisO
  • I will add to store and manipulate string data as Unicode (NVARCHAR in MS SQL).

    From Hapkido
  • If you use test data, use non-English (e.g.: Russian, Polish, Norwegian etc) strings. Encoding peeks it's little ugly head at every corner. If not in your own libraries, then in external ones.

    I personally favor Russian because although I don't speak a word Russian (despite my name's origin) it has foreign chars in it and it takes way more space then English and therefor tests your spacing too.
    Don't know if that is something language specific, or just because our Russian translator likes verbose strings.

    borisCallens : weird! made the same typo three times.. Even in my native tongue it is not written like that. And the other languages I wrote correct.. Sometimes I delude even myself
  • Internationalization will let your product be usable in other countries, it's easy and should be done from the start (this way English speaking people all over the world can use your software), those 3 rules will get you most of the way there:

    1. Support international characters - use only Unicode data types in files and databases.
    2. Support international date, time and number formats - use CultureInfo.InvariantCulture when storing data to file or computer readable storage, use CultureInfo.CurrentCulture when displaying data or parsing user input, never do your own parsing, never use any other culture objects.
    3. textual data entered by the user should be considered a black box, don't try to break it up into words or letters, especially when displaying it to the user - different languages have diffract rules and the OS knows how to display left-to-right text, you don't.

    Localization is translating the software into different languages, this is difficult and expensive, a good start is to never hard code strings and never build sentences out of smaller strings.

    From Nir
  • Some questions to think about…

    How match can you afford to delay the shipment of the English version of your application to save a bit of cost internationalize later?

    Will you still be trading if you don’t get the cash flow from shipping the English version quickly?

    How will you get the UI right, if you don’t get feedback quickly from some customers about it?

    How often will you rewrite the UI before you have to internationalize it?

    Do you English customers wish to be able to customize strings in the UI, e.g. not everyone calls a “shipping note” the same think.

    As a large part of the pain of internationalize is making sure you don’t break the English version, is automated system testing of the UI a better investment?

    The only thing I think I will always do is: “Do not use composite strings that are built at run time from concatenated phrases” and if you do so, don’t spread the code that builds up the a single string over lots of methods.

    Having your UI automatically resize (and layout) to cope with length of labels etc will save you lots of time over the years if you can do it cheaply. There a lots of 3rd party control sets for Windows Forms that lets you label text boxes etc without having to put the labels on as separate controls.

    I just starting to internationalize a WinForms application, we hope to mostly be able to use the “name” of each control as the lookup key, without having to move lots into resource files etc. It is not always as hard as you think at first….

How can I get CPU usage and/or RAM usage of a *THREAD* in C# (managed code)?

I know how to get CPU usage and memory usage for a process, but I was wondering how to get it on a per-thread level. If the best solution is to do some P-Invoking, then that's fine too.

Example of what I need:

Thread myThread = Thread.CurrentThread;

// some time later in some other function...

Console.WriteLine(GetThreadSpecificCpuUsage(myThread));
  • Here's an example which does what you want http://www.codeproject.com/KB/system/processescpuusage.aspx

    Timothy Khouri : This is as close as I think we're going to get... thanks!
  • You can't get memory usage per thread because memory is shared between all threads in a process. How would the OS know whether you allocated memory in one thread and used it in another. And what would it mean?

    From erikkallen
  • As said, memory use cannot be answered since that is an attribute of the process as a whole, but CPU use:

    Process p = Process.GetCurrentProcess;
    foreach (ProcessThread pt in p.Threads)
    {
        // use pt.Id / pt.TotalProcessorTime / pt.UserProcessorTime / pt.PrivilegedProcessorTime
    }
    
    From jerryjvl

Row Count Transformation in SSIS

Hi, I am using the 'Row Count'component to count the rows in the data flow. I have decalred a new variable called In_rec. But it is not populating the correct rowcount. Please let me know the Input Column properties for the same.

  • What do you mean it's not populating the correct row count? Are you trying to read the variable outside of the data flow task and can't? Is your scope set properly (i.e.-not just the data flow task if you're trying to access it in another task)?

    From Eric

Getting jQuery to work in Jetpack

Hi, I am experimenting with Jetpack and I would like to parse all the years in a given html page and then wrap the year with a link to the Wiki page. I tried the code in jquery and there it works but now I am using it in Jetpack and it gives an error $(doc).replace is not a function. I am definitely new to Jquery / Jetpack so maybe I am missing something really easy but your help is much appreciated.

EDIT: I have tried the suggestions but I am still stuck. The weird thing is that this

JQuery function works:

    (function($) {
        $.fn.clickUrl = function() {  
                var regexp = /([1-2][0-9][0-9][0-9])/gi;
          this.each(function() {
          $(this).html(
                $(this).html().replace(regexp,'<ahref=\"http://nl.wikipedia.org/wiki/$1\">$1<\/a>')
          );
         });
        return $(this);
        }
    })(jQuery);

and basically, I would like to 'port' this function to Jetpack.

Thanks a lot for any suggestion! Best regards, Diederik

this is the 'old' non-working port of my JQuery function to Jetpack:

jetpack.statusBar.append({
html: "Hyperlink Years",
width: 80,
onReady: function(widget){
$(widget).click(function(){
var regexp = /([1-2][0-9][0-9][0-9])/gi; var doc = jetpack.tabs.focused.contentDocument; $(doc).each(function() { $(this).html( $(doc).replace(regexp,'$1<\/a>')); }); return $(doc); });
}

});

  • I'm not familiar with jetpack, but your jquery seems to be quite messed up.

    If "doc" is an HTML document, then doing $(doc).each() doesn't really make sense. It would only loop once, and "this" would be the same as doc.

    Then later you are doing $(doc).replace(regexp, ...), but replace() is not a jquery function. You might have wanted to do .html().replace(regexp, ...); HOWEVER, I do not recommend doing this because it will not work - you will just end up replacing any numbers in the document, even if they are part of another URL or the HTML of the page.

    For more information, refer to this question or google for jquery text nodes: http://stackoverflow.com/questions/926580/find-text-string-using-jquery/926881#926881

    From BarelyFitz

Rewrite rule not working

I've done the first steps in Zend Framework with akrabat.com/zend-framework-tutorial/. The Demo-App works fine, but the CSS. I think my rewrite rules are wrong. All hrefs looks like:

  • /~cm/zf-tutorial/public/index.php/index/edit/id/1
  • /~cm/zf-tutorial/public/index.php/css/site.css

The .htaccess is:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteBase /
RewriteRule !\.(js|ico|txt|gif|jpg|png|css)$ index.php

Can someone give me a hint how to change it?

  • I think the rewrite rule looks fine. It's pretty much the one that ships with ZF. How do you include your stylesheets? Where do you place them, and where is the index.php etc located?

    Say you define your document root for the application as /htdocs/zf-tutorial/public, and that you have your stylesheets in /htdocs/zf-tutorial/public/css, then you have to remember that styles are included as /css/site.css.

    Also, your hrefs should NOT include index.php, the Apache re-write rules take care of that. Your hrefs should look like:

    • /index/edit/id/1
    • /css/site.css
    • /controller/action/parameterlist

Visual Studio having trouble painting SSIS tasks

I've got this weird behavior in Visual Studio 2005 when working with SSIS packages. Visual Studio appears to be having problems painting/repainting the tasks.

When I open a package, I see the label of the task items and the line connecting tasks, but I don't see the box outline or the icon of the task type. When I click on the task item, the outline and icon appear. If I minimize the screen and then maximize it, they disappear again.

The problems exists if I bounce my machine and load Visual Studio by itself. I don't have the problem with any other projects.

  • I've seen it couple times, and in both cases the problem disappeared after I installed the latest video drivers.

    From Michael

UINavigationController intercepting – popViewControllerAnimated:

So the the problem is that when someone touches the back button on the UINavigationControler, I would like to run some code to update the datasource.

The problem is that i cant seem to find the right delegate to do it. only these are available on the nav controller delegate, and i want the 'didfinishshowing' type method.

– navigationController:willShowViewController:animated:  optional method  
– navigationController:didShowViewController:animated:  optional method

The next best place i thought was the nav bar but when i try that.

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Cannot manually set the delegate on a UINavigationBar managed by a controller

This makes sense retrospectively, as you don't want some hacker messing around with the internals of the nav controller and stopping it from working.

This must is a common problem, and i have missed something simple.

  • Add your refresh code to the viewWillAppear:(BOOL)animated method on the view controller that is about to be displayed. In your case, that is the view controller that's already on the navigation stack.

    From dmercredi
  • Just so we're clear: view A is the starting point. User taps something and you slide right to view B. User taps the back button and you're going from B back to A and you want to do something as a result of the 'back' action.

    There are three ways to do it (and on neither do you have to go near the navigationController -- these apply to the underlying viewControllers themselves):

    • As dmercredi suggests override viewWillAppear on view controller A so when you're heading back to it, it refreshes itself. Problem is that viewWillAppear is also called when A is called the very first time. So you'll have to set some sort of flag to distinguish between the first viewWillAppear and any subsequent ones when returning from B.

    • Override viewWillDisappear on view controller B and do your refreshing there. This will only get called when B is about to go away. If there's something on B that goes one level deeper or brings up a modal dialog on top, viewWillDisappear is going to get called so again you'll have to distinguish between the coming and the going.

    • Decouple the various views and use the delegate pattern. View controller A sets itself as a delegate of B and when B updates something it invokes the delegate method, so A is notified of the change and can update whatever it needs to. You can invoke the delegate method any time the user makes a change inside B or override viewWillDisappear and just do it one time on the way out.

    From Ramin