SlideShare a Scribd company logo
1 of 55
openFrameworks
      utils
Utils

    date        screenshots       noise

list helpers   remote loading   logging

  string         threading      file utils
manipulation    system tools    constants
date

       int ofGetSeconds()          Get seconds of current time
       int ofGetMinutes()           Get minutes of current time
        int ofGetHours()             Get hours of current time
        int ofGetYear()                  Get current year
       int ofGetMonth()                 Get current month
         int ofGetDay()                  Get current day
       int ofGetWeekDay                Get current weekday
 unsigned int ofGetUnixTime()         Timestamp since 1970
unsigned long ofGetSystemTime()        System time in millis
string ofGetSystemTimeMicros()        System time in micros
 string ofGetTimestampString()    Timestamp since 1970 as string
list helpers
Remove items from a vector.
       void ofRemove(vector<T>&, BoolFunction shouldErase)




                   Step 1. Create a custom remove functor

                   class MyOwnRemover{
                   public:
                   
 bool operator()(const string& str) {
                   
 
     return str == "roxlu";
                   
 }
                   };
list helpers

void ofRemove(vector<T>&, BoolFunction shouldErase)


    Step 2. use ofRemove with remove functor
    void testApp::setup(){

    
   // create list with strings.
    
   vector<string> mystrings;
    
   mystrings.push_back("diederick");
    
   mystrings.push_back("openframeworks");
    
   mystrings.push_back("supercool");
    
   mystrings.push_back("roxlu");
    
   mystrings.push_back("do not remove");
    
   mystrings.push_back("roxlu");
    
    
   // show before removing items.
    
   for(int i = 0; i < mystrings.size(); ++i) {
    
   
     cout << "before: " << mystrings[i] << endl;
    
   }
    
   cout << "=======" << endl;
    
    
   // remove items using my own remover!
    
   ofRemove(mystrings, MyOwnRemover());
    
   for(int i = 0; i < mystrings.size(); ++i) {
    
   
     cout << "after: " << mystrings[i] << endl;
    
   }
    }
Summary ofRemove                                                      list helpers

                   void ofRemove(vector<T>&, BoolFunction shouldErase)


class MyOwnRemover{                         void testApp::setup(){
public:

 bool operator()(const string& str) {      
   // create list with strings.

 
     return str == "roxlu";              
   vector<string> mystrings;

 }                                         
   mystrings.push_back("diederick");
};                                          
   mystrings.push_back("openframeworks");
                                            
   mystrings.push_back("supercool");
                                            
   mystrings.push_back("roxlu");
                                            
   mystrings.push_back("do not remove");
                                            
   mystrings.push_back("roxlu");
                                            
                                            
   // show before removing items.
                                            
   for(int i = 0; i < mystrings.size(); ++i) {
 Result                                     
                                            
                                                
                                                }
                                                      cout << "before: " << mystrings[i] << endl;

 before: diederick                          
   cout << "=======" << endl;
 before: openframeworks
 before: supercool                          
 before: roxlu
 before: do not remove
                                            
   // remove items using my own remover!
 before: roxlu                              
   ofRemove(mystrings, MyOwnRemover());
 =======
 after: diederick                           
   for(int i = 0; i < mystrings.size(); ++i) {
 after: openframeworks                      
   
     cout << "after: " << mystrings[i] << endl;
 after: supercool
 after: do not remove                       
   }
                                            }
Randomize a vector                                           list helpers

                              void ofRandomize(vector<T>&)


void testApp::setup(){


   // create list with strings.

   vector<string> mystrings;

   mystrings.push_back("diederick");

   mystrings.push_back("openframeworks");                   Result

   mystrings.push_back("supercool");
                                                             random:   roxlu

   mystrings.push_back("roxlu");
                                                             random:   roxlu

   mystrings.push_back("do not remove");
                                                             random:   supercool

   mystrings.push_back("roxlu");
                                                             random:   openframeworks
                                                             random:   do not remove

   ofRandomize(mystrings);
                                                             random:   diederick

   // show before removing items.

   for(int i = 0; i < mystrings.size(); ++i) {

   
     cout << "random: " << mystrings[i] << endl;

   }
}
Sort a vector                                                list helpers

                                   void ofSort(vector<T>&)


void testApp::setup(){


   // create list with strings.

   vector<string> mystrings;

   mystrings.push_back("diederick");

   mystrings.push_back("openframeworks");                   Result

   mystrings.push_back("supercool");
                                                             sorted:   diederick

   mystrings.push_back("roxlu");
                                                             sorted:   do not remove

   mystrings.push_back("do not remove");
                                                             sorted:   openframeworks

   mystrings.push_back("roxlu");
                                                             sorted:   roxlu
                                                             sorted:   roxlu

   ofSort(mystrings);
                                                             sorted:   supercool

   // show before removing items.

   for(int i = 0; i < mystrings.size(); ++i) {

   
     cout << "sorted: " << mystrings[i] << endl;

   }
}
Find entry in vector                                          list helpers

                  unsigned int ofFind(vector<T>&, const T& target)




void testApp::setup(){

 vector<string> mystrings;

 mystrings.push_back("diederick");

 mystrings.push_back("openframeworks");                      Result

 mystrings.push_back("supercool");

 mystrings.push_back("roxlu");                               do not remove <--

 mystrings.push_back("do not remove");

 mystrings.push_back("roxlu");


 string fstr = "do not remove";

 unsigned int num_found = ofFind(mystrings, fstr);

 if(num_found) {

 
      cout << mystrings[num_found] << " <-- “ << endl;

 }
}
Check if entry exists                                          list helpers

                     bool ofContains(vector<T>&, const T& target)





   // create list with strings.

   vector<string> mystrings;

   mystrings.push_back("diederick");

   mystrings.push_back("openframeworks");                    Result

   mystrings.push_back("supercool");

   mystrings.push_back("roxlu");
                                                              do not remove in mystrings

   mystrings.push_back("do not remove");

   mystrings.push_back("roxlu");


   string fstr = "do not remove";

   bool contains = ofContains(mystrings, fstr);

   if(contains) {

   
     cout << fstr << " in mystrings" << endl;

   }
