We have a TI-BASIC Code Fragments and Routines, a z80 Assembly Routines thread, and even a Useful Prizm Routines thread. However, I can't find such a thread for computer, mobile, and web programming in C, C++, Python, PHP, Javascript, Java, and similar languages, so here it is. I'll start with a routine I just wrote.

[Python/PHP/Computer] Floating-Point Number to Base-10 Mantissa, Exponent, and Sign
In C, C++, and other low-level languages, you can directly extract the sign, exponent, and mantissa of a number in base-2 from its representation in the computer's memory or CPU registers. However, base-10 is more difficult, and higher-level languages don't have a way to access base-anything. Here's code in Python (the algorithm for which would work in other languages) that computes the sign, exponent, and mantissa from a floating-point number.
Code:
r00t@amethyst:# python test.py
-1.23457e+09 =?= -1.000000 * 1.234568 * 10 ^ 9
-1.23457 =?= -1.000000 * 1.234568 * 10 ^ 0
-1.23e-11 =?= -1.000000 * 1.230000 * 10 ^ -11
1.2345 =?= 1.000000 * 1.234500 * 10 ^ 0
124.236 =?= 1.000000 * 1.242356 * 10 ^ 2
2.64768e+13 =?= 1.000000 * 2.647683 * 10 ^ 13
Here it is in Python:
Code:
#!/usr/bin/python

import math
tests = [ -1234567890, -1.2345678, -0.0000000000123, 1.2345, 124.23562472, 26476832623454.453 ];

def mantexp(val):
    val = float(val)
    sign = -1 if val < 0 else 1
    val = abs(val)
    exp = 0 if val == 0 else int(math.floor(math.log10(val)))
    mant = val / ( 10 ** exp )
    return [sign, mant, exp]

for test in tests:
    sign, mant, exp = mantexp(test)
    print "%g =?= %f * %f * 10 ^ %d" % (test, sign, mant, exp)
Here it is in PHP:
Code:
<?php

$tests = Array(-1234567890, -1.2345678, -0.0000000000123, 1.2345, 124.23562472, 26476832623454.453);

function mantexp($val) {
    $sign = ($val < 0)?-1:1;
    $val = abs($val);
    $expn = ($val == 0)?0:floor(log10($val));
    $mant = $val / pow(10,$expn);
    return Array($sign, $mant, $expn);
}

foreach($tests as $test) {
    list($sign, $mant, $expn) = mantexp($test);
    printf("%g =?= %f * %f * 10 ^ %d\n", $test, $sign, $mant, $expn);
}

?>
[Python] Divide Trillian IRC Logs Into Files
After a few years of using the program, Trillian's IRC logs can get pretty out-of-control. My log for #cemetech grew to 145MB in 4 years, and there was noticeable lag every time I tried to type a line into the chat. I therefore decided to write a script to divide my logs into days, which I would merge with saxjax's IRC logs to give saxjax over four years of IRC logs. Here's the script I wrote for it:


Code:
import re
import os
import sys
import time
import datetime

def process_text(text):
   if text[0:3] != "***":
      return text            # As-is
   if len(text) >= 5 and text[4] == "-":
      return None            # Private message
   ignore = ["Topic set by", "Disconnected"]
   for sample in ignore:
      if len(text) >= 4+len(sample) and text[4:4+len(sample)] == sample:
         return None
   return text
   
with open("#cemetech.log","r") as f:
   curlog = None
   timestamp = None
   logstring = None
   linenum = 0   
   for line in f:
      linenum += 1
      oldstamp = timestamp

        # check session start
      matches = re.match('^Session Start \([^:]+:#([^\)]+)\): [A-Za-z]+ ([A-Za-z]+) (\d+) ([0-9:]+) ([0-9]+) [+-][0-9]+', line)
      if None != matches:
         montharray = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
         month = 1 + montharray.index(matches.group(2))
         curlogstring = logstring
         logstring = "%4d-%02d-%02d_%s" % (int(matches.group(5)), month, int(matches.group(3)), matches.group(1))
         timestamp = matches.group(4)
         if logstring == curlogstring:
            continue;
         if curlog != None:
            print("%s - Log close at line %d" % (curlogstring, linenum))
            curlog.close()
         print("%s - Log open at line %d" % (logstring, linenum))
         curlog = open(logstring, "w")
      # check session end
      matches = re.match('^Session Close \([^:]+:#([^\)]+)\): [A-Za-z]+ ([A-Za-z]+) (\d+) ([0-9:]+) ([0-9]+) [+-][0-9]+', line)
      if None != matches:
         if curlog == None:
            print("ERROR: State problem at line %d [1]" % linenum)
            sys.exit(-1)
         print("%s - Log close at line %d" % (logstring, linenum))
         curlog.close()
         curlog = None
         timestamp = None
         logstring = None
      # check timestamp-prefixed chat line
      matches = re.match('^\[([0-9:]+)\] <([^>]+)> (.*)$', line)
      if None != matches:
         if curlog == None:
            print("ERROR: State problem at line %d [2]" % linenum)
            sys.exit(-1)

         timestamp = matches.group(1)
         timepieces = timestamp.split(":")
         oldpieces = oldstamp.split(":")
         if (oldstamp != None and int(oldpieces[0]) > int(timepieces[0])):
            # Open new file.
            print("%s - Log close at line %d" % (logstring, linenum))
            curlog.close()
            eptime = time.mktime(time.strptime(logstring[0:10], "%Y-%m-%d"))
            eptime += (60*60*24)
            logstring = datetime.datetime.fromtimestamp(eptime).strftime("%Y-%m-%d") + logstring[10:]
            print("%s - Log open at line %d" % (logstring, linenum))
            curlog = open(logstring, "w")
         username = matches.group(2)
         text = process_text(matches.group(3))
         if None != text and username != "***":
            curlog.write("[%s] <%s> %s" % (timestamp, username, text))
      # check non-timestamp-prefixed chat line
      matches = re.match('^<([^>]+)> (.*)$', line)
      if None != matches:
         if timestamp == None or curlog == None:
            print("ERROR: State problem at line %d [3]" % linenum)
            sys.exit(-1)
         username = matches.group(1)
         text = process_text(matches.group(2))
         if None != text and username != "***":
            curlog.write("[%s] <%s> %s" % (timestamp, username, text))
         
   print "Finished at line %d" % linenum
[Javascript] Draggable Elements Without jQuery UI
jQuery UI is nifty, but quite heavy-weight. Although I am aware of the jQuery UI Draggable component, I wanted a simple, lightweight way to drag elements. Specifically, I want to make a resizeable CodeMirror, and this seemed to be one of the best ways to do it (the other possibility being hiding CodeMirror on mousedown, allowing the underlying textarea to be resized, and revealing CodeMirror on mouseup). The code below implements general-purpose moving for divs styled with the "draggable" class: simply drag-and-drop the elements.

Try it: http://jsfiddle.net/deqWV/1/ (Works in Firefox, Chrome, IE, and probably others)


Code:
var dragging = {};

$(document).ready(function() {

    $("div.draggable").on("mousedown", function (e) {
      var offset = $(e.target).offset();
        dragging.id = $(e.target).attr('id');
      
      // Want to reposition relative to initial click in element
        dragging.offset_top = e.pageY - offset.top;
        dragging.offset_left = e.pageX - offset.left;
      
      // Set up state
      dragging.active = true;
      dragging.redraw = null;
      dragging.redraw_queue = null;

      // Move handler, defers redrawing to ease CPU load
      $(document.body).on("mousemove", function(e) {
         dragging.redraw_queue_top = e.pageY;
         dragging.redraw_queue_left = e.pageX;
         if (dragging.redraw == null) {
            dragging.redraw = setTimeout(draggableRedraw, 50);
         }
      });
   
      // "Drop" handler uninstalls handlers
      $(document.body).on("mouseup", function (e) {
         if (dragging.redraw != null) {
            draggableRedraw();
         }
         dragging.active = false;
         $(document.body).off("mouseup");
         $(document.body).off("mousemove");
      });

    });
   
});

// Deferred redraw
function draggableRedraw() {
   $("#"+dragging.id).offset({
      top: dragging.redraw_queue_top - dragging.offset_top,
      left: dragging.redraw_queue_left - dragging.offset_left
   });
   dragging.redraw = null;
}
[Python] Basic Encryption/Decryption Functions
I got a bit bored today, so me and a friend decided we would write a little encryption/decryption program in python. As far as security goes, it's extremely naff, but it's a nice display of what you can do with string slices and minimal amounts of looping.

EDIT: I should also mention that this code is for python 3 rather than python 2!


Code:
#!/usr/bin/env python3

import string
import random

def decrypt(s):
    """Returns A Decrypted String"""
    s = s[2::3] #Start slicing from 3rd character in string with a step of 3
    reverse = s[::-1] #Reverses the variable 's'
    return reverse

def encrypt(s):
    """Returns An Encrypted String"""
    count = 0 #Sentry variables...
    outString = ""
    reverse = s[::-1]#Reverses the variable 's'
    while count != len(s):
        outString += random.choice(string.ascii_letters)
        outString += random.choice(string.ascii_letters)
        outString += reverse[count:count+1]
        count += 1
    return outString
[Python] Scrolling Marquee
Once more, I provide you all with an interesting little script. This one prints a scrolling marquee display on the screen to the user's desired width and scroll rate.

Once more, this code is for python 3.x, but it can easily be ported to python 2.x


Code:
#!/usr/bin/env python
import time
import os

def marquee(s,width,scrollSpeed):
    """Displays A Scrolling Marquee"""
    count = 0
    os.system('cls' if os.name=='nt' else 'clear') #Initial screen clear
    while count != len(s) + width:
        print(s[count:count + width])
        time.sleep(scrollSpeed) #Advance the string according to 'scrollSpeed'
        os.system('cls' if os.name=='nt' else 'clear')
        count += 1


(When using this with *nix, please note that you must have the command line program 'clear' - Don't worry, most distros seem to have it, though...)

Usage:

Code:
marquee("The meaning of life, according to deep thought, is forty two!",16,0.5)


This makes the string scroll across a 16 character wide marquee, scrolling by 1 character every 0.5 seconds.

Thanks to shaun for for helping me to condense the code into a single version for all the OSes.
[Javascript/jQuery] Export File To Client
The following code allows you to specify a string of binary data, a MIME type, and a filename, and it will provide the file to the user for download. It requires Firefox 20+ or other browsers that support the download attribute on <a> elements.


Code:
function pushDownload(data, mime, filename) {
   var dl_pname = "pushDownloadDiv";
   var dl_lname = "pushDownloadLink";
 
   // Remove old div, if it exists, and revoke
   // the previous object URL created.
   if ($('#' + dl_pname).length) {
      URL.revokeObjectURL($('#' + dl_lname).attr('href'));
      $('#' + dl_pname).remove();
   }
 
   // Create the virtual file
   var data_ab = new ArrayBuffer(data.length);
   var data_array = new Uint8Array(data_ab);
   for(var i = 0; i < data.length; i++) {
      data_array[i] = data.charCodeAt(i);
   }
   var file = new Blob([data_array.buffer],
                       {'type': mime});
 
   // Create the link
   var dl_link = document.createElement('a');
   $(dl_link).attr('id', dl_lname)
             .attr('download', filename)
           .attr('href', URL.createObjectURL(file))   ;
 
   // Now create a new one and populate it.
   var dl_parent = document.createElement('div');
   $(dl_parent).attr('id', dl_pname)
               .css('display', 'none')
            .append($(dl_link))
            .appendTo($("body"));

   // Click the download link
   $(dl_link)[0].click();
}
[Python/Git] Implement Git hooks in Python
The biggest pitfall for git hooks is making sure any subprocesses you launch have a clean environment if they're going to be calling git themselves. For post-update that just means unsetting GIT_DIR, but for a pre-commit or certain other hooks it's a lot more extensive ( https://www.digitalocean.com/.../how-to-use-git-hooks-to... ). Of course if you're not calling git as a subroutine in your hook, you'll be fine.


Code:
#!/usr/bin/env python
 
import sys,os,os.path,subprocess
 
print os.getcwd(),sys.argv
 
cwd = os.getcwd()
name = cwd.split("/")[-1][:-4]
 
dev_root = "/redacted/path/to/dev/directory"
dev_dir = os.path.join(dev_root,name)
old_git_dir = os.environ['GIT_DIR']
del os.environ['GIT_DIR']
if not os.path.exists(dev_dir):
        print "Cloning repo into %s" % dev_dir
        sys.stdout.flush()
        os.chdir(dev_root)
        ret = subprocess.call(["git","clone","-v","file://%s"%cwd,name],stdout=sys.stdout,stderr=subprocess.STDOUT)
elif not os.path.isdir(dev_dir):
        print "Argh! %s exists, but it is not a directory" % dev_dir
        sys.stdout.flush()
        ret = 1
else:
        print "Updating repo in %s" % dev_dir
        sys.stdout.flush()
        os.chdir(dev_dir)
        print os.getcwd(),os.listdir(os.getcwd())
        sys.stdout.flush()
        ret = subprocess.call(["pwd"],stdout=sys.stdout,stderr=subprocess.STDOUT)
        sys.stdout.flush()
        ret = subprocess.call(["git","pull","-v"],stdout=sys.stdout,stderr=subprocess.STDOUT)
os.environ['GIT_DIR'] = old_git_dir
sys.stdout.flush()
print os.getcwd()
os.chdir(cwd)
print os.getcwd()
sys.exit(ret)
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement