Posted by & filed under Coding.

Working on a small weekend project I needed an easy way to validate that a string contained a valid Twitter username. Not necessarily an active account, but that could be an account.

Found the rules on Twitter’s site that a username can be between 1 and 15 characters and can contain only the characters A-Z, a-z, 0-9, or an underscore. Sounds like a perfect use for regex. So here it is, both in JavaScript and PHP since I needed both.

Posted by & filed under Code Tips.

For a Moodle plugin I’m writing I needed a way to check if a String exists. Normally, if a string doesn’t exist then Moodle just outputs [[missing_string]] (replace missing_string with whatever you’re calling the string) and moves on. But, in developer or debug mode it also displays a stack trace.

What I needed was a way to check if a string was set, and if not display a different string which I knew was set. This is what I came up with.

function get_string_check($identifier) {
	if (!get_string_manager()->string_exists($identifier, 'plugin_name')) {
		return get_string('a_known_string', 'plugin_name');
	}
	return get_string($identifier, 'plugin_name'); 
}

The reason I needed this was that I was building strings based on error constants. So there might be a string err_1, err_2, err_3, etc. But I needed a way to not display an error if I requested err_99 without there actually being that string.

The only catch is that the you must have $string['a_known_string'], or whatever you want to call it, in the language file for your plugin. For me, it just says Unexpected Error.

Posted by & filed under Code Tips.

Not really code, but still something I need often enough to write it down.

This command will list all files in a Linux folder sorted by date with the most recently updated files at the bottom.

ls -ltrh

From the ls man page, here’s what each of the choices do.

-l – Uses a Long format which shows more information on each file

-t – Sorts by modification time

-r – Reverse order. Without this the most recently updated files would be at the top of the list instead of the bottom.

-h – Human friendly file sizes. Shows files in KB, MB, or GB instead of just bytes.

Posted by & filed under Code Tips.

This snippet will let you run the same command using each line from a file as a parameter.

cat filename.txt | while read in; do echo "$in"; done

As written it’ll open up filename.txt and echo out every line. Probably not what you want, so replace echo “$in” with whatever command you want to run. The $in variable is the line it’s pulling out of the file.

What I needed this for was to block a bunch of IP addresses that were hitting honeypot files on a server so instead of echo I was running csf to add the IP.

Posted by & filed under Code Tips.

This little batch file came about from needing to run a cron job from within XAMPP. Since it’s Windows I could have used a scheduled task, but I don’t have XAMPP running all the time and I wanted a little more control over when it runs.

And on this specific project, I’m working on a Moodle plugin that needs to run under cron every minute. So the program that’s running is PHP calling the Moodle CLI cron.php file. You’re probably going to want to change the script that’s called.

:loop
php /path/to/your/script.php
@timeout /t 60
@goto loop

You’ll want to change the 2nd line to whatever you want to run. Add as many lines as you want. And then change the 60 on the 3rd line to however many seconds you want it to wait. I needed it to run every minute so I’m using 60 seconds.

Now when I need to have cron active I just drop to the command line and run this batch file and leave it running until I’m done.

And for those that haven’t dealt with the command line in a while, or ever, pressing Ctrl-C will terminate the batch file.

Posted by & filed under Code Tips.

Fighting against an issue with the sendmail queue getting filled with junk I needed a way to delete a folder full of messages, and there were too many for rm to delete.

A post on Stack Overflow had the solution. Only thing I added was the -v option to rm so that it displays the files as they’re being deleted just to double check that something was actually happening.

for f in *.pdf; do rm -v "$f"; done

Posted by & filed under Code Tips.

Found this one on Stack Overflow needing a quick and easy way to create somewhat random strings.

function randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
    	var randomPoz = Math.floor(Math.random() * charSet.length);
    	randomString += charSet.substring(randomPoz,randomPoz+1);
    }
    return randomString;
}

If you visit the entire thread where this code was posted there’s a pretty good discussion of how to create random strings using math and date functions.

Posted by & filed under Code Tips.

As a follow up to an earlier post on double braces in Java, came up with a short, but ugly way of filling an ArrayList via an array.

String[] ray = {"Hi", "there", "Bob"};
ArrayList<String> lst = new ArrayList<String>() {{
	for (String s: ray) { add(s); }
}}

Of course, at that point you might as well just do this.

ArrayList<String> lst = Arrays.asList(new String[]{"Hi", "there", "Bob"});

Posted by & filed under Code Tips.

This is one of those that I never remember, but use a lot whenever I want to pull an entire file into a String quickly.

String text = new Scanner(new File("file.txt")).useDelimiter("\\A").next();

\\A is the start of the file, so Scanner is going to try and split on the beginning of the file. Since there’s only one beginning, there’s only one next.