string
                                                                 manipulation
    Split a string
    vector<string> ofSplitString(
        const string& source
       ,const string& delimiters
       ,bool ignoreEmpty = false
       ,bool trim = false
    );


                                                                  Result

   string items = "one|two|three|four|five |||test|";             part:   'one'

   vector<string> parts = ofSplitString(items,"|",true,true);     part:   'two'

   for(int i = 0; i < parts.size(); ++i) {                        part:   'three'

   
     cout << "part: '" << parts[i] << "'" << endl;            part:   'four'

   }                                                              part:   'five'

                                                                  part:   'test'
string
                                                               manipulation
    Split a string
    vector<string> ofJoinString(vector<string>, const string delim)




   vector<string> loose_parts;                                Result

   loose_parts.push_back("I");

   loose_parts.push_back("need");                             I-need-some-OF-examples!

   loose_parts.push_back("some");

   loose_parts.push_back("OF");

   loose_parts.push_back("examples!");


   string joined_string = ofJoinString(loose_parts, "-");

   cout << joined_string << endl;
string
                                                                            manipulation
Is a string in a string?
bool ofIsStringInString(string haystack, string needle)





    string haystack_str = "I'm searching for a needle in this haystack";

    if(ofIsStringInString(haystack_str, "searching")) {

    
     cout << "yes, 'searching' is in the string" << endl;

    }




    Result
    yes, 'searching' is in the string
string
                                                                  manipulation
Case conversion
string ofToUpper(const string& src)
string ofToLower(const string& src)




                  
   string str = "Just some string";
                  
   cout << ofToLower(str) << " = ofToLower" << endl;
                  
   cout << ofToUpper(str) << " = ofToUpper" << endl;




 Result
 just some string = ofToLower
 JUST SOME STRING = ofToUpper
string
                                                  manipulation
Type / hex conversion


                                          Convert int,float,uint,char,??
        string ofToString(const T&)
                                                    to string


        string ofToHex(string|char)


       int ofHexToInt(const string&)


    string ofHexToChar(const string&)


     float ofHexToFloat(const string&)


    string ofHexToString(const string&)
string
                                                 manipulation
String conversions


                                         Convert int,float,uint,char,??
       string ofToString(const T&)
                                                   to string



       int ofToInt(const string& str)        Convert string to int


     char ofToChar(const string& str)       Convert string to char


     float ofToFloat(const string& str)      Convert string to float


     bool ofToBool(const string& str)       Convert string to bool
string
                                                 manipulation
Binary utils




    string ofToBinary(const string& str)       String to binary

     int ofBinaryToInt(const string& str)    From binary to int

   char ofBinaryToChar(const string& str)    From binary to char

   float ofBinaryToFloat(const string& str)   From binary to float
screenshots
Screenshots


                                          Save what’s drawn to a file
                                         named by the current frame.
           void ofSaveFrame()
                                         The file is saved into the data
                                                   directory.



                                         Save the current screen to a
    void ofSaveScreen(string filename)
                                          file in the data directory.



   void ofSaveViewport(string filename)   Save current viewport to file
screenshots
 Screenshots



void testApp::draw(){

 // create filename (each call we increment the counter)

 static int screen_num = 0;

 ++screen_num;

 char buf[512];

 sprintf(buf,"screen_%04d.jpg",screen_num);


 // draw a simple circle at the center of screen and save it to image file.

 ofCircle(ofGetWidth() *0.5,ofGetHeight()*0.5,40);

 ofSaveScreen(buf);
}
screenshots
 Screenshots



void testApp::draw(){

 // create filename (each call we increment the counter)

 static int screen_num = 0;

 ++screen_num;

 char buf[512];

 sprintf(buf,"screen_%04d.jpg",screen_num);


 // draw a simple circle at the center of screen and save it to image file.

 ofCircle(ofGetWidth() *0.5,ofGetHeight()*0.5,40);

 ofSaveScreen(buf);
}
remote loading
Load from url (synchronous)


                         ofHttpResponse ofLoadURL(string url)



          ofHttpResponse resp = ofLoadURL("http://roxlu.com/ofloadurl.txt");
          cout << resp.data << endl;
          




Result
This is just a test!
remote loading
Load from url (async)


              int ofLoadURLAsync(string url, string name)




• Loads asynchronous
• Returns ID of process
• You need to listen for URL notifications in
  testApp::urlResponse(ofHttpResponse&)
remote loading
Asynchronous loading


 Step 1. declare urlResponse in class header which wants to get notifications


 class testApp : public ofBaseApp{
 
 public:
 
 
      void urlResponse(ofHttpResponse & response);
 }




Step 2. define urlResponse in class which wants to get notifications


void testApp::urlResponse(ofHttpResponse & response){

 if(response.status==200 && response.request.name == "async_req"){

 
      img.loadImage(response.data);

 
      loading=false;

 }

 else{

 
      cout << response.status << " " << response.error << endl;

 
      if(response.status!=-1) loading=false;

 }
}
Asynchronous loading                             remote loading



Step 3. enable URL notifications

void testApp::setup(){

 ofRegisterURLNotification(this);
}




Recap URL loading functions
ofHttpResponse ofLoadURL(string url)
int ofLoadURLAsync(string url, string name=””)
void ofRemoveURLRequest(int id)
void ofRemoveAllURLRequests()
threading




Threading in OF
• Very easy to create threads using ofThread
• Locking using lock/unlock() functions
• Easy start/stop/joining
• Just implement threadedFunction()
• I.e. used to perform background processes
threading
Creating a thread


Step 1. Create your thread class which extends ofThread

class MyCustomThread : public ofThread {
protected:

 virtual void threadedFunction() {

 
     while(true) {

 
     
   cout << "My own custom thread!" << endl;

 
     
   ofSleepMillis(3000);

 
     }

 }
};



Step 2. Create member in testApp.h

class testApp : public ofBaseApp{

 public:

 
      MyCustomThread my_thread;

 
      ...
}
threading
Creating a thread




Step 3. Start the thread by calling startThread()

void testApp::setup(){

 // creates a non-blocking thread. (not verbose)

 my_thread.startThread(false, false);
}
system tools
System tools


       void ofSystemAlertDialog(string)         Show system Alert window



 ofFileDialogResult ofSystemLoadDialog(string    Show system File Load
       windowtitle, bool folderselection)              window


 ofFileDialogResult ofSystemSaveDialog(string     Show system File Save
       defaultname, string messagename)                 window
