tommy

It's hard to tell the world we live in is either a reality or a dream
posts - 52, comments - 17, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

2015年1月24日

StatService.h
#pragma once

class StatService {
public:
    StatService();

    void trackPageView(const string &page);
    void trackEvent(const string &eventName, map<stringstring> &props);    

private:
    void getUrl(string url);
};

StatService.cpp
#include "StatService.h"
#include "GlobalConfig.h"
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/NetworkInterface.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/StreamCopier.h>
#include <Poco/Path.h>
#include <Poco/URI.h>
#include <Poco/Exception.h> 
#include <Poco/Base64Encoder.h>

using namespace Poco::Net;
using namespace Poco;
using namespace std;

StatService::StatService() {
}

string GetIP() {
    NetworkInterface::NetworkInterfaceList list = NetworkInterface::list();
    for(NetworkInterface::NetworkInterfaceList::iterator i = list.begin(); i != list.end(); ++i) {
        NetworkInterface nt = *i;
        IPAddress addr = nt.address();
        if(!addr.isLoopback()) { 
            return addr.toString();
        }
    }
    return "";
}

void StatService::trackPageView(const string &page) {
    const GlobalConfig *gConfig = GlobalConfig::GetInstance();
    string eventName = "VisitPage";
    stringstream ss;
    ss << "{" <<
        "\"event\":\"" << eventName << "\"," <<
        "\"properties\": {" << 
        "\"page\":\"" << page << "\"," <<
        // "distinct_id" and "token" are
        
// special properties, described below.
        "\"distinct_id\":" << "\"" << GetIP() << "\"," <<
        "\"token\":\"" << gConfig->stat_token() << "\"";
    ss << "}}";

    //encode
    std::ostringstream base64Str;
    Base64Encoder encoder(base64Str);
    encoder << ss.str();
    encoder.close();
    //cout << base64Str.str() << endl;
    
    cout << ss.str() << endl;

    ostringstream url;
    url << gConfig->stat_endpoint() << "?data=" << base64Str.str();
    string sUrl = url.str();
    //cout << sUrl << endl;
    
    sUrl.erase(remove_if(sUrl.begin(), sUrl.end(), isspace), sUrl.end());
    //replaceAll(sUrl, "\n", "$");

    
//kick off
    getUrl(sUrl);    
}


void replaceAll(std::string& str, const std::string& from, const std::string& to) {
    if(from.empty())
        return;
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
    }
}
void StatService::trackEvent(const string &eventName, map<string,string> &props) { 
    const GlobalConfig *gConfig = GlobalConfig::GetInstance();
    stringstream ss;
    ss << "{" <<
        "\"event\":\"" << eventName << "\"," <<
        "\"properties\": {" << 
        // "distinct_id" and "token" are
        
// special properties, described below.
        "\"distinct_id\":" << "\"" << GetIP() << "\"," <<
        "\"token\":\"" << gConfig->stat_token() << "\"";
    
    //plugin in properties 
    for(map<string,string>::const_iterator i = props.cbegin(); i != props.cend(); ++i) { 
        ss << ",\"" << i->first << "\":\"" << i->second << "\"";
    } 
    ss << "}}";

    //encode
    std::ostringstream base64Str;
    Base64Encoder encoder(base64Str);
    encoder << ss.str();
    encoder.close();
    //cout << base64Str.str() << endl;
    
    cout << ss.str() << endl;

    ostringstream url;
    url << gConfig->stat_endpoint() << "?data=" << base64Str.str();
    string sUrl = url.str();
    //cout << sUrl << endl;
    
    sUrl.erase(remove_if(sUrl.begin(), sUrl.end(), isspace), sUrl.end());
    //replaceAll(sUrl, "\n", "$");

    
//kick off
    getUrl(sUrl);
}
void StatService::getUrl(string url) {
    URI uri(url);
    HTTPClientSession session(uri.getHost(), uri.getPort());
    GlobalConfig * gConfig = GlobalConfig::GetInstance();
    if(gConfig->proxy().size() > 0) {
        session.setProxy(gConfig->proxy(), gConfig->proxy_port());
    }
    std::string path(uri.getPathAndQuery());
    if (path.empty()) path = "/";

    cout << "getUrl:path:" << path << endl;

    // send request
    HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
    session.sendRequest(req);

    HTTPResponse res;
    cout << res.getStatus() << " " << res.getReason() << endl;

    // print response
    istream &is = session.receiveResponse(res);
    StreamCopier::copyStream(is, cout);
}

posted @ 2015-01-24 22:48 Tommy Liang 阅读(291) | 评论 (0)编辑 收藏

2013年8月4日

  1. "new" to create an object if no arguments are needed for initialization.
    e.g.   XYZObject *object = [XYZObject new];
2. Literals offers a concise object-creation syntax.
    NSString *someString = @"Hello, World !";
3. We can create NSNumber using boxed expression, like:
    NSNumber *myInt = @(80/12);
