How to detect if your system tray icon has gone missing, C/C++, Win32
Google Tensor Flow In C On Fedora Linux
Decided to have a look at google tensor flow to see what all the hype is about.
Reading the first page of how to install under Linux just blew my mind. Nice work google.
So apparently you are supposed to run this:
TF_TYPE="cpu" # Change to "gpu" for GPU support
OS="linux" # Change to "darwin" for Mac OS
TARGET_DIRECTORY="/usr/local"
curl -L \
"https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-${TF_TYPE}-${OS}-x86_64-1.4.0.tar.gz" |
sudo tar -C $TARGET_DIRECTORY -xz
Okay that works.
Then:
sudo ldconfig
Oh wait linux generally doesn’t include /usr/local/lib by default from any ld.so conf configuration. Well, at least Fedora doesn’t.
Easy fix:
sudo echo /usr/local/lib >> /etc/ld.so.conf/usr-local.conf
Then they say to run:
gcc hello_tf.c /tmp/ccqYuwfC.o: In function `main': hello_tf.c:(.text+0xa): undefined reference to `TF_Version' collect2: error: ld returned 1 exit status
Hmm okay, that will never work. What magic voodoo will make that function appear for the linker:
Right to add the lib:
gcc hello_tf.c -ltensorflow
And then run it like google says:
a.out
Hey google guess what, linux doesn’t generally have the current directory in the path. What kind of weird linux are you running?
Maybe try:
./a.out Hello from TensorFlow C library version 1.4.0
Wowzer it works.
Google is usually good about their docs. What happened? Too many pythons?
Okay so how to use this thing in C?
Oh wait there aren’t any docs for the c library.
Check the header.. that doesn’t look too promising.
Check github project page. Hmm not much there.
So back to the Getting Started python tutorial. See if it can work in C?
Attempt Digging Through c_api.h
Good news the header has a lot of documentation.
The Computational Graph
Found this:
typedef struct TF_Graph TF_Graph;
And This:
TF_CAPI_EXPORT extern TF_Graph* TF_NewGraph();
Must be on to something.
A Tensor
Where?
typedef struct TF_Tensor TF_Tensor;
Must be that and:
TF_CAPI_EXPORT extern TF_Tensor* TF_NewTensor(
TF_DataType, const int64_t* dims, int num_dims, void* data, size_t len,
void (*deallocator)(void* data, size_t len, void* arg),
void* deallocator_arg);
So how can I get those numbers from the example in there.
Docs:
// -------------------------------------------------------------------------- // TF_Tensor holds a multi-dimensional array of elements of a single data type. // For all types other than TF_STRING, the data buffer stores elements // in row major order. E.g. if data is treated as a vector of TF_DataType:
So looking for a float holding tensor.
Have this now so far:
#include <stdio.h>
#include <tensorflow/c/c_api.h>
void tensor_free(void* data, size_t len, void* arg) {
printf("Free Called\n");
}
int main() {
int64_t dims[1] = {1.0f};
int64_t num_dims = 1;
float tens_1_data[] = {3.0f};
size_t tens_1_data_len = 1;
float tens_2_data[] = {4.0f};
size_t tens_2_data_len = 1;
printf("Hello from TensorFlow C library version %s\n", TF_Version());
TF_Tensor * tensor1 = TF_NewTensor(TF_FLOAT, dims, num_dims, tens_1_data, tens_1_data_len, tensor_free, NULL);
TF_Tensor * tensor2 = TF_NewTensor(TF_FLOAT, dims, num_dims, tens_2_data, tens_2_data_len, tensor_free, NULL);
TF_DeleteTensor(tensor1);
TF_DeleteTensor(tensor2);
return 0;
}
Quick valgrind check.
Bunch of leaks.. need to shut something down.
Can’t seem to find a shutdown/free/.. anything.. leave that for later.
valgrind --leak-check=full ./a.out
Getting Some Output
Hello from TensorFlow C library version 1.4.0 2017-12-12 17:56:58.424881: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was noTt compiled to use: SSE4.1 Free Called Free Called
Need A Session
Found this that must be it, but I need a graph and options to make one??
typedef struct TF_Session TF_Session; TF_CAPI_EXPORT extern TF_Session* TF_NewSession(TF_Graph* graph, const TF_SessionOptions* opts, TF_Status* status);
Okay says something about NULL being ok.
Try:
TF_Session * session = TF_NewSession(NULL, NULL, NULL);
Boom segfault.
So probably the first parameter is the most important.. Try to make a graph.
TF_Graph * graph = TF_NewGraph();
Nope still segfaults.
Try making options.
TF_SessionOptions * options = TF_NewSessionOptions();
Nope still segfaults.
K it’s happy now.. no more crashing.
TF_Status * status = TF_NewStatus();
And clean all those up.
TF_DeleteGraph(graph);
TF_DeleteSessionOptions(options);
TF_DeleteStatus(status);
TF_DeleteTensor(tensor1);
TF_DeleteTensor(tensor2);
Running exiting ok now.
Run The Session?
TF_CAPI_EXPORT extern void TF_SessionRun(
TF_Session* session,
// RunOptions
const TF_Buffer* run_options,
// Input tensors
const TF_Output* inputs, TF_Tensor* const* input_values, int ninputs,
// Output tensors
const TF_Output* outputs, TF_Tensor** output_values, int noutputs,
// Target operations
const TF_Operation* const* target_opers, int ntargets,
// RunMetadata
TF_Buffer* run_metadata,
// Output status
TF_Status*);
That must be it.
Looks like some TF_Operations and array of TF_Sensors for I/O.
After not finding many examples and many attempts at different guesses and reading the test code in c_api_test.cc and c_test_util.cc I’ve managed to add two numbers together.
The output tensor is allocated by session run so it has been removed.
The final extremely basic C example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tensorflow/c/c_api.h>
/*
* Super basic example of using google tensorflow directly from C
*
*/
// Using stack input data nothing to free
void tensor_free_none(void * data, size_t len, void* arg) {
}
TF_Operation * PlaceHolder(TF_Graph * graph, TF_Status * status, TF_DataType dtype, const char * name) {
TF_OperationDescription * desc = TF_NewOperation(graph, "Placeholder", name);
TF_SetAttrType(desc, "dtype", TF_FLOAT);
return TF_FinishOperation(desc, status);
}
TF_Operation * Const(TF_Graph * graph, TF_Status * status, TF_Tensor * tensor, const char * name) {
TF_OperationDescription * desc = TF_NewOperation(graph, "Const", name);
TF_SetAttrTensor(desc, "value", tensor, status);
TF_SetAttrType(desc, "dtype", TF_TensorType(tensor));
return TF_FinishOperation(desc, status);
}
TF_Operation * Add(TF_Graph * graph, TF_Status * status, TF_Operation * one, TF_Operation * two, const char * name) {
TF_OperationDescription * desc = TF_NewOperation(graph, "AddN", name);
TF_Output add_inputs[2] = {{one, 0}, {two, 0}};
TF_AddInputList(desc, add_inputs, 2);
return TF_FinishOperation(desc, status);
}
int main() {
printf("TensorFlow C library version: %s\n", TF_Version());
TF_Graph * graph = TF_NewGraph();
TF_SessionOptions * options = TF_NewSessionOptions();
TF_Status * status = TF_NewStatus();
TF_Session * session = TF_NewSession(graph, options, status);
float in_val_one = 4.0f;
float const_two = 2.0f;
TF_Tensor * tensor_in = TF_NewTensor(TF_FLOAT, NULL, 0, &in_val_one, sizeof(float), tensor_free_none, NULL);
TF_Tensor * tensor_out = NULL; // easy access after this is allocated by TF_SessionRun
TF_Tensor * tensor_const_two = TF_NewTensor(TF_FLOAT, NULL, 0, &const_two, sizeof(float), tensor_free_none, NULL);
// Operations
TF_Operation * feed = PlaceHolder(graph, status, TF_FLOAT, "feed");
TF_Operation * two = Const(graph, status, tensor_const_two, "const");
TF_Operation * add = Add(graph, status, feed, two, "add");
// Session Inputs
TF_Output input_operations[] = { feed, 0 };
TF_Tensor ** input_tensors = {&tensor_in};
// Session Outputs
TF_Output output_operations[] = { add, 0 };
TF_Tensor ** output_tensors = {&tensor_out};
TF_SessionRun(session, NULL,
// Inputs
input_operations, input_tensors, 1,
// Outputs
output_operations, output_tensors, 1,
// Target operations
NULL, 0, NULL,
status);
printf("Session Run Status: %d - %s\n", TF_GetCode(status), TF_Message(status) );
printf("Output Tensor Type: %d\n", TF_TensorType(tensor_out));
float * outval = TF_TensorData(tensor_out);
printf("Output Tensor Value: %.2f\n", *outval);
TF_CloseSession(session, status);
TF_DeleteSession(session, status);
TF_DeleteSessionOptions(options);
TF_DeleteGraph(graph);
TF_DeleteTensor(tensor_in);
TF_DeleteTensor(tensor_out);
TF_DeleteTensor(tensor_const_two);
TF_DeleteStatus(status);
return 0;
}
To build and run:
gcc -g3 hello_tf.c -ltensorflow -o hello ./hello
Notes:
The underlying library is written C++ so there is really no point in doing this unless you have some C code that needs to integrate with tensor flow from their.
Valgrind still finds some left over memory from pthread_create. Couldn’t figure away to clean up the lib completely. Doesn’t seem to be any function join the internal threads.
==5693== HEAP SUMMARY: ==5693== in use at exit: 5,358,141 bytes in 105,451 blocks ==5693== total heap usage: 310,615 allocs, 205,164 frees, 17,029,114 bytes allocated ==5693== ==5693== 640 bytes in 2 blocks are possibly lost in loss record 63,119 of 63,227 ==5693== at 0x4C2FA50: calloc (vg_replace_malloc.c:711) ==5693== by 0x4013F8A: _dl_allocate_tls (in /usr/lib64/ld-2.24.so) ==5693== by 0x8D3B2DB: pthread_create@@GLIBC_2.2.5 (in /usr/lib64/libpthread-2.24.so) ==5693== by 0x9214C92: std::thread::_M_start_thread(std::shared_ptr<std::thread::_Impl_base>, void (*)()) (in /usr/lib64/libstdc++.so.6.0.22) ==5693== by 0x9214D9C: std::thread::_M_start_thread(std::shared_ptr<std::thread::_Impl_base>) (in /usr/lib64/libstdc++.so.6.0.22) ==5693== by 0x814BFDF: tensorflow::(anonymous namespace)::PosixEnv::StartThread(tensorflow::ThreadOptions const&, std::string const&, std::function<void ()>) (in /usr/local/lib/libtensorflow_framework.so) ==5693== by 0x8124A46: tensorflow::thread::ThreadPool::ThreadPool(ten
Building an Apple OSX Kernel Module With CMake – C/C++
If you google around about how to build an osx kext you will find very few results, a few email messages saying not to bother or that it it impossible.
So what’s all the voodoo about. A few defines, some linker options, some compiler options. Also a special info.c file and Info.plist.
Note: if you want to sign your kernel module you will need to apply to apple for a special kernel module code signing certificate.
Setup basic cmake project. We need 3.8 or newer to use BUNDLE_EXTENSION for the .kext bundle type.
cmake_minimum_required (VERSION 3.8) project (example)
Setup some variables for later. These are both optional if you use the default system sdk or you don’t want to code sign.
set(CODE_SIGN_ID "Developer ID Application: Your Name. (XYZZYYZYZY)") set(CMAKE_OSX_SYSROOT /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/)
Add a debug preprocessor def. This is optional.
if(CMAKE_BUILD_TYPE MATCHES Debug)
add_definitions(-DDEBUG)
endif()
Add the special preprocessor defines to access internal kernel structures.
add_definitions(
-DKERNEL
-DKERNEL_PRIVATE
-DDRIVER_PRIVATE
-DAPPLE
-DNeXT
)
Add include directories for osx kernel headers and private headers.
include_directories(
${CMAKE_OSX_SYSROOT}/System/Library/Frameworks/Kernel.framework/PrivateHeaders
${CMAKE_OSX_SYSROOT}/System/Library/Frameworks/Kernel.framework/Headers
)
Add an executable bundle target.
add_executable(
${PROJECT_NAME}
MACOSX_BUNDLE
example.c
example_info.c
Info.plist
)
Set the target bundle extension to “kext” and the plist file.
set_target_properties(${PROJECT_NAME} PROPERTIES BUNDLE_EXTENSION kext MACOSX_BUNDLE_INFO_PLIST ${PROJECT_SOURCE_DIR}/Info.plist)
Set a million compile options. These were taken from a minimal xcode project.
Note: The -mmacosx-version-min=10.10 can be removed or changed to support older versions of OSX.
add_compile_options(${PROJECT_NAME}
-x c -arch x86_64 -fmessage-length=0
-fdiagnostics-show-note-include-stack
-fmacro-backtrace-limit=0 -nostdinc
-std=gnu99 -fmodules -gmodules
-Wnon-modular-include-in-framework-module
-Werror=non-modular-include-in-framework-module
-fno-builtin -Wno-trigraphs -msoft-float -O0 -fno-common
-mkernel -Wno-missing-field-initializers -Wno-missing-prototypes
-Werror=return-type -Wdocumentation -Wunreachable-code
-Werror=deprecated-objc-isa-usage -Werror=objc-root-class
-Wno-missing-braces -Wparentheses -Wswitch -Wunused-function
-Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value
-Wempty-body -Wconditional-uninitialized -Wno-unknown-pragmas
-Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion
-Wint-conversion -Wbool-conversion -Wenum-conversion -Wshorten-64-to-32
-Wpointer-sign -Wno-newline-eof
-fasm-blocks -fstrict-aliasing -Wdeprecated-declarations
-mmacosx-version-min=10.10 -Wno-sign-conversion
-Winfinite-recursion -iquote
)
Add the libraries required for the kernel module and linker options.
Note: The -mmacosx-version-min=10.10 can be removed or changed to support older versions of OSX.
target_link_libraries(${PROJECT_NAME}
"-lkmodc++"
"-lkmod"
"-lcc_kext"
"-arch x86_64"
"-mmacosx-version-min=10.10"
"-nostdlib"
"-Xlinker -object_path_lto"
"-Xlinker -export_dynamic"
"-Xlinker -kext"
)
Add a custom target to sign the kernel module. This can be skipped if code signing isn’t needed.
add_custom_command (TARGET ${PROJECT_NAME} POST_BUILD
COMMENT "Code Signing Kext With: ${CODE_SIGN_ID}"
VERBATIM
COMMAND
/usr/bin/codesign -s "${CODE_SIGN_ID}" "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.kext"
)
The example.c file:
#include <sys/kernel_types.h>
#include <sys/systm.h>
kern_return_t example_start(kmod_info_t * ki, void *d) {
printf("Loaded example\n");
return KERN_SUCCESS;
}
kern_return_t example_stop(kmod_info_t *ki, void *d) {
printf("example unloading.\n");
return KERN_SUCCESS;
}
The example_info.c File. This is usually generated by xcode during the build process.
It just sets the main entry points to example_start and example_stop
#include <mach/mach_types.h>
extern kern_return_t _start(kmod_info_t *ki, void *data);
extern kern_return_t _stop(kmod_info_t *ki, void *data);
__private_extern__ kern_return_t example_start(kmod_info_t *ki, void *data);
__private_extern__ kern_return_t example_stop(kmod_info_t *ki, void *data);
__attribute__((visibility("default"))) KMOD_EXPLICIT_DECL(com.example, "1.0.0d1", _start, _stop)
__private_extern__ kmod_start_func_t *_realmain = example_start;
__private_extern__ kmod_stop_func_t *_antimain = example_stop;
__private_extern__ int _kext_apple_cc = __APPLE_CC__ ;
The complete cmake file.
cmake_minimum_required (VERSION 3.8)
project (example)
set(CODE_SIGN_ID "Developer ID Application: Your Name. (XYZZYYZYZY)")
set(CMAKE_OSX_SYSROOT /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/)
if(CMAKE_BUILD_TYPE MATCHES Debug)
add_definitions(-DDEBUG)
endif()
add_definitions(
-DKERNEL
-DKERNEL_PRIVATE
-DDRIVER_PRIVATE
-DAPPLE
-DNeXT
)
include_directories(
${CMAKE_OSX_SYSROOT}/System/Library/Frameworks/Kernel.framework/PrivateHeaders
${CMAKE_OSX_SYSROOT}/System/Library/Frameworks/Kernel.framework/Headers
)
add_executable(
${PROJECT_NAME}
MACOSX_BUNDLE
example.c
example_info.c
Info.plist
)
set_target_properties(${PROJECT_NAME} PROPERTIES BUNDLE_EXTENSION kext MACOSX_BUNDLE_INFO_PLIST ${PROJECT_SOURCE_DIR}/Info.plist)
add_compile_options(${PROJECT_NAME}
-x c -arch x86_64 -fmessage-length=0
-fdiagnostics-show-note-include-stack
-fmacro-backtrace-limit=0 -nostdinc
-std=gnu99 -fmodules -gmodules
-Wnon-modular-include-in-framework-module
-Werror=non-modular-include-in-framework-module
-fno-builtin -Wno-trigraphs -msoft-float -O0 -fno-common
-mkernel -Wno-missing-field-initializers -Wno-missing-prototypes
-Werror=return-type -Wdocumentation -Wunreachable-code
-Werror=deprecated-objc-isa-usage -Werror=objc-root-class
-Wno-missing-braces -Wparentheses -Wswitch -Wunused-function
-Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value
-Wempty-body -Wconditional-uninitialized -Wno-unknown-pragmas
-Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion
-Wint-conversion -Wbool-conversion -Wenum-conversion -Wshorten-64-to-32
-Wpointer-sign -Wno-newline-eof
-fasm-blocks -fstrict-aliasing -Wdeprecated-declarations
-mmacosx-version-min=10.11 -Wno-sign-conversion
-Winfinite-recursion -iquote
)
# delete this to not code sign
target_link_libraries(${PROJECT_NAME}
"-lkmodc++"
"-lkmod"
"-lcc_kext"
"-arch x86_64"
"-mmacosx-version-min=10.11"
"-nostdlib"
"-Xlinker -object_path_lto"
"-Xlinker -export_dynamic"
"-Xlinker -kext"
)
The magic Info.plist file. All references to “example” will need to match the binary and com.example items.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>BuildMachineOSBuild</key> <string>15G31</string> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>example</string> <key>CFBundleIdentifier</key> <string>com.example</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>example</string> <key>CFBundlePackageType</key> <string>KEXT</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSupportedPlatforms</key> <array> <string>MacOSX</string> </array> <key>CFBundleVersion</key> <string>1</string> <key>DTCompiler</key> <string>com.apple.compilers.llvm.clang.1_0</string> <key>DTPlatformBuild</key> <string>8A218a</string> <key>DTPlatformVersion</key> <string>GM</string> <key>DTSDKBuild</key> <string>16A300</string> <key>DTSDKName</key> <string>macosx10.12</string> <key>DTXcode</key> <string>0800</string> <key>DTXcodeBuild</key> <string>8A218a</string> <key>NSHumanReadableCopyright</key> <string>Copyright © 2017 Someone. All rights reserved.</string> <key>OSBundleLibraries</key> <dict> <key>com.apple.kpi.bsd</key> <string>8.0.0</string> <key>com.apple.kpi.libkern</key> <string>8.0.0</string> <key>com.apple.kpi.mach</key> <string>8.0.0</string> </dict> </dict> </plist>
GitHub Repository with the example.
Cocos2dx Binary Project Mac OSX – binary template not found
Trying to build cocos2d-x-3.13.1 with a binary template for mac os x?
Problem:
cocos new bob -p com.bob.game -l cpp -t binary Template named 'binary' is not found. Multiple templates detected! You can select one via -t arguments. Or choose one now: 1 default
Solution:
Build the prebuilt libraries:
cocos gen-libs -c -p mac
Build the templates
cocos gen-templates
Now it works.
cocos new MyGame -p com.MyCompany.MyGame -l cpp -d bob -t binary
Android Studio Mac Extremely Slow
Downloaded the latest Android Studio: 2.1.3 for mac and it won’t boot or run anything.
Seems first off you need to run the emulator on sudo or it will segfault. After launching from Android Studio you see it tried to run something like: /Users/user/Library/Android/sdk/tools/emulator -netdelay none -netspeed full -avd Galaxy_Nexus_API_22. end then segfaults.
Copy the command and run:
sudo /Users/user/Library/Android/sdk/tools/emulator -netdelay none -netspeed full -avd Galaxy_Nexus_API_22
So now it doesnt’ boot or appears to boot but takes days… you reboot because you can’t kill the thing either. Maybe you have installed Virtual Box on you machine at some point and it turns out the kernel modules form virtual box interfere with the intel/google/android emulator( com.intel.kext.intelhaxm )
Solutions:
Uninstall VirtualBox…
Or
sudo kextunload -b org.virtualbox.kext.VBoxUSB sudo kextunload -b org.virtualbox.kext.VBoxNetFlt sudo kextunload -b org.virtualbox.kext.VBoxNetFlt sudo kextunload -b org.virtualbox.kext.VBoxNetAdp sudo kextunload -b org.virtualbox.kext.VBoxDrv
Enjoy the still slow emulator but it seems to work…
How to detect if your system tray icon has gone missing, C/C++, Win32
The Problem:
Sometimes if either the desktop crashes or windows decides to go wrong for whatever reason, it re-creates the system tray. There is no way to detect when that happens and your icon is now missing but your system tray application is still running.
The Solution:
Windows does send a windows message to be notified when the system tray is being created. It won’t be sent to you unless you register to receive it.
To register to receive the message do the following and store the ID that is returned. The simplest way to do this is to store it in a global variable.
const int uTaskbarCreatedMsg = RegisterWindowMessageA("TaskbarCreated");
Then later on in your windows message loop handle the message.
LRESULT CALLBACK WndProc(HWND w, UINT msg, WPARAM wparam, LPARAM lparam)
{
// ... handle other messages
if (msg == uTaskbarCreatedMsg) {
// Destroy any existing icon and recreate it
CreateSystemTrayIcon();
return 0;
}
// ... default message handling
}
Related Links
Related Searches
- how to detect if the system tray is gone msdn
- how to detect if the system tray is gone
- systray icon restart after explore.exe crashes
- catch explore restart message msdn
- win32 message for when explorer.exe starts msdn
- windows message for when explorer.exe starts msdn
- systray icon dissapears after sleep
- windows message for when system awakes from sleep
Powder Alliance Google Map
The following is a google map with all the locations of the resorts in the Powder Alliance.
How to get rid of unwanted directories from an subversion checkout
The Problem
Using svn if you’ve checked out a tree but didn’t want the entire tree how can you get rid of some of the subfolders. This is generally a problem if there are some really big folder slowing down diff or other operations in the tree.
Example
You have checked out http://server/trunk but there is a gigantic folder that was checked out and you want to remove it from the checkout but not svn continues to annoy you saying that you’ve deleted it. Further if you simply delete the folder it will show as deleted every time run svn diff.
svn co http://server/trunk
Resulting in
trunk/one trunk/two trunk/three
The Solution
cd trunk rm -rf three svn up -N three
If That Doesn’t Work
rm -rf three svn update --set-depth empty three
The folder will still be there but it will not cause problems with everyday life.