Status
Not open for further replies.

SplitIce

Active Member
2,474
2008
240
0
Disclaimer: Ok, just an idea I thought up. Might take off, might not.

With that out of the way let me introduce snippet of the day. In this thread you may post one snippet of code a day (at most) that you are particularly proud of.

Rules:
  • Snippets must be at most 15 lines long. Try to keep them as short as possible.
  • You must have written them yourself and within the course of the day.
  • Any language is allowed
  • No insulting peoples coding. Although that said, if you just started developing in a language this probably isnt the best place to post.
  • Constructuve Critisizm is allowed, just keep it constructive and polite.
  • Links to source are allowed
  • Editing of constants to increase readability is fine.
  • No short replies, use the like feature.
  • CSS/HTML and languages similar can be longer, however a link to a demo site must be provided.
  • A short explanation would also be cool.

Also remember there is no such thing as perfect code, feel free to post improvements (especially to my code). Could also be called a code review thread, so don't post if you don't want to see your code cut up and reassembled. Its all fun, join in. Share your knowledge.

The first one, nothing amazing just something to start with. Im sure you have something cooler.

PHP:
$sql = $this->table()
		->select('MAX(order)')
		->left_join(IP::TABLE)
		->where(array('lease_id'=>$lease->getId(),'ip_version'=>4));
 
Last edited:
41 comments
Not a bad idea but I doubt many people will post. Especially not enough to keep it active/bumped.

Either way:

PHP:
	array_walk($a, function(&$v, $k) {
		$v = parse_url(preg_match('#^http://#', $v) ? $v : 'http://' . $v);
	});

Just what I happened to have in vim at the minute. Nothing special really, just parses an array of URLs in one go.
I cut a chunk out to simplify it for posting here, my original code validates each URL instead of assuming ones without 'http' are valid.
 
Building a steam scraper for a client
Basically the point is to get the appid from the steamstore from a game name which is in the variable $game

PHP:
$string = file_get_contents('http://store.steampowered.com/search/?snr=1_4_4__12&term='.$game.'');

preg_match('#http://store.steampowered.com/app/(.*)/?snr=1_7_7_151_150_1#', $string, $matches);

$result = substr("$matches[1]", 0, -2);

Just a short version does more also don't laugh im still learning php
 
Nice idea :) well its not much but here :|

PHP:
$f = array_map('addExt', explode(',', $_GET['f']));
$hash = '';
foreach ($f as $files) {
	$mtime = @filemtime($files);
	$hash .= date('YmdHis', $mtime ? $mtime : NULL).$files; }
$hash = md5($hash);

Basically it gets a file extension from addExt (which is a function) which is returned and foreach file that is called will store it uniquely and their change time i usually do this when i either i want to cache something in a basic way not much in the high-end coding with php but at least its something ;)
 
Building a steam scraper for a client
Basically the point is to get the appid from the steamstore from a game name which is in the variable $game

Thats fine mate, heres a slightly improved version for you.

PHP:
$string = file_get_contents('http://store.steampowered.com/search/?snr=1_4_4__12&term='.urlencode($game)); 

if(preg_match('#http://store.steampowered.com/app/(.*)/?snr=1_7_7_151_150_1#', $string, $matches)){
     $result = substr(urldecode($matches[1]), 0, -2); 
}else
    die('Scrape Failed');


---------- Post added at 11:11 AM ---------- Previous post was at 10:59 AM ----------

Nice idea :) well its not much but here :|

Basically it gets a file extension from addExt (which is a function) which is returned and foreach file that is called will store it uniquely and their change time i usually do this when i either i want to cache something in a basic way not much in the high-end coding with php but at least its something ;)

PHP:
<?php
$files = array_map('addExt', explode(',', $_GET['f']));
echo splitice_hash($files);

function splitice_hash($files){
	//Calculate
	$hash = count($files);
	foreach ($files as $file) {
		if(file_exists($file))
			$hash ^= filemtime($file);
	}
	
	//Convert to hex, its not as long as MD5 though, you could str_repeat it if hash size is a requirement.
	$hash = dechex($hash);
}

Its not as distributed (security) but as for content matching it should do the job. For a little extra matching ability you could also add a " ^ crc32($file)"

---------- Post added at 11:36 AM ---------- Previous post was at 11:11 AM ----------

Not a bad idea but I doubt many people will post. Especially not enough to keep it active/bumped.


Just what I happened to have in vim at the minute. Nothing special really, just parses an array of URLs in one go.
I cut a chunk out to simplify it for posting here, my original code validates each URL instead of assuming ones without 'http' are valid.

Oh noes totally going to get banned for this (sarcasm). I guess there may be a reason you didnt use array_map (part of a larger function) but for the benefit of the thread readers.

PHP:
array_map(function($v) {
        return parse_url(preg_match('#^http://#si', $v) ? $v : 'http://' . $v);
    },$a);