4. The "id" type defines a generic object pointer.  (object c is a dynamic language!  this is just like "var"         keyword in C#)
    
    id someObject = @"Hello, World!";
5.  Use "isEqual" to test whether two objects represent the same data, available from NSObject.
    if([firstObject isEqual:secondObject]) ...
6.  "compare" method is provided by basic Foundation types such as NSNumber, NSString and NSDate.
    if( [someDate compare:anotherDate] == NSOrderedAscending) ...
7. It's perfectly acceptable in Object-C to send a message to nil,  it's just ignored and return nil for object return type, 0 for numeric types and NO for BOOL types.
8. If you want to make sure an object is not null, use this syntax:
    if (somePerson) ... directly, as convenient as Javascript.
9. It's important to avoid strong reference cycles.
10. Accessor methods are created by compiler:
     NSString *firstName = [somePerson firstName];
     [somePerson setFirstName:@"John"];
11. The method used to set the value (the setter method) starts with the word "set" and then uses the capitalized property name.
12. "readonly" attribute can be added to a property declaration to specify that it should be readonly, don't want it to be changed via setter method.
      @property (readonly) NSString *fullname;
13. Custom name can be specified using attribute on the property:
     @property (getter=isFinished) BOOL finished;
14. Simply include the multiple attributes on property as a comma-separated list, like this:
     @property (readonly, getter=isFinished) BOOL finished;
15.  Dot syntax is a concise alternative to accessor method calls
     NSString *firstName = someperson.firstName;
     somePerson.firstName = @"johnny";
16. Should use accessor method or dot syntax for property access even if you're accessing an object's properties from within its own implementation, in such case, should use "self":
      -(void) someMethod {
          NSString *myString = @"An interesting string";
          self.someString = myString;
          //or
          [self setSomeString:myString];
      }
      except when writing initialization, deallocation or custom accessor methods.
17. There's a default instance variable created by compiler called _propertyName,  we can direct the compiler to synthesize the variable using the following syntax:
     @implementation YourClass
     @synthesize propertyName = instanceVariableName;
     ...
     @end
18. If using @synthesize without specifying an instance variable name, like this:
     @synthesize firstName;
     the instance variable name will bear the same name as the property. (without underscore as prefix)
19. It's best practice to use a property on an object any time you need to keep track of a value or another object.
20. If you need to define your own instance variables without declaring a property, add them inside braces at the top of the class interface or implementation, like this:
     @interface SomeClass: NSObject {
        NSString *_myNonPropertyInstanceVariable;                           
     }
    or
    @implementation SomeClass {
        NSString *_anotherCustomInstanceVariable;
    }
21. Should always access the instance variables directly from within the initialization methods, like:
    - (id) init {
        self = [super init];
        
        if (self) {
            //initialize instance variables here.
        }
        
        return self;
    }
22. An init method should assign self to the result of calling the superclass's initialization method before doing
    its own initialization. A superclass may fail to initialize the object correctly and return nil. so you should
    always check to make sure self is not nil before performing your own initialization.
23. Should decide which method is the designated initializaer. This is often the method that offers the most options
    for initialization (such as the method with the most arguments)
24. Should call the superclass's designated initializer (in place of [super init];) before doing any of your own initialization.
25. You can implement custom accessor methods which is not backed by their own instance variables. like:
    @property (readonly) NSString *fullname;
    
    - (NSString *)fullName {
        return [NSString stringWithFormat: @"%@ %@", self.firstName, self.lastName];
    }
26. If need to write a custom accessor method for a property that uses an instance variable, must access the vairable directly from within the method.
    like this "lazy initialize method":
    - (XYZObject *)someImportantObject {
        if(!_someImportantObject) {
            _someImportantObject = [[XYZObject alloc] init];
        }
        return _someImportantObject;
    }
27. The compiler will not synthesize an instance variable automatically if both getter and setter for a readwrite property or a getter for a readonly 
    property are implemented by you.
28. Properties are atomic by default, the synthesized accessors ensure that a value is always fully retrieved by the getter method or fully set
    via the setter method.
29. It's not possible to combine a synthesized accessor with an accessor method that you implement yourself, for example, to provide a custom setter
    for an atomic, readwrite property but leave the compiler to synthesize the getter.
30. If property has a "nonatomic" attribute, it's not thread safe, but it's faster to access a nonatomic property, and it's fine to combine a 
    synthesized setter, for example, with your own getter implementation.
31. Property atomicity is not synonymous with an object's thread safety, thing is more complicated when properties need cooperation.
32. When one object relies on other objects and effectively taking ownership of those other objects, the first object is said to have strong references
    to the other objects. an object is kept alive as long as it has at least one strong reference to it from another object.
33. If a group of objects is connected by a circle of strong relationships, they keep each other alive even if there are no strong references from 
    outside of the group, we should avoid the strong reference cycles.
34. One way to break the strong reference cycle is to subsitute one of the strong references for a weak reference.A week reference does not
    imply ownership or responsibility between two objects, and does not keep an object alive.  
35. To declare a weak reference, add an attribute of (weak) to the property, like this:
    @property (weak) id delegate;
36. If you don't want a variable to maintain a strong reference (which is default behaviour), you can declare it as __weak, like this:
    NSObject * __weka weakVariable;
37. Weak variables can be a source of confusion, particularly in code like this:
    NSObject * __weak someObject = [[NSObject alloc] init];
    in this example, the newly allocated object has no strong reference to it, so it is immediately deallocated and someObject is set to nil.
38. It's important to consider the implications of a method that needs to access a weak property several times, like this:
    - (void) someMethod {
        [self.weakProperty doSomething];
        ...
        [self.weakProperty doSomethingElse];
    }
    in this case, we should cache the weak property in a strong variable to ensure it is kept in memory as long as you need to use it.
    - (void) someMethod {
        NSObject *cachedObject = self.weakProperty;
        [cachedObject doSomething];
        [cachedObject doSomethingElse];
    }
    
39. It's important to keep in mind if you need to make sure a weak property is not nil before using it, it's not enough just to test it, like this:
    if (self.someWeakProperty) {
        [someObject doSomethingImportantWith:self.someWeakProperty];
    }
    because in a multi-threaded application, the property may be deallocated between the test and the method call, rendering the test useless.
    should to declare a strong local variable to cache the value instead, like this:
    NSObject *cachedObject = self.someWeakProperty;     //lock it
    if (cachedObject) {
        [someObject doSomethingImportantWith:cachedObject];
    }
    cachedObject = nil;
40. There are some classes in Cocoa and Cocoa Touch that don't yet support weak references, should use unsafe reference instead, like this
    @property (unsafe_unretained) NSObject *unsafeProperty;
    for variables, need to use __unsafe_unretained:
    NSObject * __unsafe_unretained unsafeReference;
    why it's call unsafe is because it won't be set to nil if the destination object is deallocated, so it's dangling.
41. The "copy" attribute. used for object to keep its own copy of any objects that are set for its properties.
    example:
    @interface XYZBadgeView: NSView
    @property NSString *firstName;
    @property NSString *lastName;
    @end
    Two NSString properties are declaredd, which both maintain implicit strong references to their objects.
    When another object create a string to set as one of the badge view's properties, like this:
    NSMutableString *nameString = [NSMutableString stringWithString:"John"];
    self.badgeView.firstName = nameString;
    then..
    [nameString appendString:@"ny"];
    the firstName property of badgeView is now "johnny" because the mutable string was changed.
    to avoid such case, add (copy) attribute to the properties, like this:
    @interface XYZBadgeView: NSView
    @property (copy) NSString *firstName;
    @property (copy) NSString *lastName;
    @end  
42. Any object that wish to set for a copy property must conform to the NSCopying protocol.
43. If need to set a copy property's instance variable directly, for example in an initializer method,
    don't forget to set a copy of the original object:
    ...
    self = [super init];
    if (self) {
        _instanceVariableForCopyProperty = [aString copy];
    }
    return self;
    ...
44. Categories add methods to existing classes:
    @interface ClassName (CategoryName)
    @end
    
45. At runtime, there's no difference between a method added by a category and one that is implemented by the original class.
46. A category is usually declared in a separated header file and implemented in a separate source code file.
47. As well as just adding methods to existing classes, you can also use categories to split the implementation of a complex class
    across multiple source code files.
48. Categories are not usually suitable for declaring additional properties. it's not possible to declare an additional instance variable in 
    a category.
49. In order to avoid undefined behavior, it's best practice to add a prefix to method names in cateogories on framework classes.
50. Class extensions extend the internal implementation.
    The methods declared by a class extension are implemented in the @implementation block for the original class.
51. The syntax to declare a class extension is similar to category:
    @interface ClassName ()
    @end
    that's why it's also called "anonymous categories"
52. Unlike regular categories, a class extension can add its own properties and instance variables to a class.
53. Class extensions are often used to extend the public interface with additional private methods or properties for use within the implementation
    of the class itself. for example, to define a property as readonly in the interface, but as readwrite in a class extension declared above
    the implementation, in order that the internal methods of the class can change the property value directly (in implementation file!)
    example:
    @interface XYZPerson: NSObject
    ...
    @property (readonly) NSString *uniqueIdentifier;
    - (void) assignUniqueIdentifier;
    @end
    this means it's not possible to change the property from other object directly through the property itself.
    in order for the XYZPersion class to be able to change the property internally, it make sense to redeclare it in a class extension:
    @interface XYZPerson ()
    @property (readwrite) NSString *uniqueIdentifier;
    @end
    @implementation XYZPerson
    ...
    @end
    
    this means that the compiler will now also synthesize a setter method, so any method inside the XYZPerson implementation will be able
    to set the property directly using either the setter or dot syntax.
    and because it's defined in implementation file, it means it's private.
54. It's common to have two header files for a class, for example,
    XYZPerson.h and XYZPersonPrivate.h, when you release the framework, only the public XYZPerson.h header file is released.
55. Other options for class customization:
    (1) leverage inheritance and leave the decisions in methods specifically designed to be overridden by subclasses.
    (2) use a delegate object, any decision that might limit resusablity can be delegated to another object, which is left to make those 
        decisions at runtime.
    (3) interact directly with the object-c runtime, such as adding "associative references" to an object.
56. Protocol, is used to declare methods and properties that are independent of any specific class.
    @protocol ProtocolName
    //list of methods and properties
    @end
    Protocols can inlcude declarations for both instance methods and class methods, as well as properties.
57. Delegate and data source properties are usually marked as weak for object graph management reasons.
58. Protocols can have optional methods
    @protocol DataSource
    - (NSUInteger)numberOfSegments;
    ...
    @optional
    - (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;
    @required
    - ...
    @end
59. Check the optional methods are implemented at runtime:
    if( [self.dataSource respondsToSelector:@selector(titleForSegmentAtIndex:)] {
    ...
60. Protocols inherit from other protocols:
    @protocol MyProtocol <NSObject>
    ...
61. Conforming to protocol:
    @interface MyClass: NSObject <MyProtocol>
    ...
    @end
62. Adopt multiple protocols:
    @interface MyClass: NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol>
    ...
    @end
    be aware, if there are too many protocols adopted in a class, it's a sign of bad design.
63. Some protocols are used to indicate non-hierarchical similarities between classes.
64. Protocols are also useful in situations where the class of an object isn't known, or needs to stay hidden.
65. Some types like NSInteger and NSUInteger, are defined differently depending on the target architecture.
    it's best practice to use these platform-specific types if you might be passing values across API boundaries.
66. C structures can hold primitive values.
67. Strings are represented by instances of the NSString class
    NSString *str = @"Hello, World!";
68. The basic NSString class is immutable.
69. The NSMutableString class is the mutable subclass of NSString.
70. Numbers of represented by instances of the NSNumber class.
    it's possible to create NSNumber instances using Objective-C literal syntax:
    NSNumber *magicNumber = @42;
    it's possible to request the scalar value using one of the accessor methods:
    int scalarMagic = [magicNumber intValue];
    note:  NSNumber is actually a class cluster.
    NSNumber class is itself a subclass of the basic NSValue, NSValue can also be used to represent pointers and structures.
   
71. @encode compiler directive:
    typedef struct {
        int i;
        float f;
    } MyIntegerFloatStruct;
    struct MyIntegerFloatStruct aStruct;
    aStruct.i = 42;
    aStruct.f = 3.14;
    
    NSValue *structValue = [NSValue value:&aStruct
                                withObjCType:@encode(MyIntegerFloatStruct)];
72. Most collections are objects. 
    collection classes use strong references to keep track of their contents.
73. NSArray, NSSet and NSDictionary classes are immutable, each has a mutable subclass to allow you to add or remove objects at will.
74. NSArray is used to represent an ordered collection of objects, the only requirement is that each item is an Objective-C object.
75. The arrayWithObjects: and initWithObjects: methods both take nil-terminated, variable number of arguments.
    It's possible to truncate the list of items unintentionally if one of the provided values is nil.
76. It's possible to create an array using the Objective-C literal like this:
    NSArray *someArray = @[firstObject, secondObject, thirdObject];
    SHOULD NOT terminate the list of objects with nil when using this literal syntax.
    if you do need to represent a nil value in it, should use the NSNull singleton class.
77. When try to access item of array using "objectAtIndex" method, should always check the number of items first:
    if([someArray count] > 0) {
        NSLog(@"First item is: %@", [someArray objectAtIndex:0]);
    }
78. NSArray class offers methods to sort its collected objects, because it is immutable, each of these methods returns
    a new array containing the items in the sorted order.
79. Usage of NSMutableArray:
    NSMutableArray *mutableArray = [NSMutableArray array];
    [mutableArray addObject: @"gamma"];
    ...
    [mutableArray replaceObjectAtIndex:0 withObject:@"epision"];
80. Sort a mutable array in place, without creating a secondary array:
    [mutableArray sortUsingSelector:@selector(caseInsensitiveCompare:)];
81. Sets are unordered collections, they don't maintain order, and offer a performance improvement.
82. As with NSArray, the iniWithObjects: and setWithObjects: methods of NSSet both take a nil-terminated, variable number of arguments.
    The mutable NSSet subclass is NSMutableSet.
83. About NSDictionary, it's best practice to use string objects as dictionary keys.
84. Creating dictionaries:
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
        someObject, @"anObject",
        @"Hello, World!", @"hellowString",
        @42, @"magicNumber",
        someValue, @"aValue",
        nil];
    each object is specified before its key, and the list of objects and keys must be nil-terminated.
objectAtIndex" method, should always check the number of items first:
    if([someArray count] > 0) {
        NSLog(@"First item is: %@", [someArray objectAtIndex:0]);
    }
85. Like NSArray, NSDictionary also can be created in a literal form:
    NSDictionary *dictionary = @{
        @"anObject": someObject,
        @"helloString": @"Hello, World!",
        @magicNumber": @42,
        @"aValue": someValue
    };
    and with out nil-terminated,  the structure is just like Javascript object definition.
86. Query dictionary:
    NSNumber *storedNumber = [dictionary objectForKey:@"magicNumber"];
    if the object isn't found, nil will be returned.
    we can also use subscript syntax alternative like this:
    NSNumber *storedNumber = dictionary[@"magicNumber"];
87. Mutable version:  NSMutableDictionary
    [dictionary setObject:@another string" forKey:@"secondString"];
    [dictionary removeObjectForKey:@"anObject"];
88.Representing nil with NSNull
    NSArray *array = @[@"string", @42, [NSNull null]];
89. The NSArray and NSDictionary classes make it easy to write their contents directly to disk like this:
    NSURL *fileURL = ...
    NSArray *array = @[@"first", @"second", @"third"];
    BOOL success = [array writeToURL:fileURL atomically:YES];
    if(!success) {
        //an error occured
    }
    if every contained object is one of the property list types( NSArray, NSDictionary, NSString, NSData, NSDate and NSNumber),
    it's easy to recreate the entire hierarchy from disk:
    NSURL *fileURL = ...
    NSArray *array = [NSArray arrayWithContentsOfURL:fileURL];
    if(!array) {
        //an error occured
    }
90. If need to persist other types of objects, we can use an archiver object such as NSKeyedArchiver, the only requirement to 
    create an archive is that each object must support the NSCoding protocol.
91. Many collection classes conform to the NSFastEnumeration protocol, including NSArray, NSSet and NSDictionary, syntax:
    for (<type> <variable> in <colleciton>) {
        ...
    }
92. If you use fast enumeration with a dictionary, you iterate over the dictionary keys like this:
    for( NSString *eachKey in dictionary) {
        id object = dictionary[eachKey];
        NSLog(@"Object: %@ for key: %@", object,eachKey);
    }
93. You cannot mutate a collection during fast enumeration.
94. It's also possible to enumeratemany Coca and Cocoa Touch collections by using an NSEnumerator object.
    for (id eachObject in [array reverseObjectEnumerator]) {
        ...
    }
95. It's also possible to iterate through the contents by calling the enumerator's nextObject method repeatedly like this:
    id eachObject;
    while ( (eachObject = [enumerator nextObject]) ) {
        NSLog(@"Current object is: %@", eachObject);
    }
96. Because it's a common programmer error to use the C assignment operator (=) when you mean the quality test operator (==), 
    the compiler will warn you if you set a variable in a conditional branch or loop, like this:
    if (someVariable = YES) {
        ...
    }
    if you really want to do this,  indicate this by placing the assignment in parentheses like this:
    if ( (someVariable = YES ) ) {
        ...
    }
97. Many collections support block-based enumeration.
98. Blocks are like closures or lambdas in other programming language.
99. Syntax of blocks:
    ^{
        NSLog(@"This is a block");
    }
100.You can declare a variable to keep track of a block, like this:
    void (^simpleBlock)(void);
    the same syntax as function pointers:)
101.Block can operate just like a method, can have arguments and return value:
    ^ double (double firstValue, double secondValue) {
        return firstValue * secondValue;
    }
102.Blocks can capture values from the enclosing scope
    - (void)testMethod {
        int anInteger = 42;
        void (^testBlock)(void) = ^{
            NSLog(@"Integer is: %i", anInteger);
        };
        testBlock();
    }
103.The block cannot change the value of the original variable, or even the captured value (it's captured as a const variable)
104.Use __block variables to share storage:
    if you need to be able to change the value of a captured variable from within a block, use __block storage type modifier on the original
    variable declaration like this:
    
    __block int anInteger = 42;
    void (^testBlock)(void) = ^{
        NSLog(@"Integer is: %i", anInteger);
    }
    anInteger = 84;
    testBlock();
105.You can pass blocks as arguments to methods or functions, an simplify some tasks:
   - (IBAction)fetchRemoteInformation:(id)sender {
        [self showProgressIndicator];
        
        XYZWebTask *task = ...
        
        [task beginTaskWithCallbackBlock:^{
            [self hideProgressIndicator];
        }];
    }
    It's important to take care when capturing "self" because it's easy to create strong reference cycle.
106.A block should always be the last argument to a method.
107.We can use type definition to simplify block syntax, like this:
    typedef void (^XYZSimpleBlock)(void);
108.We can use properties to keep track of blocks, like this:
    @interface XYZObject: NSObject
    @property (copy) void (^blockProperty)(void);
    @end
109.It's possible to use type definition for block property declarations, like this:
    typedef void (^XYZSimpleBlock)(void);
    
    @interface XYZObject: NSObject
    @property (copy) XYZSimpleBlock blockProperty;
    @end
110.To avoid strong reference when capturing "self" in block, should use weak reference like this:
    - (void)configureBlock {
        XYZBlockKeeper * __weak weakSelf = self;
        self.block = ^{
            [weakSelf doSomething];
        }
    }
111.Blocks can simplify iteration:
    NSArray *array = ...
    [array enumerateObjectsUsingBlock:^ (id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"Object at index %lu is %@", idx, obj);
    }];
112.If the code in the enumeration block is process-intensive--and safe for concurrent execution-- can use this:
    [array enumerateObjectsWithOptions:NSEnumerationConcurrent
        usingBlock:^ (id obj, NSUInteger idx, BOOL *stop) {
        ...
    }];
113.Block based method in NSDictionary:
    NSDictionary *dictionary = ...
    [dictionary enumerateKeysAndObjectsUsingBlock:^ (id key, id obj, BOOL *stop) {
        NSLog(@"key:%@, value: %@", key, obj);
    }];
114.Blocks can simplify concurrent tasks, you can create NSOperation instance to encapsulate a unit of work along with
    any neccessary data, the add that operation to an NSOperationQueue for execution.
    although you can create your own custom NSOperation subclass to implement complex tasks, it's also possible to use
    the NSBlockOperation to create an operation using a block, like this:
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        ..
    }];
115.Queue:
    //schedule task on main queue:
    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
    [mainQueue addOperation:operation];
    //schedule task on background queue:
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];
116.Schedule blocks on dispatch queues with Grand Central Dispatch:
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        NSLog(@"Block for asynchronous execution");
    });
