Petals's profilePetals on a wet, black b...PhotosBlogListsMore Tools Help

Petals on a wet, black bough

Windows Media Player

July 02

How to force a point to sit on a rectangle ?


rectange rec;

/**
 * Force the point to sit inside (or on) rectangle.
 */
if ( point.x > rec.width ){
    point.x = rec.width;
}

if ( point.x < 0.0 ){
    point.x = 0.0;
}

if ( point.y > rec.height){
    point.y = rec.height;
}

if ( point.y < 0.0 ){
    point.y = 0.0;
}

/**
 * Force the point to sit on the rectangle.
 */

if ( point.x > (rec.width - point.x) ){
        
    if (point.y > (rec.height - point.y) ){
       
        if ( (rec.width - point.x) > (rec.height - point.y) ){
            point.y = rec.height;
        }
        else{
            point.x = rec.width;
        }
    }
    else{
        if ( point.y > (rec.width - point.x) ){
            point.x = rec.width;
        }
        else{
            point.y = 0.0;
        }
    }
}
else{
       
    if ( point.y > (rec.height - point.y) ){
       
        if ( point.x > (rec.height - point.y) ){
            point.y = rec.height;
        }
        else{
            point.x = 0.0;
        }
    }
    else{
        if ( point.x > point.y ){
            point.y = 0.0;
        }
        else{
            point.x = 0.0;
        }
    }
}
 
July 01

configure.ac tips

--------------------------------------------------------------------------------------------------------------------------------------------
1. configure.ac 和 Makefile.am 的对应:

configure.ac:
PKG_CHECK_MODULES([GLIBMM], [glibmm-2.4])
PKG_CHECK_MODULES([GTKMM], [gtkmm-2.4])


Makefile.am:
AM_CPPFLAGS = \
            $(GLIBMM_CFLAGS) \
            $(GTKMM_CFLAGS) \

AM_LDFLAGS = \
             $(GLIBMM_LIBS) \
             $(GTKMM_LIBS) \


2. AC_ARG_ENABLE的一个例子

dnl ================== Graphviz checks ===============================

AC_ARG_ENABLE(gvc,
              [AC_HELP_STRING([--enable-gvc], [Compile with Graphviz support])],
              [case "${enableval}" in
               yes)  enable_gvc=yes ;;
                no) enable_gvc=no ;;
                *) AC_MSG_ERROR(bad value ${enableval} for --enable-gvc) ;;
                esac],
               [enable_gvc=yes]) dnl Default value

if test "x$enable_gvc" = "xyes"; then
    PKG_CHECK_MODULES([GVC], [libgvc], [enable_gvc=yes], [enable_gvc=no])

    if test "x$enable_gvc" = "xyes"; then
        AC_DEFINE([ENABLE_GVC], [1], [Enable Graphviz support.])
    else
        AC_DEFINE([ENABLE_GVC], [0], [Disable Graphviz support.])
        AC_MSG_WARN("Grahpviz support is disabled since libgvc is not found")
    fi
fi

AM_CONDITIONAL(ENABLE_GVC, test x$enable_gvc = xyes)

dnl ================== end of Graphviz checks ==========================


Generated file: config.h
/* Disable Graphviz support. */
#define ENABLE_GVC 1

3. Summary:

echo "
Configure summary:
    DBUS Support.......:  $enable_dbus
    Nautilus Plugin....:  $HAVE_NAUTILUS
    Thumbnailer........:  $ENABLE_THUMBNAILER
    Gtk-Doc Support....:  $enable_gtk_doc

    PDF Backend........:  $enable_pdf
    PostScript Backend.:  $enable_ps
"

It is useful when we check the configuration result.

--------------------------------------------------------------------------------------------------------------------------------------------

June 26

让gnome-terminal进入指定目录的方法:



1 点击鼠标右键,选择"properties"。

2 在"Command"编辑框输入:
gnome-terminal  --working-directory=你要进入的绝对目录



或者修改gnome-terminal.desktop文件(通常在你的home目录):
Exec=gnome-terminal  --working-directory=你要进入的绝对目录

June 25

Makefile Tips

1. Makefile.am should include head source files (*.h, *.hh etc) .

2. A source directory without source can have some other files to distribute. The file Makefile.am in this directory can only have "EXTRA_DIST" field.

3. bootstrap:

gettextize -f

cd po
intltool-update --pot
mv xxx.pot en_GB.po
# easy to forget
cd ..

autoreconf -fvi -Wall

intltoolize -f -c --automake

 ./configure

June 24

Tips

1 C++ head file suffix should be "hh", souce file suffix should be "cc".