system tools
System tools




               void testApp::setup(){
               
 ofSystemAlertDialog("Whoot! Look out!");
               }
system tools
System tools




  ofFileDialogResult dialog_result = ofSystemLoadDialog("Load image",false);
  if(dialog_result.bSuccess) {
  
 cout << "name: " << dialog_result.getName() << endl;
  
 cout << "file path: " << dialog_result.getPath() << endl;
  }
noise
Simplex noise

                                             1D, 2D, 3D and 4D
float   ofNoise(float)
                                             simplex noise.
float   ofNoise(float, float)
                                             Returns values in
float   ofNoise(float, float, float)
                                             range
float   ofNoise(float, float,float,float)
                                             0.0 - 1.0
                                             1D, 2D, 3D and 4D
float   ofSignedNoise(float)
                                             simplex noise.
float   ofSignedNoise(float, float)
                                             Returns values in
float   ofSignedNoise(float, float, float)
                                             range
float   ofSignedNoise(float, float,float,float)
                                             -1.0 - 1.0
noise
Simplex noise

                                                            float scale = 0.001;



                                                            float scale = 0.01;




                                                            float scale = 0.1;



                                                            float scale = 0.7;



            void testApp::draw(){
            
 float scale = 0.001;
            
 glBegin(GL_LINE_STRIP);
            
 for(float i = 0; i < ofGetWidth(); ++i) {
            
 
      glVertex2f(i,ofNoise(i*scale) * 50);
            
 }
            
 glEnd();
            }
logging
 Logging




• Simple logging to console or file
• Support for basic log levels
• Log level filtering
• More advanced stuff, see ofxLogger
  (file rotation)
logging
Logging

                                       Set level to log. Only this
    void ofSetLogLevel(ofLogLevel)   level will show up in console
                                                  or file

      ofLogLevel ofGetLogLevel()         Get current log level



     void ofLogToFile(string path)           Log to path



          void ofLogToConsole()        Log to console (default)
logging
Logging


                ofSetLogLevel(OF_LOG_VERBOSE);
                ofLog(OF_LOG_VERBOSE,"log something");
                ofLog(OF_LOG_VERBOSE,"Something to log");
                ofLog(OF_LOG_VERBOSE,"Something else to log");
                




Result
OF: OF_VERBOSE: log something
OF: OF_VERBOSE: Something to log
OF: OF_VERBOSE: Something else to log
logging
Logging

                                       Set level to log. Only this
    void ofSetLogLevel(ofLogLevel)   level will show up in console
                                                  or file

      ofLogLevel ofGetLogLevel()         Get current log level



     void ofLogToFile(string path)           Log to path



          void ofLogToConsole()        Log to console (default)
file utils
File utils


   ofBuffer    Raw byte buffer class


  ofFilePath   A file system path


    ofFile     File class; handy functions


 ofDirectory   Directory class; i.e. dirlists
file utils

                                                                  ofBuffer
 ofBuffer




• Allows you to store raw data
• This is useful when working on networked
    applications or hardware (arduino) when you want to
    use a custom protocol.


Two handy global functions:
ofBuffer ofBufferFromFile(const string& p, bool binary = false)
bool ofBufferToFile(const string& p, ofBuffer& buf, bool bin=false);
file utils

                                                                             ofBuffer
    ofBuffer



    string data = "This isnjust a bunchnof rawndata withn somenline breaks.";

    ofBuffer buffer;

    buffer.set(data.c_str(), data.size());

    while(!buffer.isLastLine()) {

    
    cout << "Buffer line: " << buffer.getNextLine() << endl;

    }




    Result
    Buffer   line:   This is
    Buffer   line:   just a bunch
    Buffer   line:   of raw
    Buffer   line:   data with
    Buffer   line:    some
    Buffer   line:   line breaks.
file utils

                                                ofBuffer
read file into buffer

  // read from file into buffer

  ofBuffer buf = ofBufferFromFile("of.log");
  cout
 << "********"
 << endl

 
     
    << buf 

    << endl

 
     
    << "********"
 << endl;



Other functions...
void set(const char*, int size)
bool set(istream&)
bool writeTo(ostream &stream)
void clear()
void allocate(long)
char* getBinaryBuffer()
const char* getBinaryBuffer()
string getText()
string getNextLine()
string getFirstLine()
bool isLastLine()
file utils

                                         ofFilePath
 File paths




• Just easy class to play with paths
• Use this for cleaning up paths, retrieving absolute
  paths, retrieving basenames, filenames, enclosing
  directories, current working dir.

• All member functions are static
file utils

                                                                      ofFilePath
File paths
static string getFileExt(string filename)

static string removeExt(string filename)

static string addLeadingSlash(string path)

static string addTrailingSlash(string path)

static string removeTrailingSlash(string path)

static string getPathForDirectory(string path)

static string getAbsolutePath(string path, bool rel_data = true)

static bool isAbsolute(string path)

static string getFileName(string f,bool rel_data = true)

static string getBaseName(string file)
static string getEnclosingDirectory(string p, bool rel_data = true)

static string getCurrentWorkingDirectory()
file utils

                                                          ofFilePath
File paths

cout << ofFilePath::getPathForDirectory("~/Documents");
/Users/roxlu/Documents/


cout << ofFilePath::getPathForDirectory("data");
data/


string path = "/just/some/path/photo.jpg";
cout << ofFilePath::getFileExt(path);
jpg

string path = "/just/some/path/photo.jpg";
cout << ofFilePath::removeExt(path);
/just/some/path/photo


string path = "/just/some/path/photo.jpg";
cout << ofFilePath::getFilename(path) << endl;
photo.jpg
file utils

                                                             ofFilePath
File paths
string path = "/just/some/path/photo.jpg";
cout << ofFilePath::getBaseName(path) << endl;
photo


string path = "/just/some/path/photo.jpg";
cout << ofFilePath::getEnclosingDirectory(path) << endl;

/just/some/path/


cout << ofFilePath::getCurrentWorkingDirectory() << endl;
/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/
emptyExampleDebug.app/Contents/MacOS/
file utils

                                                                           ofFile