117.Only programming error using exception, all other errors are represented by instances of the NSError class.
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
    rather than making the requirement that every possible error have a unique numeric code, Cocoa and CocoaTouch 
    errors are divided into domains.
    example, the connection:didFailWithError: method above will privide an error from NSURLErrorDomain.
    the error object also incudes a localized description.
118.Some Methods pass errors by reference:
    - (BOOL)writeToURL:(NSURL *)aURL
        options:(NSDataWritingOptions)mask
        error:(NSError **)errorPtr;
    //invoke
    NSError *anyError;
    BOOL success = [receivedData writeToURL:someLocalFileURL
                        options:0
                        error:&anyError];
    if(!success) {
        NSLog(@"Write failed with error: %@", anyError);
        //present errors to user
    }
119.It's important to test the return value of the method to see whether an error occured, don't just test whether the
    error pointer was set to point to an error, it's not reliable.
120.Create your own errors:
    first you need to define your own error domain, like this:
    com.companyName.appOrFrameworkname.ErrorDomain
    you'll also need to pick a unique error code for each error that may occur in your domain, along with a suitable
    description, which is stored in the user info dictionary for the error, like this:
    NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain";
    NSString *desc = NSLocalizedString(@"Unable to...", @"");
    NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: desc };
    NSError *error = [NSError errorWithDomain:domain
                    code:-101
                    userInfo:userInfo];