Just a quick explanation of the changes since they are minor:
  1. preg match 's' flag optimizes the expression (good when it needs to be used multiple times)
  2. preg_match 'i' flag for case insensitivity
  3. array_map not array_walk for mapping values (no reference)

Also just note the parameter order switch, an example of the inconsistencies in PHP.

Using radical-php if anyone is interested.
PHP:
$array = new \Basic\Arr\Object\ArrayObject();
//...
$array->Map(function($v) {
        return parse_url(preg_match('#^http://#S', $v) ? $v : 'http://' . $v);
 });

EDIT 4:
Actually on second thoughts if you wanted to be pedantic:
PHP:
function($v) {
    return parse_url(substr_compare($v, 'http://', 0, 7) ? 'http://' . $v : $v);
}
Although thats taking it too far right? Still I dont think anyone could do it more efficiently (a challenge).
 
Last edited:
Oh noes totally going to get banned for this (sarcasm). I guess there may be a reason you didnt use array_map (part of a larger function) but for the benefit of the thread readers.

PHP:
array_map(function($v) {
        return parse_url(preg_match('#^http://#si', $v) ? $v : 'http://' . $v);
    },$a);

Just a quick explanation of the changes since they are minor:
  1. preg match 's' flag optimizes the expression (good when it needs to be used multiple times)
  2. preg_match 'i' flag for case insensitivity
  3. array_map not array_walk for mapping values (no reference)

Also just note the parameter order switch, an example of the inconsistencies in PHP.

EDIT 4:
Actually on second thoughts if you wanted to be pedantic:
PHP:
function($v) {
    return parse_url(substr_compare($v, 'http://', 0, 7) ? 'http://' . $v : $v);
}
Although thats taking it too far right? Still I dont think anyone could do it more efficiently (a challenge).

Here:
- No, 's' does not make it more efficient, it makes the dot character ('.') include newlines, the default is to exclude newlines
- Case insensitivity was not needed in my code, it was passed through strtolower beforehand (paths were irrelevant for my usage, so loss of case did not matter)
- array_walk because I wanted to change the array in place, not allocate memory for a copy of the array and change that instead.

Doing it more efficiently... well the fact that I used array_walk to change the same array in-place likely outperforms your suggested alternative already. I am not creating any new variables, rather changing the same ones in memory, one by one.

As for the guy above using regex, use (\d+) not (.*).
 
My fault, 'S'. Ill fix that pure typo.
When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for matching. If this modifier is set, then this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that do not have a single fixed starting character.
Guess it wouldn't help you anyway.



And yep (\d+) would be better persuming steam IDs are numeric (urldecode isnt actually necessary then either. Although im not sure about why the substr is there in that case. Guess we shouldnt improve code we know nothing about. Ey.
 
Last edited:
Code:
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))

Just a little something to get rid of absolute paths.
Very common in code.
Extremely useful.

I didn't invent it. But I did figure it out myself. Reinvented the wheel.
 
Yeah very common, in PHP for those who dont know.

pre 5.3
PHP:
$PROJECT_PATH = realpath(dirname(__FILE__));

post 5.3
PHP:
$PROJECT_PATH = realpath(__DIR__);
 
Day 2 and ready for another post :D
Anyhow this is something i done awhile back for vBulletin. For those whom use cyb - chatbox may see this useful its only the gist of things to make custom commands since cyb lacks on it :P Anyhow here is a /ban one limited to 15 lines so this is gist

PHP:
$vbulletin->GPC['ccb_newmessage'] = str_replace('/ban ', "".'', $vbulletin->GPC['ccb_newmessage']);
$banuserthis = $vbulletin->db->query_read("SELECT user.username, user.usergroupid, user.displaygroupid,user.userid FROM ".TABLE_PREFIX."user WHERE user.username = '".$banusername."' AND user.userid !='".$banusername."'");
$banuserthisone = $db->fetch_array($banuserthis);
$lists = explode(',',$vbulletin->options['cybchatbox_excluded_users']);
$userid = $banuserthisone['userid'];

$cybcb_banuser = $vbulletin->options['cybchatbox_excluded_users'].','.$cybcb_usertoban;                
$cybcb_banuser = str_replace(',,',',',$cybcb_banuser);                          
$cybcb_banuser = trim($cybcb_banuser, ',');
$vbulletin->db->query_write("UPDATE " . TABLE_PREFIX . "setting SET value = '".$cybcb_banuser."' WHERE varname = 'cybchatbox_excluded_users' ");

Basically once /ban {username} is executed, it'll select that user off the DB and ban that user following the correct order from , in the vBulletin options for cyb ban section is. Have note this is not the full code upon it, its just the gist upon it so hopefully it can help for those whom like to make their own commands :) I done this off the top of my head :P
(I may post the full code not sure though)
 
