#!/usr/bin/env ruby
server_url = ""
username = ""
passwd = ""
require 'net/ftp'
ftp=Net::FTP.new
ftp.connect(server_url,21)
ftp.login(username,passwd)
ftp.chdir("faraim-ios")
# ftp.getbinaryfile(filename)
ftp.list { |item|
puts item
}
ftp.close
Saturday, March 16, 2013
connect to an ftp server with a ruby script
Wednesday, March 13, 2013
get dimensions of a ruby image using the Dimensions gem
#!/usr/bin/env ruby
require 'dimensions'
images = %w(31.SpecialAirspace.png 31.SpecialAirspace@2x.png)
images.each { |image|
puts image
size = Dimensions.dimensions(image)
w = Dimensions.width(image)
h = Dimensions.height(image)
p size
p w
p h
}
Sunday, March 10, 2013
.command file to run scss watch
double-click to open up a watch command in a new terminal window.
for an example, see:
for an example, see:
/Users/smr/current_projects/oeg-ios/scss/oeg-i/oegi-sass-compile.command
cd /Users/smr/current_projects/oeg-ios/scss/oeg-i/; sass --watch oeg.scss:oeg.css --compass --no-cache
customize google code prettify syntax highlighting styles
create a css class that defines your desired colors, e.g.:
/Users/smr/Sites/prettify/google-code-prettify/xcode.css
/* Pretty printing styles. Used with prettify.js. */
/* SPAN elements with the classes below are added by prettyprint. */
.pln { color: #000 } /* plain text */
@media screen {
.str { color: #C51A16 } /* string content */
.kwd { color: #AA0D91 } /* a keyword */
.com { color: #007400 } /* a comment */
.typ { color: #5B2699 } /* a type name */
.lit { color: #066 } /* a literal value */
/* punctuation, lisp open bracket, lisp close bracket */
.pun, .opn, .clo { color: #000 }
.tag { color: #008 } /* a markup tag name */
.atn { color: #606 } /* a markup attribute name */
.atv { color: #080 } /* a markup attribute value */
.dec, .var { color: #606 } /* a declaration; a variable name */
.fun { color: #26474B } /* a function name */
}
/* Use higher contrast and text-weight for printable form. */
@media print, projection {
.str { color: #060 }
.kwd { color: #006; font-weight: bold }
.com { color: #600; font-style: italic }
.typ { color: #404; font-weight: bold }
.lit { color: #044 }
.pun, .opn, .clo { color: #440 }
.tag { color: #006; font-weight: bold }
.atn { color: #404 }
.atv { color: #060 }
}
/* Put a border around prettyprinted code snippets. */
pre.prettyprint { padding: 2px; border: 1px solid #888 }
/* Specify class=linenums on a pre to get line numbering */
ol.linenums { margin-top: 0; margin-bottom: 0 } /* IE indents via margin-left */
li.L0,
li.L1,
li.L2,
li.L3,
li.L5,
li.L6,
li.L7,
li.L8 { list-style-type: none }
/* Alternate shading for lines */
li.L1,
li.L3,
li.L5,
li.L7,
li.L9 { background: #eee }
Saturday, March 9, 2013
UIWebview and the display of 2x retina images
see:
/Users/smr/current_projects/oeg-ios/work/2x-bg-image-workthrough/
Out of the box, UIWebView doesn't automatically use 2x images for retina displays (as is the ase when doing iOS SDK programming), so you have to fudge it.
Three different approaches to this problem are discussed here:
http://spritebandits.wordpress.com/2012/01/17/using-uiwebview-with-retina-displays/
The problem looks like this (note the blurry image):
this particular example uses a div with a background url to display an image. red and green borders are added just to show that the media query version is being used on retina displays.
the 1x image is taken care of with css like:
to handle the 2x version, use a media query that targets retina displays:
the fix looks like this:
note that the
/Users/smr/current_projects/oeg-ios/work/2x-bg-image-workthrough/
Out of the box, UIWebView doesn't automatically use 2x images for retina displays (as is the ase when doing iOS SDK programming), so you have to fudge it.
Three different approaches to this problem are discussed here:
http://spritebandits.wordpress.com/2012/01/17/using-uiwebview-with-retina-displays/
The problem looks like this (note the blurry image):
![]() |
| blurry 1x image being used on a retina device |
this particular example uses a div with a background url to display an image. red and green borders are added just to show that the media query version is being used on retina displays.
the 1x image is taken care of with css like:
.header-bg-image {
/*non-retina and shared values*/
width: 174px;
height: 65px;
margin-right: 10px;
background: url('OEG-phone-pvt-menu-header.png');
-webkit-background-size: 174px 65px;
float: right;
border: 1px solid green;
}
to handle the 2x version, use a media query that targets retina displays:
@media screen and (-webkit-device-pixel-ratio: 2) {
.header-bg-image {
background: url('OEG-phone-pvt-menu-header@2x.png');
border: 1px solid red;
}
}
the fix looks like this:
![]() |
| 2x image being used after implementing a media query |
note that the
-webkit-background-size: 174px 65px; must be present or the image gets rendered funkily:![]() |
| forgot the -webkit-background-size, so no bueno |
Thursday, March 7, 2013
bootstrap cdn
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap.css" rel="stylesheet"> <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap.min.css" rel="stylesheet"> <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"> <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
Wednesday, March 6, 2013
find-tags.pl perl script to dump the tags used in an xml file
creates an html page.
~/bin/find-tags.pl
~/bin/find-tags.pl
#!/usr/bin/perl -w
#usage:
#find-tags.pl *.xml
use strict;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
#
# global variables
#
my %elements;
my @element_stack; # remembers element names
my $in_intset; # flag: are we in the internal subset?
my $q = new CGI();
my @filenames;
# initialize the parser
#
use XML::Parser::PerlSAX;
my $parser = XML::Parser::PerlSAX->new( Handler => MyHandler->new( ) );
foreach my $infile (@ARGV)
{
print '$infile = ' . $infile . "\n";
push @filenames, $infile;
$parser->parse( Source => {SystemId => $infile} );
}
# use bootsrap served from a cdn
my $html = q{
<!DOCTYPE html>
<html>
<head>
<title>find-tags</title>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
};
$html .= $q->h1("find-tags.pl");
$html .= $q->h2("found these tags:");
$html .= $q->start_ul;
for (sort {lc $a cmp lc $b} keys %elements)
{
$html .= $q->li({-style=>'padding-top:5px;padding-bottom:5px;'}, qq{<code>$_</code> <span class="badge">$elements{$_}</span>} );
}
$html .= $q->end_ul;
$html .= $q->h2("while searching these files:");
$html .= $q->start_ul;
foreach my $file (@filenames)
{
$html .= $q->li("$file");
}
$html .= $q->end_ul;
$html .= q{
</div>
</body>
</html>
};
my $html_filename = "/tmp/find-tags.html";
open(OUTFILE, "> $html_filename") or die "can't open $html_filename: $!";
print OUTFILE $html;
close OUTFILE;
system("open", "$html_filename");
exit;
###
### Document Handler Package
###
package MyHandler;
#
# initialize the handler package
#
sub new {
my $type = shift;
return bless {}, $type;
}
#
# handle a start-of-element event: output start tag and attributes
#
sub start_element {
my( $self, $properties ) = @_;
# note: the hash %{$properties} will lose attribute order
#example porperty hash:
# {
# 'Attributes' => {
# 'align' => 'left',
# 'valign' => 'middle'
# },
# 'Name' => 'entry'
# }
# remember the name by pushing onto the stack
push( @element_stack, $properties->{'Name'} );
$elements{$properties->{'Name'}}++;
}
Tuesday, February 26, 2013
media queries for standard devices
http://css-tricks.com/css-media-queries/
http://css-tricks.com/snippets/css/media-queries-for-standard-devices/
http://css-tricks.com/snippets/css/media-queries-for-standard-devices/
/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}
pass parameters to an xslt transform using nokogiri
you need to supply an array of specially quoted key value pairs:
# transformer needs a doc
doc_from_xml_hunk = Nokogiri::XML(examquestion.to_xml)
# do the transformation, passing some params
#pass an array of key value pairs, quoted for stylesheet safety
ary = Nokogiri::XSLT.quote_params([
'message', 'hello world',
'message2', 'hello again'
])
puts xslt.transform(doc_from_xml_hunk, ary) # [, xslt_parameters]
in the stylesheet, you define the params at the global level, then access them using the '$' notation.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html"> <xsl:param name="message"></xsl:param> <xsl:param name="message2"></xsl:param> <!-- RULE FOR EXAMQUESTION --> <xsl:template match="examquestion"> <xsl:text disable-output-escaping="yes"><!doctype html></xsl:text> <html lang="en"> <head> <xsl:text disable-output-escaping="yes"><meta charset="utf-8"></xsl:text> <title>Document</title> </head> <body> <h3> <xsl:value-of select="$message"></xsl:value-of></h3> <xsl:value-of select="$message2"></xsl:value-of><br /> </body> </html> </xsl:template> </xsl:output></xsl:stylesheet></pre>
Monday, February 25, 2013
transform an xml hunk using nokogiri
#!/usr/bin/env ruby
# encoding: utf-8
require "nokogiri"
filename = "study-OEG-P10Ch02.xml"
f = File.open(filename)
doc = Nokogiri::XML(f)
f.close
xslt = Nokogiri::XSLT(File.read('transform.xsl'))
doc.xpath('Root/chapter').each do |chapter|
chapter_title = chapter.at_xpath('title').text #like: puts chapter.xpath('title').first.text
puts chapter_title
chapter.xpath('section').each { |section|
section_title = section.at_xpath('title').text
puts section_title
section.xpath('examquestion').each { |examquestion|
# transformer needs a doc
doc_from_xml_hunk = Nokogiri::XML(examquestion.to_xml)
# do the transformation
# puts xslt.transform(doc_from_xml_hunk) # [, xslt_parameters]
}
}
end
Sunday, February 24, 2013
parse an xml file with nokogiri, traverse with xpath
#!/usr/bin/env ruby
# encoding: utf-8
require "nokogiri"
filename = "study-OEG-P10Ch02.xml"
f = File.open(filename)
doc = Nokogiri::XML(f)
f.close
doc.xpath('Root/chapter').each do |chapter|
# puts chapter
chapter_title = chapter.at_xpath('title').text #like: puts chapter.xpath('title').first.text
puts chapter_title
chapter.xpath('section').each { |section|
section_title = section.at_xpath('title').text
puts section_title
section.xpath('examquestion').each { |examquestion|
puts "examquestion"
}
}
end
Saturday, February 23, 2013
parse an xml file with rexml, traverse with xpath
#!/usr/bin/env ruby
# encoding: utf-8
require "rexml/document"
filename = "study-OEG-P10Ch02.xml"
file = File.new( filename )
doc = REXML::Document.new file
doc.elements.each("Root/chapter") { |chapter_element|
chapter_title = chapter_element.elements["title"].text
puts 'chapter_title=' + chapter_title.inspect
chapter_element.elements.each("section") { |section|
section_title = section.elements["title"].text
puts 'section_title=' + section_title.inspect
section.elements.each("examquestion") { |examquestion|
puts 'examquestion'
}
}
}
list power management settings with pmset -g
[smr@macpro ~]$ pmset -g Active Profiles: AC Power -1* Currently in use: hibernatemode 0 womp 1 networkoversleep 0 sleep 0 powerbutton 0 ttyskeepawake 1 hibernatefile /var/vm/sleepimage autorestart 0 disksleep 30 displaysleep 15
Friday, February 22, 2013
create xml with Nokogiri::XML::Builder
#!/usr/bin/env ruby
require 'nokogiri'
# When the builder is supplied with a block that has a parameter, the outside
# scope is maintained. This means you can access variables that are outside
# your builder.
my_var = 999
builder = Nokogiri::XML::Builder.new do |xml|
xml.document { # root node can be named whatever
xml.widgets {
(1..7).each { |i|
xml.widget(attr1:"value #{i}") {
# use an underscore to disambiguate your tag name from the method call.
xml.id_ "widget #{i}"
xml.name "Awesome widget"
xml.somevalue my_var
}
}
}
}
end
puts builder.to_xml
reinstall nokogiri after mountain lion upgrade
sudo ln -s /usr/bin/gcc /usr/bin/gcc-4.2 gem uninstall nokogiri libxml-ruby brew update brew uninstall libxml2 brew install libxml2 --with-xml2-config brew install libxslt gem install nokogiri -- --with-xml2-include=/usr/local/Cellar/libxml2/2.9.0/include/libxml2 --with-xml2-lib=/usr/local/Cellar/libxml2/2.9.0/lib --with-xslt-dir=/usr/local/Cellar/libxslt/1.1.28/
install log
note the nokogiri reference in the 'brew install libxslt' output[smr@macpro nokogiri-builder]$ brew install libxml2 --with-xml2-config
==> Downloading ftp://xmlsoft.org/libxml2/libxml2-2.9.0.tar.gz
######################################################################## 100.0%
######################################################################## 100.0%==> Downloading patches
######################################################################## 100.0%
######################################################################## 100.0%
==> Patching
patching file threads.c
patching file xpath.c
==> ./configure --prefix=/usr/local/Cellar/libxml2/2.9.0 --without-python
==> make
==> make install
==> Caveats
This formula is keg-only: so it was not symlinked into /usr/local.
Mac OS X already provides this software and installing another version in
parallel can cause all kinds of trouble.
Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:
LDFLAGS: -L/usr/local/opt/libxml2/lib
CPPFLAGS: -I/usr/local/opt/libxml2/include
==> Summary
🍺 /usr/local/Cellar/libxml2/2.9.0: 273 files, 11M, built in 56 seconds
[smr@macpro nokogiri-builder]$ brew install libxslt
==> Downloading ftp://xmlsoft.org/libxml2/libxslt-1.1.28.tar.gz
######################################################################## 100.0%
######################################################################## 100.0%==> ./configure --prefix=/usr/local/Cellar/libxslt/1.1.28 --with-libxml-prefix=/usr/local/Cellar/libxml2/2.9.0
==> make
==> make install
==> Caveats
To allow the nokogiri gem to link against this libxslt run:
gem install nokogiri -- --with-xslt-dir=/usr/local/Cellar/libxslt/1.1.28
This formula is keg-only: so it was not symlinked into /usr/local.
Mac OS X already provides this software and installing another version in
parallel can cause all kinds of trouble.
Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:
LDFLAGS: -L/usr/local/opt/libxslt/lib
CPPFLAGS: -I/usr/local/opt/libxslt/include
==> Summary
🍺 /usr/local/Cellar/libxslt/1.1.28: 145 files, 3.3M, built in 39 seconds
Thursday, February 21, 2013
Disable the annoying key repeat limitation in mountain lion
Disable repeat limitations
While the default behavior in OS X is to prevent these key repeats, you can revert this behavior permanently by issuing the following command in the Terminal, and then logging out and logging back in to your account:
While the default behavior in OS X is to prevent these key repeats, you can revert this behavior permanently by issuing the following command in the Terminal, and then logging out and logging back in to your account:
defaults write -g ApplePressAndHoldEnabled -bool false
The "defaults" command is used to manage preference files (aka the Defaults system in OS X). Here we've told it to "write" and have specified the "-g" flag for the hidden global preferences file instead of specifying a program domain such as com.apple.TextEdit for Apple's TextEdit program (which would write to the com.apple.TextEdit.plist file). We've then told it to create or modify the ApplePressAndHoldEnabled setting, and change its Boolean value (yes or no, on or off, true or false) to false, thereby disabling this setting. To re-enable this setting, just repeat the command in the Terminal and replace "false" with "true."
set the hard drive sleep time on the command line
http://reviews.cnet.com/8301-13727_7-10346924-263.html
When this setting is enabled, the system changes the power management system to turn off the disks after 10 minutes of use. When the option is unchecked, the disks are set to never turn off. Despite the limits in the control panel, this behavior can be changed manually, by using the "pmset" command in Terminal. The command alters the power management settings, giving users fine-tune control of the disk sleep settings. It also can set the display and system sleep times (though, the sliders work pretty well for those), and what behaviors will cause the computer to sleep and wake (lid opening, wake-on-LAN magic packet via Ethernet, and so on). For specific information on using this command, review its manual page on it by typing "man pmset" in the Terminal.
To adjust the disk's sleep time, enter the following command in the Terminal (Note: for 10.4 users, "disksleep" will be "spindown"):
sudo pmset -a disksleep VALUE
sudo pmset -a disksleep 20
sudo pmset -a disksleep 20
In this command, VALUE is the number of minutes after which the drives will spin down (with "0" being "never"). The "-a" flag applies the setting to all power configurations (battery, wall power, and UPS). To specify only one of these configurations, change the "-a" (indicating "All") to one of the following: "-b" for battery, "-c" for charger or wall power, "-u" for UPS.
sublime text: show the full path of the currently active document
tasty preference: show the full path of the currently active document in the window title bar.
"show_full_path": true,
jquery on block that handles UIWebView touchstart and touchend events
$("#answer_button").on({
//UIWebView
touchstart: function() {
$(this).addClass('btn-active');
},
touchend: function() {
$(this).removeClass('btn-active');
},
mousedown: function() {
$(this).addClass('btn-active');
},
mouseup: function() {
$(this).removeClass('btn-active');
}
});
Wednesday, February 20, 2013
upload bulk iOS device UDIDs
tab-delimited text file
first row is a header
http://stackoverflow.com/questions/1341472/anyone-tried-to-bulk-upload-device-udids-to-the-iphone-dev-portal
first row is a header
http://stackoverflow.com/questions/1341472/anyone-tried-to-bulk-upload-device-udids-to-the-iphone-dev-portal
# the first line is ignored
device_id_hex_40_chars description_text
... ...
Tuesday, February 19, 2013
create a SASS build system for sublime text
the build systems mimics this command line:
/Users/smr/Library/Application Support/Sublime Text 2/Packages/SASS Build/SASS-with-compass-SMR.sublime-build
sass --update oeg.scss:oeg.css --stop-on-error --no-cache --compass
{
"cmd": ["sass", "--update", "$file:${file_path}/${file_base_name}.css", "--stop-on-error", "--no-cache", "--compass"],
"selector": "source.sass, source.scss",
"line_regex": "Line ([0-9]+):",
"osx":
{
"path": "/usr/local/bin:$PATH" // home brew path?
},
"windows":
{
"shell": "true"
}
}
the use of --compass allows you to @include compass helpers like:
body {
background-color: #0b3253;
@include filter-gradient(#0b3253, #56a3e5, vertical);
@include background-image(linear-gradient(top, #0b3253 0%,#56a3e5 100%));
}
Monday, February 18, 2013
force a toolbar to have flexible height
if you want the toolbar height to change in landscape mode, you have to:
do
http://stackoverflow.com/questions/5219833/uitoolbar-height-on-device-rotation
do
toolbar.autoresizingMask = toolbar.autoresizingMask | UIViewAutoresizingFlexibleHeight; programmatically as Interface Builder doesn't allow you to change the flexible height!http://stackoverflow.com/questions/5219833/uitoolbar-height-on-device-rotation
copy a file with FileUtils.cp
#!/usr/bin/env ruby require 'fileutils' FileUtils.cp 'oeg-private.db', '../../source/oeg'
load a webview with a string, specifying base url
NSURL *baseURL = [[NSURL alloc] initFileURLWithPath:CONTENT_PATH];
[self.webview loadHTMLString:html baseURL:baseURL];
get the path to the documents directory
+ (NSString *)pathToDocumentsDirectory; {
//get the path to the docs directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
load a UIWebView with content from a file in the bundle
- (void)viewDidLoad {
[super viewDidLoad];
// load html content from file in bundle
NSString *path = [CONTENT_PATH stringByAppendingPathComponent:@"help_iphone.html"];
NSURL *fileURL = [[[NSURL alloc] initFileURLWithPath:path] autorelease];
NSURLRequest *req = [NSURLRequest requestWithURL:fileURL];
[self.webview loadRequest:req];
self.navigationController.toolbarHidden = YES;
}
Sunday, February 17, 2013
navigate the sublime text sidebar with arrow keys
The sidebar can be navigated with the arrow keys, but first you need to give it the input focus by pressing
Ctrl+0. To return input focus to the buffer, press Esc.
open a preferences pane from the command line
open /System/Library/PreferencePanes/UniversalAccessPref.prefPane
Friday, February 15, 2013
resolve a sublime text SASS build system issue
the SASS build system was failing on a file that had a method with variable arguments:
forced its hand by using a path to a specific version of SASS:
// border-radius: top-left top-right bottom-right bottom-left using variable
// arguments. note that when using this approach commas are not used to
// separate the arguments when calling the mixin
@mixin border-radius($radii...) {
-webkit-border-radius: $radii;
-moz-border-radius: $radii;
border-radius: $radii;
}
fiddling with the command showed that it was pointing to an older version of sass for some reason.forced its hand by using a path to a specific version of SASS:
{
// "cmd": ["sass", "--watch", ".:."], //broken
// "cmd": ["sass", "--version"], //show me the version
// "cmd": ["/Users/smr/.rvm/gems/ruby-1.9.2-p320@rails3/bin/sass", "--version"],
"cmd": ["/Users/smr/.rvm/gems/ruby-1.9.2-p320@rails3/bin/sass", "--watch", ".:."],
"working_dir": "$file_path",
"selector": "source.sass"
}
keymando command to open a folder location in terminal using osascript
# open dbeditor project folder in terminal
command "dbeditor dir in terminal" do
system("/usr/bin/osascript",
"-e", %q(tell application "Terminal" to activate),
"-e", %q(tell application "System Events" to tell process "Terminal" to keystroke "n" using command down),
"-e", %q(tell application "Terminal" to do script "cd /Users/smr/current_projects/prepware-questions-app/db-editor/" in selected tab of the front window)
)
end
applescript to tell terminal to open a new window and cd to a directory
http://stackoverflow.com/questions/7171725/open-new-terminal-tab-from-command-line-mac-os-x
long-winded but it works
long-winded but it works
/usr/bin/osascript -e 'tell application "Terminal" to activate' -e 'tell application "System Events" to tell process "Terminal" to keystroke "n" using command down' -e 'tell application "Terminal" to do script "cd /Users/smr/current_projects/prepware-questions-app/db-editor/" in selected tab of the front window'
extract text from a pdf using a ruby script
use the PDF::Reader module:
https://github.com/yob/pdf-reader
https://github.com/yob/pdf-reader
#!/usr/bin/env ruby
# coding: utf-8
# usage:
# ./00-extract-text.rb 00-pdf/*.pdf
# require 'rubygems'
require 'pdf/reader'
ARGV.each do|pdf_filename|
puts "processing #{pdf_filename}"
path = File.expand_path(File.dirname(__FILE__)) + "/#{pdf_filename}"
# puts path
PDF::Reader.open(path) do |reader|
contents = ""
reader.pages.each do |page|
contents += page.text
end
# save string to a file.
basename = File.basename(path, ".pdf")
aFile = File.new("01-text-pre-cleanup/#{basename}.txt", "w")
aFile.write(contents)
aFile.close
end
end
Thursday, February 14, 2013
open a sublime text project using a keymando custom command
this allows you to open a project using mnemonics instead of hunting through the file system.
# open the dbeditor project in sublime text
# note that you have to use the full path to the subl command (which is itself a sym link)
command "dbeditor" do
system("/Users/smr/bin/subl", "/Users/smr/current_projects/prepware-questions-app/db-editor")
end
prepareForSegue for a table row click
when using storyboards, pass info between scenes using:
note that we aren't using:
which is the typical approach when not using segues.
prepareForSegue:sender:
note that we aren't using:
tableView:didSelectRowAtIndexPath:
which is the typical approach when not using segues.
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// get the selected table row.
UITableViewController *tvc = segue.sourceViewController;
UITableView *tv = (UITableView *)tvc.view;
NSIndexPath *indexPath = [tv indexPathForSelectedRow];
if (indexPath != NULL)
{
// pass a data object or something
}
}
Wednesday, February 13, 2013
custom view that draws a linear gradient
http://smr.prepware.com.s3.amazonaws.com/simple-examples/ios/gradient-view.zip
// FMIGradientView.m
#import "FMIGradientView.h"
#import "AppTypeDefs.h"
@implementation FMIGradientView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
//draw a gradient
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGGradientRef glossGradient;
CGColorSpaceRef rgbColorspace;
// 2 locations
size_t num_locations = 2;
CGFloat locations[2] = { 0.5, 1.0 };
// CGFloat components[8] = {
// 90.0/255.0, 166.0/255.0, 231.0/255.0, 1.0,
// 11.0/255.0, 50.0/255.0, 83.0/255.0, 1.0
// };
CGFloat components[8] = GRADIENT_COMPONENTS;
rgbColorspace = CGColorSpaceCreateDeviceRGB();
glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
CGRect currentBounds = self.bounds;
CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
CGPoint bottomCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMaxY(currentBounds));
CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, bottomCenter, 0);
CGGradientRelease(glossGradient);
CGColorSpaceRelease(rgbColorspace);
}
@end
Tuesday, February 12, 2013
create a read-only private property in Objective-C
@interface FMIModelController() @property (readonly, strong, nonatomic) NSArray *pageData; @end
using submodules in a git repository
If while working on one project, you need to use another project from within it, use submodules.
See: http://git-scm.com/book/en/Git-Tools-Submodules for details.
everything works pretty much as expected.
you can add a submodule, which amounts to pulling the contents of another repo into a project subfolder. the two repos are tracked separately.
the one semi-quirky thing is if you do a new clone of a repo that contains submodules, the submodule directories are initially empty. you have to run a couple of commands to populate them:
$ git submodule init $ git submodule update
Monday, February 11, 2013
unhide the library folder in OS X 10.7/10.8
chflags nohidden /Users/[username]/Library/
implement a private property using an interface
@interface FMIViewController () @property (readonly, strong, nonatomic) FMIModelController *modelController; @end
create a view controller form a storyboard scene
// create a view controller FMIDataViewController *startingViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"FMIDataViewController"];
distinguish between multiple UIStoryboardSegues using the identifier property
set the identifier for the segue in Interface Builder (or programmatically).
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSLog(@"%s", __FUNCTION__);
NSLog(@"%@", segue.sourceViewController);
NSLog(@"%@", segue.destinationViewController);
if ([segue.identifier isEqualToString:@"SegueFromButtonPush"]) {
NSLog(@"SegueFromButtonPush");
}
}
Sunday, February 10, 2013
create rounded corners and a drop shadow on a UIView
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// see the CALayer Class Reference for details
UIView *v = self.view;
[v.layer setCornerRadius:20.0f];
// [v.layer setBorderColor:[UIColor lightGrayColor].CGColor];
// [v.layer setBorderWidth:1.5f];
// [v.layer setShadowColor:[UIColor blackColor].CGColor];
//
// [v.layer setShadowOpacity:0.8];
// [v.layer setShadowRadius:3.0];
//
// [v.layer setShadowOffset:CGSizeMake(2.0, 2.0)];
}
check for portrait orientation on an iOS device
use
UIInterfaceOrientationIsPortrait(orientation)
if (UIInterfaceOrientationIsPortrait(orientation) || ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)) {
//...
}
Saturday, February 9, 2013
paste a hunk of text using a keymando command
command "ppd prettyprint div" do
# copy a hunk of text to the clipboard (pipe to pbcopy)
`echo '<pre class="prettyprint">\n</pre>
' | pbcopy`
# paste it by sending cmd-v to the app
send("")
end
ruby script to generate normal and 2x placeholder images for iOS development
/Users/smr/bin/placeholder
#!/usr/bin/env ruby
# generate placeholder graphics using http://placehold.it/
if ARGV.length > 1
# the normal version
w = ARGV[0]
h = ARGV[1]
`wget http://placehold.it/#{w}x#{h}.png`
# the 2x scaled version for retina displays
w_doubled = Integer(w) * 2
h_doubled = Integer(h) * 2
`wget http://placehold.it/#{w_doubled}x#{h_doubled}.png --output-document=#{w}x#{h}@2x.png`
end
access command line arguments in ruby
#!/usr/bin/env ruby
ARGV.each do|a|
puts "Argument: #{a}"
end
make a system call in a custom keymando command
# same as a ruby system call
# place call in backticks
command "sys call test" do
# `osascript -e 'set volume output volume (output volume of (get volume settings) + 7)'`
`say 'hello world'`
# these work too:
# system("say 'hello world'")
# system("say", 'hello world')
end
iOS - customize the title of the back button
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// we want the back button to have a title of "Back" and not one derived
// from the title of the previous view contoller on the nav stack
self.navigationItem.backBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:@"Back"
style: UIBarButtonItemStyleBordered
target:nil
action:nil];
}
generate placeholder graphics using http://placehold.it/
http://placehold.it/
you can specify size (WxH) and format like:
http://placehold.it/350x150.png
using wget for this task is handy if you want to generate a file straightaway.
you can specify size (WxH) and format like:
http://placehold.it/350x150.png
using wget for this task is handy if you want to generate a file straightaway.
Friday, February 8, 2013
Hide a toolbar/navbar in iOS
toolbar
// in a UIViewController subclass
- (void)viewWillAppear:(BOOL)animated {
[self.navigationController setToolbarHidden:NO animated:YES];
[super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[self.navigationController setToolbarHidden:YES animated:YES];
[super viewWillDisappear:animated];
}
navbar
// in a UIViewController subclass
- (void)viewWillAppear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:YES animated:NO];
[super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:NO animated:NO];
[super viewWillDisappear:animated];
}
sublime text - move lines keyboard shortcut
Move lines of code up and down
Shortcut for moving line up: Ctrl + ⌘ + ↑
Shortcut for moving line down: Ctrl + ⌘ + ↓
Sometimes a line of code is in the wrong place. Instead of selecting, copying, deleting and pasting it to the desired place, Sublime Text 2 allows you to move the current line up and down with shortcuts. This also works with several selected lines.
ruby shebang line with RVM
#!/usr/bin/env ruby
Thursday, February 7, 2013
using google code prettify for syntax highlighting with Blogger
experiment with using google code prettify to do syntax highlighting for source code snippets.
for details see:
http://stackoverflow.com/questions/1852537/how-to-use-prettify-with-blogger-blogspot
and
http://notepad2.blogspot.com/2012/05/use-google-code-prettify-in-blogger.html
for details see:
http://stackoverflow.com/questions/1852537/how-to-use-prettify-with-blogger-blogspot
and
http://notepad2.blogspot.com/2012/05/use-google-code-prettify-in-blogger.html
Objective-C
int foo=0; NSLog(@"%i", foo);
Ruby
#create a zip file
sourcefolder = File.join(Rails.root, 'tmp', V11_FOLDERNAME) #the source folder
zipfile_name = File.join(Rails.root, 'tmp', V11_FOLDERNAME, 'databases_v11.zip')
#delete any existing zip file
begin
File.delete(zipfile_name)
rescue Errno::ENOENT
end
Zip::ZipFile.open(zipfile_name, Zip::ZipFile::CREATE) do |zipfile|
input_filenames.each do |filename|
# Two arguments:
# - The name of the file as it will appear in the archive
# - The original file, including the path to find it
zipfile.add(filename, sourcefolder + '/' + filename)
end
end
send_file(zipfile_name, type: "application/zip", disposition: 'attachment')
setup
to make this work, edit your site template (Design > Edit HTML) and add these lines before the closing head tag:<link href='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css' rel='stylesheet' type='text/css'/> <script language='javascript' src='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js' type='text/javascript'/> <script language='javascript' src='http://google-code-prettify.googlecode.com/svn/trunk/src/lang-css.js' type='text/javascript'/>
and add this to the body tag attributes:
onload='prettyPrint()'
usage
wrap your code in pre blocks like this:<pre class="prettyprint"> int foo=0; NSLog(@"%i", foo); </pre>
Subscribe to:
Comments (Atom)