121.If you need to pass back an error by reference as describe above your method signature should include a parameter for
    a pointer to a pointer to an NSError object. should also use the return value to indicate success or failure, like this:
    - (BOOL)doSomethingThatMayGenerateAnError:(NSError **)errorPtr {
        ...
        //error occured
        if (errorPtr) {
            *errorPtr = [NSError errorWithDomain:...
                                code:...
                                userInfo:...];
        }
        return NO;
    }
122.Exceptions are used for programming errors:
    @try {
        //do something that might throw an exception
    }
    @catch (NSException *exception) {
        //deal with the exception
    }
    @finally {
        //optional block of clean-up code
    }
123.Some naming conventions:
    NS -- Foundation (OSX and iOS) and Application Kit(OSX)
    UI -- UIKit (iOS)
    AB -- Address Book
    CA -- Core Animation
    CI -- Core Image
124.Method names do not have a prefix, and should start with a lowercase letter; camel case is used again for multiple words.
125.If a method includes an error pointer parameter to be set if an error occurred, this should be the last parameter to the method.
126.Accessor method names must follow conventions, the compiler automatically synthesizes the relevant getter and setter methods,
    a getter method should use the same name as property, the exception to this rule is for Boolean properties, for which the getter
    method should start with is.
127.the setter method for a property should use the form setPropertyname:
128.Althoug the @property syntax allows you to specify different accessor method names, you should only do so for situations like
    a Boolean property. It's essential to follow the conventions described here, otherwise technques like Key Value Coding won't work.