2. if ( !boost::filesystem::exists( "myfile.txt" ) )
{
  std::cout << "Can't find my file!" << std::endl;
}

3. Read compilation error carefully and check if it is a link or load error.

4. Only apply polymorphism to polymorphic classes( virtual functions).

5. A data type is a set of values plus operations to work with them.

6. inline
struct test{

    int x;
    
    inline int get_x(){
        std::cout<<"x: "<<x<<std::endl;
        return x;
    }
};

7. new

void * new (const void * _class, ...)
{   const struct Class * class = _class;
   
    void * p = calloc(1, class —> size);
   
    assert(p);
   
    * (const struct Class **) p = class;
   
    if (class —> ctor)
    {   va_list ap;
        va_start(ap, _class);
        p = class —> ctor(p, & ap);
        va_end(ap);
    }
   
    return p;
}


8. std::getline(stream,line)
--------------------------------------------------------------------------------------------------------------------------------------------
 
June 16

Media Independent Interface (MII)

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

The Media Independent Interface (MII) is a standard interface used to connect a Fast Ethernet (i.e. 100Mb/s) MAC-block to a PHY. The MII may connect to an external transceiver device via a pluggable connector (see photo) or simply connect two chips on the same printed circuit board. Being media independent means that any of several different types of PHY devices can be used without redesigning or replacing the MAC hardware. The equivalents of MII for other speeds are AUI (for 10 megabit Ethernet), GMII (for gigabit Ethernet), and XAUI (for 10 gigabit Ethernet).


To compile pango with cairo backend

The documentation and configure file in pango does need improve. During in the configuration, there is a config error in config.log. It can be found around line 193xx and we could find a false condition of $freetype.

So the solution is:
1. Install fontconfig newest version from:
  http://fontconfig.org/wiki/

2. Install freetype newest version from:
http://www.freetype.org/

After that, we can install pango, and then pangomm.
June 03

acronyms