Interesting, but i do prefer my own implementation of such functionality.
Actually, it is in use on WJ right now, handles several commands in a generic fashion, meaning none of the main code needs to be altered when adding new ones.

I actually replaced a huge amount of the original code when modifying WJ's copy. Deleted most of the code and reimplemented it myself because the original was inadequate and inefficient.
 
JmZ but thats the vBulliten way. Its also the way you can tell vbulliten code appart.

My snippet, an example of when SQL is better than a query builder/prepared statements/ORM.

PHP:
function swap($inc){
		if($inc>=0) $inc = '+'.$inc;
		$sql = 'UPDATE '.self::TABLE.' t1, '.self::TABLE.' t2
				SET
				t1.cr_order=(@temp:=t1.cr_order),
				t1.cr_order = t2.cr_order ,
				t2.cr_order = @temp
				WHERE
				t1.cr_id='.$this->id.' and 
						(t2.lease_id='.$this->getLease()->getId().' AND t2.cr_order=t1.cr_order'.$inc.')';
		\DB::Q($sql);
	}

Its code for reordering values in a database (e.g moving cr:1 up one position might involve swapping with cr:3). The table is partitioned by lease_id.

$inc would be +1 to move up or -1 to move down.
 
Last edited:
Nah splitice you misunderstood.

Of course it'd be the "vbulletin way" either way. I was merely stating that I preferred my code as it has a generic (and secure) handler for commands, allowing for easy addition to the selection.

I re-coded half of the mod because I found the original code to be insufficient and inefficient. It was very procedural and repetative, very specific to the default features, meaning it didn't allow easy modification/extension.

Basically I didn't like the code, it wasn't up to standard, so I deleted most of it and wrote it myself.

The resulting code was still the 'vbulletin way', so I have absolutely no idea why you thought otherwise, lol.
 
Didnt say your new comment, just stating that repeated code, repeated SQL and long functions / scopes is how vbulliten is written (as apposed to normal programming practices).

I cant speculate as to your 'new' code as I havent seen it. My observations are based on my own experience and in response to 1only's sample.
 
How vB is written, probably, but plugins may be written in any way you wish as long as they work.

Most recent vb releases use classes for the data managers and what not anyway, pretty useful if you're coding plugins.

Anyway, a snippet:

PHP:
m = re.findall('^(?:(?:(?:(?:(SELECT) ([\w, ]+) FROM ([\w]+))|(?:(DELETE) FROM ([\w]+))|(?:(UPDATE) ([\w]+) SET ([\w,= ]+)))(?:(?: WHERE ([\w=>< ,]+))?))|(?:(INSERT) INTO ([\w]+) VALUES ([\w, \(\)]+)))$', query)[0]

From a few years back, I could write it way better now.

Basically I got bored one day so I made a small python app. It parsed SQL queries and performed their actions on dictionaries. So I essentially wrote an SQL interpreter to interface with python dictionaries (a standard python data type, like arrays).

It has absolutely no use really, the most pointless thing ever. Ridiculous idea, but I was bored and felt like coding something crazy.
 
I like it, Ive toyed with the idea of a SQL parser class in my framework for the purpose of running only on development/testing servers for advanced debugging (also things like efficiency scores). Although I wouldnt do in regex (prefering an objective parser, utilising the same parse tree as mysql).

Still a nice regex, certainly thorough.
 
PHP:
	public function saltGenerator($limitChars=8) {
		$symb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-=_+[]{}\\|;:'\",./<>?~`";//letters,numbers,& symbols
		$saltv = '';
		for ($i = 0; $i < $limitChars; $i++)
			$saltv .= $symb[rand(0, strlen($symb) - 1)];
		return $saltv;
	}

well this is pretty small but its a mini function to generate salt hash value(s) to make secure when inserted in the database for either when a user registers or w/e which then when you want use of the function for making the pass-hash you can do something like this:
PHP:
$saltv = $saltv ?: $this->saltGenerator();
$phash = md5(md5($saltv) . md5($pass));
$sql->password = $phash;
$sql->salt = $saltv;
This is really something that can be used in a class to make things easier. Did this off the top of my head so if there is room for improvement let me know :P
 
well this is pretty small but its a mini function to generate salt hash value(s) to make secure when inserted in the database for either when a user registers or w/e which then when you want use of the function for making the pass-hash you can do something like this:

This is really something that can be used in a class to make things easier. Did this off the top of my head so if there is room for improvement let me know :P

Ask and ye shall receive.
PHP:
function saltGenerator($limitChars=8) {
	$saltv = '';
	for (; $limitChars; --$limitChars)
		$saltv .= chr(rand(33,126));
	return $saltv;
}
Best I can think of, also includes a few more symbols in the calculation, see ascii table: http://www.asciitable.com/index/asciifull.gif
 
Status
Not open for further replies.
Back
Top