Saturday, April 30, 2011

Call python script from AIR application?

How can we invoke a python script using AIR 1.5?

From stackoverflow
  • You cannot directly invoke system commands or run an executable (the python interpreter) from within an AIR application. If it's possible to share what exactly you want to do, maybe we can suggest alternatives.

    If it's really really (that's two reallys) important to run an executable from AIR lookup the CommandProxy demo.

  • For example through AMF: http://pyamf.org/

  • Hypothetically, Adobe Alchemy technology may allow you to port Python interpreter to Flash.

    Though I seriously doubt that's the approach you want to use. Depending on task there should be easier solutions.

  • Air 2.0 has a native process API.

Why doesn't SQL Server come preinstalled with .net Framework for CLR Integration?

If I want to reference something in the .net framework for use in my CLR stored proc, for example, I have to first load it into the Sql server database.

Why isn't it preinstalled? Is it performance related or for security issues or what else?

thanks.

From stackoverflow
  • I'd imagine it's for security reasons as not installing it by default reduces the attack surface available to any hackers.

  • Probably because it is an optional feature that isn't used that much. Yet.

  • It's off by default because it's increased attack surface area and won't be needed in may places. Lots of other SQL Server stuff has to be enabled specifically too.

    Some fairly basic stuff can be off by default: KB 914277 for "remote access"

    Secondary to this, it won't be allowed in many shops, which leads me to my cheeky answer: "because developers might use it". Using CLR in a relational engine has benfits: custom datatypes, custom aggregates etc, but it will be abused because it's easier to write c# rather than T-SQL for many folk.

  • SQL Server 2000 came with everything turned on, after the slammer worm Microsoft learned their lesson and on SQL Server 2005 and up all the things that were enabled like xp_cmdshell, openrowset etc etc are turned off by default to reduce the attack surface. CLR is also turned off because of the same reason.

ADO.NET, Closing an OracleConnection without prior Commit or Rollback: Will it leak?

Suppose I am doing the following:

using (OracleConnection conn = new OracleConnection(connStr))
{
    OracleTransaction trans = conn.BeginTransaction();
    OracleCommand command = new OracleCommand(cmdTxt, conn, trans);
    // this statement is executed in a transaction context:
    command.ExecuteNonQuery();
}
// the using statement will dispose and thus close the connection.
// a rollback is done implicitly

Although I did not executed transaction.Rollback(), my tests showed that a rollback is done implicitly.

My question is: Will this code leak connections or anything else?

Edit1: I am the System.Data.OracleClient namespace.

Edit2: This is a contrieved example code. The more realistic scenario is when within the using statement an exception occures and the Commit() statement is not executed yet.

Edit3: From the answer I think that this is favorable:

using (OracleConnection conn = new OracleConnection(connStr))
using (OracleTransaction trans = conn.BeginTransaction())
using (OracleCommand command = new OracleCommand(cmdTxt, conn, trans))
{
    command.ExecuteNonQuery();
    trans.Commit();
}

Should cleanly dispose anything and make clear what is happening.

From stackoverflow
  • It will not leak. The using clause guarantees that the OracleConnection will be disposed, regardless of whether the command completes successfully or fails with an exception, and it will take the transaction with it.

    But since OracleTransaction is IDisposable, it would probably be good form to put a using clause around the transaction as well, e.g.

    using (OracleTransaction trans = conn.BeginTransaction())
    {
      // ...
      trans.Commit();
    }
    

    This will make it clearer to readers of the code that the transaction is being cleaned up; in particular, it may become important if a subsequent enhancement performs multiple transactions on the same connection.

    Also, as per John's comment below, you should put a using statement around the OracleCommand, so that it can be cleaned up promptly.

    John Saunders : Same with OracleCommand, I suspect. Anything disposable needs to be disposed, probably in a using block.
    itowlson : Thanks John -- updated.

Correctly doing redirect_to :back in Ruby on Rails when referrer is not available

Hi there,

I'm having a problem with redirect_to :back. Yes, it's referrers.

I often get the exception (ActionController::RedirectBackError) "No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env[\"HTTP_REFERER\"]."