list of acronyms in alphabetical order:

    * AFAICS = As far as I can see
    * BTW = By the way
    * FWIW = For what it's worth
    * FYI = For your information
    * HAND = Have a nice day
    * IMHO = In my humble opinion (egoless)
    * IMAO = In my arrogant opinion (oodles of ego)
    * IMNSHO = In my not-so humble opinion (a lot of ego)
    * IMO = In my opinion (not much ego)
    * KUTGW = Keep up the good work
    * MYOB = Mind your own business
    * OO = Object-oriented
    * OTOH = On the other hand
    * PEBCAC = Problem exists between chair and computer
    * PEBCAK = Problem exists between chair and keyboard
    * PMFJI = Pardon me for jumping in
    * RTFM = Read the ___ manual
    * SO = Significant other (as in, "My SO and I went for a walk...")
    * SSO = Small String Optimization (where short strings don't use the heap)
    * YHBT = You have been trolled
    * YHL = You have lost

Gtk tips

1. Glib::KeyFile Class


    This class lets you parse, edit or create files containing groups of key-value pairs, which we call key files for lack of a better name.


http://www.gtkmm.org/docs/glibmm-2.4/docs/reference/html/classGlib_1_1KeyFile.html#_details

2. Undo & Redo

    It needs 2 stacks: Undo stack and Redo Stack.


3. Recent file

    Glib::RefPtr<Gtk::Action> action =
        mp_action_group->get_action("ProjectRecent");

    Glib::RefPtr<Gtk::RecentAction> recentAction =
        Glib::RefPtr<Gtk::RecentAction>::cast_static(action);

    Glib::RefPtr<Gtk::RecentInfo> cur =
        recentAction->get_current_item();
        
    if(cur)
    {
        std::cout<<"Recent "<<cur->get_uri()<<std::endl;
    }

4.  sigc::ptr_fun

    main_window.signal_unmap().connect(sigc::ptr_fun(&Gtk::Main::quit) );

5. Gtk::AccelKey

    When we create acceleration key, we need add the acceleration group in the main window and indicate the window to accept keyboard messages.

    Window.add_events( Gdk::EXPOSURE_MASK |
                            Gdk::BUTTON_PRESS_MASK |
                            Gdk::BUTTON_RELEASE_MASK |
                            Gdk::KEY_PRESS_MASK |
                            Gdk::KEY_RELEASE_MASK |
                            Gdk::BUTTON1_MOTION_MASK |
                            Gdk::SCROLL_MASK |
                            Gdk::POINTER_MOTION_MASK |
                            Gdk::POINTER_MOTION_HINT_MASK );

    Window.add_accel_group(->get_accel_group());
 
May 28

A complete example for sigc::signal<* * >

/**
 * A complete example for sigc::signal<* * >.
 */
#include <syslog.h>

#include <iostream>
#include <vector>
#include <deque>
#include <queue>
#include <list>
#include <string>
#include <algorithm>
#include <iterator>
#include <map>
#include <memory>

#include <boost/shared_ptr.hpp>

#include <gtkmm.h>    

using namespace std;
using namespace boost;


class Document
{
};


class A{

private:
    sigc::signal<void, Document*>    m_signal_document_create;
    
   
public:
    A(){
        /**
         * Just one example. The function signal_document_create can be called
         * lots of times.
         */
        this->signal_document_create().connect
            (sigc::mem_fun(*this, &A::on_document_create));


    }

    /**
     * This function is used and it provides a way for other class to build
     * signal connection many times. This structure is very flexible.
     */
    sigc::signal<void, Document*>& signal_document_create(){

        return m_signal_document_create;
    }

    void on_document_create(Document *doc){
        /** ... */
    }
};



int main()
{
    A a;
   
    return 1;
}
 
May 27

Gtk::manage

Function:

template <class T>
T* Gtk::manage     
( T* obj ) [inline]

Mark a Gtk::Object as owned by its parent container widget, so you don't need to delete it manually.

For instance,

 Gtk::Button* button = Gtk::manage( new Gtk::Button("Hello") );
 vbox.pack_start(*button); //vbox will delete button when vbox is deleted.

Parameters:
    obj A Gtk::Object, such as a gtkmm widget.

Returns:
    The Gtk::Object passed as the obj parameter.

May 26

C++ Tips:




1. modify linux version in:

Makefile
linux/utsrelease.h

2. export_symbol, module_init or module_exit exports symbols for different uses.

3. Gtk::ActionGroup

mp_action_group->add( Gtk::RecentAction::create("ProjectRecent", "_Recent Projects"),
                          sigc::mem_fun(*this, &galaxy::ui_manager::on_project_recent));

4. Global variable:

    template <typename Dummy>
    class tlm_global_quantum
    {
    public:
      //
      // Returns a reference to the tlm_global_quantum singleton
      //
      static tlm_global_quantum& instance()
      {
        if (!m_instance) {
          m_instance = new tlm_global_quantum;
        }
        return *m_instance;
      }
    .........
  }

May 22

Gtk::StockID

http://www.gtkmm.org/docs/gtkmm-2.4/docs/reference/html/namespaceGtk_1_1Stock.html#bf965c1d305e2880ac77f830477bb282

Glib::SListHandle<Gtk::StockID,Gtk::StockID_Traits>
Gtk::Stock::get_ids      
(             ) ;


typedef std::vector<Gtk::StockID> type_vecIDs;
type_vecIDs vecIDs = Gtk::Stock::get_ids();

// iterate through them, populating the ListStore as appropriate
for(type_vecIDs::const_iterator iterIDs = vecIDs.begin();
    iterIDs != vecIDs.end();
    ++iterIDs){
    ...

    }
May 20

C++ Tips



1. C++ calls C function.

When a C++ program calls a C function, we can use a declartion like:

extern "C" c_function();

Please note we should not include the c_function associated file header.

2. std::stringstream

std::stringstream ss( "33" );
ss >> (int_tst);

std::stringstream text;
text<<"( "<< i<< ", "<<j<<" )";

May 19

Bill Clinton, George W. Bush and George Washington

Bill Clinton, George W. Bush and George Washington are on a sinking ship.

As the boat sinks, George Washington heroically shouts, "Save the women!"

George W. Bush hysterically hollers, "Screw the women!"

Bill Clinton's asks excitedly, "Do we have time?"

Home Theater PC (HTPC) or media PC

A Home Theater PC (HTPC) or media PC is a convergence device that combines the functions of a personal computer and a media center software which feature video and music playback, and usually but not always also digital video recorder functionality. It usually has a 10-foot user interface and is connected to a television or a television-sized computer display, and is often used as a digital photo, music, video player, TV receiver and digital video recorder, and normally controlled with a remote control.

The general goal of an HTPC is usually to combine many or all components of a home theater setup into one single box that will be located in the living room and is controlled with a remote control as the main interface, and the GUI normally has a 10-foot user interface design so that it can be comfortably viewed from a such distance. An HTPC can be purchased pre-configured with the required hardware and software needed to add television programming to the PC, or can be cobbled together out of discrete components as is commonly done with Windows Media Center, MediaPortal ,SageTV, MythTV, Freevo, or LinuxMCE.

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

May 11

Two random uninterruptable processing logic:



Scenario:

    Two events happen interchangably and any one of them can happen first. But if one event happens, it cannot be interrupted.

Initialization:

    state: STATE_1ST and STATE_2ND not set.

Procedure:

    if ( both STATE_1ST and STATE_2ND not set ) {

        if (STATE_1ST) {

            set STATE_1ST;
        }
        else {
            set STATE_2ND;
        }
    }

    if (STATE_1ST set) {

        do STATE_1ST;
    }
    else {
        do STATE_2ND;
    }

Reset:

    state: STATE_1ST and STATE_2ND not set.

End the University as We Know It


By MARK C. TAYLOR

GRADUATE education is the Detroit of higher learning. Most graduate programs in American universities produce a product for which there is no market (candidates for teaching positions that do not exist) and develop skills for which there is diminishing demand (research in subfields within subfields and publication in journals read by no one other than a few like-minded colleagues), all at a rapidly rising cost (sometimes well over $100,000 in student loans).

Widespread hiring freezes and layoffs have brought these problems into sharp relief now. But our graduate system has been in crisis for decades, and the seeds of this crisis go as far back as the formation of modern universities. Kant, in his 1798 work “The Conflict of the Faculties,” wrote that universities should “handle the entire content of learning by mass production, so to speak, by a division of labor, so that for every branch of the sciences there would be a public teacher or professor appointed as its trustee.”

Unfortunately this mass-production university model has led to separation where there ought to be collaboration and to ever-increasing specialization. In my own religion department, for example, we have 10 faculty members, working in eight subfields, with little overlap. And as departments fragment, research and publication become more and more about less and less. Each academic becomes the trustee not of a branch of the sciences, but of limited knowledge that all too often is irrelevant for genuinely important problems. A colleague recently boasted to me that his best student was doing his dissertation on how the medieval theologian Duns Scotus used citations.

The emphasis on narrow scholarship also encourages an educational system that has become a process of cloning. Faculty members cultivate those students whose futures they envision as identical to their own pasts, even though their tenures will stand in the way of these students having futures as full professors.

The dirty secret of higher education is that without underpaid graduate students to help in laboratories and with teaching, universities couldn’t conduct research or even instruct their growing undergraduate populations. That’s one of the main reasons we still encourage people to enroll in doctoral programs. It is simply cheaper to provide graduate students with modest stipends and adjuncts with as little as $5,000 a course — with no benefits — than it is to hire full-time professors.

In other words, young people enroll in graduate programs, work hard for subsistence pay and assume huge debt burdens, all because of the illusory promise of faculty appointments. But their economical presence, coupled with the intransigence of tenure, ensures that there will always be too many candidates for too few openings.

The other obstacle to change is that colleges and universities are self-regulating or, in academic parlance, governed by peer review. While trustees and administrations theoretically have some oversight responsibility, in practice, departments operate independently. To complicate matters further, once a faculty member has been granted tenure he is functionally autonomous. Many academics who cry out for the regulation of financial markets vehemently oppose it in their own departments.

If American higher education is to thrive in the 21st century, colleges and universities, like Wall Street and Detroit, must be rigorously regulated and completely restructured. The long process to make higher learning more agile, adaptive and imaginative can begin with six major steps:

1. Restructure the curriculum, beginning with graduate programs and proceeding as quickly as possible to undergraduate programs. The division-of-labor model of separate departments is obsolete and must be replaced with a curriculum structured like a web or complex adaptive network. Responsible teaching and scholarship must become cross-disciplinary and cross-cultural.

Just a few weeks ago, I attended a meeting of political scientists who had gathered to discuss why international relations theory had never considered the role of religion in society. Given the state of the world today, this is a significant oversight. There can be no adequate understanding of the most important issues we face when disciplines are cloistered from one another and operate on their own premises.

It would be far more effective to bring together people working on questions of religion, politics, history, economics, anthropology, sociology, literature, art, religion and philosophy to engage in comparative analysis of common problems. As the curriculum is restructured, fields of inquiry and methods of investigation will be transformed.

2. Abolish permanent departments, even for undergraduate education, and create problem-focused programs. These constantly evolving programs would have sunset clauses, and every seven years each one should be evaluated and either abolished, continued or significantly changed. It is possible to imagine a broad range of topics around which such zones of inquiry could be organized: Mind, Body, Law, Information, Networks, Language, Space, Time, Media, Money, Life and Water.

Consider, for example, a Water program. In the coming decades, water will become a more pressing problem than oil, and the quantity, quality and distribution of water will pose significant scientific, technological and ecological difficulties as well as serious political and economic challenges. These vexing practical problems cannot be adequately addressed without also considering important philosophical, religious and ethical issues. After all, beliefs shape practices as much as practices shape beliefs.

A Water program would bring together people in the humanities, arts, social and natural sciences with representatives from professional schools like medicine, law, business, engineering, social work, theology and architecture. Through the intersection of multiple perspectives and approaches, new theoretical insights will develop and unexpected practical solutions will emerge.

3. Increase collaboration among institutions. All institutions do not need to do all things and technology makes it possible for schools to form partnerships to share students and faculty. Institutions will be able to expand while contracting. Let one college have a strong department in French, for example, and the other a strong department in German; through teleconferencing and the Internet both subjects can be taught at both places with half the staff. With these tools, I have already team-taught semester-long seminars in real time at the Universities of Helsinki and Melbourne.

4. Transform the traditional dissertation. In the arts and humanities, where looming cutbacks will be most devastating, there is no longer a market for books modeled on the medieval dissertation, with more footnotes than text. As financial pressures on university presses continue to mount, publication of dissertations, and with it scholarly certification, is almost impossible. (The average university press print run of a dissertation that has been converted into a book is less than 500, and sales are usually considerably lower.) For many years, I have taught undergraduate courses in which students do not write traditional papers but develop analytic treatments in formats from hypertext and Web sites to films and video games. Graduate students should likewise be encouraged to produce “theses” in alternative formats.

5. Expand the range of professional options for graduate students. Most graduate students will never hold the kind of job for which they are being trained. It is, therefore, necessary to help them prepare for work in fields other than higher education. The exposure to new approaches and different cultures and the consideration of real-life issues will prepare students for jobs at businesses and nonprofit organizations. Moreover, the knowledge and skills they will cultivate in the new universities will enable them to adapt to a constantly changing world.

6. Impose mandatory retirement and abolish tenure. Initially intended to protect academic freedom, tenure has resulted in institutions with little turnover and professors impervious to change. After all, once tenure has been granted, there is no leverage to encourage a professor to continue to develop professionally or to require him or her to assume responsibilities like administration and student advising. Tenure should be replaced with seven-year contracts, which, like the programs in which faculty teach, can be terminated or renewed. This policy would enable colleges and universities to reward researchers, scholars and teachers who continue to evolve and remain productive while also making room for young people with new ideas and skills.

For many years, I have told students, “Do not do what I do; rather, take whatever I have to offer and do with it what I could never imagine doing and then come back and tell me about it.” My hope is that colleges and universities will be shaken out of their complacency and will open academia to a future we cannot conceive.

Mark C. Taylor, the chairman of the religion department at Columbia, is the author of the forthcoming “Field Notes From Elsewhere: Reflections on Dying and Living.”

on_key_press_event


bool
galaxy::graph_view::on_key_press_event
( GdkEventKey * event )
{
    /**
     * <b> High level design of the function is :</b>
     */
    Gtk::DrawingArea::on_key_press_event(event);

    switch (event->keyval){
       
    case 61:
        /**
         * Ctrl +
         * \note
         * - It is so strange that '+' cannot be used.
         * .
         */

        if (event->state & GDK_CONTROL_MASK){
           
            std::cout<<"Ctrl +"<<std::endl;

            zoom_in_transform();
            zoom_in_transform();
           
            redraw_notify();
        }
       
        break;

    case 45:
        /**
         * Ctrl -
         * \note
         * - '-' can be used.
         * .
         */
       
        if (event->state & GDK_CONTROL_MASK){

            zoom_out_transform();
            zoom_out_transform();
           
            redraw_notify();
        }
       
        break;

    default:

        break;
    }
   
    return true;
}

For Gtk::DrawingArea to respond "KEY_PRESS" event

    /**
     * To allow the view accept the following messages.
     */
    this->add_events( Gdk::EXPOSURE_MASK |
                      Gdk::BUTTON_PRESS_MASK |
                      Gdk::BUTTON_RELEASE_MASK |
                      Gdk::KEY_PRESS_MASK |
                      Gdk::KEY_RELEASE_MASK |
                      Gdk::BUTTON1_MOTION_MASK |
                      Gdk::SCROLL_MASK |
                      Gdk::POINTER_MOTION_MASK |
                      Gdk::POINTER_MOTION_HINT_MASK );
    /**
     * To accept the key press event.
     */
    this->set_flags( Gtk::CAN_FOCUS );

 

Petals

Occupation
Location
Interests
生于田野,长于自然,学于行伍,活于尘嚣,逝于中...
Photo 1 of 2