129.Class factory methods should always start with the name of the class (without the prefix) that they create, with the exception
    of subclasses of classes with existing factory methods. for example, NSArray, the factory methods start with array.
    the NSMutableArray class doesn't define any of its own class-specific factory methods, so the factory methods for a mutable array 
    still begin with array.

posted @ 2013-08-04 21:01 Tommy Liang 阅读(455) | 评论 (0)编辑 收藏

2013年1月19日

资料转自网络:
原文在此: http://www.qtcn.org/bbs/simple/?t52158.html

1  安装vs2012 update1

2  下载qt5源码包,记住,windows下要下载zip结尾的,不要看到tar.gz的小就下它,tar.gz的源码包不能直接在windows下编译

编译

1) 我要编译x86, 所以打开vc x86命令提示符,其他版尚未成功

2) cd <path>\qt-everywhere-opensource-src-<version>
   configure -prefix %CD%\qtbase -opensource -nomake tests -nomake examples -mp

   如果想编译例子,可以去掉-nomake examples

3) 执行nmake 开始编译。

posted @ 2013-01-19 13:23 Tommy Liang 阅读(2122) | 评论 (0)编辑 收藏

2012年12月29日

摘自 《The Boost Graph Library》
代码示例在 vc2012下编译通过。

图类与适配器