ofFile
bool open(string path, Mode m=ReadOnly, bool binary=false)

bool changeMode(Mode m, bool binary=false)


void close()                                      bool canExecute()
bool exists()                                     bool isFile()
string path()                                     bool isLink()
string getExtension()                             bool isDirectory()
string getFileName()                              bool isDevice(
string getBaseName()                              bool isHidden
string getEnclosingDirectory()                    void setWriteble(bool writable)
string getAbsolutePath()                          void setReadOnly(bool readable)
bool canRead()                                    void setExecutable(bool exec)
bool canWrite()                                   uint64_t getSize()
file utils

                                                                               ofFile

ofFile
bool copyTo(string path, bool rel_to_data = true, bool overwrite = false)
bool moveTo(string path, bool rel_to_data = true, bool overwrite = false)
bool renameTo(string path, bool rel_to_data = true, bool overwrite = false)




ofFile <> ofBuffer
ofBuffer readToBuffer()
bool writeFromBuffer(ofBuffer& buffer)
bool renameTo(string path, bool rel_to_data = true, bool overwrite = false)
file utils

                                                                                                    ofFile
ofFile - static functions


static bool copyFromTo(string src, string dest, bool rel_to_data = true, bool overwrite = false)
static bool moveFromTo(string src, string dest, bool rel_to_data = true, bool overwrite = false)
static bool doesFileExist(string path,bool rel_to_data = true)
static bool removeFile(string path,bool rel_to_data = true)
file utils

                                                           ofDirectory
ofDirectory

• Similar to ofFile
• Lots of handy function for moving, renaming,
     copying, deleting, file listing, etc...
void open(string path)               void setWriteble(bool writable)
void close()
                                     void setReadOnly(bool readable)
bool create(bool recursive = true)
bool exists()                        void setExecutable(bool exec)
string path()
                                     For more functions ofFileUtils.h
bool canRead()
bool canWrite()
bool canExecute()
bool isDirectory()
bool isHidden()
bool remove(bool recursive)
file utils

                                                                                  ofDirectory


Retrieve all jpegs from a directory
ofDirectory dir;
dir.allowExt("jpg");
int num_jpegs_in_datapath = dir.listDir(ofToDataPath(".",true));
cout << "Num files in data path : " << num_jpegs_in_datapath << endl;
for(int i = 0; i < num_jpegs_in_datapath; ++i) {

 cout << dir.getPath(i) << endl;
}




Result
/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0001.jpg
/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0002.jpg
/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0003.jpg
/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0004.jpg
/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0005.jpg
/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0006.jpg
file utils

                                                                                            ofDirectory
Some static functions



static bool createDirectory(string path, bool rel_to_data = true, bool recursive = false)

static bool isDirectoryEmtpy(string path, bool rel_to_data = true)

static bool doesDirectoryExist(string path, bool rel_to_data = true)

static bool removeDirectory(string path, bool deleteIfNotEmpty, bool bRelativeToData = true)
constants



Development        Math/Trig
OF_VERSION         HALF_PI      CLAMP(val,min,max)

OF_VERSION_MINOR   PI           ABS(x)

TARGET_WIN32       TWO_PI
                                OF_OUTLINE
TARGET_OF_IPHONE   FOUR_PI
                                OF_FILLED
TARGET_ANDROID     DEG_TO_RAD

TARGET_LINUS       RAD_TO_DEG   Window
TARGET_OPENGLES    MIN(x,y)     OF_WINDOW
                                OF_FULLSCREEN
OF_USING_POCO      MAX(x,y)
                                OF_GAME_MODE
constants


Rectangle modes        Pixel formats      Blend modes
OF_RECTMODE_CORNER
                       OF_PIXELS_MONO     OF_BLENDMODE_DISABLED

OF_RECTMODE_CENTER
                       OF_PIXELS_RGB      OF_BLENDMODE_ALPHA

                       OF_PIXELS_RGBA     OF_BLENDMODE_ADD
Image types
                       OF_PIXELS_BGRA     OF_BLENDMODE_SUBTRACT
OF_IMAGE_GRAYSCALE
                       OF_PIXELS_RGB565   OF_BLENDMODE_MULTIPLY
OF_IMAGE_COLOR

                                          OF_BLENDMODE_SCREEN
OF_IMAGE_COLOR_ALPHA

OF_IMAGE_UNDEFINED
constants


Orientations                      ofLoopType

OF_ORIENTATION_UNKNOWN            OF_LOOP_NONE

OF_ORIENTATION_DEFAULT            OF_LOOP_PALINDROME

OF_ORIENTATION_90_LEFT            OF_LOOP_NORMAL


OF_ORIENTATION_180

OF_ORIENTATION_90_RIGHT




For more defines see ofConstants
constants

Function keys                           Cursor keys

OF_KEY_F1                               OF_KEY_LEFT

OF_KEY_F2                               OF_KEY_RIGHT

...                                     OF_KEY_DOWN

OF_KEY_F12                              OF_KEY_UP



Special keys

OF_KEY_PAGE_UP          OF_KEY_INSERT      OF_KEY_ALT

OF_KEY_PAGE_DOWN        OF_KEY_RETURN      OF_KEY_SHIFT

OF_KEY_HOME             OF_KEY_ESC         OF_KEY_BACKSPACE

OF_KEY_END              OF_KEY_CTRL        OF_KEY_DEL

For more defines see ofConstants
roxlu
www.roxlu.com

More Related Content

What's hot

Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Platonov Sergey
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
Better Software: introduction to good code
Better Software: introduction to good codeBetter Software: introduction to good code
Better Software: introduction to good codeGiordano Scalzo
 
Stamps - a better way to object composition
Stamps - a better way to object compositionStamps - a better way to object composition
Stamps - a better way to object compositionVasyl Boroviak
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscexjeffz
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)jeffz
 
6.1.1一步一步学repast代码解释
6.1.1一步一步学repast代码解释6.1.1一步一步学repast代码解释
6.1.1一步一步学repast代码解释zhang shuren
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptjeffz
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Platonov Sergey
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Codestasimus
 
The Macronomicon
The MacronomiconThe Macronomicon
The MacronomiconMike Fogus
 