I realise that this is a result of a referrer not being available. Is there a way that, for example, one can set a session variable on each access with the last page visited, and, when HTTP_REFERER is not available, utilize this session variable to redirect to?

Thanks!

From stackoverflow
  • def store_location
      session[:return_to] = request.request_uri
    end
    
    def redirect_back_or_default(default)
      redirect_to(session[:return_to] || default)
      session[:return_to] = nil
    end
    

    Try that! (Thanks to the Authlogic plugin)

    : rock! that's awesome. thank you!
    Maran : You are welcome :)
  • It is unlikely that you do have a session and don't have a referrer.

    The situation that a referrer is not set isn't that uncommon and I usually rescue that expection:

    def some_method
      redirect_to :back
    rescue ActionController::RedirectBackError
      redirect_to root_path
    end
    

    If you do this often (which I think is a bad idea) you can wrap it in an other method like Maran suggests.

    BTW I think that's a bad idea because this makes the userflow ambiguous. Only in the case of a login is this sensible.

    Toby Hede : +1 because this is what I was going to say
    Bob Aman : I suspect that I would alter this to use rescue_from instead.
    harm : That is indeed a very good suggestion!

Playing short sound on timer end?

Hi...

In my app I have a timer that counts down, and when it stops an image is displayed and a sound is played.

The sound is loaded like this:

NSString *path = [[NSBundle mainBundle] pathForResource:@"scream" ofType:@"wav"]; AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);

And Played like this on timer end:

AudioServicesPlaySystemSound(soundID);

My problem is that the sound doesn't get played on time. Even though the sound instance is called before the image, the image appears before the sound. This only occurs the first time the sound is played. The sound is loaded in the viewDidLoad method.

Is there a better way to do it, or what am I doing wrong?

Thanks...

From stackoverflow
  • Maybe the sound is delayed while the speaker is powered up (for the first sound). If so, maybe you can work around it by playing a different, unnoticeable sound earlier so that the speaker is ready to go when you request the "real" sound.

    CC : this might work... I will try that thanks...

.Net Release build working slower than Debug

I am experiencing a weirdest thing for the last couple of days. I found out that my Release build actually executes slower than the Debug version.

1. The problem

I finally stripped all stuff from my entry point (Main) in my Windows Forms exe, leaving only this:

 [STAThread]
 static void Main(params string[] args)
 {
     Stopwatch sw = Stopwatch.StartNew();
     System.Xml.Serialization.XmlSerializer xmlS =
         new System.Xml.Serialization.XmlSerializer(typeof(TestClass));
     sw.Stop();
     MessageBox.Show(sw.Elapsed.ToString());
 }

So I am actually not instantiating any Forms anymore, only testing. TestClass is a small class with only three public int properties and nothing else. My main .exe (Windows Forms) is ~1Mb large, if that makes any difference.

2. Results

In Debug mode, my Elapsed time is ~200ms, while in Release it takes ~1.2s.

3. Additional info

The strange thing is when I try to set some other project in that solution as Startup project, because in that case it works fast (exactly the same code as above).

4. Quick hack

To fix this bug as quickly as possible, I created a new .exe Startup project in my solution, which instantiates and runs the main Application Form by referencing my first entry project. In that case it works fast again, my entry exe is now only 24kb large, containing only a static Main method.

Has anyone encountered similar behavior before? If I had stumbled upon this somewhere else, by looking at the code above, I would probably presume that there is a static initializer somewhere, doing tons of work in a separate thread (but it's not the case here, I don't have that stuff), and furthermore running only in Release build?

[Edit] More info: I am aware that XmlSerializer generates IL code in runtime, but my actual question is why it works slower in this case than in other cases. When I benchmark only the actual serialization, it is 3x slower in Release (but only if I run it from my initial project).

[Update] Now for the weirdest part ever: After a couple of modify/rebuild steps, my new entry project started to behave as the first one - slow startup, slow loading. I changed the project name and GUID and rebuilt it and it's working fast again.