1.类

adjacency_list 用于稀疏图,用例如下:
#include <iostream>
#include <vector>
#include <string>
#include <boost/graph/adjacency_list.hpp>
#include <boost/tuple/tuple.hpp>

enum family { Jeanie, Debbie, Rick, John, Amanda, Margaret, Benjamin, N };

int main()
{
    using namespace boost;
    const char *name[] = {"Jeanie", "Debbie", "Rick", "John", "Amanda", "Margaret", "Benjamin"};
    adjacency_list<> g(N);
    add_edge(Jeanie,Debbie,g);
    add_edge(Jeanie,Rick,g);
    add_edge(Jeanie,John,g);
    add_edge(Debbie,Amanda,g);
    add_edge(Rick,Margaret,g);
    add_edge(John,Benjamin,g);

    graph_traits<adjacency_list<> >::vertex_iterator i,end;
    graph_traits<adjacency_list<> >::adjacency_iterator ai,a_end;
    property_map<adjacency_list<>,vertex_index_t>::type index_map = get(vertex_index,g);

    for(tie(i,end) = vertices(g); i != end; ++i) {
        std::cout << name[get(index_map,*i)];

        boost::tie(ai,a_end) = adjacent_vertices(*i, g);
        if(ai == a_end)
            std::cout << " has no children.";
        else
            std::cout << " is the parent of "; 
        for(; ai != a_end; ++ai) {
            std::cout << name[get(index_map, *ai)];
            if(boost::next(ai) != a_end)
                std::cout << ", ";
        }
        std::cout << std::endl;
    }
    return EXIT_SUCCESS;
}  


