lessphp: watch imported files, too - less

An always annoying problem i had with lessphp (and also less compiling in rails or python/django) is that it is only watching the file which to compile but NOT the imported files.
For example my less structure looks something like this:
// main.less
// (compiled to styles.css)
#import "variables"
#import "objects"
#import "theme"
.
// theme.less
// (actual styles)
body { background:#efefef }
So the actual compiled file is only the root to import the styles and files i work on. Everytime i make a change on my styles(theme.less) i have to edit the main.less so it gets recompiled.
Is there any option to check ALL files for changes like it does on client-side compile(less.js)?

When you inspect the source of the php lessc compiler, which can be found at https://raw.githubusercontent.com/oyejorge/less.php/master/bin/lessc, you will found that the script only evaluate the modification time of the Less file that you have passed as argument.
When you less files are in /home/project/less you can add for instance the following code inside the while(1) loop in bin/less, around line 125:
while (1) {
clearstatcache();
//keep original code here
$dir = '/home/project/less';
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
if(preg_match('/\.less$/',$filename) && filemtime($filename) > $lastAction)
{
$updated = true;
break;
}
}
if($updated) break;
}

Related

less variables in different files with gulp

I'm working on a gulp task about compressing less and minify css, the only point it's troublesome is that I need some hardcoded 3 different variables in the 3 different environments(local, dev, prod) with 3 files.less. I swap the right version of right environment each time after deleting it (the original file).
And in the main.less file I include the original.less file.
(Mi english and explication skills doesn't bright)
gulp.task('before-less', function(cb) {
if(gutil.env.dev === true) {
gutil.log(' preprod environment \n'); gulp.src('path/to/dev.less').pipe(rename('original.less')).pipe(gulp.dest('path/to/css'));
} else if (gutil.env.prod === true) {
gutil.log(' prod environment \n');
gulp.src('path/to/prod.less').pipe(rename('original.less')).pipe(gulp.dest('path/to/css'));
} else {
gutil.log(' local environment \n');
gulp.src('path/to/local.less').pipe(rename('original.less')).pipe(gulp.dest('path/to/css'));
}
});
gulp.task('less', ['before-less'], function() {
gutil.log(' LESSing ');
gulp.src(rute + 'css/*.less')
.pipe(less({
paths: [path.join(__dirname, 'less', 'includes')]
})).on('error', gutil.log)
.pipe(minifycss()) // Minify
.pipe(gulp.dest(rute + 'css'))
// .pipe(notify({message : "Modifications LESS" }))
.pipe(connect.reload());
});
The task of less I think that runs correctly, but the question is when the gulp less include my file of original.less they should be read the var first or they include it first and later read the var?
I include my gulp task for someone have a better organization about this "problem"
I think you should considersubtasks or complete different tasks for your different situations.
The task of less I think that runs correctly, but the question is when
the gulp less include my file of original.less they should be read the
var first or they include it first and later read the var?
Less uses lazy loading and last declaration wins for variables, see also http://lesscss.org/features/#variables-feature-lazy-loading. The preceding means that if you declare the same variable again after your include it will override the variable everywhere in your code.
I find the solution with runSequence gulp package.
Because I find that Gulp can work synchronously and mi second task less begins after mi first task before-less and they fail and gives me an Error.
With runSequence I can do something like that:
var runSequence = require('run-sequence');
gulp.task('default', function(callback) {
runSequence('before-less', ['less'], callback);
});
source
finding more information about gulp synchronously this could be really good other option and more 'elegant node' (using callbacks).

How to create a Dynamic Library in D?

I want to create a Dynamic library (cross-platform) in D, so I did some Googling. After some time I found this page. I am absolutely stunned by how much complexities there are in writing, compiling and even linking to a DLL. Isn't there a uniform way of creating a shared library like you would in C? (just leave out the main function and pass some flags to the linker)
Well, I decided to spend some time today messing with this and I kinda sorta have something that works, at least if the main program is also written in D (on Linux, I think it will work from C too on Windows. The reason is I didn't link to phobos in the .so in the D one, so it relies upon the exe for those symbols. I think, tbh I don't know exactly what is going on here, maybe it would work better if I used the shared phobos lib too)
Anyway, first, let's throw some code down.
This is testdll.d and it builds our dll
module testdll;
import std.stdio;
extern(C)
export void lol() {
import core.stdc.stdio;
printf("hello from C\n");
writeln("hello!");
}
version(Windows)
extern(Windows) bool DllMain(void* hInstance, uint ulReason, void*) {
import std.c.windows.windows;
import core.sys.windows.dll;
switch (ulReason)
{
default: assert(0);
case DLL_PROCESS_ATTACH:
dll_process_attach( hInstance, true );
break;
case DLL_PROCESS_DETACH:
dll_process_detach( hInstance, true );
break;
case DLL_THREAD_ATTACH:
dll_thread_attach( true, true );
break;
case DLL_THREAD_DETACH:
dll_thread_detach( true, true );
break;
}
return true;
}
You'll notice most that code is the WinMain which just calls druntime functions. I think that main should be available at least as a mixin, or maybe even fully automatic, since it is pure boilerplate.
And the client code:
import core.runtime;
alias extern(C) void function() functype;
version(Posix) {
extern(C) void* dlsym(void*, const char*);
extern(C) void* dlopen(const char*, int);
extern(C) char* dlerror();
pragma(lib, "dl");
} else version(Windows) {
extern(Windows) void* LoadLibraryA(const char* filename);
extern(Windows) void* GetProcAddress(void*, const char*);
}
void main() {
version(Posix) {
auto thing = dlopen("./testdll.so", 2);
if(thing is null) {
import std.conv;
import std.stdio;
writeln(to!string(dlerror()));
return;
}
auto proc = cast(functype) dlsym(thing, "lol");
} else version(Windows) {
auto thing = LoadLibraryA("testdll.dll");
assert(thing !is null);
auto proc = cast(functype) GetProcAddress(thing, "lol");
}
assert(proc !is null);
//import std.stdio; writeln("calling proc");
proc();
}
This has different code for Windows and Linux, though it is pretty similar. The druntime stuff is supposed to start taking care of this soon as we mentioned in the comments.
The compile commands aren't too bad but a little weird. Linux first:
dmd -fPIC -shared testdll.d -defaultlib= # builds the dll
PIC and shared tell it to build the .so. I did the blank defaultlib because without it, loading the dll at runtime failed with "symbol already defined" errors.
Building the client is straightforward:
dmd testdllc.d
Note that there's the pragma(lib) in the file that links with the -ldl option automatically. Run it and get some hello! BTW be sure both are in the same directory since this loads ./ in the loader.
Now, let's build on Windows.
dmd -oftestdll.dll -shared testdll.d testdll.def
Tell it to output our dll, use -shared so it knows, and then the other thing is the def file, like described here http://dlang.org/dll.html/dllmain
These are the contents of that file:
LIBRARY testdll
EXETYPE NT
CODE SHARED EXECUTE
DATA WRITE
EXPORTS
lol
If you don't use the .def file, the dll will build successfully, but the procedure won't be found because it isn't exported. (I think the export keyword in D should be able to do this automatically, bypassing hte .def file, and I believe there's a discussion on doing this, but right now it is required as far as I know.)
And the client is similarly easy:
dmd testdllc.d
Run it and get some hellos, if all goes well.
Now, why did I do the functype alias in the client? Easier than doing the other casting and such, and it makes it nicely extern(C).
Why is the lol function extern(C) in the first place? Just so it has an easier name to use in GetProcAddress/dlsym. Could have also pragma(mangle) or did .mangleof with an import thing. All kinds of options there, fairly straightforward, I just wanted to keep it simple to make the test easier to focus on. "lol" is a simpler name than "_D7testdll3lolFZv" or whatever the mangled name would be.... (OMG I mangled it correctly by hand! Sometimes I think I write too much D lol) and yeah that works too it is just harder to do by eyeball. Note: on Windows, the .def file might have to leave off the leading underscore if you do it that way.
anyway, yeah, this made a working dll/so for me and a program to load and use it successfully. Not as pretty as it could/should be, but it works. For me at least.

OpenNI 1.5::Could not run code from documentation

I am trying to run a sample code from the OpenNI 1.5 documentation.I have imported the library required XnCppWrapper.h so that I can use C++.The code has only one error on a particular variable "bshouldrun".I know that it should be declared as something but since I am new at this and the documentation does not contain anything above the main, I dont know what to declare it as..Please help!!
And thanks in advance.
#include <XnOpenNI.h>
#include <XnCppWrapper.h>
#include <stdio.h>
int main()
{
XnStatus nRetVal = XN_STATUS_OK;
xn::Context context;
// Initialize context object
nRetVal = context.Init();
// TODO: check error code
// Create a DepthGenerator node
xn::DepthGenerator depth;
nRetVal = depth.Create(context);
// TODO: check error code
// Make it start generating data
nRetVal = context.StartGeneratingAll();
// TODO: check error code
// Main loop
while (bShouldRun) //<-----------------------------**ERROR;bShouldRun Undefined**
{
// Wait for new data to be available
nRetVal = context.WaitOneUpdateAll(depth);
if (nRetVal != XN_STATUS_OK)
{
printf("Failed updating data: %s\n", xnGetStatusString(nRetVal));
continue;
}
// Take current depth map
const XnDepthPixel* pDepthMap = depth.GetDepthMap();
// TODO: process depth map
}
// Clean-up
context.Shutdown();
}
Here's what I did to run a sample from Visual Studio 2010 Express on Windows (8):
Opened the NiSimpleViewer.vcxproj VS2010 project from C:\Program Files (x86)\OpenNI\Samples\NiSimpleViewer
Edited OpenNI.rc to comment out #include "afxres.h" on line 10(might be missing this because I'm using Express version, not sure. Your machine might compile this fine/not complain about the missing header file)
Enabled Tools > Options > Debugging > Symbols > Microsoft Symbol Servers (to get past missing pdb files issue)
Optionally edit the SAMPLE_XML_PATH to "SamplesConfig.xml" rather than the default "../../../Data/SamplesConfig.xml", otherwise you need to run the sample executable from ..\Bin\Debug\NiSimpleViewer.exe by navigating to there rather than using the Ctrl+F5. A;so copy the SamplesConfig.xml file into your sample folder as you can see bellow
Here are a few images to illustrate some of the above steps:
You can also compile the NiHandTracker sample, which sounds closer to what you need.
So this explains the setup for OpenNI 1.5 which is what your question is about.
I've noticed your OpenNI 2 lib issue in the comments. It should be a matter of linking against SimpleHandTracker.lib which you can do via Project Properties (right-click project->select Properties) > Linker > Input > Additional Dependencies > Edit.
I don't have OpenNI2 setup on this machine, but assuming SimpleHandTracker.lib would be in OpenNI_INSTALL_FOLDER\Lib. Try a file search in case I might be wrong.