From stackoverflow
  • I think possibly this is because the XmlSerializer does NGEN-ish work at startup time in Release mode, but not in Debug mode. See e.g.

    http://blogs.msdn.com/billwert/archive/2008/02/23/use-of-sgen-exe-to-avoid-common-xmlserializer-performance-pitfalls.aspx

    for some details.

    Groo : Thanks, I actually used SGEN to generate serialization assemblies in Release mode, but it was slower anyway. It is even slower when I create a serializer first and then benchmark only the serialization itself. (by the way, your link shows this in mozilla: "web site at www.topxml.com has been reported as an attack site")
    0xA3 : Yes, get the same warning. Also Google warns about this site: http://www.google.de/search?hl=de&q=site%3Awww.topxml.com
    Brian : Thanks, I fixed the url to the original msdn blog.

How can i arrange columns in asp.net gridview?

How can i arrange columns in asp.net gridview? i want to change 4 columns' location. ForExample:

column1 | column2 | column3 | column4 |

ChangeOrder()

column2 | column1 | column3 | column4 |

ChangeOrder()

column4 | column2 | column3 | column1 |


I want to move columns in Gridview.

From stackoverflow
  • I don't know if this is an option for you, but the Telerik RadGrid supports this. See this online demo for details.

  • 2 options from the top of my head:

    1. Turn AutoGenerateColumns off and add the columns yourself, mapping them to what you want in the dataset and in the order you want them.

    2. Change your SQL query to return the columns in the order that you want.

How to count number of same data in a column

Hi all, I have a table:

Id  Catg
1   cat01
2   cat01
3   cat01
1   cat02
2   cat02

now I want to detect number of occurance of catg01 and catg02,like in this ex, catg01 is 3 times and catg02 is 2 times,I want to count that through LINQ/ simple db query. Pls note: cant use Where clause and hardcode Catg01/catg 02,as there can n number of category.Is it possible to detect? if yes then pls help.

From stackoverflow
  • Select Catg, Count(*) From TableName Group By CatG
    

    For the LINQ Version. Imagine a Class

        class Table
        {
            public int ID { get; set; }
            public string CatG { get; set; }
        }
    

    Then if you had a list of that class, you could query it as follows

    List<Table> y = new List<Table>();
    
    y.Add(new Table() { ID = 1, CatG = "a" });
    y.Add(new Table() { ID = 2, CatG = "a" });
    y.Add(new Table() { ID = 3, CatG = "a" });
    y.Add(new Table() { ID = 4, CatG = "b" });
    y.Add(new Table() { ID = 5, CatG = "b" });
    
    
    var query = y.GroupBy(table => table.CatG);
    
    // Iterate over each IGrouping in the collection.
    foreach (var item in query)
    {
        Console.WriteLine("CatG: {0} Number of Items: {1}", item.Key, item.Count());
    }
    
    Wondering : Thanks,it worked.can u pls help me with LINQ
    Eoin Campbell : sure... will edit the post.
  • SELECT Catg, COUNT(*)
    FROM myTable GROUP BY Catg
    

Whats the overhead of creating a Log4j Logger

I have some webservices in my application and i want to log them to diferent files, based on the webservice name. For that i am creating loggers with

myLogger = Logger.getLogger(logKey);

I am wondering if i should cache these loggers to avoid creating them for every call, or can i ignore the overhead.

From stackoverflow
  • Loggers are already cached by log4j using the default log repository (Hierarchy). In other words, it's just a hashtable lookup.

    However, in my experience you tend to make the logger static, so it only ends up being called once per class anyway.

    willcodejavaforfood : +1 but it is more fun voting up people with less reputation
    Nicolas : Wouldn't making the logger static prevent you from changing its level at runtime (through an MBean for example)? In theory not, but I thought that was the case with java logging.
    Jon Skeet : I don't *think* so. I think the level stuff is checked dynamically, rather than being frozen in the constructed logger.
  • This method Logger.getLogger(logKey) looks in logger cache for a logger with the name passed in logKey. If it doesn't exist it creates one. First call for a logger name, a Logger will be created but later calls will get it from cache so you don't need to handle this in your code.