2. 拓扑排序算法

#include <deque>
#include <vector>
#include <list>
#include <iostream>
#include <boost/graph/vector_as_graph.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/graph/adjacency_list.hpp>

int main()
{
    using namespace boost;

    const char *tasks[] = {
        "pick up kids from school",
        "buy groceries snacks",
        "get cash at ATM",
        "drop off kids at soccer practice",
        "cook dinner",
        "pick up kids from soccer",
        "eat dinner",
        "before drop off"
    };
    const int n_tasks = sizeof(tasks) / sizeof(char*);
    /*
    std::vector<std::list<int> > g(n_tasks);
    g[0].push_back(3);
    g[1].push_back(3);
    g[1].push_back(4);
    g[2].push_back(1);
    g[3].push_back(5);
    g[4].push_back(6);
    g[5].push_back(6);
    
*/
    adjacency_list<listS,vecS,directedS> g(n_tasks);
    add_edge(7,3,g);

    add_edge(0,3,g);
    add_edge(1,3,g);
    add_edge(1,4,g);
    add_edge(2,1,g);
    add_edge(3,5,g);
    
    add_edge(5,6,g);
     
    add_edge(4,6,g);
    

    //perform the topological sort and output the result
    std::deque<int> topo_order;
    topological_sort(g, std::front_inserter(topo_order),
        vertex_index_map(identity_property_map()));
    int n = 1;
    for(std::deque<int>::iterator i=topo_order.begin();
        i != topo_order.end(); ++i, ++n)
        std::cout << tasks[*i] << std::endl;

    return EXIT_SUCCESS;
}

今天还学习了 BCCL 库,即  Boost concept check library, 检查模型是否满足模板要求并提供较精准的编译错误信息。

关于如何存取BGL的算法: 应加boost前缀,如 boost:breadth_first_search

posted @ 2012-12-29 20:17 Tommy Liang 阅读(533) | 评论 (0)编辑 收藏

2012年5月24日

I need to package PyQt program to windows executable file, there's Alchemy library used.
when "setup.py" file prepared and run, "No module named Alchemy" encountered.

so trace to mf.py file, py2exe just parse the lib directory to find modules, so I checked python27 folder,
in the lib directory, there's no sqlalchemy found, so i decide to download the sources of sqlalchemy,
check the site and several steps needed:

1. download Mercurial and install it.
2. use Mercurial to clone sqlalchemy's source
3. copy the module source folder (with __init__.py inside) to python27/lib/, like this: c:\python27\lib\sqlalchemy

now run setup.py again, problem resolved.

posted @ 2012-05-24 15:16 Tommy Liang 阅读(361) | 评论 (0)编辑 收藏

2012年4月19日