The Ring programming language version 1.5.4 book - Part 59 of 185
The Ring programming language version 1.5.4 book - Part 59 of 185The Ring programming language version 1.5.4 book - Part 59 of 185
The Ring programming language version 1.5.4 book - Part 59 of 185Mahmoud Samir Fayed
 
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019corehard_by
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programmingjeffz
 
Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Alexander Granin
 

What's hot (20)

Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
Better Software: introduction to good code
Better Software: introduction to good codeBetter Software: introduction to good code
Better Software: introduction to good code
 
Stamps - a better way to object composition
Stamps - a better way to object compositionStamps - a better way to object composition
Stamps - a better way to object composition
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
 
6.1.1一步一步学repast代码解释
6.1.1一步一步学repast代码解释6.1.1一步一步学repast代码解释
6.1.1一步一步学repast代码解释
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Code
 
The Macronomicon
The MacronomiconThe Macronomicon
The Macronomicon
 
The Ring programming language version 1.5.4 book - Part 59 of 185
The Ring programming language version 1.5.4 book - Part 59 of 185The Ring programming language version 1.5.4 book - Part 59 of 185
The Ring programming language version 1.5.4 book - Part 59 of 185
 
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019Статичный SQL в С++14. Евгений Захаров ➠  CoreHard Autumn 2019
Статичный SQL в С++14. Евгений Захаров ➠ CoreHard Autumn 2019
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
YUI Tidbits
YUI TidbitsYUI Tidbits
YUI Tidbits
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Functional microscope - Lenses in C++
Functional microscope - Lenses in C++
 

Similar to openFrameworks 007 - utils

#includeiostream#includestack#includestring #include .pdf
#includeiostream#includestack#includestring #include .pdf#includeiostream#includestack#includestring #include .pdf
#includeiostream#includestack#includestring #include .pdfsrinivas9922
 
Java binary subtraction
Java binary subtractionJava binary subtraction
Java binary subtractionCharm Sasi
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Sunil Kumar Gunasekaran
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
Creating custom views
Creating custom viewsCreating custom views
Creating custom viewsMu Chun Wang
 
Collection v3
Collection v3Collection v3
Collection v3Sunil OS
 
public class TrequeT extends AbstractListT { .pdf
  public class TrequeT extends AbstractListT {  .pdf  public class TrequeT extends AbstractListT {  .pdf
public class TrequeT extends AbstractListT { .pdfinfo30292
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfHIMANSUKUMAR12
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsBaruch Sadogursky
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210Mahmoud Samir Fayed
 
Import java
Import javaImport java
Import javaheni2121
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196Mahmoud Samir Fayed
 
Cppt 101102014428-phpapp01
Cppt 101102014428-phpapp01Cppt 101102014428-phpapp01
Cppt 101102014428-phpapp01Getachew Ganfur
 
The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88Mahmoud Samir Fayed
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Tracy Lee
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3Simon Su
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Baruch Sadogursky
 

Similar to openFrameworks 007 - utils (20)

#includeiostream#includestack#includestring #include .pdf
#includeiostream#includestack#includestring #include .pdf#includeiostream#includestack#includestring #include .pdf
#includeiostream#includestack#includestring #include .pdf
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Java binary subtraction
Java binary subtractionJava binary subtraction
Java binary subtraction
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Creating custom views
Creating custom viewsCreating custom views
Creating custom views
 
Collection v3
Collection v3Collection v3
Collection v3
 
Java programs
Java programsJava programs
Java programs
 
public class TrequeT extends AbstractListT { .pdf
  public class TrequeT extends AbstractListT {  .pdf  public class TrequeT extends AbstractListT {  .pdf
public class TrequeT extends AbstractListT { .pdf
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdf
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210
 
Import java
Import javaImport java
Import java
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
Cppt 101102014428-phpapp01
Cppt 101102014428-phpapp01Cppt 101102014428-phpapp01
Cppt 101102014428-phpapp01
 
The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 

Recently uploaded

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 

Recently uploaded (20)

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 

openFrameworks 007 - utils