Creating a Mono binary install package for CentOS 5.2

Hi, All

I'm new to Linux but have to port a asp.net app to Linux platform. (CentOS 5.2)

I downloaded the mono source files and manually build them on my dev box, because there's no aviable Binary package for CentOS 5.2 (almost the same as RedHat), the app works well on the dev box.

The next step is to setup the production server, which has minimal libraries installed. My question is... how to make the Mono binary files into a install package so I don't need to download and build them in the production server. (My dev box is the same configuration as the production one)

I have tried to copy all mono related files into the server, but with no luck... May I missed some files or some settings...

From stackoverflow
  • EDIT:

    Recently, Mono announced support for RHEL/CentOS. You can get packages from them here.

Rhyme in PHP

I am having a hard time to find a way to detect if two words has the same rhyme in English. It has not to be the same syllabic ending but something closer to phonetically similarity.

I can not believe in 2009 the only way of doing it is using those old fashioned rhyme dictionaries. Do you know any resources (in PHP would be a plus) to help me in this painful task?

Thank you.

Your hints were all really hepful. I will take some time to investigate it. Anyway, more info about DoubleMetaPhone can be found here in a proper PHP code (the other one is an extension). There are interesting information about MethaPhone function and doublemetaphone in Php.net.

They specially alert about how slow double metaphone is compared with metaphone (something like 100 times slower).

From stackoverflow
  • Did you try the soundex() function? It should give you at least some indication if the words sound alike.

    Schnalle : i don't think the soundex function is well suited for this. look at the examples - two words that produce the same soundex rhyme almost never. double metaphone may make more sense.
    Schnalle : the double metaphone algorithm is available as a pecl package here: http://pecl.php.net/package/doublemetaphone
  • Besides the soundex() function ramonzoellner mentioned, there is another function called levenshtein() which calculates the levenshtein distance between the two words. That may help you further.

  • See Bradley Buda's CS project summary from U. Michigan, which uses Levenshtein distance as an atom in finding rhyming English words. I believe combining Levenshtein and soundex should give better results.

  • Soundex won't help you. Soundex focuses on the beginning of the word, not its ending. Generally it think you'll have hard time finding any tool to do this. Even to the linguist the root of the word is more interesting, than it's ending.

    Generally what you'll have to do is to divide words in syllables and compare their last syllable. Even better if you could divide it in phonemes, reverse their order and do comparison on reversed word.
    You might trying comparing last part of metaphone keys.

    Yuval F : Double Metaphone is a nice idea. Alternatively, Sortea2 could reverse the original words and compare their Soundex.
  • Seems like you need to find a database containing pronunciation, and possibly stress/emphasis: multisyllabic words with similar last syllables, but stresses on different syllables don't quite rhyme, at least in the sense of being able to use them in poems; e.g. "poems" and "hems". The other answers (levenshtein & soundex) should help for locating candidates, but they won't confirm it:

    • tough
    • cough
    • dough
    • through
    • bough

Zend From Decorators not working with ZendX_JQuery_Form

I am using two decorator - To get tabular form alignment - To get date picker (ZendX_JQuery_Form_Element_DatePicker)

both are working individually, but not at a same time

Error:

Warning: Exception caught by form: Cannot render jQuery form element without at least one decorator implementing the 'ZendX_JQuery_Form_Decorator_UiWidgetElementMarker' interface. Default decorator for this marker interface is the 'ZendX_JQuery_Form_Decorator_UiWidgetElement'. Hint: The ViewHelper decorator does not render jQuery elements correctly.

My Get Form Function:

$form = new Form_Job();
$form->setDecorators(Decorator::$formDecorators);
$form->setElementDecorators(Decorator::$elementDecorators);
$form->getElement('submit')->setDecorators(Decorator::$buttonDecorators);

Form class Form_Job()

class Form_Job extends ZendX_JQuery_Form {
   public function init() {
        $element = new ZendX_JQuery_Form_Element_DatePicker('date_from');
        $element->setLabel('Campaign Period From :');
        $element->setRequired(true);
        $element->setAttrib('size', '10');
        $element->setJQueryParam('dateFormat', 'yy-mm-dd');

        $this->addElement($element);
   }
}