Syntax best practice:
  • List Comprehensions
    >>> [i for i in range(10if i % 2 == 0]

    Enumeration:
    >>> def _treatment(pos, element):
     return '%d: %s' % (pos, element)

    >>> seq = ["one""two""three"]
    >>> [_treatment(i, el) for i, el in enumerate(seq)]
    ['0: one''1: two''2: three']

    Iterators and Generators
    >>> def fibonacci():
     a, b = 0, 1
     while True:
     yield b  # 这里返回 generator,一个特殊的iterator
     a, b = b, a + b

    >>> fib = fibonacci()
    >>> fib.next()
    1
    >>> fib.next()
    1
    >>> fib.next()
    2
    >>> [fib.next() for i in range(10)]
    [3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
    generators should be considered every time you deal with a
    function that returns a sequence or works in a loop;
    It is better to have a lot of simple iterable functions that work over
    sequences of values than a complex function that computes the result for
    one value at a time.
    >>> def my_generator():
     try:
     yield 'something'
     except ValueError:
     yield 'dealing with the exception'
     finally:
     print "ok let's clean"

    >>> gen = my_generator()
    >>> gen.next()
    'something'
    >>> gen.throw(ValueError('mean mean mean'))
    'dealing with the exception'
    >>> gen.close()
    ok let's clean
    >>> gen.next()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    StopIteration

posted @ 2012-04-19 02:09 Tommy Liang 阅读(308) | 评论 (0)编辑 收藏

2012年3月23日

http://codebetter.com/jeremymiller/2007/07/06/build-your-own-cab-13-embedded-controllers-with-a-dash-of-dsl/ 

posted @ 2012-03-23 14:51 Tommy Liang 阅读(202) | 评论 (0)编辑 收藏

2011年11月22日

<script language=javascript>
function ceil(number,significance){
if(significance){
return Math.ceil(number/significance) * significance;
}
return Math.ceil(number);
}
document.write(ceil((2025.4/(2000+2*19.05-12.7)).toFixed(3),1));
document.write("<br/>");
document.write(ceil(2.98,2));
</script>

note:  ceil((2025.4/(2000+2*19.05-12.7)),1) = 2, because of float problem, toFixed(prec) fix the problem.

posted @ 2011-11-22 18:16 Tommy Liang 阅读(324) | 评论 (0)编辑 收藏

2011年11月11日



Hmm the output from the system monitor is weired, you can’t have a process not using memory at all (the virtual memory is huge but matches with the way you configured your VM).

 

I advise you to use “top” in a terminal, as root, to get some reliable info.

Concerning your performance problem, you should not swap within the virtual machine with such an impressive of allocated memory.

How much physical memory do you have ? Maybe, the problem is that your machine lacks of memory and makes your Ubuntu swapping…

To boost performance, I use the following settings :

(1) in the options of VMWare, I deactivate “taking snapshots in the background” and, in the memory section, I force all the virtual memory to fit in the available physical memory (no swap)

(2) I also adjust the swappiness parameter of the linux kernel.

By default, the linux kernel uses quite often the swap even if you still have plenty of free memory.

You can change this behaviour with this command :
echo “15″ > /proc/sys/vm/swappiness

I use “15″, which gives a pretty high priority to the physical memory, before the kernel uses the swap. By default, the value is 60. The higher, the more it will use the swap.

After testing, you can make it permanent by adding such a line at the end of /etc/sysctl.conf :

vm.swappiness = 15

(3) I would, anyway, just try to reduce the memory amount you allocate to you VM. Just in case.

(4) Also check the processes runing on your XP when it is slow ! Are you sure that your Windows image did not get infected by some trojan or virus ?

(5) For graphics, did you set up VMWare tools ?

posted @ 2011-11-11 07:02 Tommy Liang 阅读(263) | 评论 (0)编辑 收藏

2011年11月3日

here is the screen capture video demo: 
http://youtu.be/CO0mHBMWmmg

Qt/OpenGL UI imitate UNITY

Dynamic 3D view control

Easy to rotate (yaw/pitch) parts with mouse left button and pan with right button. With the mouse wheel you can scale it and double clicking to locate the central point of the view;

Easy manipulate apparatus

Rotate or move individual parts with mouse, the parts can move correctly according to the joint relations, current support pairs: prismatic-pair and revolute-turning-pair;

Free room dimension set up

rooms width、length、height and other parameters can be manually setup and modified;



Parts Library

Apparatus parts can be dragged from the parts library into the 3D scene, and assembled to the anchor points of the pre-assembled parts; assembled parts are removable;



· Part joints dynamically changed 

Change the part joints motion-constraint-parameters dynamically, like the hanging arms rotation angle range, i.e. change it from 360 degree to 90 degree, the scene will respond the changed data immediately;



· Collision detection

If the apparatus collide with each other or the room’s walls, it will turn red to indicate the collision occurring as to adjust the equipments position;



· Real-time dimension measure

User can switch to Dimension measure mode to measure chosen points from apparatus to the wall/floor/ceiling or points on the other apparatus, when press Ctrl
the scene will enter 
transparency dimension measure mode, when user move or rotate the apparatus parts, related dimension numbers will change accordingly;



· Apparatus library management

user can manage the parts category hierarchy as deep as needed; support OBJ file imported into the library and preview; user can manage the parts motion-pair parameter dynamically;

· Data export

Scene can be saved as project file and reopen; the structure of the scene including all the apparatus parameters can be exported to word/excel files; the scene can also be exported to 
an independent window
s executable file (exe, prototype written with MFC), when opened, user can also control the scene and the apparatus without CMaxSpore product installed;
The exported executable support only observation but not parameter manipulation;



Technical Key points

· Qt library (open source version)

· OpenGL

· Computer graphics

· OOA,OOD

· Multi-threading

· MFC/Win32 SDK

Constructing features

NVidia Optix-Real-time-ray-tracing engine embed 



Exploring ideas

· Import rooms from AutoCAD DWG file; (AutoCAD API/Pattern recognition)

· Export scene to AutoCAD DWG file directly;

· JavaScript engine embed;

· Apparatus parts data network storage and multiple-user rights control;

· I18;

· Augmented reality support;

· Flash publishing

 

 

posted @ 2011-11-03 11:14 Tommy Liang 阅读(373) | 评论 (0)编辑 收藏