  • 2. Utils date screenshots noise list helpers remote loading logging string threading file utils manipulation system tools constants
  • 3. date int ofGetSeconds() Get seconds of current time int ofGetMinutes() Get minutes of current time int ofGetHours() Get hours of current time int ofGetYear() Get current year int ofGetMonth() Get current month int ofGetDay() Get current day int ofGetWeekDay Get current weekday unsigned int ofGetUnixTime() Timestamp since 1970 unsigned long ofGetSystemTime() System time in millis string ofGetSystemTimeMicros() System time in micros string ofGetTimestampString() Timestamp since 1970 as string
  • 4. list helpers Remove items from a vector. void ofRemove(vector<T>&, BoolFunction shouldErase) Step 1. Create a custom remove functor class MyOwnRemover{ public: bool operator()(const string& str) { return str == "roxlu"; } };
  • 5. list helpers void ofRemove(vector<T>&, BoolFunction shouldErase) Step 2. use ofRemove with remove functor void testApp::setup(){ // create list with strings. vector<string> mystrings; mystrings.push_back("diederick"); mystrings.push_back("openframeworks"); mystrings.push_back("supercool"); mystrings.push_back("roxlu"); mystrings.push_back("do not remove"); mystrings.push_back("roxlu"); // show before removing items. for(int i = 0; i < mystrings.size(); ++i) { cout << "before: " << mystrings[i] << endl; } cout << "=======" << endl; // remove items using my own remover! ofRemove(mystrings, MyOwnRemover()); for(int i = 0; i < mystrings.size(); ++i) { cout << "after: " << mystrings[i] << endl; } }
  • 6. Summary ofRemove list helpers void ofRemove(vector<T>&, BoolFunction shouldErase) class MyOwnRemover{ void testApp::setup(){ public: bool operator()(const string& str) { // create list with strings. return str == "roxlu"; vector<string> mystrings; } mystrings.push_back("diederick"); }; mystrings.push_back("openframeworks"); mystrings.push_back("supercool"); mystrings.push_back("roxlu"); mystrings.push_back("do not remove"); mystrings.push_back("roxlu"); // show before removing items. for(int i = 0; i < mystrings.size(); ++i) { Result } cout << "before: " << mystrings[i] << endl; before: diederick cout << "=======" << endl; before: openframeworks before: supercool before: roxlu before: do not remove // remove items using my own remover! before: roxlu ofRemove(mystrings, MyOwnRemover()); ======= after: diederick for(int i = 0; i < mystrings.size(); ++i) { after: openframeworks cout << "after: " << mystrings[i] << endl; after: supercool after: do not remove } }
  • 7. Randomize a vector list helpers void ofRandomize(vector<T>&) void testApp::setup(){ // create list with strings. vector<string> mystrings; mystrings.push_back("diederick"); mystrings.push_back("openframeworks"); Result mystrings.push_back("supercool"); random: roxlu mystrings.push_back("roxlu"); random: roxlu mystrings.push_back("do not remove"); random: supercool mystrings.push_back("roxlu"); random: openframeworks random: do not remove ofRandomize(mystrings); random: diederick // show before removing items. for(int i = 0; i < mystrings.size(); ++i) { cout << "random: " << mystrings[i] << endl; } }
  • 8. Sort a vector list helpers void ofSort(vector<T>&) void testApp::setup(){ // create list with strings. vector<string> mystrings; mystrings.push_back("diederick"); mystrings.push_back("openframeworks"); Result mystrings.push_back("supercool"); sorted: diederick mystrings.push_back("roxlu"); sorted: do not remove mystrings.push_back("do not remove"); sorted: openframeworks mystrings.push_back("roxlu"); sorted: roxlu sorted: roxlu ofSort(mystrings); sorted: supercool // show before removing items. for(int i = 0; i < mystrings.size(); ++i) { cout << "sorted: " << mystrings[i] << endl; } }
  • 9. Find entry in vector list helpers unsigned int ofFind(vector<T>&, const T& target) void testApp::setup(){ vector<string> mystrings; mystrings.push_back("diederick"); mystrings.push_back("openframeworks"); Result mystrings.push_back("supercool"); mystrings.push_back("roxlu"); do not remove <-- mystrings.push_back("do not remove"); mystrings.push_back("roxlu"); string fstr = "do not remove"; unsigned int num_found = ofFind(mystrings, fstr); if(num_found) { cout << mystrings[num_found] << " <-- “ << endl; } }
  • 10. Check if entry exists list helpers bool ofContains(vector<T>&, const T& target) // create list with strings. vector<string> mystrings; mystrings.push_back("diederick"); mystrings.push_back("openframeworks"); Result mystrings.push_back("supercool"); mystrings.push_back("roxlu"); do not remove in mystrings mystrings.push_back("do not remove"); mystrings.push_back("roxlu"); string fstr = "do not remove"; bool contains = ofContains(mystrings, fstr); if(contains) { cout << fstr << " in mystrings" << endl; }
  • 11. string manipulation Split a string vector<string> ofSplitString( const string& source ,const string& delimiters ,bool ignoreEmpty = false ,bool trim = false ); Result string items = "one|two|three|four|five |||test|"; part: 'one' vector<string> parts = ofSplitString(items,"|",true,true); part: 'two' for(int i = 0; i < parts.size(); ++i) { part: 'three' cout << "part: '" << parts[i] << "'" << endl; part: 'four' } part: 'five' part: 'test'
  • 12. string manipulation Split a string vector<string> ofJoinString(vector<string>, const string delim) vector<string> loose_parts; Result loose_parts.push_back("I"); loose_parts.push_back("need"); I-need-some-OF-examples! loose_parts.push_back("some"); loose_parts.push_back("OF"); loose_parts.push_back("examples!"); string joined_string = ofJoinString(loose_parts, "-"); cout << joined_string << endl;
  • 13. string manipulation Is a string in a string? bool ofIsStringInString(string haystack, string needle) string haystack_str = "I'm searching for a needle in this haystack"; if(ofIsStringInString(haystack_str, "searching")) { cout << "yes, 'searching' is in the string" << endl; } Result yes, 'searching' is in the string
  • 14. string manipulation Case conversion string ofToUpper(const string& src) string ofToLower(const string& src) string str = "Just some string"; cout << ofToLower(str) << " = ofToLower" << endl; cout << ofToUpper(str) << " = ofToUpper" << endl; Result just some string = ofToLower JUST SOME STRING = ofToUpper
  • 15. string manipulation Type / hex conversion Convert int,float,uint,char,?? string ofToString(const T&) to string string ofToHex(string|char) int ofHexToInt(const string&) string ofHexToChar(const string&) float ofHexToFloat(const string&) string ofHexToString(const string&)
  • 16. string manipulation String conversions Convert int,float,uint,char,?? string ofToString(const T&) to string int ofToInt(const string& str) Convert string to int char ofToChar(const string& str) Convert string to char float ofToFloat(const string& str) Convert string to float bool ofToBool(const string& str) Convert string to bool
  • 17. string manipulation Binary utils string ofToBinary(const string& str) String to binary int ofBinaryToInt(const string& str) From binary to int char ofBinaryToChar(const string& str) From binary to char float ofBinaryToFloat(const string& str) From binary to float
  • 18. screenshots Screenshots Save what’s drawn to a file named by the current frame. void ofSaveFrame() The file is saved into the data directory. Save the current screen to a void ofSaveScreen(string filename) file in the data directory. void ofSaveViewport(string filename) Save current viewport to file
  • 19. screenshots Screenshots void testApp::draw(){ // create filename (each call we increment the counter) static int screen_num = 0; ++screen_num; char buf[512]; sprintf(buf,"screen_%04d.jpg",screen_num); // draw a simple circle at the center of screen and save it to image file. ofCircle(ofGetWidth() *0.5,ofGetHeight()*0.5,40); ofSaveScreen(buf); }
  • 20. screenshots Screenshots void testApp::draw(){ // create filename (each call we increment the counter) static int screen_num = 0; ++screen_num; char buf[512]; sprintf(buf,"screen_%04d.jpg",screen_num); // draw a simple circle at the center of screen and save it to image file. ofCircle(ofGetWidth() *0.5,ofGetHeight()*0.5,40); ofSaveScreen(buf); }
  • 21. remote loading Load from url (synchronous) ofHttpResponse ofLoadURL(string url) ofHttpResponse resp = ofLoadURL("http://roxlu.com/ofloadurl.txt"); cout << resp.data << endl; Result This is just a test!
  • 22. remote loading Load from url (async) int ofLoadURLAsync(string url, string name) • Loads asynchronous • Returns ID of process • You need to listen for URL notifications in testApp::urlResponse(ofHttpResponse&)
  • 23. remote loading Asynchronous loading Step 1. declare urlResponse in class header which wants to get notifications class testApp : public ofBaseApp{ public: void urlResponse(ofHttpResponse & response); } Step 2. define urlResponse in class which wants to get notifications void testApp::urlResponse(ofHttpResponse & response){ if(response.status==200 && response.request.name == "async_req"){ img.loadImage(response.data); loading=false; } else{ cout << response.status << " " << response.error << endl; if(response.status!=-1) loading=false; } }
  • 24. Asynchronous loading remote loading Step 3. enable URL notifications void testApp::setup(){ ofRegisterURLNotification(this); } Recap URL loading functions ofHttpResponse ofLoadURL(string url) int ofLoadURLAsync(string url, string name=””) void ofRemoveURLRequest(int id) void ofRemoveAllURLRequests()
  • 25. threading Threading in OF • Very easy to create threads using ofThread • Locking using lock/unlock() functions • Easy start/stop/joining • Just implement threadedFunction() • I.e. used to perform background processes
  • 26. threading Creating a thread Step 1. Create your thread class which extends ofThread class MyCustomThread : public ofThread { protected: virtual void threadedFunction() { while(true) { cout << "My own custom thread!" << endl; ofSleepMillis(3000); } } }; Step 2. Create member in testApp.h class testApp : public ofBaseApp{ public: MyCustomThread my_thread; ... }
  • 27. threading Creating a thread Step 3. Start the thread by calling startThread() void testApp::setup(){ // creates a non-blocking thread. (not verbose) my_thread.startThread(false, false); }
  • 28. system tools System tools void ofSystemAlertDialog(string) Show system Alert window ofFileDialogResult ofSystemLoadDialog(string Show system File Load windowtitle, bool folderselection) window ofFileDialogResult ofSystemSaveDialog(string Show system File Save defaultname, string messagename) window
  • 29. system tools System tools void testApp::setup(){ ofSystemAlertDialog("Whoot! Look out!"); }
  • 30. system tools System tools ofFileDialogResult dialog_result = ofSystemLoadDialog("Load image",false); if(dialog_result.bSuccess) { cout << "name: " << dialog_result.getName() << endl; cout << "file path: " << dialog_result.getPath() << endl; }
  • 31. noise Simplex noise 1D, 2D, 3D and 4D float ofNoise(float) simplex noise. float ofNoise(float, float) Returns values in float ofNoise(float, float, float) range float ofNoise(float, float,float,float) 0.0 - 1.0 1D, 2D, 3D and 4D float ofSignedNoise(float) simplex noise. float ofSignedNoise(float, float) Returns values in float ofSignedNoise(float, float, float) range float ofSignedNoise(float, float,float,float) -1.0 - 1.0
  • 32. noise Simplex noise float scale = 0.001; float scale = 0.01; float scale = 0.1; float scale = 0.7; void testApp::draw(){ float scale = 0.001; glBegin(GL_LINE_STRIP); for(float i = 0; i < ofGetWidth(); ++i) { glVertex2f(i,ofNoise(i*scale) * 50); } glEnd(); }
  • 33. logging Logging • Simple logging to console or file • Support for basic log levels • Log level filtering • More advanced stuff, see ofxLogger (file rotation)
  • 34. logging Logging Set level to log. Only this void ofSetLogLevel(ofLogLevel) level will show up in console or file ofLogLevel ofGetLogLevel() Get current log level void ofLogToFile(string path) Log to path void ofLogToConsole() Log to console (default)
  • 35. logging Logging ofSetLogLevel(OF_LOG_VERBOSE); ofLog(OF_LOG_VERBOSE,"log something"); ofLog(OF_LOG_VERBOSE,"Something to log"); ofLog(OF_LOG_VERBOSE,"Something else to log"); Result OF: OF_VERBOSE: log something OF: OF_VERBOSE: Something to log OF: OF_VERBOSE: Something else to log
  • 36. logging Logging Set level to log. Only this void ofSetLogLevel(ofLogLevel) level will show up in console or file ofLogLevel ofGetLogLevel() Get current log level void ofLogToFile(string path) Log to path void ofLogToConsole() Log to console (default)
  • 37. file utils File utils ofBuffer Raw byte buffer class ofFilePath A file system path ofFile File class; handy functions ofDirectory Directory class; i.e. dirlists
  • 38. file utils ofBuffer ofBuffer • Allows you to store raw data • This is useful when working on networked applications or hardware (arduino) when you want to use a custom protocol. Two handy global functions: ofBuffer ofBufferFromFile(const string& p, bool binary = false) bool ofBufferToFile(const string& p, ofBuffer& buf, bool bin=false);
  • 39. file utils ofBuffer ofBuffer string data = "This isnjust a bunchnof rawndata withn somenline breaks."; ofBuffer buffer; buffer.set(data.c_str(), data.size()); while(!buffer.isLastLine()) { cout << "Buffer line: " << buffer.getNextLine() << endl; } Result Buffer line: This is Buffer line: just a bunch Buffer line: of raw Buffer line: data with Buffer line: some Buffer line: line breaks.
  • 40. file utils ofBuffer read file into buffer // read from file into buffer ofBuffer buf = ofBufferFromFile("of.log"); cout << "********" << endl << buf << endl << "********" << endl; Other functions... void set(const char*, int size) bool set(istream&) bool writeTo(ostream &stream) void clear() void allocate(long) char* getBinaryBuffer() const char* getBinaryBuffer() string getText() string getNextLine() string getFirstLine() bool isLastLine()
  • 41. file utils ofFilePath File paths • Just easy class to play with paths • Use this for cleaning up paths, retrieving absolute paths, retrieving basenames, filenames, enclosing directories, current working dir. • All member functions are static
  • 42. file utils ofFilePath File paths static string getFileExt(string filename) static string removeExt(string filename) static string addLeadingSlash(string path) static string addTrailingSlash(string path) static string removeTrailingSlash(string path) static string getPathForDirectory(string path) static string getAbsolutePath(string path, bool rel_data = true) static bool isAbsolute(string path) static string getFileName(string f,bool rel_data = true) static string getBaseName(string file) static string getEnclosingDirectory(string p, bool rel_data = true) static string getCurrentWorkingDirectory()
  • 43. file utils ofFilePath File paths cout << ofFilePath::getPathForDirectory("~/Documents"); /Users/roxlu/Documents/ cout << ofFilePath::getPathForDirectory("data"); data/ string path = "/just/some/path/photo.jpg"; cout << ofFilePath::getFileExt(path); jpg string path = "/just/some/path/photo.jpg"; cout << ofFilePath::removeExt(path); /just/some/path/photo string path = "/just/some/path/photo.jpg"; cout << ofFilePath::getFilename(path) << endl; photo.jpg
  • 44. file utils ofFilePath File paths string path = "/just/some/path/photo.jpg"; cout << ofFilePath::getBaseName(path) << endl; photo string path = "/just/some/path/photo.jpg"; cout << ofFilePath::getEnclosingDirectory(path) << endl; /just/some/path/ cout << ofFilePath::getCurrentWorkingDirectory() << endl; /Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/ emptyExampleDebug.app/Contents/MacOS/
  • 45. file utils ofFile ofFile bool open(string path, Mode m=ReadOnly, bool binary=false) bool changeMode(Mode m, bool binary=false) void close() bool canExecute() bool exists() bool isFile() string path() bool isLink() string getExtension() bool isDirectory() string getFileName() bool isDevice( string getBaseName() bool isHidden string getEnclosingDirectory() void setWriteble(bool writable) string getAbsolutePath() void setReadOnly(bool readable) bool canRead() void setExecutable(bool exec) bool canWrite() uint64_t getSize()
  • 46. file utils ofFile ofFile bool copyTo(string path, bool rel_to_data = true, bool overwrite = false) bool moveTo(string path, bool rel_to_data = true, bool overwrite = false) bool renameTo(string path, bool rel_to_data = true, bool overwrite = false) ofFile <> ofBuffer ofBuffer readToBuffer() bool writeFromBuffer(ofBuffer& buffer) bool renameTo(string path, bool rel_to_data = true, bool overwrite = false)
  • 47. file utils ofFile ofFile - static functions static bool copyFromTo(string src, string dest, bool rel_to_data = true, bool overwrite = false) static bool moveFromTo(string src, string dest, bool rel_to_data = true, bool overwrite = false) static bool doesFileExist(string path,bool rel_to_data = true) static bool removeFile(string path,bool rel_to_data = true)
  • 48. file utils ofDirectory ofDirectory • Similar to ofFile • Lots of handy function for moving, renaming, copying, deleting, file listing, etc... void open(string path) void setWriteble(bool writable) void close() void setReadOnly(bool readable) bool create(bool recursive = true) bool exists() void setExecutable(bool exec) string path() For more functions ofFileUtils.h bool canRead() bool canWrite() bool canExecute() bool isDirectory() bool isHidden() bool remove(bool recursive)
  • 49. file utils ofDirectory Retrieve all jpegs from a directory ofDirectory dir; dir.allowExt("jpg"); int num_jpegs_in_datapath = dir.listDir(ofToDataPath(".",true)); cout << "Num files in data path : " << num_jpegs_in_datapath << endl; for(int i = 0; i < num_jpegs_in_datapath; ++i) { cout << dir.getPath(i) << endl; } Result /Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0001.jpg /Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0002.jpg /Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0003.jpg /Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0004.jpg /Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0005.jpg /Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0006.jpg
  • 50. file utils ofDirectory Some static functions static bool createDirectory(string path, bool rel_to_data = true, bool recursive = false) static bool isDirectoryEmtpy(string path, bool rel_to_data = true) static bool doesDirectoryExist(string path, bool rel_to_data = true) static bool removeDirectory(string path, bool deleteIfNotEmpty, bool bRelativeToData = true)
  • 51. constants Development Math/Trig OF_VERSION HALF_PI CLAMP(val,min,max) OF_VERSION_MINOR PI ABS(x) TARGET_WIN32 TWO_PI OF_OUTLINE TARGET_OF_IPHONE FOUR_PI OF_FILLED TARGET_ANDROID DEG_TO_RAD TARGET_LINUS RAD_TO_DEG Window TARGET_OPENGLES MIN(x,y) OF_WINDOW OF_FULLSCREEN OF_USING_POCO MAX(x,y) OF_GAME_MODE
  • 52. constants Rectangle modes Pixel formats Blend modes OF_RECTMODE_CORNER OF_PIXELS_MONO OF_BLENDMODE_DISABLED OF_RECTMODE_CENTER OF_PIXELS_RGB OF_BLENDMODE_ALPHA OF_PIXELS_RGBA OF_BLENDMODE_ADD Image types OF_PIXELS_BGRA OF_BLENDMODE_SUBTRACT OF_IMAGE_GRAYSCALE OF_PIXELS_RGB565 OF_BLENDMODE_MULTIPLY OF_IMAGE_COLOR OF_BLENDMODE_SCREEN OF_IMAGE_COLOR_ALPHA OF_IMAGE_UNDEFINED
  • 53. constants Orientations ofLoopType OF_ORIENTATION_UNKNOWN OF_LOOP_NONE OF_ORIENTATION_DEFAULT OF_LOOP_PALINDROME OF_ORIENTATION_90_LEFT OF_LOOP_NORMAL OF_ORIENTATION_180 OF_ORIENTATION_90_RIGHT For more defines see ofConstants
  • 54. constants Function keys Cursor keys OF_KEY_F1 OF_KEY_LEFT OF_KEY_F2 OF_KEY_RIGHT ... OF_KEY_DOWN OF_KEY_F12 OF_KEY_UP Special keys OF_KEY_PAGE_UP OF_KEY_INSERT OF_KEY_ALT OF_KEY_PAGE_DOWN OF_KEY_RETURN OF_KEY_SHIFT OF_KEY_HOME OF_KEY_ESC OF_KEY_BACKSPACE OF_KEY_END OF_KEY_CTRL OF_KEY_DEL For more defines see ofConstants

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n