Open file with own application written in objective-c

I would like to know how can I open a file with my OS X application, which I wrote in Objective-C. I registered the file types in Info.plist and I have application:openFile: in my code. I did everything by this post, which was marked as solved.
The problem is that this works only if I drag and drop my file on my application while it is running. But it doesn't work if I just double click on my file. It starts my application, but not as it would start if I would drag and drop. So the code which is in application:openFile: doesn't run when double-clicked, but only when I drag and drop my file.
EDIT:
Some more detail about my code, and what I am trying to achieve.
I created a wrapper application for an other app. Let's call the other app the "HelperApp.app". This HelperApp is inside the /Contents/ folder of my wrapper app. With the wrapper app I specified a new file type, let's call it ".ha" in the Info.plist file. This file contains some argument commands. What I try to achieve, that when a user clicks on a file which is a ".ha" file, then my wrapper app reads in the argument from this file and sets it for the HelperApp, then starts the HelperApp. This HelperApp is opening different things depending on the argument it gets. Below you can check my code.
I have an AppDelegate.h and an AppDelegate.mm by default how the newest Xcode creates it. I added this line to my AppDelegate.h, just before the "#end":
- (BOOL)processFile:(NSString *)file;
I have these functions in my AppDelegate.mm:
#import "AppDelegate.h"
#import "ArgumentParser.h"
#implementation AppDelegate
- (void)dealloc
{
[super dealloc];
}
- (BOOL)application:(NSApplication *)WrapperApp openFile:(NSString *)filename
{
return [self processFile:filename];
}
- (BOOL)processFile:(NSString *)file
{
NSLog(#"The following file has been dropped or selected: %#",file);
std::string path = [file cStringUsingEncoding:[NSString defaultCStringEncoding]];
ArgumentParser parser = ArgumentParser();
parser.getArgumentfromFile(path);
parser.setArgumentinFile(); // <== This is the "corrupted" function
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *helperAppPath = [[mainBundle bundlePath]
stringByAppendingString:#"/Contents/HelperApp.app"];
[[NSWorkspace sharedWorkspace] launchApplication:helperAppPath];
return YES;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
}
The corrupted function - setArgumentinFile():
void ArgumentParser::setArgumentinFile() {
std::string content = ""; // The file content
std::fstream file;
file.open("HelperApp.app/Contents/Wrapper/HelperApp.app/Contents/Info.plist");
// Open the file and modify the arguments
if(file.is_open()) {
std::stringstream stream;
stream << file.rdbuf();
std::string line = "";
bool isIt = false;
while(getline(stream, line)) {
// This line is the argument list, which needs to be modifyed
if(isIt) {
int index = (int)line.find_last_of("<");
std::string start = line.substr(0, index);
std::string end = line.substr(index, std::string::npos);
std::string argument_list = start + " " + _argument + end;
content += argument_list + '\n';
isIt = false;
}
// Save the rest of the file so we can overwrite it
else {
content += line + '\n';
}
// Next line is the argument list
if(line.find("WineProgramArguments") != std::string::npos) {
isIt = true;
}
}
file.flush();
file.close();
}
else {
file.flush();
file.close();
throw std::runtime_error("File isn't opened");
}
file.open("HelperApp.app/Contents/Wrapper/HelperApp.app/Contents/Info.plist", std::ios::out);
// Open the file and overwrite it with the modifyed argument
if(file.is_open()) {
file << content;
file.flush();
file.close();
}
else {
file.flush();
file.close();
throw std::runtime_error("File isn't opened");
}
}
If I comment out the above function from the processFile function in AppDelegate, then everything works "smoothly". I mean the wrapper app starts and it starts the HelperApp with default arguments. So here should be the error...
If you've implemented -application:openFile:, it should be called when you double-click a file of the type that you've registered. You say that the app launches, so the OS is trying to use your app to open the file. Here's a useful note from the documentation:
If the user started up the application by double-clicking a file, the
delegate receives the application:openFile: message before receiving
applicationDidFinishLaunching:. (applicationWillFinishLaunching: is
sent before application:openFile:.)
So, if you're doing anything in -applicationDidFinishLaunching: that has to be done before you open any files, that could be your problem. Consider moving your app initialization code to -applicationWillFinishLaunching:.
I've figured it out. When you double-click on a file icon, the application will launch itself, other things done correctly. But the application that responds to your action is not necessarily the one that you built for the last time. Probably, an old copy of your application is responding. Take a look at Library > Developer > Xcode > DrivedData. You should see many folders for your application. You can locate your application folders by right-clicking and choosing Shown In Finder after build one. Trash them all, and build a new application. Then double-click and see what happens now.
The problem was, that I gave the wrong path in my function. This path worked if I started the app from Xcode, but did not if I started the app by itself.
Here is the post which solved my problem!
right-click vs. double-click to open a file behave differently!
Apple Docs:
If the user started up the application by double-clicking a file, the delegate receives the application:openFile: message before receiving applicationDidFinishLaunching:. (applicationWillFinishLaunching: is sent before application:openFile:.)
The Apple Docs leave out a vital piece of info...
I had assumed that a right-click -> 'Open With'
operation in Finder would be the same as a double-click.
Its NOT!
application:openFile: happens AFTER applicationDidFinishLaunching: in this case!
Was scratching my head for an hour on this one.

User defined functions with LessCSS?

I have just recently gotten into LessCSS and I am running into what I feel is major limitation and I was wondering if there was a way to do this?? I want to say I read somewhere that Sass allows for user defined functions but will LessCSS do the same?
What I'm wanting to do:
#fs: 16;
// either return the value
.s(#t,#s,#u) {
// return #t/#s*#u;
}
#elem {
margin-top: .s(30,#fs,1em);
width: .s(900,#fs,1em);
.child {
width: .s(100,900,100%);
}
}
// or have a property argument
.s(#t,#s,#u,#p) {
#{p}: #t/#s*#u;
}
#elem {
.s(30,#fs,1em,margin-top);
.s(900,#fs,1em,width);
.child {
.s(100,900,100%,width);
}
}
The only way I can figure it out, but it is very limited because I have to have multiple mixins:
.s(#t,#s,#u,#p) when (#p = margin-top) { margin-top: #t/#s*#u; }
// margin[-top|-right|-bottom|-left]
// padding[-top|-right|-bottom|-left]
.s(#t,#s,#u,#p) when (#p = width) { width: #t/#s*#u; }
.s(#t,#s,#u,#p) when (#p = height) { height: #t/#s*#u; }
I know I can always modify the less.js file to add a spacing function like the built-in round() or ceil() function. But, that kills the option of compiling the .less files for production using LessPHP, Crunch, SimpLess.
As far as I know, there's no property argument: you must write it down.
That is, a function will return a calculated value or instruction(s) (property/ies and calculated values).
There aren't thousands of properties in CSS, it's not a CMS with hundreds of classes and functions, so your list won't be as long as you can imagine. You should use other CSS preprocessors or a backend language to generate your CSS if you want to do such complicated things. Or better keep it simple.
That said, lessphp allows for user functions:
lessphp has a simple extension interface where you can implement user functions that will be exposed in LESS code during the compile. They can be a little tricky though because you need to work with the lessphp type system.
Notice that you also can easily add custom functions to the default Less compiler, which enable you to use the client side less.js compiler for testing and the command line lessc compiler for production.
For Less 1.x
Download and unzip the source from github at: https://github.com/less/less.js/releases/latest
Run npm install
Open the lib/functions.js file
Add your custom function (returncenter() in this example) inside the tree.functions object, for instance as follows:
tree.functions = {
returncenter: function() {
return new(tree.Anonymous)('center');
},
//original function below
}
Run grunt dist
After the preceding step you can include dist/less-1.x.x/js in your HTML or compile your Less code with the dist/lessc compiler.
For Less 2.x
Download and unzip the source from github at: https://github.com/less/less.js/archive/master.zip
Run npm install
Create a file caleld lib/less/functions/custom.js and write down the following content into it:
var Anonymous = require("../tree/anonymous"),
functionRegistry = require("./function-registry");
functionRegistry.addMultiple({
returncenter: function() {
return new(Anonymous)('center');
}
});
Open the lib/less/function/index.js file and append require("./custom"); to the list of register functions, just before return functions;
Run grunt dist
Now you can use the following Less code:
selector {
property: returncenter();
}
The preceding Less code will compile into the following CSS code:
selector {
property: center;
}