I got this help from http://framework.zend.com/manual/en/zend.form.decorators.html

jQuery Decorators: Beware the Marker Interface for UiWidgetElements

By default all the jQuery Form elements use the ZendX_JQuery_Form_Decorator_UiWidgetElement decorator for rendering the jQuery element with its specific view helper. This decorator is inheritly different from the ViewHelper decorator that is used for most of the default form elements in Zend_Form. To ensure that rendering works correctly for jQuery form elements at least one decorator has to implement the ZendX_JQuery_Form_Decorator_UiWidgetElementMarker interface, which the default decorator does. If no marker interface is found an exception is thrown. Use the marker interface if you want to implement your own decorator for the jQuery form element specific rendering.

But i need code to implement this, please suggest

From stackoverflow
  • Got my answer:-

    I used

    public static $formJQueryElements = array(
            array('UiWidgetElement', array('tag' => '')), // it necessary to include for jquery elements
            array('Errors'),
            array('Description', array('tag' => 'span')),
            array('HtmlTag', array('tag' => 'td')),
            array('Label', array('tag' => 'td', 'class' =>'element')),
            array(array('row' => 'HtmlTag'), array('tag' => 'tr')),
    );
    $form->getElement('jq_date')->setDecorators(Decorator::$formJQueryElements);
    

    this works well for tabular alignment, for jquery elements !!!!!

Invariant stroke thickness of Path regardless of the scale

Hello!

We are using wpf to develop a cad like application where drawings placed on the canvas using the Path object. I just ran into a slight issue that whenver i scale/zoom my canvas, all the elements in the canvas get scaled and this is the behaviour i wanted but this also increases the stroke thickness of the Path.

Is there a way by which i increase/scale/zoom the objects but still i maintain the same stroke thickness of the path.

Any help in this regard will be very useful for me.

From stackoverflow
  • Hello !

    Finally i got the workaround for the above solution what i have done is i m setting the strokethickness of the path relative to the scaling i m doing on canvas.

    like this

    path.strokeness = 1/(scaling factor applied to the canvas)

    Klay : This is fine if your x and y scales are uniform, but does not work if the scales are not the same.
  • A better solution would be to use one or more System.Windows.Media.Geometry object to store your paths, points etc.

    This geometry can be drawn with a Pen, so you could indeed change the stroke thickness when you zoom, but more flexible is to use the Transform property.

    Using the transform, you can "zoom" the actual coordinates of the geometric representation and not the visualization - so when you draw it, you don't need to fiddle with render transforms.

    To compute the transform, I use the following code like:

    public static Matrix TransformShape(Rect fromPosition, Rect toPosition, bool flipVertical) {
        Matrix translateThenScale = Matrix.Identity;
        //we first translate to origin since that's just easier
        translateThenScale.Translate(-fromPosition.X, -fromPosition.Y);
        //now we scale the graph to the appropriate dimensions
        translateThenScale.Scale(toPosition.Width / fromPosition.Width, toPosition.Height / fromPosition.Height);
        //then we flip the graph vertically around the viewport middle since in our graph positive is up, not down.
        if (flipVertical)
         translateThenScale.ScaleAt(1.0, -1.0, 0.0, toPosition.Height / 2.0);
        //now we push the graph to the right spot, which will usually simply be 0,0.
        translateThenScale.Translate(toPosition.X, toPosition.Y);
    
        return translateThenScale;
    }
    

    where the fromPosition Rect should contain the untransformed bounds, and the toPosition Rect should contain the transformed bounds. This also trivially allows for scaling X and Y separately, which is often necessary for plotting.

    It's easy to compute the bounds of your geometry:

    Geometry graphGeom;
    //[...]   
    //the bounds are modified by the transform, so we want no transform!    
    graphGeom.Transform = Transform.Identity; 
    Rect graphBounds = graphGeom.Bounds;
    //then set the transform again
    
    //or, if the transform is axis-aligned, the following _should_ work:
    Rect graphBoundsAlt = graphGeom.Transform.Inverse.TransformBounds(graphGeom.Bounds);
    

    And of course WPF can tell you which bounds you need to render into, should that be necessary. Putting it together, you could do something like

    public void RecomputeTransform(Rect targetRect, bool flipVertical) {
        graphGeom.Transform = Transform.Identity; 
        Rect graphBounds = graphGeom.Bounds;
        Matrix transMat = TransformShape(graphBounds,targetRect,flipVertical);
        graphGeom.Transform = new MatrixTransform(transMat);
    }
    

    The advantage of using this solution is that you don't need to mess with RenderTransforms, you're free to use transforms that shear and/or scale X and Y independently without getting weird distortions in your lines, and you can treat the Pen as an opaque object (i.e. easier to customize from the UI - if you select Pen width or whatnot, no further correction is necessary).

