Skip to content

Instantly share code, notes, and snippets.

@ispedals
Created May 20, 2013 22:02
Show Gist options
  • Save ispedals/5615947 to your computer and use it in GitHub Desktop.
Save ispedals/5615947 to your computer and use it in GitHub Desktop.
Perl
+----------------------------------------------------------------+
| Determine memory load |
|----------------------------------------------------------------|
| use Win32::SystemInfo; |
| my %status; |
| Win32::SystemInfo::MemoryStatus(%status); |
| if($status{'MemLoad'} > 90) { |
| … |
| } |
+----------------------------------------------------------------+
+----------------------------------------------------------------+
| Bidirectional Socket |
|----------------------------------------------------------------|
| use IO::Socket; |
| my $socket = new IO::Socket::INET ( |
| PeerAddr => '192.168.0.101', |
| PeerPort => 5000, |
| Proto => 'tcp' |
| ); |
| my $recv_data; |
| $socket->recv($recv_data,1024); |
| |
| if($recv_data eq "go"){ |
| my ($read_ok, $print_ok) = ( 1, 1 ); |
| while ( $read_ok and $print_ok ){ |
| my $chunk; |
| $read_ok = read ( INPUT, $chunk, 1024 ); |
| if ( defined $chunk and defined $read_ok ){ |
| $print_ok = print $socket $chunk; |
| } |
| } |
| } |
+----------------------------------------------------------------+
+----------------------------------------------------------------+
| Sample WWW::Mechanize use with HTML::TagParser |
|----------------------------------------------------------------|
| use WWW::Mechanize; |
| use HTML::TagParser; |
| my $mech = WWW::Mechanize->new; |
| $mech->agent_alias('Windows IE 6'); |
| $mech->get($url); |
| $mech->submit_form(form_number => 1, fields => |
{ user_id => $cardNumber, password => $password}); |
| $mech->follow_link(text => 'My Account'); |
| $mech->follow_link(text_regex => |
qr/Renew Materials.*Review My Account/i); |
| $html=$mech->response->content; |
| my $tagParser=HTML::TagParser->new($html); |
| my @items = $tagParser->getElementsByAttribute("value","on"); |
| foreach(@items) { |
| push @names, $_->getAttribute("name"); |
| } |
| $mech->form_name($formName); |
| foreach(@names) { |
| $mech->tick($_,'on'); |
| } |
| $mech->submit(); |
+----------------------------------------------------------------+
+----------------------------------------------------------------+
| TK usage |
|----------------------------------------------------------------|
| my $mw = MainWindow->new; |
| $mw->title("Books Due"); |
| $mw->Label(-text => $text)->pack(); |
| $mw->Button(-text => "Close", -command => |
| sub{exit})->pack(-side => 'left'); |
| MainLoop; |
+----------------------------------------------------------------+
+-----------------------------------------------------------------------------------+
| Convert Ruby to HTML |
|-----------------------------------------------------------------------------------|
| s/(\p{InCJK_Unified_Ideographs}*?)\x{300a}(.*?)\x{300b}/<ruby>$1<rt>$2<\/ruby>/g; |
+-----------------------------------------------------------------------------------+
+----------------------------------------------------------------+
| Extract by filename |
|----------------------------------------------------------------|
| use Archive::Zip qw(:ERROR_CODES); |
| my $zip = Archive::Zip->new(); |
| my $status = $zip->read('kore-sound-sentences-munged.zip'); |
| for (@data){ |
| chomp; |
| $status = $zip->extractMember("$_"); |
| } |
+----------------------------------------------------------------+
+-------------------------------------------------------------------+
| Extention renamer |
|-------------------------------------------------------------------|
| foreach(glob("*ass")){/\[(\d+?)\]/;rename $_, "K-ON.s01e$1.ass";} |
+-------------------------------------------------------------------+
+------------------------------------------------------------------------------+
| Determine mimetype of file |
|------------------------------------------------------------------------------|
| perl -MFile::Type -e "print File::Type->new()->checktype_filename('<file>')";|
+------------------------------------------------------------------------------+
+----------------------------------------------------------------+
| use of File::Find |
|----------------------------------------------------------------|
| use File::Find; |
| use File::Path qw( rmtree ); |
| use File::Spec::Functions qw( catfile ); |
| find(\&rm_dot_svn, $_) for @ARGV; |
| sub rm_dot_svn { |
| return unless -d $File::Find::name; |
| return if /^\.svn\z/; |
| rmtree(catfile $File::Find::name, '.svn'); |
| return; |
| } |
+----------------------------------------------------------------+
+----------------------------------------------------------------+
| List files in FTP Server |
+----------------------------------------------------------------+
| use Net::FTP::Recursive; |
| my $ftp = Net::FTP::Recursive->new('192.168.0.105'); |
| $ftp->login('xbox','xbox'); |
| $ftp->cwd('/E/SCREENSHOTS/cuu'); |
| $ftp->rls(Filehandle => *STDOUT); |
+----------------------------------------------------------------+
+-----------------------------------------------------------------+
| Seconds to HMS |
+-----------------------------------------------------------------+
| use Time::Seconds; |
| my $a=Time::Seconds->new(<seconds>); |
| my $h=int($a->hours()); |
| my $m=int($a->minutes()); |
| my $s=int($a->minutes())<1?$a->seconds():$a->seconds()-($m*60); |
| $a=sprintf("%01d:%02d:%.2f",$h,$m,$s); |
+-----------------------------------------------------------------+
+----------------------------------------------------------------+
| UUEncode file |
+----------------------------------------------------------------+
| use Convert::UU 'uuencode'; |
| open(ATTCH, 'C:\Users\Viqar Samad\Desktop\STAT.EXE'); |
| print uuencode(\*ATTCH,'ecopop',777); |
+----------------------------------------------------------------+
===================================================================================
Batch
+----------------------------------------------------------------+
| Schedule and run repeated task |
+----------------------------------------------------------------+
| schtasks /create /tn <name> /tr "<command>" /sc minute /mo 2 |
| schtasks /run /tn <name> |
+----------------------------------------------------------------+
===================================================================================
Javascript
+----------------------------------------------------------------+
| createObjectURL example |
+----------------------------------------------------------------+
| function handleFiles(files){ |
| var objectURL = window.URL.createObjectURL(files[0]); |
| document.getElementsByTagName('video')[0].src=objectURL; |
| foo=files[0]; |
| } |
+----------------------------------------------------------------+
+------------------------------------------------------------------------+
| Recurse DOM |
+------------------------------------------------------------------------+
| (function(el){ |
| if (el.nodeType == 3) { |
| ret+=el.nodeValue; |
| } |
| else if (el.nodeName!=='IFRAME' ||el.nodeName!=='SCRIPT'|| |
el.nodeName!='IMG'||el.nodeName!='LINK'||el.nodeName!='STYLE' ){ |
| for (var i=0; i < el.childNodes.length; ++i){ |
| arguments.callee(el.childNodes[i]); |
| } |
| } |
| })(b.contentDocument.body); |
+------------------------------------------------------------------------+
===================================================================================
VBA
+----------------------------------------------------------------+
| Delete hyperlinks |
+----------------------------------------------------------------+
| With ThisDocument |
| 'Loop while there are hyperlinks afoot! |
| While .Hyperlinks.Count > 0 |
| .Hyperlinks(1).Delete |
| Wend |
| End With |
+----------------------------------------------------------------+
+----------------------------------------------------------------+
| Center Text |
+----------------------------------------------------------------+
| ' Aligns the text horizontally within the selected shape |
| ' and aligns the text vertically by setting the top margin |
| ' to be half the height of the shape |
| Dim height, margin As Single |
| Selection.WholeStory |
| Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter |
| Selection.ShapeRange.Select |
| height = Selection.ShapeRange.height |
| margin = height / 2 |
| Selection.ShapeRange.TextFrame.MarginTop = margin |
| Selection.ShapeRange.TextFrame.MarginBottom = 0 |
| Selection.ShapeRange.TextFrame.MarginLeft = 0 |
| Selection.ShapeRange.TextFrame.MarginRight = 0 |
+----------------------------------------------------------------+
===================================================================================
Python
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Load smb files from xbmc python |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| # use httpapi for smb:// paths if xbox, with hack for change in xbmc so older revisions still work |
| if ( song.lyrics_path.startswith( "smb://" ) and os.environ.get( "OS", "n/a" ) == "xbox" ): |
| song.lyrics = unicode( base64.standard_b64decode( xbmc.executehttpapi( "FileDownload(%s,bare)" % ( song.lyrics_path ) ).split("\r\n\r\n")[ -1 ].strip( BOM_UTF8 ) ), "utf-8" ) |
| |
| # use httpapi for smb:// paths if xbox |
| if ( song.lyrics_path.startswith( "smb://" ) and os.environ.get( "OS", "n/a" ) == "xbox" ): |
| # no way to create dirs for smb:// paths on xbox |
| xbmc.executehttpapi( "FileUpload(%s,%s)" % ( song.lyrics_path, base64.standard_b64encode( BOM_UTF8 + song.lyrics.encode( "utf-8", "replace" ) ), ) ) |
| |
| example: |
| import xbmc |
| import base64 |
| path='smb://VIQARSAMAD-PC/Users/Viqar Samad/Desktop/gogakumono/b.txt' |
| f=xbmc.executehttpapi("FileDownload(%s, bare)"%path) |
| f=f.split("\r\n\r\n")[ -1 ] |
| f=base64.standard_b64decode(f) |
| print f |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------------------------+
| Query Database |
+----------------------------------------------------------------------------------------------------+
| def query_db(query, callback): |
| from urllib import quote |
| query_url='http://192.168.0.104/xbmcCmds/xbmcHttp?command=queryvideodatabase(%s)'%quote(query) |
| response=getUrl(query_url,callback=None) |
| return re.compile(callback).findall(response) |
+----------------------------------------------------------------------------------------------------+
+-------------------------------------------------------------------------------------+
| Recursive Map |
+-------------------------------------------------------------------------------------+
| def recur_map(f, data): |
| return [ not hasattr(x, "__iter__") and f(x) or recur_map(f, x) for x in data ] |
+-------------------------------------------------------------------------------------+
+----------------------------------------------------------------+
| Flatten List |
+----------------------------------------------------------------+
| def flatten(l, ltypes=(list, tuple)): |
| ltype = type(l) |
| l = list(l) |
| i = 0 |
| while i < len(l): |
| while isinstance(l[i], ltypes): |
| if not l[i]: |
| l.pop(i) |
| i -= 1 |
| break |
| else: |
| l[i:i + 1] = l[i] |
| return ltype(l) |
+----------------------------------------------------------------+
+----------------------------------------------------------------+
| Print to Console in Anki |
+----------------------------------------------------------------+
| def p(s): |
| os.system('echo %s && pause'%s) |
+----------------------------------------------------------------+
===================================================================================
XUL
+---------------------------------------------------------------------+
| Add text to clipboard |
+---------------------------------------------------------------------+
var str = Components.classes["@mozilla.org/supports-string;1"]. |
createInstance(Components.interfaces.nsISupportsString); |
if (!str) { |
return; |
} |
str.data=<data>; |
var trans = Components.classes["@mozilla.org/widget/transferable;1"]. |
createInstance(Components.interfaces.nsITransferable); |
if (!trans) return; |
trans.addDataFlavor("text/unicode"); |
trans.setTransferData("text/unicode",str,total.length * 2); |
var clipid = Components.interfaces.nsIClipboard; |
var clip = Components.classes["@mozilla.org/widget/clipboard;1"]. |
getService(clipid); |
if (!clip) return; |
clip.setData(trans,null,clipid.kGlobalClipboard); |
+---------------------------------------------------------------------+
+---------------------------------------------------------------------+
| Traverse tabs |
+---------------------------------------------------------------------+
| var num = gBrowser.browsers.length; |
| for (var i = 0; i < num; i++) { |
| var b = gBrowser.getBrowserAtIndex(i); |
| b.contentDocument.body |
| … |
| } |
+---------------------------------------------------------------------+
+------------------------------------------------------------------------------------------+
| Prompts |
+------------------------------------------------------------------------------------------+
| var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] |
| .getService(Components.interfaces.nsIPromptService); |
| var result = promptService.prompt(null, "Start Text", "Start Text", input, null, check); |
+------------------------------------------------------------------------------------------+
+--------------------------------------------------------------------------+
| Print to Console |
+--------------------------------------------------------------------------+
| var consoleService = Components.classes["@mozilla.org/consoleservice;1"] |
| .getService(Components.interfaces.nsIConsoleService); |
| consoleService.logStringMessage(''); |
+--------------------------------------------------------------------------+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment