Thursday, April 28, 2011

Simulating a global revision number with git

How would I go about simulating a global increasing revision number for every commit in the git main line?

So, after I commit I would like a script to run increases a number somewhere.

This will allow me to tell my customers easily that X feature was fixed in git revision XYZ.

I am looking for a practical sample script that is robust enough to handle pushes and merges to a degree.

From stackoverflow
  • I think you're confusing revision numbers with release numbers.

    Subversion uses revision numbers because it can: it's a centralized repository. Git of course has SHA-1 hashes not revision numbers because it has no central repository (but you know this).

    That revision number (and the hash is technically a 160 bit number, it's just not sequential) shouldn't really be of concern to your customers. What they should be concerned with is the release number. That's when you package up your source code and say "this is version 2.3.4", complete with release notes to say what's changed.

    Ideally such a list is generated by issue-tracking software and your source code is simply tagged to say which revision constitutes that release number.

    Juliano : Except that Git doesn't use 128-bit GUIDs at all. Git uses 160-bit SHA-1 hashes of the each object stored. A GUID is a completely different beast:
    cletus : Oh woops, thanks. Fixed.
  • It's possible to simulate a revision number in git, however it's important to know that it's not a perfect match and not the easiest to trace back to. Personally I use it to make more simple revision numbers for a web app because I'm the sole developer. I use the following function in my .bashrc to get the revision number which I then use for the release notes (however if you aren't already I highly recommend tagging the release - then the number is just for users). If the limitations are well known it gives a much more human friendly revision number.

    function rgit() {
        git rev-list --abbrev-commit HEAD | wc -l | awk '{print $1}'
    Sam Saffron : That is truely awesome, I have the exact same problem, single dev on a web app that is moving really quickly. I understand that this can go pear shape if I start re-writing history but accept that limitation.
  • git describe gives you a version description like the following: v2.0-64-g835c907. The v2.0 part is the name of the latest annotated tag preceding the commit, 64 is the number of commits after that, and 835c907 is the abbreviated commit id. It is basically there to identify any revision in an exact and convenient (although technical) way.

    Note: For this to work you will need at least one annotated tag. To create one for version v2.0 run - git tag -a v2.0, if you have no annotated tags this command will fail, unless given a fallback argument like --tags or --always.

    Sam Saffron : I think I will accept this, it is the git-way and will be robust enough long term to handle multi dev scenarios ... I can always show the customers on the web site 2.0.64 and then keep the rest of the info on the file system somewhere so I can track the commit.
  • I (being unaware of git describe) have been using the following script:

    FULL_BRANCH=`git branch | grep '*'`
    REV=`git rev-parse --short HEAD`

    This gives you a name that contains the current branch name, followed by the short commit ID. For example: master-c03f862.

    It is enough to do what you are after, but perhaps git describe is the correct way to go here.

how eq(0) works with DOM

Hi All,

I want to know in below case will the browser stop traversing the DOM after getting the first .myclass

From stackoverflow
  • No. In your example, the browser will fetch all the elements with class myclass. Then you apply a filter for the first element.

    You might be able to call .end() after your .eq(0) to get the whole elements back.

    You need the selector eq, like in the following example $(".myclass:eq(0)").

    Wondering : ok, thanks for ur inputs.
  • I don't believe so.


    Will return a jQuery object that (behind the scenes) contains an array of all matching DOM elements.

    You are then calling a method on that object to return the first element.

    If you want to avoid this, you need your selector to only select one element. Take a look at the documentation for selectors:

    Try this instead:

    Wondering : No i just wanted to know how it works.Thanks for the info.
    bobince : Note that in practice this will actually slow it down in recent browsers! This is because `:first` isn't a standard CSS selector, so jQuery won't be able to pass the work off the the new Selectors-API function `document.querySelectorAll`, and will have to fall back to the usual native-JavaScript ‘Sizzle’ selector library. The fastest solution would be to use `document.querySelector` (without the `All`) which gets just one element. However there is currently no jQuery integration for this method. You could sniff for it and fall back to jQuery, but it's probably a premature optimisation.
    SpoonMeiser : Does jQuery use this API now? In my experience, selecting by class (for large documents, at least) is slow anyway.

Why does CakePHP bork when I use jquery to modify values of hidden inputs?

I'm using cakephp to build a survey and want to use javascript (specifically jquery as it's used elsewhere) to modify some hidden inputs.

To be clear, commenting out the offending lines of jquery allows cake to do it's thing properly. But when the values are modified with jquery, this happens:

(default) 2 queries took 2 ms

To take just one of the hidden inputs in question, here's the relevant code:

<?php echo $form->hidden('bigLayout', array('value'=>'1')); ?>

<script> $('#ResponseBigLayout').val('0');</script>

Additionally, I can use Firebug to replicate the error using just that line of javascript. Using Tamper Data doesn't reveal anything obvious. Lastly, changing the default value in the php doesn't cause the error.

Anyone know what might be going on here?

From stackoverflow
  • Try using

    <?php echo $form->hidden('bigLayout', array('value'=>'1','secure'=>false)); ?>


    <?php echo $form->hidden('bigLayout', array('value'=>'1','secure'=>'false')); ?>

    From the source (FormHelper: hidden())it looks like CakePHP for hidden inputs uses secure = true by default.

    Tom Wright : Unfortunately, that didn't change anything. Strangely though, when I used 'secure'=>'false' and $('#ResponseBigLayout').val('1'); I get a different error with 0 queries. Is this a useful clue to anyone?
  • If I do modify form values (for hidden) or attributes (i.e. disabled) then in controller in beforeFiler I use something like this:

    function beforeFilter() {
        if ($this->action == 'add') {
            $this->Security->enabled = false;

Auto Indentation Off

Hi All,

In Visual Studio, when I press Enter, it automatically indents my text, and I don't like that. Is there a way to turn that 'feature' off?

Thank you :)


From stackoverflow
  • Try changing:

    Tools -> Options -> Text Editor -> C# -> Tabs -> Intenting

    To "none"

  • Tools->Options->Text Editor->C#->Tabs->select none under Indenting or change the tab size to 0

    baeltazor : Thank you, I did already go into the settings. but i obviously missed it. thanks again :) jase.

Actionscript 3: Is there a way to detect collisions between a class and a class within a class?

So I'm currently making a platformer game in flash. I want to detect a collision between my player class, and the enemy class. The enemy class is inside of a class called ground. I tried to detect it using hitTestPoint (ground.enemy.hitTestPoint(player.x, player.y, true)), but to no avail. How would I go about doing this?

From stackoverflow
  • Without seeing your code it's hard to say what's going on... what exactly didn't work with your hitTestPoint() approach? You might need to translate the player point coordinates to a value relative to ground (see: localToGlobal() AND globalToLocal()).

    Miles : Well, as far as I know, flash didn't like that I was accessing hitTestPoint by ground.enemy.hitTestPoint? If this wasn't clear, I dragged the enemy movieclip onto ground's timeline, so I'm trying to detect a collision with that.
    heavilyinvolved : Posting some of your code or the error messages you are getting would be helpful in working towards a resolution.
  • Maybe it could be one of the following issues:

    • Have in mind that the hitTestPoint method work with the root coordinate system. If your player and ground objects are not both placed in the root, then some coordinate transformations will be needed.
    • The player.x and player.y values are located through the origin point within the player clip. If by chance the origin point lies outside the player graphic, then the hit test will fail since the coordinate you are checking will probably not be where you would expect.
    • If everything else fails, try to check that everything is working right by checking the hit test with the mouse: ground.enemy.hitTestPoint(stage.mouseX, stage.mouseY, true);

CREATE SCHEMA gives 1064 error

   DEFAULT CHARACTER SET 'utf8' COLLATE default collation ;

this line results with error 1064. MySql 5.4.3-beta.

From stackoverflow
  • This works:

       DEFAULT CHARACTER SET 'utf8' COLLATE default;

    There was an extra "collation" at the end. : Thanks, strange Workbench generate me this

HTML forms working offline

I need to be able to run HTML forms offline. I mean they have to work without direct connection to the web server.

In an application I wrote over 5 years ago I did it by implementing a custom protocol handler - when a user initiated form submit the resulting HTTP request was recorded locally. At later time when a connection to the server becomes available a synchronization program loops through collected requests and submits them to the server collects the responses and again saves them locally for later use.

That was then. Now another customer approached me with a very similar request. What technology do you guys think I should use today?

Support for HTML5 is very limited just yet. Google gears? Or should I go back and continue using the protocol handler and custom synchronizer?

From stackoverflow
  • Google Gears is a very good candidate - as an example, Google recently just announced that users would be able to attach files to emails while 'offline'. Another method might be to store the posted form data in a cookie, and when the user is able to get back online the server picks up the cookie and data with it.

    mfeingold : A cookie will not cut it. The forms can have pretty significant amount of data, dozens of fields. I would not want to use cookies for it
    Josh : I understand. However, keep in mind that cookies can store literally megabytes of data, depending on the browser. Even dozens of fields should not be an issue. Only issue will be with actual file data (i.e. PDF upload).
  • I'd say go for HTML5. Not all browsers support it; but all will. In the meanwhile, i think it's better to say "to get offline features try such or such browser", instead of "please download this huge plugin with lots of scary warnings".

    Also a simple demographics: HTML5 is in what, 5% of all browsers? 10%? still a lot more than the 0% of users with Gears already installed.

    It's a real pity, thanks a lot Google for pushing the envelope with Gears; but in the wild the only plugin generally accepted is Flash. Fortunately, HTML5 is almost there already, with nearly the same features.

    tosh : +1 for proposing a good long term solution
  • Dojo.Storage/ Dojo Offline , has a flash bridge that will enable you to store data using flash's data store. The limit is user set, but starts at 5Mb. The library component is an abstraction, and also supports HTML 5, cookies, and gears.

    Plus gears will allow you to store binary blobs, if memory serves.

  • Rumors are running around that Google Gears is no longer under development. When you look at the gears features and issue tracker at for the new Gears development, there are only 3 items which will be fixed in version 0.6. Also, according to this Wikipedia article (, it seems that Google is not doing any development, and the open source project does not have a lot of steam either. Taken from the article is this:

    "In late November 2009, numerous online news sources reported that Google is going to migrate to use HTML 5 rather than Gears in the future. A Google spokesman later clarified that Google will however continue to support Gears to not break sites using it."

    In other words, Gears has been deprecated. Use HTML 5 instead.

Global variables in Visual C#

How do I declare global variables in Visual C#?

From stackoverflow
  • How about this

    public static class Globals {
        pulic static int GlobalInt { get; set; }

    Just be aware this isn't thread safe. Access like Globals.GlobalInt

    This is probably another discussion, but in general globals aren't really needed in traditional OO development. I would take a step back and look at why you think you need a global variable. There might be a better design.

    Pavel Minaev : In what sense is it not thread safe? And how is that any different from a non-static property?
    0A0D : -1 for not explaining why it isn't thread safe... needs more explanation
    Bob : This isn't a question about thread safety. If you are interested in thread safety then ask in another question or update this question to explicitly include a thread safe solution. Also see this question for what thread safety is if you never heard the term
    Russell : +1 for "I would take a step back and look at why you think you need a global variable. There might be a better design." I found in large projects, it is a lot more difficult to track the use of global variables opposed to instance variables. This helps, especially during maintenance.
  • Use the const keyword:

    public const int MAXIMUM_CACHE_SIZE = 100;

    Put it in a static class eg

    public class Globals
        public const int MAXIMUM_CACHE_SIZE = 100;

    And you have a global variable class :)

    Phenom : Doesn't the const keyword make it constant? Can it be changed?
    mykhaylo : "The const keyword is used to modify a declaration of a field or local variable. It specifies that the value of the field or the local variable cannot be modified." -
    JohannesH : A const field isn't varable. ;)
    Russell : lol yeah - i read the question too quickly, I usually only provide contants when exposing values globally. Everything else are in instance variables. :)
  • You can'nt declare global variables - use static class or Singleton pattern

  • The nearest you can do this in C# is to declare a public variable in a public static class. But even then, you have to ensure the namespace is imported, and you specify the class name when using it.

  • A public static field is probably the closest you will get to a global variable

    public static class Globals
      public static int MyGlobalVar = 42;

    However, you should try to avoid using global variables as much as possible as it will complicate your program and make things like automated testing harder to achieve.

Finding end/start date in MySQL

Look at this MySQL table:

| date_key   | stude_key |
| 2005-09-01 | COM       | 
| 2005-09-02 | COM       | 
| 2005-09-06 | COM       | 
| 2005-09-07 | COM       | 
| 2005-09-08 | COM       | 
| 2005-09-09 | COM       | 
| 2005-09-12 | COM       | 
| 2005-09-01 | YUM       | 
| 2005-09-02 | YUM       | 
| 2005-09-06 | YUM       | 
| 2005-09-07 | YUM       | 
| 2005-09-08 | YUM       | 
| 2005-09-09 | YUM       | 
| 2005-09-12 | YUM       | 
| 2005-09-01 | DSA       | 
| 2005-09-02 | DSA       | 
| 2005-09-06 | DSA       | 
| 2005-09-07 | DSA       | 
| 2005-09-01 | JRA       | 

It contains the days when a class took place, and student attendance. I want to know the students that gave up (stop going to classes) and when. A student cannot miss a class and return.

For instance, the course took place between 01 and 12 of September 2005. COM and YUM attended all the classes but DSA gave up on 2009-09-07 and JRA only got 1 class.

I'm trying to get a table with:

| gave_up    | student   |
| 2005-09-07 | DSA       | 
| 2005-09-01 | JRA       | 

Any ideas on how to efficiently do that?


From stackoverflow
  • If you're just after the last entry for each student:

    SELECT MAX(date_key) AS gave_up, student
    FROM [table_name]
    GROUP BY student
  • SELECT MAX(date_key) AS gave_up, stude_key AS student
     FROM thetable
     GROUP BY stude_key
     HAVING MAX(date_key) != '2005-09-12'

Instantiation of objects

If I use multiple instances of the same object in my code, do the instance methods for each separate object require memory, or do all of those objects share the same instance methods?

It could have a big effect on memory use.

Thanks in advance for any insights.

John Doner

From stackoverflow
  • It might depend on the language you are using ;-)

    In all language implementations that I'm aware of, the methods are shared. In most C++ implementations, for example, the method gets an implicit first parameter (this) that points to the particular instance of the object.

  • You didn't specify what language you're talking about. But, in general, the separate instance methods will not take up more memory.

    To tell you the truth, you probably shouldn't even think about these details, as modern language designers have thought about this for you, and they have probably chosen the best thing. So, if there's no real reason to keep another copy (because all of the methods are actually the same), they won't save another copy.

Anyone know where I can download a zipped Python distribution?

Yeah, kind of random, but I was wondering if anyone could link me to a .zip file containing a Python distribution. I know I could download the installer, so please don't suggest that. :P.

From stackoverflow
  • I didn't exactly understand what you want. Is Portable Python enough for you? If it isn't, check Python's official download website where you have a lot of options - including compressed source tarballs. You can downlod the tarballs, extract and create a zip file.

  • Can you use the official Source Distribution of Python? It is not zipped, but you can unpack the whole thing in one line of Python.

    import tarfile;'Python-3.1.1.tar.bz2').extractall()
    S.Mark : Nice! but Its like CD Driver is in CD
    Andrew : I guess that'll work.

IS (Intentional Shared) lock

Hi, can anyone give a simple example of a db transaction using an Intentional Shared lock, and (if can) one using an intentional exclusive lock.

I'm studying them and trying to understand.


From stackoverflow
  • Intent locks are needed because the lock manager does not understand the physical structure of the entities locked. If one transaction S-locks a record, say R1, and another transaction asks for an X-lock on a page, say P1, what happens if R1 is actually located on P1? the lock manager should not honor the P1 request until R1 is released, but to do so it would have to understand that R1 is contained in P1.

    Since the lock manager clearly cannot know the structural details of the objects locked, the intent lock were introduced. The first transaction will place an IS-lock on P1 then an S-lock on R1. When the second transaction requests for X-lock on P1, it will conflict with the IS-lock placed by the first transaction.

    Sheldon : Thank you Remus!
    Sheldon : So Intent locks are not locks as it, but ways to define wether certain data can be locked or not, and if can, how to lock it? as a top-down tree, with granularity gown down on the three as greater.
    Remus Rusanu : From the lock manager point of view the locks are of 4 types: IS, IX, S, X (ignoring U locks and other types). LM understand them all as locks and has a compatibility matrix that makes IS-IX and IX-IX compatible (but not S-IX, X-IS and X-IX). The 'accessor' (which understand the structure of the hierarchy tree) will navigate the tree, asking for I locks as it goes down the hierarhy, until it finds the actual item of interests on which it requests an S or X lock.
    Remus Rusanu : You can best think at I locks as breadcrumbs. You leave them behind so that someone else does not cut the branch you're standing on. If Gretel ever climbs into a tree, that is... sort of.
    Sheldon : Thank you very much, now I have it clear!

Windows mobile program without form

Is there a way to have a windows mobile app without a form?

I'm writing a small program which is intercepting SMS messages, but I don't want the program to pop up every time it receives a message (which it does right now). any way to have the sms processed in the background instead of popping up the window?

From stackoverflow
  • Sure. Don't create a Form in the Main entry point of the application and it won't have a Form.

    Sam : But then I would need to multi-thread, letting the main thread wait for some event to end the program, since I don't have a form to handle events (sms interception, timer)?
    ctacke : Of course. How else would you propose to do this? You can always create your own message pump (the Smart Device Framework has a Form-less pump as well) but you have to have some sort of loop to keep the app from exiting the entry method.

Why I cannot derive from long?


My function returns some long value which contains two values in lower and higher 32 bits.

I thought the best ways to handle return value is to derive my custom type from long and provide type extenders like GetLowerValue(), GetHigherValue().

The problem is that .NET does not allow to derive from long

If you compile that

public class SubmitOrderResult : long

you get:

cannot derive from sealed type 'long'

Why is that designed so and how can overcome it?


From stackoverflow
  • You can't derive from any of the .NET Value Types - they are all sealed by definition.

    Perhaps you could implement your GetLowerValue and GetHigherValue methods as extension methods?

    James : +1 extension methods are definetly the way to go in this instance.
    Captain Comic : Right. So I'll go for extension. What I dislike about extension is that I will extend a common long type which might not necessarily be "my" long and does not contain two values in it. Deriving a new type would be more type-safe.
    Konrad Rudolph : @James: I somehow doubt that … a distinct types seems much more appropriate.
    Matt Howells : Create a new type which wraps a long field. See Bojan Resnik's answer.
    James : @Captain Comic, It is easy enough to simply ignore the methods and only use them when required.
    Tor Haugen : Well, a downside of this approach is that the extension methods will show up in intellisense for every long, whether appropriate or not.
    James : @Tor, valid point however as I commented in one of the other posts, you would only ever use the methods where appropriate. I find (maybe not everyone) that there are a always methods on various types/classes that aren't always relevant to what I need to do, this doesn't mean I am going to go create a custom type just to narrow down my intellisense.
  • As already mentioned value types in .NET are sealed so there is no way you can derive from long. You should create extension methods as suggested.


    public static class LongExtensions
        public static long GetLowerValue(this long value)
        public static long GetHigherValue(this long value)
  • You can't overcome it.

    As long is a sealed type and therefore you can't inherit from them. See the MSDN

    Because structs are implicitly sealed, they cannot be inherited.

    For more information, see Inheritance (C# Programming Guide).

  • If I understand correctly, your function actually returns two values, and the fact that you pack them into a long is an implementation detail. In that case, hide this detail and create a class which contains the value and the required operations:

    public class SubmitOrderResult
        private readonly long value_;
        public int OneValue
            get { return (int)(value_ >> 32); } 
        public int TheOtherValue
            get { return (int)(value_ & 0xFFFFFFFF); } 
        public SubmitOrderResult(long value)
        { value_ = value; }
    Konrad Rudolph : Why use `long` for storage at all? I fail to see the advantage … unless for interop with P/Invoke (or similar scenarios where low-level access makes sense).
    Bojan Resnik : I completely agree, and I used `long` because it was OP's requirement. The point I am trying to make is that whether or not OP chooses to actually use `long` in his function is an implementation detail and clients do not need to know about that.
  • My function returns some long value which contains two values in lower and higher 32 bits.

    That sounds like a really, really dirty hack. It could be appropriate for close-to-metal languages (e.g. C) but not for a higher-level, object-oriented language.

    In OO languages, you extend the type system, not harass existing types to do your bidding. Thus, the solution should be to create a new type which carries your information.

    Tor Haugen : My guess is it's not actually 'his' function, because then he wouldn't have this problem. Perhaps it's an extern, or at least some class library out of his control.
  • What you can do is write a struct with implicit conversion operators. That will work exactly the way you want:

    public struct SubmitOrderResult
        private long _result;
        public SubmitOrderResult(long result)
            _result = result;
        public long Result
            get { return _result; }
            set { _result = value; }
        public int GetHigherValue()
            return (int)(_result >> 32);
        public int GetLowerValue()
            return (int)_result;
        public static implicit operator SubmitOrderResult(long result)
            return new SubmitOrderResult(result);
        public static implicit operator long(SubmitOrderResult result)
            return result._result;

    Then you can do:

    SubmitOrderResult result = someObject.TheMethod();

    ...just like you wanted.

Javascript OnclickOff

Hi there,

I have a div that I want to trigger a function when I click on it (easy enough using onclick) that shows child divs that have been hidden. I also want to make it so that when you click anywhere else on the document after the child divs have been shown, it will hide the child divs.

I am not sure of the best way to approach this, thanks in advance.

From stackoverflow
  • Put an onclick handler on the body element. This handler will contain the code to hide the div.

    Walt : right but if you click on the div, it toggles the body as well.
    Mark Byers : You can put a click handler in the div that does nothing except "event.cancelBubble=true;" then the body handler is never invoked.
  • Using jQuery:

    function handleGeneralClick(evt)
        if ($(evt.currentTarget).attr('id') == 'my_div')
            // Show child div's
            // Hide child divs

    Or something like that anyway...

Mode is not changing in detailsview

hi in details view once i click edit mode. all the controls are getting into edit mode. i make the changes and give update data is updated in database . but still all the controls are in edit mode only "actaully once we give click then update then i should again gone to read only mode means all the values should again be showing in label field"

i am doing this in .cs file only no sqldatadource is used or object datasource

right now this feature is not happening to me. what is the issue here?

looking forward for an solution thank you

From stackoverflow
  • Since you aren't using any built-in code to do the update, you probably need to change the display mode manually during your update.

    myDetailsView.ChangeMode( DetailsViewMode.ReadOnly );
    prince23 : ya added this line of code in ItemUpdating event that is after i do update to database: { myDetailsView.ChangeMode( DetailsViewMode.ReadOnly ); } but i get an error telling that as you are in edit mode you cannot do readonly here
  • you need to put this code in itemupdated event of detailsview rather itemupdating event.

    prince23 : hi Muhammad Akhtar i have put this code in itemupdated event { yourDetailsView.ChangeMode(DetailsViewMode.ReadOnly); } but this event is not getting fired only after itemupdating event. is exceuted
    prince23 : i am placing my detailsview control update panel and have set the update mode ="conditional" there
    prince23 : protected void DetailsView1_ItemUpdating(object sender, DetailsViewInsertEventArgs e) { Updatedetailsview(); DetailsView1.ChangeMode(DetailsViewMode.ReadOnly); BindDetailsView(); } } this was the code which finally made my probmlem solve we can put this code itemupdating event. only DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);

Problem with textfields and scene transition + cocos2d

I am having problems with my textfield not flowing with the scene transistion. Basically my scene is transition with this call:

Scene* gs = [[[QuestionsScene alloc] initWithPage:2] autorelease];   
[[Director sharedDirector] replaceScene: [SlideInRTransition transitionWithDuration:0.5 scene: gs]];

However in my init i have a textfield called here:

    [answerBox setTextColor:[UIColor blackColor]];
    [answerBox setTextAlignment:UITextAlignmentLeft];
    [answerBox setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [answerBox setClearsOnBeginEditing:YES];
    [answerBox setBorderStyle:UITextBorderStyleRoundedRect];

[answerBox setDelegate:self]; [answerBox setReturnKeyType:UIReturnKeyDone]; [answerBox setAutocapitalizationType:UITextAutocapitalizationTypeWords]; [[[Director sharedDirector] openGLView] addSubview: answerBox];
The textbox does not follow the transition, it just sits there into the next scene. Anyone have an idea on how to fix this?

From stackoverflow
  • You add the answerBox to the openGLView directly, not to the scene. So naturally when the scene changes, the answerBox is not affected.

    If you use a UILabel, you cannot add it as a child on a CocosNode object, so you can't add it to your scene.

    Look into using the Cocos2d label class instead. Either use Label or it's faster cousin LabelAtlas

    I haven't checked how Cocos2d manages its views. Perhaps there might be another option? You can try on the cocos2d forums.

  • For this solution, i just did removed the textbox upon transition

    [nameBox removeFromSuperview];

    and reappear when it comes back to the scene:

    [nameBox becomeFirstResponder];

    which there was a smoother transition to this though.

Linq To Sql 'Where Or' operator

I need to create a query which checks if a field (string) contains one or more words supplied at run time.

Basically I need to be able to ask a WhereOr question. This seems like it should be a common issue when dealing with LinqToSql.

I found the following reference but can't make sense out of it - and have no idea how to use it in my project.

i've tried the following loop:

        var query = from d in context.Domains select d;
        for (int i = 0; i < words.Length; i++)
            query = query.Where(d => d.Name.Contains(words[i]));

but this builds a SQL query with WHERE AND Clauses NOT Where OR

From stackoverflow
  • I use PredicateBuilder for such things.

    The predicate construction looks like this:

         var query = from d in context.Domains select d;
         var predicate = PredicateBuilder<Domains>.False();
         for (int i = 0; i < words.Length; i++)
                predicate = predicate.Or(d => d.Name.Contains(words[i]));
        query = query.Where(predicate);
    RichardOD : +1. Yes, this is what I'd also recommend
    Harry : Wonder why this wasn't backed into LinqToSql

ASP.NET Data Cache - preserve contents after app domain restart

I am using ASP.NET's data caching API. For example:

HttpRuntime.Cache.Insert(my_data, my_key);

Is there any way to configure cache so its contents are preserved when the App Domain recycles?

I load many object into cache, but there is a substantial delay re-loading these every time the app domain restarts. Assume for this question that I can't prevent the appdomain restart due to a server configuration.

From stackoverflow
  • Recycling the appdomain dumps the cache. If you want to get around this you'd need to use a distributed cache. Here's an example.

  • For your most expensive data you can cache the objects with a distributed cache such as Memcached or velocity. Depending on the size of the object and the length of runtime you could also serialize it to disk or to your database provided that the access speed to these resources is less than the time to create the object.

    Now since the in-proc cache is super fast compared to any other solution since it just holds a reference to the memory object you will want to use it where possible. You can keep a copy of your cached object on disk until it is lost and then re-create it from that and place it in memory. Where this is tricky is when you have to expire the data so only use the cache/disk/sql combo where you won't need to expire/invalidate the data otherwise you will need to ensure that you clear both. This will also get around not being able to implement distributed caching on a shared server for example.

  • Is there any way to configure cache so its contents are preserved when the App Domain recycles?

    No. The Cache object holds references in RAM. Period.


    1. Out-of-process Session state (although that's per-user)
    2. Distributed cache
    3. Use SQL Server as a cache (where it keeps data in memory, rather than on disk)
    4. Write the objects to disk at the web tier

    I generally prefer #3 myself, although there are scenarios where the others are appropriate.

    frankadelic : The Cache API can't be configured to persists to SQL Server though, right? I would need to modify my current Cache API calls to go through another API.
    RickNZ : Correct. The Cache API works for in-memory references only; there aren't any options to make the entries persistent. The reason is that persistence requires serialization in some form, which is expensive. One of common uses of the Cache API, in fact, is specifically to avoid serialization and the related overhead. However, if your data originated from SQL Server, then you don't need to persist it again yourself; you just need to be notified if it changes, which is what SqlDependency is all about.

Conversion of a Java Web Start app to an Applet

I'm trying to figure out how difficult it would be to convert a Java Web Start app to an applet. Theoretically, if the application didn't do anything such as write to the file system...basically if all of it's actions should be safe within the Applet sandbox, how tricky would it be? Is it a matter of wrapping the main app inside of an applet?

From stackoverflow
  • It should be quite straight forward. Simply create an applet class. From within the applet class you can instantiate whatever class JWS would normally start.

    You then need to convert the JWS xml file to an applet tag and put it on a web page.

    crowne : Why on earth would anyone still want to use an applet? Why not look into using some kind of ajax framework like GWT or have a look at Java Fx.
    brianegge : Applet's continue to look uglier as they haven't kept pace with native look and feels. However, an applet or JWS can be run just by going to a web page - which GWT/RCP can't. JavaFX is immature, and would require rewriting the apps entire GUI.

A splash screen which doesnot just disappear but fades in/out.

I have a splash screen which appears for a few seconds before the application home screen is loaded. And then the home screen is pushed in. But I need to fade out the splash screen before the home screen appears. Any idea how to do that??

From stackoverflow
  • Yeah, you should do two things:

    1. push application home screen, and after that push splash screen
    2. inside splash screen before close start png "animation" with growing transparency (image should be size of screen)

    See also
    Blackberry - background image/animation RIM OS 4.5.0

    Bohemian : Ok. There is a method setGlobalAlpha for transparency.Thanks
    Max Gontar : You're welcome!

design of fact table(s) for data warehouse

how would you model this in a data warehouse:

  1. there are municipalities which are geographical areas, that exist in geographical hierarchies, such a province (i.e. state, e.g. Minnesota), region (e.g. MidWest).

  2. a performance evaluation is done on these municipalities, by calculating performance indicators such as "% of housing backlog completed", "% of budget spent", "% of budget allocated to infrastructure", "debtor coverage", etc.

  3. there are about 100 of these performance indicators.

  4. these indicators are grouped into "performance groups", which are themselves grouped into "key performance areas"

  5. calculations are applied to the performance indicators (the calculations vary based on certain factors such as municipality type, size, region, etc) to produce "performance scores".

  6. weightings are then applied to the scores to create "final weighted scores". (i.e. some indicators are weighted more than others when aggregated into the "key performance areas")

  7. there will be a time dimension (evaluations done yearly), but for now just the one data set.

NB: users need to be able to easily query the data across any combination of indicators. i.e. someone might want to see: (i) the performance level of (ii) "debtor coverage" against (iii) "% budget spent" against (iv) "debtor days" at a (v) provincial level.

I tried this by having "IndicatorType" as a dimension, and then having the [indicator / performance group / performance area] hierarchy in that table - but then i can't work out how to easily get multiple indicators on the same line, as it would need a fact table alias(?). So I thought of putting all 100 items as columns in a (very wide!) fact table - but then I would lose the [group/area] heirarchy on the indicators...?

Any ideas?


From stackoverflow
  • This is a very involved question but I took the time to go through some of your points and came up with this model (should be a good start for you).




    Hierarchy = {COUNTRY <-- REGION <-- STATE_PROV <-- CITY?}





    Fields = {DATE_KEY, CALENDAR_DATE (SQL datetime), YEAR, MONTH, WEEK, DAY...}

    Hierarchy = {YEAR <-- MONTH <-- WEEK <-- DAY <-- DATE_KEY}

    Then in your fact table (say MYFACT) you would do something like the following:



    The fact table could have all these Measure columns (BUDGET, ETC) or you could do them in Calculated members, it all depends on how you want to make the accessible.

    Hope this helps you get a good start!

    : thanks for your post. however, i'm confused: if the indicator-level dimension exists, then there is no need for multiple measure columns in the fact table, as they are the same thing. it's really about the design benefits of having a 100-wide column fact table, versus a single numeric measure column and a "measure type" dimension (in this case, the indicator dimension). with a wide table, i can easily pull out multiple columns alongside each other, but i lose the PI/PG/KPA hierarchy. with the indicator dimension, i lose the reporting flexibility. or is there another way?
    : more: i'd think 3 fact tables: - performance indicator - performance score - final weighted score (the calculations are done in the load, i.e. scoring rules & weightings are applied then, NOT in the d/w) so: if i have 100 columns in the "performance indicator" fact table, i have 100 measures. now it's easy to report on 15 different measures. if the measures are in a DIM, then i only have 1 measure object, and need to a filter to get the right one, and aliases to get multiple? and when reporting from excel, this is not possible? so go wide & lose the PI/PG/KPA heirarchy?
    ajdams : I didn't mean put the measures in the DIM, I was uncertain by what you meant by size score (if that';s what you are referring to). I must have misinterpreted what you meant by indicator. In the Indicator dimension I would store the fields that describe and denote a certain indicator and then the actual measure of that value in the FACT.
  • alt text

    KenFar : This looks about right: by putting the IndicatorKey in the fact table and having just one generic IndicatorValue you've got a bit of a key-value pair approach. This isn't very useful for reporting, but it is a practical way to handle the inevitability of your Indicators changing over time. Based on this data you could then publish this data to a flattened table with different measures as dedicated columns. This secondary table would be easier to change - and perhaps you don't need each individual measure - maybe just the much more static performance area & group numbers.

iPhone create folder inside documents folder


i just want to create new folders in the documents folder of my iPhone app

does anybody know how to do that ?

appreciate your help!

From stackoverflow
  • I do that the following way:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyFolder"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath attributes:nil]; //Create folder
    zanque : thanks for the reply, it works but it creates the folder "MyFolder" beside the documents folder of the app .. not inside it. don't know why actually
    Vladimir : Sorry - was a typo there - must append @"/MyFolder", not @"MyFolder" to a documents path.
    zanque : yes, i discovered that, thanks for help :)
    Andreas : You might want to change the third line to NSString *dataPath = [documentsDirectory stringByAppendingString:@"/MyFolder"]; since NSSearchPathForDirectoriesInDomains doesn't return trailing slashes.
    Kendall Helmstetter Gelner : I fixed the code to use the more correct "stringByAppendingPathComponent", which does the right thing regardless of either input string having a "/" or not.