Disable Exe From Task Manager

how to Disable The My Exe From Task Manager . it should't visible when the user is open the task manager.... there is lot of exe run in the same name. here to avoid the confiution to other users .

k fine..... tell me, the exe should't allow to kill by any others form task manager...

From stackoverflow
  • Google the term "rootkit". Basically, this is considered very evil and is usually only used for evil purposes, therefor this is bad practice since modern antivirus-software would probably flag your software as malware.

    http://en.wikipedia.org/wiki/Rootkit

  • If you really need to do this, you basically need to use a rootkit. See the Hoglund & Butler book, "Rootkits: Subverting the Windows Kernel." But you will be fighting the operating system and the anti-malware vendors every step of the way.

    See also Raymond Chen's repeated discussions of "arms races" for why Windows doesn't support this -- basically if you are allowed to remove yourself from Task Manager then users are going to want another utility which shows them hidden processes, and then you are going to want a way to remove yourself from that utility, et cetera ad infinitum.

    If you really must do this, by the way, you will need to use C or assembler, not C#.

Linq to Objects - Where search within a list

Linq to Objects - Where search within a list

    internal class ProdQtyByWarehouse
    {
        public int id { get; set; }
        public List<ProdWarehouseQty> ProdWarehouseQtys { get; set; }
    }

    internal class ProdWarehouseQty
    {
        public int id { get; set; }
        public string PName { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var list1 = new List<ProdWarehouseQty>
                        {
                            new ProdWarehouseQty
                                {
                                    id = 3,
                                    PName = "list1PN1"
                                },
                            new ProdWarehouseQty
                                {
                                    id = 4,
                                    PName = "list1PN2"
                                }

                        };
        var list2 = new List<ProdWarehouseQty>
                        {
                            new ProdWarehouseQty
                                {
                                    id = 5,
                                    PName = "list2PN1"
                                },
                            new ProdWarehouseQty
                                {
                                    id = 6,
                                    PName = "list2PN2"
                                }

                        };
        var prodQtyByWarehouses = new List<ProdQtyByWarehouse>
                                      {
                                          new ProdQtyByWarehouse {id = 1, ProdWarehouseQtys = list1},
                                          new ProdQtyByWarehouse {id = 1, ProdWarehouseQtys = list2}

                                      };
        List<int> integers = new List<int>{2,3,4,6};

        List<ProdQtyByWarehouse> list =
            (from c in prodQtyByWarehouses
             where c.ProdWarehouseQtys.Contains(new ProdWarehouseQty {id = 3})
             select c).ToList(); // no object is returned
    }

How can i achieve:

List<ProdQtyByWarehouse> list =
            (from c in prodQtyByWarehouses
             where c.ProdWarehouseQtys.Contains(new ProdWarehouseQty {id in integers})
             select c).ToList();
From stackoverflow
  • List<ProdQtyByWarehouse> list =
        (
            from c in prodQtyByWarehouses
            where c.ProdWarehouseQtys.Exists(x => integers.Contains(x.id))
            select c
        ).ToList();
    

How to display difference between two dates as 00Y 00M

Given two DateTimes in C#, how can I display the difference in years and months?

I can do basic arithmatic on the timespan that comes from a simple subtraction but this won't take into account the differing lengths of months, leap years etc.

Thanks for any help.

From stackoverflow
  • You could try this:

    DateTime date1 = new DateTime(1954, 7, 30);
    DateTime today = DateTime.Now;
    
    TimeSpan span = today - date1;
    DateTime age = DateTime.MinValue + span;
    
    int years = age.Year - 1;
    int months = age.Month - 1;
    int days = age.Day - 1;
    
    Console.WriteLine("years: {0}, months: {1}, days: {2}", years, months, days);
    
    Stefan Steinegger : I think starting from MinValue is not correct. You get a value, but it has nothing to do with the current month. Of course, the difference is small, its about having a month of 28 instead of 31 days. But then you can also take the ticks and divide the year into 12 parts of the same size...
  • Because the underlying representation is measured in 100-nanosecond ticks since 12:00 midnight, January 1, 1 A.D., a subtraction will handle leap years etc. quite correctly:

    DateTime date1 = ...
    DateTime date2 = ...
    
    // date2 must be after date1
    
    TimeSpan difference = date2.Subtract(date1);
    DateTime age=new DateTime(tsAge.Ticks); 
    
    int years = age.Years - 1;
    int months = age.Month - 1;
    
    Console.WriteLine("{0}Y, {1}M", years, months);
    
  • Different length of month? Which month should it take? the time span is not bound to a certain year or month in the year. You can only count the days between two dates:

    Timspan span = date2 - date1;
    
    Console.Writeline("Days between date1 and date2: {0}", span.Days);
    

    Counting from DateTime.MinValue just take the year 0001 as start and counts the months from January. I don't think that this is of practical use.

    EDIT:

    Had another idea. You can count the month since date1:

    // primitive, inelegant, but should work if date1 < date2
    int years = date2.Year - date1.Year;
    int month = date2.Month - date1.Month;
    if (month < 0) 
    {
      years -= 1;
      month += 12;
    }
    Console.Writeline("{0}Y {1}M", years, month);
    

    The problem here is that you just ignore the days. After all it's not a good solution.

  • FWIW here's what i've ended up with

            DateTime servicelength = new DateTime(DateTime.Now.Subtract(employee.StartDate).Ticks);
            LengthOfService.Text = String.Format("{0}Y {1}M", servicelength.Year - 1, servicelength.Month - 1);
    

Choosing an area on a Mac OS X Desktop

If you press cmd+shift+4 in Mac OS X you are able to select an area on your screen with the corrosponding coordinates shown. I need to implement such a function in one of my applications and have no idea of how to do it. Could anyone give me some advices on that?

Thx.

From stackoverflow
  • This code fragment will return a CGImageRef that contains everything shown on the desktop for a given rectangle. It requires the ApplicationServices framework. The screen coordinates are flipped and the origin is at the top-left corner of the screen. In this case, the image ref would be owned by the caller and would need to be released with CGImageRelease when the caller was finished with it.

    #import <ApplicationServices/ApplicationServices.h>
    
    CGImageRef createScreenCapture(CGRect rect) {
      CGImageRef image = CGWindowCreateImage(
                           rect,
                           kCGWindowListOptionOnScreenOnly,
                           0,
                           kCGWindowImageDefault);
      return image;
    }
    
    Chuck : 10.5-only, it's worth noting.
    Jason Coco : @Chuck: Thanks, definitely worth mentioning!
  • Typically this is done with an translucent overlay window which covers the entire desktop space.

    Apple's got some older sample code which should give you a start.

How to comment out calls to a specific API in Java source code

I want to comment out all calls to an API (java.util.Logging, in my case) in my codebase. Is there a good library to accomplish this easily? I tried Eclipse ASTParser, but that is tied to Eclipse. I am now struggling with PMD's parser. I haven't yet looked at it, but can Jackpot do this? Any other suggestions?

From stackoverflow
  • sed? Just substitute with a commented line. You'll need to think about the match regex to catch multiline calls.

    binil : Show me a good regex to match multiline calls. :-)
    Charlie Martin : well, it's going to have a ';' in it.
    izb : There could be a ';' in the logged string. Now you're writing a parser, worrying about escaped quote characters and regretting ever starting the task.
    Charlie Martin : Oh, let's send out for a grip here, shall we? I said it would have a ';' in it. It's also going to have a number of other things in it. Unless your string includes the calling sequence in which it's contained, you'll be okay. Something like /\.info(\".*\")\.*;\.*$/ should be a start.
  • I know this isn't what you asked for, but I just want to draw your attention to the fact that you can turn logging OFF in your configuration file.

    binil : Thanks Bill, although that functionally achieves the same, that is not what I am after. I wanted to comment out the logger.log(..) calls so that the arguments are not evaluated.
    Bill the Lizard : No problem. I'm going to leave this here rather than deleting it, since others may find it useful someday.
  • You can use slf4j's jul-to-slf4j module to redirect all java.util.logging calls into slf4j, and then you can choose the slf4j-nop module to ignore all the logging statements.

    Will this do, or do you REALLY need to get rid of these source lines?

  • using a tool to comment out or remove all of the logging code might be a bad idea.

    There might be side effect code that you don't notice:

    while ( x > 5)
    {
        // some code here
        Logger.global.finest( "X is now bigger: " + (x++) );
    }
    

    thats a real obvious example, but it could be very subtle with a method call or something inside the logger call.

    It is probably safer to turn off the logging output, or go through the whole thing manually...

    Robin : If this is in your code, your deserve the side effects ;-)
  • If you're looking to avoid evaluation of arguments, as you say in your comments, then I assume you have calls like:

    logger.log("Expensive toString() operation on " + this);
    

    which you want to disable ?

    If that's the case, and it's scattered through your code, I'd use something like AspectJ to surround all instances of the above with:

    if (loggingEnabled) {
       ...
    }
    

    and set the loggingEnabled flag to false.

    Brian Agnew : It would be nice to know *why* somebody voted this down ?
  • If you wanted to comment out this:

    Log.doLog("Here is a" /* With a block comment to make it hard */
        + " multiline log statement"
        ); doSomethingEssential();
    

    then you'd have a trickier time of it because you'd need to parse the code to some extend to know where to put the comments. I.e. you want to be able to do this:

    // Log.doLog("Here is a" /* With a block comment to make it hard */
    //     + " multiline log statement"
    //     ); // Line break inserted here
    doSomethingEssential();
    

    It's much more trivial to do this instead:

    if (false) Log.doLog("Here is a" /* With a block comment to make it hard */
        + " multiline log statement"
        );
    

    The 'if false' part ends up being optimised out by the compiler and the Log statement won't make it to the final .class file.

    That way all you need is a search/replace step in your build script that replaces all occurences of

    "Log.doLog("
    

    with either

    "if (false) Log.doLog(" or
    "if (true) Log.doLog("
    

    without resorting to tricky parsing of the code.

    binil : izb, I ended up using this solution. I used sed to make this change. Thanks for taking the time to write this solution up, instead of making useless, supposedly-humorous-but-lame, mysterious comments which does not add anything to the discussion at hand. :-)

ASP.NET MVC Problem of creating strong-typed view

I'm learning ASP.MVC now. I got some problems of creating strong-typed view. I added Entity Data Model to Models, and then I tried to add a strong-typed view based on the Entity Data Model I created. But I cannot see any class in "View data class" in "Add View" dialog.

Did I miss sonmething?

From stackoverflow
  • Steps I did to do this were;

    Create an entities data model in a new project under the solution.

    Add some objects to the EDM using the model browser.

    Make a model class in the Models folder of my MVC project, then add some method that gets objects from the Entity Data Model. Don't forget to reference you EDM project from your MVC project.

    In my controller cerate a new ActionResult (or View Result), get it to call for it's objects from the models folder model. Then right click and create view...

    You should see your entities data model and your models folder objects in the view data class dropdown. The reason for using the models folder, for me, is so that I can make it very clear when I am lazy loading objects, for instance, order items from a parent order.

  • Build your project before you add view.