Thursday, December 8, 2011

Use Linq to obtain a unique list of properties from a list

Use the Distinct operator:
var idList = yourList.Select(x=> x.ID).Distinct();

Wednesday, December 7, 2011

Linq calculate average of a list C#

Only one line of code will do it:

List<float> f = new List<float>();
for (int i = 0; i < 10; i++)
float ave = f.Aggregate((acc, cur) => acc + cur) / f.Count;

Wednesday, November 30, 2011

How to play audio files on a particular soundcard C#

I have been working on playing audio files on particular audio devices for a few days. On windows platform. the [C#]using Microsoft.DirectX.AudioVideoPlayback; only works for the default audio device. We need to work on a lower layer, using DirectShow.

I will post the detail of the implementation a few days later.

Wednesday, November 23, 2011

Get regex matched strings (Regex Capture) C#

Program that uses Match [C#]
using System;
using System.Text.RegularExpressions;

class Program
    static void Main()
 // A
 // The input string we are using
 string input = "OneTwoThree";

 // B
 // The regular expression we use to match
 Regex r1 = new Regex(@"One([A-Za-z0-9\-]+)Three");

 // C
 // Match the input and write results
 Match match = r1.Match(input);
 if (match.Success)
     string v = match.Groups[1].Value;
     Console.WriteLine("Between One and Three: {0}",
Output Between One and Three: Two

Sunday, November 13, 2011

UI String Matching in XAML and CS

A few month ago, we were doing String Localization for our software. It is lame for us to manually find the strings in the .cs and .xaml files and replace them with localization resource files.

So I look for help from REGEX, which is always helpful when dealing with strings.

Below is the regex to match UI String in xaml and cs files:

for .cs files:

^(~(ArgumentNullException|AddCMEventLog|//|dw\.add|OnPropertyChanged|Assembly\:|\[System\.|this\.RaisePropertyChanged|GeneratedCodeAttribute|throw\ new\ Exception).)+".*"(~(ArgumentNullException|AddCMEventLog).)+$

for .xaml files:

(Title="[^{])|(\ Text="[^{])|(Content="[^{])|(Header="[^{])|(ToolTip="[^{])|(Label="[^{])|(\ Value="[^{])|(Description="[^{])|(\>[^<>]+\<)

This may work in Visual Stdio only

Thursday, November 10, 2011

When you want to import dll

using System.Runtime.InteropServices;//DLLimport

[DllImport("winmm.dll", SetLastError = true)]

Tuesday, September 20, 2011

How special var is in C#, var can't be the type of property of class C#

var is static typed - the compiler and runtime know the type - they just save you some typing... the following are 100% identical:
var s = "abc";
string s = "abc";

Finding an ancestor and children of a WPF dependency object

Below are from :

This is a simple snippet which helps you to find a specified parent of a given WPF dependency object somewhere in its visual tree:
(Snippet updated 2009.09.14)

/// <summary>
/// Finds a parent of a given item on the visual tree.
/// </summary>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="child">A direct or indirect child of the
/// queried item.</param>
/// <returns>The first parent item that matches the submitted
/// type parameter. If not matching item can be found, a null
/// reference is being returned.</returns>
public static T TryFindParent<T>(this DependencyObject child)
    where T : DependencyObject

Saturday, September 10, 2011

Mercurial .hgrc

username = Steven You <email>
[hostfingerprints] = 81:2b:08:90:dc:d3:71:ee:e0:7c:b4:75:ce:9b:6c:48:94:56:a1:fe
color =

Monday, September 5, 2011

Read binary in Hex

$ hexdump dog


$ cat dog | xxd

od -x can be used in mac, but the hight byte and low byte position is different

Thursday, September 1, 2011

Mac Dev Utilities


Thursday, August 25, 2011

C# Invoke particular EventHandler in InvocationList

I am trying to get particular EventHandler get fired.

Event ProjectChanged was hooked by several EventHandlers

public static event EventHandler ProjectChanged;

foreach (var eventHandler in ProjectChanged.GetInvocationList())
    if (eventHandler.Method.Name == "UserContext_ProjectChanged")

String to Guid in C#

public static Guid StringToGUID(string value)
    // Create a new instance of the MD5CryptoServiceProvider object.
    MD5 md5Hasher = MD5.Create();
    // Convert the input string to a byte array and compute the hash.
    byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(value));
    return new Guid(data);

Sunday, August 21, 2011

configure git with color

To display color in the output of git diff, you need to configure git. Try running
$ git config --global color.diff true
to set your $HOME/.gitconfig appropriately.
To enable color for all:
$ git config --global color.ui true

Thursday, August 18, 2011

Popular Command Lines for Linux

The original article are in three parts:

In my post, part_1part_2part_3part_4

I love working in the shell. Mastery of shell lets you get things done in seconds, rather than minutes or hours, if you chose to write a program instead.
In this article I’d like to explain the top one-liners from the It’s a user-driven website where people get to choose the best and most useful shell one-liners.

Wednesday, August 17, 2011

WPF GridViewColumn Width 100 percent

    <GridView ColumnHeaderContainerStyle="{StaticResource CustomHeaderStyle}">
        <GridViewColumn Header="xxx" 
             Width="{Binding RelativeSource={RelativeSource FindAncestor, 
             AncestorType=ListView}, Path=ActualWidth}">

Monday, August 8, 2011

OpenCV material

PYTHON iterate all files in a directory

To iterate through all the files within the specified directory (folder), with ability to use wildcards (*, ?, and [ ]-style ranges), use the following code snippet:
  1. import os
  2. import glob
  4. path = 'sequences/'
  5. for infile in glob.glob( os.path.join(path, '*.fasta') ):
  6.     print "current file is: " + infile
If you do not need wildcards, then there is a simpler way to list all items in a directory:
  1. import os
  3. path = 'sequences/'
  4. listing = os.listdir(path)
  5. for infile in listing:
  6.     print "current file is: " + infile

PYTHON RuntimeError: maximum recursion depth exceeded in cmp

if your python code produces the following error: “RuntimeError: maximum recursion depth exceeded in cmp,” try adding this line to the beginning of your code:
note that python’s default limit is 1000.

Saturday, August 6, 2011


g++ hello-world.cpp -o hello-world \
    -I /usr/local/include/opencv -L /usr/local/lib  \
    -lm -lcv -lhighgui -lcvaux
c++ find_obj.cpp -o o -I /usr/local/include -L /usr/local/lib -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_ml -lopencv_video -lopencv_features2d -lopencv_calib3d -lopencv_objdetect -lopencv_contrib -lopencv_legacy -lopencv_flann

Monday, August 1, 2011

Monday, June 27, 2011

Icon Render WPF

RenderOptions.BitmapScalingMode="NearestNeighbor"                            RenderOptions.EdgeMode="Aliased"

Sunday, June 26, 2011

Text Trimming and ToolTip bind to itself

TextTrimming="CharacterEllipsis" TextWrapping="Wrap" ToolTip="{Binding Text, RelativeSource={RelativeSource Mode=Self}}

Monday, June 13, 2011

VIM increase number, increase alpha

Press Ctrl+A increase the number under cursor.

:set nrformats=alpha

can help you increase character.

Monday, June 6, 2011


The origin of the older computer term "CRLF" - which redirects to this Newline article - or "Carriage Return [and] Line Feed", derives from standard manual typewriter design, whereby at the end of a line of text the typist pushes a lever at the left end of the carriage to return it to position for beginning the next line.

Tuesday, May 31, 2011

eclipse comments short cut

Ctrl+/Toggle CommentAdd/remove line comments (//…) from the current line. The position of the cursor can beanywhere on the line. Works with multiple selected lines as well.
Ctrl+Shift+/Add Block CommentWrap the selected lines in a block comment (/*… */).
Ctrl+Shift+\Remove Block CommentRemove a block comment (/*… */) surrounding the selected lines.
Alt+Shift+JAdd Javadoc CommentAdd a Javadoc comment to the active field/method/class. See the notes below for more details on where to position the cursor.

Friday, May 27, 2011

Cool stuff in .NET 4.0: System.Threading.Tasks.TaskScheduler

private void Save()
    System.Threading.Tasks.TaskScheduler uiScheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
    System.Threading.Tasks.Task<ErrorEnum>.Factory.StartNew(() =>
        ErrorEnum callResult = ErrorEnum.OK;
            IsIdle = false;
            callResult = (ErrorEnum)DataContext.DomainRepository.SaveDomain(_domain);
            if (callResult != ErrorEnum.OK)
                // If remote saving fails, rollback all the changes
                // If remote saving succeeds, save changes to local db
            return callResult;
        catch (Exception ex)
            LogManager.AddCMEventLog("DomainSettingsViewModel.Save", ex);
            // If anything goes wrong, rollback all the changes
            return ErrorEnum.LocalFatalAnonymousError;
            IsIdle = true;
    }).ContinueWith(task => ShowResult(task.Result), uiScheduler);

This running tasks in background thread, then call UI thread to execute the ShowResult() function, Just like UIDispatcher

Monday, May 23, 2011

perl send email cgi

Lots of tutorials about sending email with perl depend on some uncommon libs.
There is a common way to do so:

use Net::SMTP::SSL;

sub send_mail {
    my $to      = $_[0];
    my $subject = $_[1];
    my $body    = $_[2];

perl session cgi

$session = CGI::Session->load() or die CGI::Session->errstr;
if ( $session->is_expired ) {
    die "Your session expired. Please refresh your browser to re-start your session";
if ( $session->is_empty ) {
    $session = $session->new();

print $session->header();

#save into session

#read from session
$variable = $session->param('username');

Tuesday, May 10, 2011

Java sort list -- Collections.sort sample

public static void Sort(List<Movies> items) {
Collections.sort(items, SENIORITY_ORDER);
static final Comparator<Movies> SENIORITY_ORDER =
        new Comparator<Movies>() {
public int compare(Movies e1, Movies e2) {
if (e1.getReleaseDate().after(e2.getReleaseDate()))
return 1;
return -1;

Thursday, April 14, 2011

New View of Blogger is awesome!!

Set Window on top of others

The correct way to implement a modal window is by setting  this.Owner = Application.Current.MainWindow; in the XAML, and show the dialog by using DialogName.ShowDialog();

Monday, March 28, 2011

Sunday, March 27, 2011

TextTrimming ToolTip in WPF

<TextBlock Text="{Binding State}" TextTrimming="CharacterEllipsis" Foreground="#6D6D6D"
                                                           ToolTip="{Binding Text, RelativeSource={RelativeSource Mode=Self}}"/>

Wednesday, March 23, 2011

Change ubuntu default shell to bash

Found out that the C-style for loop does not work in ubuntu shell. After a few google search, answer is at below:
C-style for loop on works In bash (since version 2.04)
The sh command in /bin/sh is a symbolic link to /bin/dash:

steven@steven-laptop:/bin$ ls -l sh
lrwxrwxrwx 1 root root 4 2010-05-03 06:48 sh -> dash

$sudo ln -sf /bin/bash /bin/sh
to replace
To change the login shell, use the command $chsh

Tuesday, March 22, 2011

Conditional Operations

Let's look at the if/then/else construct in a Bash shell script and see how to control the flow of a script with conditional logic. The general form of if/then/else is shown here, with the actual syntax shown in boldface and the parts you must supply in normal type:
if [ condition is true ]

execute these commands


execute those commands

VIM set tab key == 4 spaces

in your .vimrc:
set smartindent
set tabstop=4
set shiftwidth=4
set expandtab

Tuesday, March 8, 2011

ListView ObservableCollection Selection

I have ListView with GridView inside (in order to divide ListView for some columns). I bind ObservableCollection of some objects with that ListView.DataContext when main UserControl is loaded. Items show up but when i create two objects which fields have same values (and put them to observable collection), that new items show up in ListView. Problem is that, when user clicks and select one of the new item - both select.

When value of one of mentioned objects changes (and is different) problem doesn't exist, ListView treat them as it should.

Friday, March 4, 2011

The filter

head t.txt; echo ... tail t.txt

%sort -r +1-2 t1_data.txt
%sort -r -n -k2 t1_data.txt
%grep ' [6-9]' t1_data.txt

Wednesday, February 23, 2011

C# Write Access Check

        /// <summary> Checks for write access for the given file.
        /// </summary>
        /// <param name="fileName">The filename.</param>
        /// <returns>true, if write access is allowed, otherwise false</returns>
        public static bool WriteAccess(string dire)

            // Get the access rules of the specified files (user groups and user names that have access to the file)
            var rules = Directory.GetAccessControl(dire).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

            // Get the identity of the current user and the groups that the user is in.
            var groups = WindowsIdentity.GetCurrent().Groups;
            string sidCurrentUser = WindowsIdentity.GetCurrent().User.Value;

            // Check if writing to the file is explicitly denied for this user or a group the user is in.
            if (rules.OfType<FileSystemAccessRule>().Any(r => (groups.Contains(r.IdentityReference) || r.IdentityReference.Value == sidCurrentUser) && r.AccessControlType == AccessControlType.Deny && (r.FileSystemRights & FileSystemRights.WriteData) == FileSystemRights.WriteData))
                return false;

            // Check if writing is allowed
            return rules.OfType<FileSystemAccessRule>().Any(r => (groups.Contains(r.IdentityReference) || r.IdentityReference.Value == sidCurrentUser) && r.AccessControlType == AccessControlType.Allow && (r.FileSystemRights & FileSystemRights.WriteData) == FileSystemRights.WriteData);