BOURBON, NEAT, BITTERS CHEAT SHEET presented by Tower - the best Git client for Mac and Windows GRID AND LAYOUT BASICS GRID CONFIGURATION Configure your grid in base/_grid-settings. scss $column: 40px; HELPFUL MIXINS AND FUNCTIONS BACKGROUNDS & GRADIENTS @include background(lineargradient(red, green) left repeat, radial-gradient(red, $gutter: 44px; orange) left repeat); $max-width: em(960); @include background-image(url("/ $grid-columns: 12; images/a.png"),linear-gradient (white 0, yellow 50%, STYLE YOUR OUTER CONTAINER(S) outer-container marks the items that contain our columns. These items shall be constrained to the grid’s max-width (amongst other things that outer-container provides). .element { } @include outer-container(); row makes sure that floats are cleared and a clean “block” display is applied. @include span-columns(8); } @include shift(2); borders margins and other spacings _GRID-SETTINGS.SCSS @include linear-gradient(to top, breakpoints for media queries #8fdce5, #3dc3d1); MEDIA QUERIES ANIMATIONS & TRANSITIONS @include animation(scale 1.0s _TYPOGRAPHY.SCSS h1 - h6 a p img blockquote _LISTS.SCSS ul ol dl li ease-in, slide 2.0s ease); @include transition(opacity 1.0s .element { font settings sizes, weights, line heights grid configuration column & gutter sizes, max-width... .element { @include row(); } ITEM WIDTH AND POSITION _VARIABLES.SCSS transparent 50%)); @include media($breakpoint) {…} MARK ROWS IN YOUR GRID BITTERS STRUCTURE ease-in 0s, width 2.0s ease-in 2s); RETINA IMAGES @include retina-image("../img logo", 100px 200px); _BUTTONS.SCSS button input _FORMS.SCSS input label select textarea fieldset Nested items: @include shift-in-context(1 of 12); @include span-columns(10 of 12); CLEAR FLOATS @include clearfix; The best Git Client for Mac & Windows 30-day free trial available at www.git-tower.com BOURBON, NEAT, BITTERS CHEAT SHEET presented by Tower - the best Git client for Mac and Windows PROJECT SETUP INSTALLING THE RUBY GEMS Ruby is required to install the components. Execute this in your Command Line application: $ sudo gem install bourbon neat bitters IMPORTING COMPONENTS e @import “lib/bourbon/bourbon”; @import “base/grid-settings”; @import “lib/neat/neat”; PROJECT SETUP r Add Bitters to the project: $ bitters install t Create a “lib” folder inside of “scss” and change into it: bourbon.io neat.bourbon.io bitters.bourbon.io In “base/_grid-settings.scss”, make sure to have a correct import path: GETTING STARTED TUTORIAL: git-tower.com/learn/bourbon-neat-bitters @import “../lib/neat/neat-helpers”; into your project’s “scss” folder: $ cd my-project/scss OFFICIAL PROJECT WEBSITES @import “base/base”; r e In your Command Line app, change Create your main stylesheet (e.g. “styles.scss”) in the “scss” folder and import the components there: HELP AND DOCUMENTATION t If you want to use “normalize.css”, add this as your first line in “styles. scss”: @import “lib/normalize-css/ normalize”; u Don’t forget to start your SASS $ mkdir lib $ cd lib u Install both Bourbon and Neat: $ bourbon install $ neat install We make Tower the best Git client for Mac and Windows We help over 100,000 users in companies like Apple, Google, Amazon, Twitter, and Facebook to easily & productively work with the Git version control system. Try it 30 days for free! COMMAND LINE CHEAT SHEET presented by Tower - the best Git client for Mac and Windows DIRECTORIES $ pwd FILES $ rm <file> Display path of current working directory $ cd <directory> Change directory to <directory> $ cd .. Delete <file> $ rm -r <directory> Delete <directory> $ rm -f <file> Navigate to parent directory $ ls List directory contents Force-delete <file> (add -r to forcedelete a directory) $ mv <file-old> <file-new> Rename <file-old> to <file-new> $ ls -la List detailed directory contents, including hidden files $ mkdir <directory> Create new directory named <directory> OUTPUT $ cat <file> Output the contents of <file> $ less <file> Output the contents of <file> using the less command (which supports pagination etc.) $ <cmd> > <file> Direct the output of <cmd> into <file> $ <cmd> >> <file> Append the output of <cmd> to <file> $ <cmd1> | <cmd2> Direct the output of <cmd1> to <cmd2> $ clear Clear the command line window 30-day free trial available at www.git-tower.com $ find <dir> -name "<file>" Find all files named <file> inside <dir> (use wildcards [*] to search for parts of filenames, e.g. "file.*") $ grep "<text>" <file> Output all occurrences of <text> inside <file> (add -i for case-insensitivity) $ grep -rl "<text>" <dir> Search for all files containing <text> inside <dir> $ mv <file> <directory> Move <file> to <directory> (possibly overwriting an existing file) $ cp <file> <directory> Copy <file> to <directory> (possibly overwriting an existing file) $ cp -r <directory1> <directory2> Copy <directory1> and its contents to <directory2> (possibly overwriting files in an existing directory) $ touch <file> Update file access & modification time (and create <file> if it doesn’t exist) $ head <file> Output the first 10 lines of <file> SEARCH PERMISSIONS NETWORK $ ping <host> Ping <host> and display status $ whois <domain> Output whois information for <domain> $ curl -O <url/to/file> Download <file> (via HTTP[S] or FTP) $ ssh <username>@<host> Establish an SSH connection to <host> with user <username> $ scp <file> <user>@<host>:/remote/path Copy <file> to a remote <host> PROCESSES $ chmod 755 <file> Change permissions of <file> to 755 $ chmod -R 600 <directory> Change permissions of <directory> (and its contents) to 600 $ chown <user>:<group> <file> Change ownership of <file> to <user> and <group> (add -R to include a directory’s contents) $ ps ax Output currently running processes $ top Display live information about currently running processes $ kill <pid> Quit process with ID <pid> The best Git Client for Mac & Windows COMMAND LINE CHEAT SHEET presented by Tower - the best Git client for Mac and Windows GETTING HELP THE “CTRL” KEY HOME FOLDER On the command line, help is always at hand: you can either type man <command>| or <command> --help to receive detailed documentation about the command in question. Various keyboard shortcuts can assist you when entering text: Hitting CTRL+A| moves the caret to the beginning and CTRL+E to the end of the line. File and directory paths can get long and awkward. If you’re addressing a path inside of your home folder though, you can make things easier by using the ~ character. So instead of writing cd /Users/your-username/projects/, a simple cd ~/projects/ will do. FILE PERMISSIONS On Unix systems, file permissions are set using three digits: the first one representing the permissions for the owning user, the second one for its group, and the third one for anyone else. Add up the desired access rights for each digit as following: 4 — access/read (r) 2 — modify/write (w) 1 — execute (x) For example, 755 means “rwx” for owner and “rx” for both group and anyone. 740| represents “rwx” for owner, “r” for group and no rights for other users. COMBINING COMMANDS If you plan to run a series of commands after another, it might be useful to combine them instead of waiting for each command to finish before typing the next one. To do so, simply separate the commands with a semicolon ( ;) on the same line. Additionally, it is possble to execute a command only if its predecessor produces a certain result. Code placed after the &&| operator will only be run if the previous command completes successfully, while the opposite || operator only continues if the previous command fails. The following command will create the folder “videos” only if the cd command fails (and the folder therefore doesn’t exist): $ cd ~/videos || mkdir ~/videos 30-day free trial available at www.git-tower.com In a similar fashion, CTRL+K deletes all characters after and CTRL+U all characters in front of the caret. Pressing CTRL+L clears the screen (similarly to the clear command). If you should ever want to abort a running command, CTRL+C will cancel it. And in case you should forget your user name, whoami will remind you. THE “TAB” KEY The less command can display and paginate output. This means that it only displays one page full of content and then waits for your explicit instructions. You’ll know you have less in front of you if the last line of your screen either shows the file’s name or just a colon (:). Whenever entering paths and file names, the TAB key comes in very handy. It autocompletes what you’ve written, reducing typos quite efficiently. E.g. when you want to switch to a different directory, you can either type every component of the path by hand: $ cd ~/projects/acmedesign/docs/ …or use the TAB key (try this yourself): $ cd ~/pr[TAB]ojects/ ac[TAB]medesign/d[TAB]ocs/ In case your typed characters are ambiguous (because “ac” could point to the “acmedesign” or the “actionscript” folder), the command line won’t be able to autocomplete. In that case, you can hit TAB twice to view all possible matches and then type a few more characters. THE ARROW KEYS The command line keeps a history of the most recent commands you executed. By pressing the ARROW UP key, you can step through the last called commands (starting with the most recent). ARROW DOWN will move forward in history towards the most recent call. Bonus tip: Calling the history command prints a list of all recent commands. OUTPUT WITH “LESS” Apart from the arrow keys, hitting SPACE| will scroll one page forward, b will scroll one page backward, and q will quit the less program. DIRECTING OUTPUT The output of a command does not necessarily have to be printed to the command line. Instead, you can decide to direct it to somewhere else. Using the > operator, for example, output can be directed to a file. The following command will save the running processes to a text file in your home folder: $ ps ax > ~/processes.txt It is also possible to pass output to another command using the | (pipe) operator, which makes it very easy to create complex operations. E.g., this chain of commands will list the current directory’s contents, search the list for PDF files and display the results with the less command: $ ls | grep ".pdf" | less The best Git Client for Mac & Windows 010010100101011010101101001010101001011101011010 Namespace using Namespace; Data Types byte,sbyte,int,uint,short,ushort,long,ulong,float,double,decimal,bool,char,string, object Variable Declaration public | protected internal | protected | internal | private <type> As <variable_name> If Else if(expression) { <statement 1>; } else { <statement 2>; } C# version of IIF() variable == ?true:false; Type Declaration public | internal | private <variable><suffix> For Loop for(statement) { <statement>; } Suffixes f -float, l,L - long, No double suffix, U,u - unsigned Arrays <type>[] <name> = new <type>[ArraySize]; Initialize Array <type>[] <name> = new <type>[ArraySize] {<value1>, <value2>, ... , <valueN>}; Change Size of Array <type>[] <name> = new <type>[ArraySize]; Array.Resize<type>(ref <name>, <size>); Comments //Comment text Multi-line comments /* This is commented */ For Each Loop foreach(<variable> In <object>) { <statements>; [break]; [continue]; } While Loop while(<expression>) { <statement> } XML Comments Press the / (forward slash) key 3 times. Do-While Loop do { <statement>; } while <expression>; Line Continuation string strtext = @“To break a long string across multiple lines, end the string, add the line continuation character and continue the string on the next line.”; Arithmetic Operators + (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus) String Concatenation + Relational Operators < (Less Than), <= (Less Than or Equal To), > (Greater Than), >= (Greater Than or Equal To), == (Equal To),! = (Not Equal To), is, as Logical Operators & (And), | (Or), ^ (Xor),&& (AndAlso), || (OrElse) Assignment Operators = (Equals), += (Addition), -= (Subtraction), *= (Multiplication), /= (Division), %= (Modulus), &= (And),|= (OR), ^= (Exclusive OR), <<= (Left Shift), >>= (Right Shift), ?? String Manipulation .Substring(<start>,[<length>]) .Trim() <trims from beginning & end of string> .TrimEnd([<char array>]) .TrimStart([char array]) .ToLower() <to lower case> .ToUpper() <to upper case> .Replace(<find>,<replace>) .Equals(<expression>) <6 available overloads> .Contains(<string>) .Join(<seperator>,<value>,[<count>]) .Compare(<string1>,<string2>,[<ignore case>]) <7 overloads available> .Copy(<string>) Error Handling try { //<statements that may cause an error>; } catch(Exception ex) { //<statements to use when an error occurs>; } finally { //<statements to use no matter what happens> } Select Case Statement switch(<expression>) { case <literal or type>: <statement>; <break>; case <literal or type>: <statement>; <break>; ' ' default: <statement>; <break>; } Function Structure <private, public, protected, internal> [static] <ReturnType> <Function_Name>([Parameters]) { //body of the function; return <ReturnType>; } Sub Procedure Structure <private, public, protected, internal> void <method_name>([Parameters]) { //body of the procedure; } Class Structure public class <Class_Name> { //body of class } public 'method_prototypes 'data_attributes private 'method_prototypes 'data_attributes internal 'method_prototypes static 'method_prototypes 'data_attributes Download More Reference Sheets & Get Programming Help @ http://www.DreamInCode.net Edited By:PsychoCoder, Martyr2 Published: October 9, 2007 Boxes margin * margin-top margin-right margin-bottom margin-left padding * padding-top padding-right padding-bottom padding-left border border-top border-bottom border-right border-left * * * * * border-color * border-top-color border-right-color border-bottom-color border-left-color border-style * border-top-style border-right-style border-bottom-style border-left-style border-width * border-top-width border-right-width border-bottom-width border-left-width Positioning display position top right bottom left float clear z-index direction unicode-bidi overflow clip visibility Dimensions width min-width max-width height min-height max-height line-height vertical-align Miscellaneous content quotes counter-reset counter-increment marker-offset list-style * list-style-type list-style-image list-style-position Shorthand properties are marked with * Paging size marks page-break-before page-break-after page-break-inside page orphans widows css /* Comment */ Color / Background color * background background-color background-image background-repeat background-attachment background-position Width Visible Area @media type { selector { property: values; } } (Media type optional) Styles apply to: * All elements div <div> div * Elements within <div> div span <span> within <div> div, span <div> and <span> div > span <span> with <div> as div + span Height Border Padding Margin parent px Pixels <span> preceded by em 1em equal to font size of <div> ... </div> parent (same as 100%) .class Elements of class "class" ex Height of lower case "x" div.class <div> of class "class" % Percentage #itemid Element with id "itemid" in Inches div#itemid <div> with id "itemid" cm Centimeters a[class] <a> with class attribute mm Millimeters a[class='x'] <a> when class is "x" pt 1pt = 1/72in a[class~='x'] <a> when class is a list a[lang|='en'] pc 1pc = 12pt of space-seperated values #789abc RGB Hex Notation and one of those is 'x' #acf Equates to "#aaccff" <a> when lang begins rgb(0,25,50) Value (0 to 255) of each with "en" of red, green, and blue. May also be percentages 0 0 requires no unit Styles apply to: :first-child First child of element :first-line First line of element :first-letter First letter of element :hover Element when mouse over :active Active element :focus Element with focus :link Non-active, unvisited links without mouse over. :visited Visited links :lang(lang) Element with text of language "lang" all projection braille screen embossed speech handheld tty print tv azimuth list-style border-collapse list-style-image border-spacing list-style-position caption-side list-style-type color orphans cursor page direction page-break-inside empty-cells quotes font speak font-family speak-header font-stretch text-align font-size text-indent font-size-adjust text-transform font-style volume font-variant white-space font-weight widows letter-spacing word-spacing line-height Fonts * font font-family font-style font-variant font-weight font-stretch font-size font-size-adjust Text text-indent text-align text-decoration text-shadow letter-spacing word-spacing text-transform white-space Tables caption-side table-layout border-collapse border-spacing empty-cells speak-header Interface cursor * outline outline-width outline-style outline-color Aural volume speak * pause pause-before pause-after * cue cue-before cue-after play-during azimuth elevation speech-rate voice-family pitch pitch-range stress richness speak-punctuation speak-numeral Available free from ILoveJackDaniels.com JavaScript Cheat Sheet by Dave Child (DaveChild) via cheatography.com/1/cs/7/ Regular Expressions Syntax Pattern Modifiers (cont) JavaScript Arrays ^ x* Allow comments and whitespace in concat() slice() pattern join() sort() length splice() pop() toSource() push() toString() reverse() unshift() shift() valueOf() $ . Start of string End of string Any single character (a|b) a or b (...) Group section [abc] In range (a, b or c) [^abc] Not in range \s White space a? Zero or one of a a* Zero or more of a a*? Zero or more, ungreedy a+ One or more of a a+? One or more, ungreedy a{3} Exactly 3 of a a{3,} 3 or more of a a{,6} Up to 6 of a a{3,6} 3 to 6 of a a{3,6}? 3 to 6 of a, ungreedy \ Escape character [:punct:] Any punctuation symbol [:space:] Any space character [:blank:] Space or tab e* Evaluate replacement U* Ungreedy pattern * PCRE modifier JavaScript RegExp Object compile() lastParen exec() leftCOntext JavaScript Numbers and Maths global multiline abs() min() ignoreCase rightContext acos() NEGATIVE_INFINITY input source asin() PI lastIndex test() atan() POSITIVE_INFINITY atan2() pow() ceil() random() cos() round() E sin() exp() sqrt() floor() SQRT1_2 LN10 SQRT2 LN2 tan() log() toSource() LOG10E toExponential() LOG2E toFixed() max() toPrecision() MAX_VALUE toString() MIN_VALUE valueOf() lastMatch JavaScript Event Handlers onabort onmousedown onblur onmousemove onchange onmouseout onclick onmouseover ondblclick onmouseup ondragdrop onmove onerror onreset onfocus onresize onkeydown onselect Pattern Modifiers onkeypress onsubmit g Global match onkeyup onunload i* Case-insensitive onload m* Multiple lines s* Treat string as single line There's an excellent regular expression tester at: http://regexpal.com/ NaN By Dave Child (DaveChild) Published 19th October, 2011. Sponsored by Readability-Score.com cheatography.com/davechild/ Last updated 11th May, 2016. Measure your website readability! www.getpostcookie.com Page 1 of 2. https://readability-score.com JavaScript Cheat Sheet by Dave Child (DaveChild) via cheatography.com/1/cs/7/ JavaScript Booleans toSource() JavaScript Strings valueOf() toString() JavaScript Dates charAt() slice() charCodeAt() split() x concat() substr() fromCharCode() substring() Date() setMonth() indexOf() toLowerCase() getDate() setFullYear() lastIndexOf() toUpperCase() getDay() setHours() length toLocaleLowerCase() getMonth setMinutes() localeCompare() toLocaleUpperCase() getFullYear setSeconds() match() x toSource() getYear setMilliseconds() replace() x valueOf() getHours setTime() search() x getMinutes setUTCDate() getSeconds setUTCDay() getMilliseconds setUTCMonth() getTime setUTCFullYear() getTimezoneOffset() setUTCHours() decodeURI() isNaN() getUTCDate() setUTCMinutes() decodeURIComponent() Number() getUTCDay() setUTCSeconds() encodeURI() parseFloat() getUTCMonth() setUTCMilliseconds() encodeURIComponent() parseInt() getUTCFullYear() toSource() escape() String() getUTCHours() toString() eval() unescape() getUTCMinutes() toGMTString() isFinite() getUTCSeconds() toUTCString() getUTCMilliseconds() toLocaleString() parse() UTC() setDate() valueOf() String object methods with an x support regular expressions. JavaScript Functions By Dave Child (DaveChild) Published 19th October, 2011. Sponsored by Readability-Score.com cheatography.com/davechild/ Last updated 11th May, 2016. Measure your website readability! www.getpostcookie.com Page 2 of 2. https://readability-score.com Python Cheat Sheet by Dave Child (DaveChild) via cheatography.com/1/cs/19/ Python sys Variables Python Class Special Methods Python String Methods (cont) argv Command line args __new__(cls) __lt__(self, other) istitle() * title() * builtin_module_names Linked C modules __init__(self, args) __le__(self, other) isupper() * translate(table) byteorder Native byte order __del__(self) __gt__(self, other) join() upper() * check_interval Signal check __repr__(self) __ge__(self, other) ljust(width) zfill(width) frequency __str__(self) __eq__(self, other) lower() * exec_prefix Root directory __cmp__(self, other) __ne__(self, other) executable Name of executable Methods marked * are locale dependant for 8- __index__(self) __nonzero__(self) bit strings. exitfunc Exit function name modules Loaded modules path Search path platform Current platform stdin, stdout, stderr File objects for I/O __delattr__(self, name) version_info Python version info __call__(self, args, kwargs) winver Version number __hash__(self) Python File Methods __getattr__(self, name) __getattribute__(self, name) __setattr__(self, name, attr) Python List Methods Python sys.argv append(item) pop(position) sys.argv[0] foo.py count(item) remove(item) sys.argv[1] bar extend(list) reverse() sys.argv[2] -c index(item) sort() sys.argv[3] qux insert(position, item) sys.argv[4] --h close() readlines(size) flush() seek(offset) fileno() tell() isatty() truncate(size) next() write(string) read(size) writelines(list) readline(size) Python Indexes and Slices len(a) 6 a[0] 0 a[5] 5 sys.argv for the command: Python String Methods a[-1] 5 $ python foo.py bar -c qux --h capitalize() * lstrip() a[-2] 4 center(width) partition(sep) a[1:] [1,2,3,4,5] count(sub, start, end) replace(old, new) a[:5] [0,1,2,3,4] decode() rfind(sub, start ,end) a[:-2] [0,1,2,3] encode() rindex(sub, start, end) a[1:3] [1,2] endswith(sub) rjust(width) a[1:-1] [1,2,3,4] expandtabs() rpartition(sep) b=a[:] Shallow copy of a find(sub, start, end) rsplit(sep) Indexes and Slices of a=[0,1,2,3,4,5] index(sub, start, end) rstrip() isalnum() * split(sep) isalpha() * splitlines() today() fromordinal(ordinal) isdigit() * startswith(sub) now(timezoneinfo) combine(date, time) islower() * strip() utcnow() strptime(date, format) isspace() * swapcase() * fromtimestamp(timestamp) Python os Variables altsep Alternative sep curdir Current dir string defpath Default search path devnull Path of null device extsep Extension separator linesep Line separator name Name of OS pardir Parent dir string pathsep Patch separator sep Path separator Registered OS names: "posix", "nt", "mac", "os2", "ce", "java", "riscos" Python Datetime Methods utcfromtimestamp(timestamp) By Dave Child (DaveChild) Published 19th October, 2011. Sponsored by ApolloPad.com cheatography.com/davechild/ Last updated 12th May, 2016. Everyone has a novel in them. Finish Yours! www.getpostcookie.com Page 1 of 2. https://apollopad.com Python Cheat Sheet by Dave Child (DaveChild) via cheatography.com/1/cs/19/ Python Time Methods replace() utcoffset() isoformat() dst() __str__() tzname() strftime(format) Python Date Formatting %a Abbreviated weekday (Sun) %A Weekday (Sunday) %b Abbreviated month name (Jan) %B Month name (January) %c Date and time %d Day (leading zeros) (01 to 31) %H 24 hour (leading zeros) (00 to 23) %I 12 hour (leading zeros) (01 to 12) %j Day of year (001 to 366) %m Month (01 to 12) %M Minute (00 to 59) %p AM or PM %S Second (00 to 61⁴) %U Week number¹ (00 to 53) %w Weekday² (0 to 6) %W Week number³ (00 to 53) %x Date %X Time %y Year without century (00 to 99) %Y Year (2008) %Z Time zone (GMT) %% A literal "%" character (%) ¹ Sunday as start of week. All days in a new year preceding the first Sunday are considered to be in week 0. ² 0 is Sunday, 6 is Saturday. ³ Monday as start of week. All days in a new year preceding the first Monday are considered to be in week 0. ⁴ This is not a mistake. Range takes account of leap and doubleleap seconds. By Dave Child (DaveChild) Published 19th October, 2011. Sponsored by ApolloPad.com cheatography.com/davechild/ Last updated 12th May, 2016. Everyone has a novel in them. Finish Yours! www.getpostcookie.com Page 2 of 2. https://apollopad.com Regular Expressions Cheat Sheet by Dave Child (DaveChild) via cheatography.com/1/cs/5/ Anchors Assertions ^ Start of string, or start of line in multi-line ?= Lookahead assertion . Any character except new line (\n) pattern ?! Negative lookahead (a|b) a or b ?<= Lookbehind assertion (...) Group ?!= or ?<! Negative lookbehind (?:...) Passive (non-capturing) group ?> Once-only Subexpression [abc] Range (a or b or c) ?() Condition [if then] [^abc] Not (a or b or c) ?()| Condition [if then else] [a-q] Lower case letter from a to q ?# Comment [A-Q] Upper case letter from A to Q [0-7] Digit from 0 to 7 \x Group/subpattern number "x" \A Start of string $ End of string, or end of line in multi-line pattern \Z End of string \b Word boundary \B Not word boundary \< Start of word \> End of word Character Classes \c Control character \s White space \S Not white space \d Digit \D Not digit \w Word \W Not word \x Hexadecimal digit \O Octal digit Groups and Ranges Quantifiers * 0 or more {3} Exactly 3 + 1 or more {3,} 3 or more ? 0 or 1 {3,5} 3, 4 or 5 Add a ? to a quantifier to make it ungreedy. Escape Sequences Pattern Modifiers g Global match i* Case-insensitive m* Multiple lines \ Escape following character s* Treat string as single line \Q Begin literal sequence x* Allow comments and whitespace in \E End literal sequence pattern "Escaping" is a way of treating characters e* Evaluate replacement which have a special meaning in regular U* Ungreedy pattern expressions literally, rather than as special POSIX Ranges are inclusive. characters. [:upper:] Upper case letters [:lower:] Lower case letters [:alpha:] All letters ^ [ . $ [:alnum:] Digits and letters { * ( \ [:digit:] Digits + ) | ? [:xdigit:] Hexadecimal digits < > [:punct:] Punctuation The escape character is usually \ [:blank:] Space and tab [:space:] Blank characters [:cntrl:] Control characters [:graph:] Printed characters [:print:] Printed characters and spaces [:word:] Digits, letters and underscore * PCRE modifier String Replacement Common Metacharacters $n nth non-passive group $2 "xyz" in /^(abc(xyz))$/ $1 "xyz" in /^(?:abc)(xyz)$/ $` Before matched string $' After matched string $+ Last matched string Special Characters $& Entire matched string \n New line Some regex implementations use \ instead of $. \r Carriage return \t Tab \v Vertical tab \f Form feed \xxx Octal character xxx \xhh Hex character hh By Dave Child (DaveChild) Published 19th October, 2011. Sponsored by CrosswordCheats.com cheatography.com/davechild/ Last updated 12th May, 2016. Learn to solve cryptic crosswords! www.getpostcookie.com Page 1 of 1. http://crosswordcheats.com Rails 4 Cheat Sheet by entaro via cheatography.com/4988/cs/931/ Activer record queries Match routes Post.where(author: 'admin') match '/items/:id/purchase', to: execute 'CREATE INDEX comics_properties Post.where(author: 'admin').last 'items#purchase', via: :post ON comics USING gin(properties)' match '/items/:id/purchase', to: end Post.find_by(title: 'Rails 4', author: 'admin') Post.find_or_initialize_by(title: 'Rails 4') Post.find_or_create_by(title: 'Rails 4') @post.update(post_params) - preferred @post.update_columns(post_params) executes directly in database(skip validation) Scopes scope :sold, ->{ where(state: 'sold') } default_scope ->{ where(state: 'available') } scope :recent, ->{ where(published_at: 2.weeks.ago) } scope :recent_red, ->{ recent.where(color: 'red') } Post.where.not(author: author) 'items#purchase', via: :all Collection form helpers Using the store_accessor macro style method in Active Record models, we can add read/write end accessors to key/value hstore properties: class Item < ActiveRecord::Base class Comic < ActiveRecord::Base belongs_to :owner store_accessor :properties, :story_arc end end collection_select(:item, :owner_id, Owner.all, comic = Comic.create :id, :name) comic.properties # => nil collection_radio_buttons(:item, :owner_id, comic.story_arc = 'Throne of Atlantis' Owner.all, :id, :name) comic.save collection_check_boxes(:item, :owner_id, To query against hstore data in Active Record, Owner.all, :id, :name) use SQL string conditions with the where query <%= f.date_select :return_date %> method: Comic.where("properties -> 'story_arc' = Post.includes(:comments).where(comments: { To get started, first setup your database to use the hstore extension: Post.includes(:comments).where('comments.na class AddHstoreExtension < me' => 'foo') ActiveRecord::Migration e') def up execute 'CREATE EXTENSION hstore' end def down Flash types execute 'DROP EXTENSION hstore' class ApplicationController < end ActionController::Base end add_flash_types :grunt, :snarl Indexes end If you are doing any queries on an hstore flash[:grunt] = 'braaains...' property, be sure to add the appropriate index. redirect_to @user, grunt: 'braaains...' When adding an index, you will have to decide <div id="grunt"><%= grunt %></div> to use either GIN or GiST index types. The distinguishing factor between the two index types is that GIN index lookups are three times Concerns concern :sociable do |options| resources :comments, options resources :categories, options end resources :messages, concerns: :sociable resources :items do concerns :sociable, only: :create end end has_many :items Postgres support Post.includes(:comments).order('comments.nam def down execute 'DROP INDEX comics_properties' class Owner < ActiveRecord::Base User.order(:name, created_at: :desc) name: 'foo' }) Postgres support (cont) faster than GiST indexes, however they also take three times longer to build. Checkout the documentation, which goes into detail about the differences. 'Throne of Atlantis'") Array support class AddTagsToArticles < ActiveRecord::Migration def change change_table :articles do |t| t.string :tags, array: true end end article.tags = ['rails'] article.save Another example def due_date_params params.require(:due_date).permit( :name { :tags => [] }, :day_of_month, :day_of_week, :frequency ) end class DueDate < ActiveRecord::Base store_accessor :recur, :frequency store_accessor :recur, :day_of_week store_accessor :recur, :day_of_month end class AddIndexToComicsProperties < ActiveRecord::Migration def up end By entaro Published 5th April, 2013. Sponsored by CrosswordCheats.com cheatography.com/entaro/ Last updated 2nd June, 2014. Learn to solve cryptic crosswords! Page 1 of 1. http://crosswordcheats.com Flash ActionScript Quick Reference Author: Jialong He Jialong_he@yahoo.com http://tiger.la.asu.edu Introduction Using Flash to create animations on the web is popular because the flash player is installed on most computers and the published flash file (SWF file) is small. Flash has a powerful scripting language called ActionScript. You can use write script to manipulate and control objects on the stage. Its syntax is similar to JavaScript (or C++). Note: this quick reference is based on ActionScript 2.0 language reference. if (condition){ statement(s); } else { statement(s); } if (age>=18) { trace("welcome, user"); } else { trace("sorry, junior"); } for (init; condition; next) { statement(s); } for (Cnt = 1; Cnt<10; Cnt++) { trace(Cnt); } switch (expression){ caseClause: [defaultClause:] } Switch (myChar) { case "A" : case "a" : trace("you pressed A or a"); break; default : trace("you did not press A"); } Script Example A script can be associated with a keyframe or with an object. To test the following script, copy it to the action panel. Press “Ctrl + Enter” to start the flash file. //==================== // A simple ActionScript //==================== for (Cnt=1; Cnt<10; Cnt++) { trace(Math.random()); } trace ("Hello, World!"); Operator +, -, *, /, % +=, -=, *=, =/, =% Add, Subtract, Multiply, Division, Remainder Combine with assignment operator ++, --, [] Increase, decrease, Array access ==, !=, <, <=, >, >= Comparison, equal, not equal, less than, … !, &&, || Logical NOT, AND, OR <<, >>, >>> Bit shift, left, right, right unsigned ~, &, |, ^ Bitwise NOT, AND, OR, XOR new, delete Allocate (delete) an object typeof, instanceof get expression type, test an instance //, /* */ One line and multiple line comments Constants and Compiler Directives true, false, undefined, null, NaN, Infinity newline Predefined constants #initclip statements(s) #endinitclip Initialization actions are executed only once when a SWF file is played for (var in object) { statement(s); } while(condition) { statement(s); } \\========= Example========= var intervalId:Number; var count:Number = 0; var maxCount:Number = 10; var duration:Number = 20; function myCallback():Void { trace(count); if(count >= maxCount) {clearInterval(intervalId);} count++; } intervalId = setInterval(this, "myCallback", duration); escape, unescape Converts the parameter to a string and encodes it in a URL-encoded format, where all nonalphanumeric characters are replaced with % hexadecimal sequences (e.g, @ to %40). getProperty, setProperty Get (set) movie clip property for (var prop in myObject) { trace(myObject[prop]); } getURL Load a web page in browser on (event) { var Cnt:Number = 0; while (Cnt < 20) { trace(Cnt); i += 3; } } Mouse/ket event handler Press, release, releaseOutside, rollOut, rollOver, dragOut, dragOver, keyPress var myObject:Object = {Name:"Tara", age:27, city:"San Francisco"}; do { statement(s) } while (condition) var myVar:Number = 0; do { trace(myVar); myVar++; } while (myVar < 5); function FName(P){ statement(s) } function mySquared(x:Number) { return Math.pow(x, 2); } class, interface, implement, dynamic, extend, private, public, intrinsic Define custom class related statements e.g.; on (press) { startDrag(this); } onClipEvent(movieEvent: Movie clip event handler. load, unload, enterFrame, mouseMove, MouseDown, Object) { MouseUp, KeyDown, KeyUp, Data. statements; } onClipEvent (keyDown) { if (Key.getCode() == Key.RIGHT) { this._parent.nextFrame(); } else if (Key.getCode() == Key.LEFT) { this._parent.prevFrame(); } } startDrag, stopDrag play, stop, nextFrame, prevFrame Main timeline movie clip play head control gotoAndPlay, gotoAndStop nextScene, prevScene Loads (unload) a SWF, JPEG, GIF, or PNG file from local disk or web server into a movie clip Makes the target movie clip draggable while the movie plays. my_mc.onPress = function () { startDrag(this); } my_mc.onRelease = function() { stopDrag(); } Global Functions loadMovie, loadMovieNum unloadMovie, unloadMovieNum #include “filename.as" Include external ActionScript setInterval, clearInterval Repeatly execute a function (or an object). Program Flow Control fscommand loadVariables, loadVariablesNum Reads data from an external file either on local disk or on web server Lets the SWF file communicate with either Flash Player or the program that is hosting Flash Player, such as a web browser. e.g, fscommand("fullscreen", true); isFinite, isNaN Test number Miscellaneous functions. getVersion , targetPath, trace, getTimer, removeMovieClip duplicateMovieClip Math Mouse Properties E, LN10, LN2, LOG10E, LOG2E, PI, SORT1_2, SORT2 Methods Global Properties Example abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow, random, round, sin, sqrt, tan A reference to the global object that holds the core ActionScript classes, such as String, Object, Math, and Array. _parent Specifies or returns a reference to the movie clip or object that contains the current movie clip or object. String _root Specifies or returns a reference to the root movie clip Timeline. Methods This References an object or movie clip instance. charAt, charCodeAt, concat, fromCharCode, indexOf, lastIndexOf, slice, split, substr, substring, toLowerCase, toString, toUpperCase, valueOf Example var my_str:String = new String("Hello world"); var mySubstring:String = new String(); Properties constructor, _proto_, prototype, _resolve, Methods addProperty, hasOwnProperty, isPropertyEnumerable, isPrototypeOf, registerClass, toString, unwatch, valueOf, watch mySubstring = my_str.substr(6,5); trace(mySubstring); // output: world trace (mySubstring.toUpperCase()); //WORLD Stage Properties align, height, scaleMode, showMenu, width Event onResize Array Methods addListener, removeListener Properties CASEINSENSITIVE, DESCENDING, length, NUMRIC, RETURNINDEXEDARRAY, UNIQUESORT Example Stage.scaleMode = "noScale" var myListener:Object = new Object(); myListener.onResize = function () { trace("Stage size is now " + Stage.width + " by " + Stage.height); } Stage.addListener(myListener); Methods concat, join, pop, push, reverse, shift, slice, sort, sortOn, splice, toString, unshift. Example var myA:Array = new Array("a","b","c"); var myN:Array = new Array(1,2,3); var myAN:Array =myA.concat(myN); trace(myAN.length); // Creates array [a,b,c,1,2,3]. addListener, hide, removeListener, show Example var mouseListener:Object = new Object(); mouseListener.onMouseDown = function() { trace("Mouse down"); }; mouseListener.onMouseMove = function() { trace(_xmouse); trace(_ymouse); }; mouseListener.onMouseUp = function() { trace("Mouse up"); }; Mouse.addListener(mouseListener); Properties length Common Classes Object Object onMouseDown, onMouseMove, onMouseUp, onMouseWheel Methods trace(Math.log(0)); // output: -Infinity trace(Math.atan(-1)); // output: -0.785398163397448 _global constructor Events Button Properties _alpha, blendMode, cacheAsBitmap, enabled, filters, _focusrect, _height, _highquality, menu, _name, _parent, _quality, _rotation, scale9Grid, _soundbuftime, tabEnabled, tabIndex, _target, trackAsMenu, _url, useHandCursor, _visible, _width, _x, _xmouse, _xscale, _y, _ymouse, _yscale Events onDragOut, onDragOver, onKeyDown, onKeyUp, onKillFocus, onPress, onRelease, onReseaseOutside, onRollOut, onRollOver, onSetFocus Methods getDepth Example myBtn1_btn.enabled = true; myBtn2_btn.enabled = false; myBtn1_btn.onRelease = function() { trace( "you clicked : " + this._name ); }; myBtn2_btn.onRelease = function() { trace( "you clicked : " + this._name ); }; Key Date Properties BACKSPACE, CAPSLOCK, CONTROL, DELETEKEY, DOWN, END, ENTER, ESCAPE, HOME, INSERT, LEFT, PGDN, PGUP, RIGHT, SHIFT, SPACE, TAB, UP, _listeners Properties Only have properties inherited from Object. Events onKeyDown, onKeyUp Constructor TextFormat Methods addListener, getAscii, getCode, isAccessible, isDown, isToggled, removeListener Properties Example var myListener:Object = new Object(); myListener.onKeyDown = function () { trace ("You pressed a key."); } myListener.onKeyUp = function () { trace ("You released a key."); } Key.addListener(myListener); align, blockIndent, bold, bullet, color, font, indent, italic, kerning, leading, leftMargin, letterSpacing, rightMargin, size, tabStops, target, underline, url Methods getTextExtent Example var my_fmt:TextFormat = new TextFormat(); my_fmt.bold = true; my_fmt.font = "Arial"; my_fmt.size = 12; my_fmt.color = 0xFF0000; Methods Example getDate, getDay, getFullYear, getHours, getMilliseconds, getMinutes, getMonth, getSeconds, getTime, getTimezoneOffset, getYear, setDate, setFullYear, setHours, setMilliseconds, setMinutes, setMonth, setSeconds, setTime, setYear, toString, valueOf, (most functions have UTC ones) var my_date:Date = new Date(2004,4,25); trace(my_date.getYear()); // output: 104 trace(my_date.getFullYear()); // output: 2004 my_date.setYear(99); trace(my_date.getYear()); // output: 99 trace(my_date.getFullYear()); // output: 1999 TextFormat this.createTextField("stats_txt", 5000, 10, 0, 530, 22); stats_txt.setNewTextFormat(my_fmt); TextField Properties _alpha, antiAliasType, autoSize, background, backgroundColor, border, borderColor, bottomScroll, condeseWhite, enbedFonts, filter, gridFitType, _height, _highquality, hscroll, html, htmlText, length, maxChars, maxhscroll, maxscroll, menu, mouseWheelEnabled, multiline, _name, _parent, password, _quality, restrict, _rotation, scroll, selectable, sharpness, _soundbuftime, styleSheet, tabEnabled, tabIndex, _target, text, textColor, textHeight, textWidth, thickness, type, _url, variable, _visible, _width, wordWrap, _x, _xmouse, _xscale, _y, _ymouse, _yscale Event onChanged, onKillFocus, onScroller, onSetFocus Methods addListener, getDepth, getFontList, getNewTextFormat, getTextFormat, removeLisener, removeTextField, replaceSel, replaceText, setNewTextFormat, setTextFormat Example my_txt.border = true; my_txt.type = "input"; my_txt.onChanged = function(textfield_txt:TextField) { trace(textfield_txt._name+" changed"); }; var txtListener:Object = new Object(); txtListener.onChanged = function(textfield_txt:TextField) { trace(textfield_txt._name+" changed and notified myListener"); }; my_txt.addListener(txtListener); Video XMLNode Properties _alpha, deblocking, _height, height, _name, _parent, _rotation, smoothing, _visible, _width, width, _x, _xmouse, _xscale, _y, _ymouse, _yscale Constructor XMLNode Methods attachVideo, clear Example var my_video:Video; var my_nc:NetConnection = new NetConnection(); my_nc.connect(null); var my_ns:NetStream = new NetStream(my_nc); my_video.attachVideo(my_ns); my_ns.play("video1.flv"); Sound Properties duration, id3, position Events onID3, onLoad, onSoundComplete Methods attachSound, getBytesLoaded, getBytesTotal, getPan, getTransform, getVolume, loadSound, setPan, setTransform, setVolume, start, stop Example var my_sound:Sound = new Sound(); my_sound.attachSound("logoff_id"); my_sound.onSoundComplete = function() { trace("mySoundID completed"); }; my_sound.start(); attributes, childNodes, firstChild, lastChild,localName, namespaceURI, nextSibling, nodeName, nodeType, nodeValue, parendNode, prefix, previousSibling Methods appendChild, cloneNode, getnamespaceForPrefix, getPrefixForNamespace, hasChildNodes, removeNode, toString MovieClip XML Properties _alpha, blendMode, cacheAsBitmap, _currentframe, _droptarget, enabled, filters, focusEnabled, _focusrect, _framesloaded, _height, _highquality, hitArea, _lockroot, menu, _name, opaqueBackground, _parent, _quality, _rotation, scale9Grid, scrollRect, _soundbuftime, tabChildren, tabEnabled, tabIndex, _target, _totalframes, trackAsMenu, transform, _url, useHandCursor, _visible, _width, _x, _xmouse, _xscale, _y, _ymouse, _yscale Constructor XML Methods Sound constructor Properties Events Example Properties contenttype, docTypeDecl, idMap, ignoreWhite, loaded, status, xmlDecl Events onData, onHTTPStatus, onLoad Methods addRequestHeader, createElement, createTextNode, getBytesLoaded, getBytesTotal, load, parseXML, send, sendAndLoad attachAudio, attachBitmap, attachMovie, beginBitmapFill, beginFill, beginGradientFill, clear, createEmptyMovieClip, createTextField, curveTo, duplicateMovieClip, endFill, getBounds, getBytesLoaded, getBytesTotal, getDepth, getInstanceAtDepth, getNextHightsDepth, getRect, getSWFVersion, getTextSnapshot, getURL, globalToLocal, gotoAndPlay, gotoAndStop, hitTest, lineGradientStyle, lineStyle, lineTo, loadMoive, loadVariables, localToGlobal, moveTo, nextFrame, play, prevFrame, removeMovieClip, setMask, setMask, startDrag, stop, stopDrag, swapDepths, unloadMovie Example var myXML:XML = new XML(); myXML.ignoreWhite = true; onData, onDragOut, onDragOver, onEnterFrame, onKeyDown, onKeyUp, onKillFocus, onLoad, onMouseDown, onMouseMove, onMouseUp, onPress, onRelease, onReleaseOutside, onRollOut, onRollOver, onSetFocus, onUnload XMLsocket this.createEmptyMovieClip("triangle", this.getNextHighestDepth()); triangle.beginFill(0x0000FF, 100); triangle.moveTo(10, 10); triangle.lineTo(10, 100); triangle.lineTo(100, 10); triangle.lineTo(10, 10); triangle.onRollOver = function() { this._alpha = 50; }; triangle.onRollOut = function() { this._alpha = 100; }; myXML.onLoad = function () { trace(this.childNodes); } myXML.load ("flute.xml"); Constructor XMLSocket Events onClose, onConnect, onData, onXML Methods close, connect, send Example var socket:XMLSocket = new XMLSocket() socket.onConnect = function (success:Boolean) { if (success) { trace ("Connection succeeded!") } else { trace ("Connection failed!") } } if (!socket.connect(null, 2000)) { trace ("Connection failed!") } Gimp Quick Reference Card v.1.0 File Management Ctr+N Ctr+O Ctr+S Ctr+W Create new image Open existing image Save current image Close current image Image Editing Ctr+Z Ctr+R Ctr+X Ctr+C Ctr+V Shift+Ctr+X Undo last change Redo last change Cut current image/selection Copy current image/selection Paste current image/selection Cut current image/selection into named buffer Shift+Ctr+C Copy current image/selection into named buffer Shift+Ctr+V Paste current image/selection from named buffer Ctr+K Clear image/selection with current background color Ctr+, (comma) Fill current image/selection with current background color Ctr+. (dot) Fill current image/selection with current foreground color Image Selection Ctr+I Ctr+A Shift+Ctr+A Shift+Ctr+L Shift+Ctr+F Shift+Ctr+H Invert current selection Select all image Remove all selections Create floating selection Feather selection Sharpen selection Image Viewing = (equal) - (minus) 1 Shift+Ctr+I Shift+Ctr+N Ctr+T Shift+Ctr+R Shift+Ctr+S Shift+Ctr+T Ctr+E Zoom in image Zoom out Image Zoom 1:1 scale Open info window Open zoom navigation window Toggle selection on/off Toggle rullers on/off Toggle status bar on/off Toggles Shrink wrap window to image size Image Manipulation Alt+R Alt+G Alt+I Shift+Ctr+O Ctr+D Switch image to RGB mode Switch image to grayscale mode Switch image to indexed (GIF) mode Offset image Duplicate image Layers Manipulation Ctr+H Ctr+M Anchor layer Merge visible layers Tools D X O T Default colors Swap colors Color picker Text tool Rectangular Selection Tools Shift+Left Mouse Button Square selection Ctr+Left Mouse Button Rectangle selection with begining in the middle of the rectangle Shift+Ctr+Left Mouse Button Square selection with begining in the middle of the square Ellipse Selection Tools Shift+Left Mouse Button Circle selection Ctr+Left Mouse Button Elipse selection with begining in the middle of the ellipse Shift+Ctr+Left Mouse Button Circle selection with begining in the middle of the circle Zoom In/Out Tool Ctr+Left Mouse Button Flip Tool Ctr+Left Mouse Button Selection R E F Z B I Select Rectangle tool Select Ellipse tool Select Freehand tool Select Magic Wand (Fuzzy) tool Select Bezier tool Select Intelligent Scissors tool Transform M Select Move tool Shift+M Select Magnify tool Shift+C Select Crop & Resize tool Shift+T Select Transform tool Shift+F Select Flip tool Painting Shift+B Bucket Fill tool L Blending tool Shift+P Pencil tool P Paintbrush tool Shift+E Eraser tool A Airbrush tool C Clone tool V Convolve tool I Ink tool Shift+D Dodge/Burn tool Shift+S Smudge tool Bucket Tool Ctr+Left Mouse Button Toggle flip horizontaly/vertically Erase Tool Ctr+Left Mouse Button Shift+Left Mouse Button Cloning Tool Ctr+Left Mouse Button Left Mouse Button Convolve Tool Ctr+Left Mouse Button Dodge/Burn Tool Ctr+Left Mouse Button Keyboard keys pressed before Mouse button with Rectangular, Ellipse, Freehand and Magic Wand Shift+Left Mouse Button Selection tools Ctr+Left Mouse Button Subtract selection Smudge Tool Shift+Left Mouse Button Add selection Shift+Left Mouse Button Shift+Ctr+Left Mouse Button Intersect selection Measurement Tool Keyboard keys pressed after Mouse key Horizontal distance Duble click add guide Dialogs Ctr+L Shift+Ctr+B Shift+Ctr+P Ctr+G Ctr+P Open Layers, Channels & Path Dialog Open Brushes Dialog Open Patterns Dialog Open Gradients Dialog Open Pallette Dialog Help F1 Shift+F1 Help Context help Add a key as a shortcut to the menu item Open menu, place cursor over item, press desired shortcut key Useful Links Toggle fill foreground/backgroun d colors Pencil, Brush, Airbrush Tool Ctr+Left Mouse Button Pick colors from the image Shift+Left Mouse Button Draw a line Shift+Left Mouse Button Tools + Mouse Manipulation Toggle zoom in/out Ctr+Left Mouse Button Ctr+Left Mouse Button http://www.gimp.org/ Main gimp web site http://manual.gimp.org/ Gimp manual http://gimp-savvy.com/BOOK/ Grokking the Gimp book http://registry.gimp.org/ Gimp plugin registry Anti erase image Erase a line Sets the source point in the image Sets the destination point, hold to draw with clone Toggle blur/sharpen image Blur/Sharpen in line Toggle dodge/burn image Dodge/Burn in line Smudge in line Copyright © Ilia Tyker 2002 ityker@hotmail.com Designed for Gimp version 1.2.2 Permission is granted under General Public License (GPL) to distribute and make a copies of this card provided the copyright notice and this permission notice preserverd on all copies fournova GIT CHEAT SHEET presented by Tower - the best Git client for Mac and Windows CREATE Clone an existing repository $ git clone ssh://user@domain.com/repo.git Create a new local repository $ git init LOCAL CHANGES Changed files in your working directory $ git status Changes to tracked files $ git diff Add all current changes to the next commit $ git add . Add some changes in <file> to the next commit BRANCHES & TAGS List all existing branches $ git branch -av Switch HEAD branch $ git checkout <branch> Create a new branch based on your current HEAD $ git branch <new-branch> Create a new tracking branch based on a remote branch $ git checkout --track <remote/branch> Delete a local branch $ git branch -d <branch> Mark the current commit with a tag $ git tag <tag-name> $ git add -p <file> Commit all local changes in tracked files $ git commit -a Commit previously staged changes $ git commit Change the last commit Don‘t amend published commits! $ git commit --amend COMMIT HISTORY Show all commits, starting with newest $ git log Show changes over time for a specific file $ git log -p <file> Who changed what and when in <file> $ git blame <file> UPDATE & PUBLISH List all currently configured remotes $ git remote -v Show information about a remote $ git remote show <remote> Add new remote repository, named <remote> $ git remote add <shortname> <url> Download all changes from <remote>, but don‘t integrate into HEAD $ git fetch <remote> Download changes and directly merge/integrate into HEAD $ git pull <remote> <branch> Publish local changes on a remote $ git push <remote> <branch> Delete a branch on the remote $ git branch -dr <remote/branch> Publish your tags MERGE & REBASE Merge <branch> into your current HEAD $ git merge <branch> Rebase your current HEAD onto <branch> Don‘t rebase published commits! $ git rebase <branch> Abort a rebase $ git rebase --abort Continue a rebase after resolving conflicts $ git rebase --continue Use your configured merge tool to solve conflicts $ git mergetool Use your editor to manually solve conflicts and (after resolving) mark file as resolved $ git add <resolved-file> $ git rm <resolved-file> UNDO Discard all local changes in your working directory $ git reset --hard HEAD Discard local changes in a specific file $ git checkout HEAD <file> Revert a commit (by producing a new commit with contrary changes) $ git revert <commit> Reset your HEAD pointer to a previous commit …and discard all changes since then $ git reset --hard <commit> …and preserve all changes as unstaged changes $ git reset <commit> …and preserve uncommitted local changes $ git reset --keep <commit> $ git push --tags 30-day free trial available at www.git-tower.com The best Git Client for Mac & Windows fournova VERSION CONTROL BEST PRACTICES COMMIT RELATED CHANGES A commit should be a wrapper for related changes. For example, fixing two different bugs should produce two separate commits. Small commits make it easier for other developers to understand the changes and roll them back if something went wrong. With tools like the staging area and the ability to stage only parts of a file, Git makes it easy to create very granular commits. COMMIT OFTEN Committing often keeps your commits small and, again, helps you commit only related changes. Moreover, it allows you to share your code more frequently with others. That way it‘s easier for everyone to integrate changes regularly and avoid having merge conflicts. Having few large commits and sharing them rarely, in contrast, makes it hard to solve conflicts. DON‘T COMMIT HALF-DONE WORK You should only commit code when it‘s completed. This doesn‘t mean you have to complete a whole, large feature before committing. Quite the contrary: split the feature‘s implementation into logical chunks and remember to commit early and often. But don‘t commit just to have something in the repository before leaving the office at the end of the day. If you‘re tempted to commit just because you need a clean working copy (to check out a branch, pull in changes, etc.) consider using Git‘s «Stash» feature instead. 30-day free trial available at www.git-tower.com TEST CODE BEFORE YOU COMMIT Resist the temptation to commit something that you «think» is completed. Test it thoroughly to make sure it really is completed and has no side effects (as far as one can tell). While committing half-baked things in your local repository only requires you to forgive yourself, having your code tested is even more important when it comes to pushing/sharing your code with others. WRITE GOOD COMMIT MESSAGES Begin your message with a short summary of your changes (up to 50 characters as a guideline). Separate it from the following body by including a blank line. The body of your message should provide detailed answers to the following questions: › What was the motivation for the change? › How does it differ from the previous implementation? Use the imperative, present tense («change», not «changed» or «changes») to be consistent with generated messages from commands like git merge. VERSION CONTROL IS NOT A BACKUP SYSTEM Having your files backed up on a remote server is a nice side effect of having a version control system. But you should not use your VCS like it was a backup system. When doing version control, you should pay attention to committing semantically (see «related changes») - you shouldn‘t just cram in files. USE BRANCHES Branching is one of Git‘s most powerful features - and this is not by accident: quick and easy branching was a central requirement from day one. Branches are the perfect tool to help you avoid mixing up different lines of development. You should use branches extensively in your development workflows: for new features, bug fixes, ideas… AGREE ON A WORKFLOW Git lets you pick from a lot of different workflows: long-running branches, topic branches, merge or rebase, git-flow… Which one you choose depends on a couple of factors: your project, your overall development and deployment workflows and (maybe most importantly) on your and your teammates‘ personal preferences. However you choose to work, just make sure to agree on a common workflow that everyone follows. HELP & DOCUMENTATION Get help on the command line $ git help <command> FREE ONLINE RESOURCES http://www.git-tower.com/learn http://rogerdudler.github.io/git-guide/ http://www.git-scm.org/ The best Git Client for Mac & Windows GIT FOR SUBVERSION USERS presented by TOWER — the best Git client for Mac and Windows Creating a New Repository Committing Local Changes With gitinit, an empty repository is created in the current folder of your local hard drive. The gitadd command then marks the current contents of your project directory for the next (and in this case: first) commit. Inspecting your current local changes is very similar in both systems. $ svnadmin create /path/to/repo $ svn import /path/to/local/project http:// example.com/svn/ trunk -m "Initial import" SUBVERSION GIT $ git init $ git add . $ git commit -m "Initial commit" Cloning a Remote Repository Getting a copy of the project from a remote server seems almost identical. However, after performing gitclone, you have a fullblown local repository on your machine, not just a working copy. $ svn checkout svn+ssh://svn@example.com/svn/trunk $ git clone ssh://git@example.com/path/to/git-repo.git SUBVERSION GIT SUBVERSION $ svn status $ svn diff | less GIT $ git status $ git diff In case you’ve created new files or deleted old ones, you should tell Git with the gitadd and gitrm commands. You’ll be pleased to hear that it’s safe to inform Git after deleting or moving a file or even a folder. This means you should feel free to delete or move even complete directory structures in your favorite editor, IDE, or file browser and later confirm the action with the add and rm| commands. SUBVERSION $ svn add <file> $ svn rm <file> GIT $ git add <file> $ git rm <file> In its simplest form, committing can feel just like in Subversion. With the -a option, you tell Git to simply add all current local changes to the commit. $ svn commit -m "message" Inspecting History $ git commit -a -m "message" To inspect historic commits, both systems use the log command. Keep in mind, however, that gitlog doesn’t need to ask the remote server for data: your project’s history is already at hand, saved in your local repository. $ svn log | less $ git log SUBVERSION GIT GIT Although short-circuiting Git’s staging area like this can make sense, you’ll quickly begin to love it once you understand how valuable it is: You can add selected files to the staging area and even limit this to certain parts (or even lines) of a file by specifying the -p option. This allows you to craft your commits in a very granular way and only add changes that belong to the same topic in a single commit. $ git add <file1> <file2> $ git add -p <file3> 30-day free trial available at www.git-tower.com SUBVERSION GIT The best Git Client for Mac & Windows GIT FOR SUBVERSION USERS Branching & Tagging In contrast to Subversion, Git doesn’t use directories to manage branches. Instead, it uses a more powerful and lightweight approach. As you might have already noticed, the gitstatus command also informs you about which branch you are currently working on. And in Git, you are always working on a branch! $ svn copy http://example.com/svn/trunk/ http://example.com/svn/branches/<new-branch> SVN GIT $ git branch <new-branch> To switch to a different branch and make it active (then also referred to as the HEAD branch), the gitcheckout command is used. Because switching can take some time in Subversion, it’s not unusual to instead have multiple working copies on your disk. In Git, this would be extremely uncommon: since operations are very fast, you only keep a single local repository on your disk. Everything else is taken care of for you: you can merge two branches as often as you like, don’t have to specify any revisions and can expect the operation to be blazingly fast if you’re merging two local branches. If a merge conflict should occur, Git will already update the rest of the working copy to the new state. After resolving a conflicted file, you can mark it using the gitadd command. SUBVERSION $ svn resolved <file> GIT $ git add <file> Sharing & Collaborating To download & integrate new changes from a remote server, you use the gitpull command. SUBVERSION $ svn update SUBVERSION $ svn switch http://example.com/svn/branches/<branch> GIT $ git checkout <branch> Listing all available local branches just requires the gitbranch| command without further arguments. GIT $ git branch Creating tags is just as quick & cheap as creating branches. SVN $ svn copy http://example.com/svn/trunk/ http://example.com/svn/tags/<tag-name> GIT $ git fetch In Subversion, data is automatically uploaded to the central server when committing it. In Git, however, this is a separate step. This means you can decide for yourself if and when you want to share your work. Once you’re ready, the gitpush command will upload the changes from your currently active branch to the remote branch you specify. GIT $ git push <remote> <branch> GIT $ git tag -a <tag-name> Merging Changes Like in newer versions of SVN, you only need to provide the branch you want to integrate to the gitmerge command. SUBVERSION $ svn merge -r REV1:REV2 http://example.com/svn/branches/<other-branch> $ svn merge (or in newer SVN versions) http://example.com/svn/branches/<other-branch> 30-day free trial available at www.git-tower.com If you only want to download & inspect remote changes (before integrating them), you can use gitfetch. Later, you can integrate the downloaded changes via gitmerge. SVN $ svn list http://example.com/svn/branches/ $ git merge <other-branch> GIT $ git pull Your teammates, too, will publish their work like this on a remote (with the gitpush command). If you want to start working on such a branch, you need to create your own local copy of it. You can use the gitcheckout command with the --track option to do just that: create a local version of the specified remote branch. You can later share the additional commits you’ve made at any time with the gitpush command, again. SUBVERSION $ svn switch http://example.com/svn/branches/<branch> $ git checkout --track <remote>/<branch> GIT GIT The best Git Client for Mac & Windows Python3 Cheat Sheet by ordowe (hahahaha) via cheatography.com/80914/cs/19454/ Lists Logic and Math Operators (cont) Create an empty list newlist=[] Bitwise Exclusive Or Assign value at index alist[index]= value Access value at index alist[index] Add item to list alist.append(new item) Insert into list alist.insert(at position, new item) Count # of an item in list alist.count( item ) Delete 1 matching item alist.remove(del item) Remove item at index del alist[index] a^b xor(a, b) Converting Data Types Covert Syntax Example Result Num -> string str(number) str(100) '100' int, float or long str(3.14) '3.14' str(txt,encoding) str(data,"utf8") string Encoded bytes -> string with data Looping int("string",base) int("42") 42 For loop 0 thru 9 for x in range(10): Num String -> int default base is int("101",2) 5 For loop 5 thru 10 for x in range(5,11): 10 int("ff", 16) 255 For each char in a string for char in astring: hex(integer) hex(255) '0xff' hex(10) '0xa' bin(5) bin(3) '0b101' For items in list for x in alist: For indexes/values in a list for index,value in int -> hex string integer -> binary string bin(integer) '0b11' enumerate(alist): For each key in a dict for x in adict.keys(): For all items in dict for key,value in adict.items(): while <logic test> do: Exit loop immediately break Skip rest of loop and do loop continue float -> integer int or str -> float String -> ASCII int(float) int(3.14159) 3 drops decimal int(3.9) 3 float(int or str) float("3.4") 3.4 float(3) 3.0 ord("A") ord("1") 65 ord(str) 49 again int -> ASCII Logic and Math Operators chr(integer) chr(65) 'A' chr(49) '1' bytes -> string <bytes>.decode() b'ABC'.decode() 'ABC' string -> bytes <str>.encode() 'abc'.encode() b'abc' Math Operator Example X=7, Y=5 Addition X+Y 12 Subtraction X-Y 2 Useful OS functions Multiplication X*Y 35 import os Division X/Y 1.4 Executing a shell command os.system() Floor X // Y 1 Rename the file or directory src to dst os.rename(src, dst) Exponent X ** Y 16807 Change working directory os.chdir(path) Modulo X%Y 2 Get the users environment os.environ() Returns the current working directory os.getcwd() Equality X == Y False Greater Than X>Y False Less Than X<Y True Less or Equal X <= Y True Not Equal X !=Y or X<>Y True Logic Operator By ordowe (hahahaha) Published 23rd April, 2019. Sponsored by CrosswordCheats.com cheatography.com/hahahaha/ Last updated 24th April, 2019. Learn to solve cryptic crosswords! Page 1 of 2. http://crosswordcheats.com Python3 Cheat Sheet by ordowe (hahahaha) via cheatography.com/80914/cs/19454/ Dictionaries Misc (cont) Create an empty dict dict={} Initialize a non-empty dictionary dict= { #code block here will execute #when logic test 1 is True “key”:”value”,”key2”:”value2”} elif <logic test 2>: #code block executes if logic test 1 is Assign a value dict[“key”]=”value” Determine if key exists "key" in dict Access value at key dict[“key”], dict.get(“key”) Iterable View of all keys dict.keys() Iterable View of all values dict.values() python3 shebang Iterable View of (key,value) dict.items() #!/usr/bin/env python3 #False and logic test 2 is True else: #else has no test and executes when if #and all elif are False tuples Printing Slicing and Indexing Standard print print('{}'.format(STRING)) x[start:stop:step] x=[4,8,9,3,0] x=”48930” Print string variable print ("I am %s" % name) x[0] 4 ‘4’ Print int variable print ("I am %d" % number) x[2] 9 '9' Print with + print ("I am " + name) x[:3] [4,8,9] '489' x[3:] [3,0] '30' String Operations x[:-2] [4,8,9] '489' Make lowercase "Ab".lower()="ab" x[::2] [4,9,0] ‘490’ Make UPPERCASE "Ab".upper()="AB" x[::-1] [0,3,9,8,4] ‘03984’ Make Title Format "hi world".title()="Hi World" len(x) 5 5 Replace a substring "123".replace('2','z')= "1z3" sorted(x) [0,3,4,8,9] ['0','3','4','8','9'] Count occurrences of substring "1123".count("1")=2 Get offset of substring in string "123".index("2")=1 Detect substring in string “is” in “fish” == True Misc Adding Comments to code: #Comments begin the line with a pound sign Adding Multi-line Comment to code """ Multi-Line Comment """ Get user input from keyboard name = input("What is your name? ") Functions def add(num1, num2): #code blocks must be indented #each space has meaning in python myresult = num1 + num2 return myresult if then else statements if <logic test 1>: By ordowe (hahahaha) Published 23rd April, 2019. Sponsored by CrosswordCheats.com cheatography.com/hahahaha/ Last updated 24th April, 2019. Learn to solve cryptic crosswords! Page 2 of 2. http://crosswordcheats.com HTML 5 Browser Support Desktop 11.0 38.0 43.0 8.0 15.0 Mobile 2.3 8.0 29.0 7.0 35.0 43.0 43.0 Below is a table showing the individual browser support specifications for each of the major web browsers in both desktop and mobile. We have given an over all percentage score on each browser, based on scores gathered by html5test.com Fully Supported Partially Supported Not Supported HTML Cheatsheet Basic Tags <html> </html> Creates an HTML document <head> </head> Sets off the title & other info that isn't displayed <body> </body> Sets off the visible portion of the document <title> </title> Puts name of the document in the title bar; when bookmarking pages, this is what is bookmarked Body attributes (only used in email newsletters) <body bgcolor=?> Sets background color, using name or hex value <body text=?> Sets text color, using name or hex value <body link=?> Sets color of links, using name or hex value <body vlink=?> Sets color of visited links, using name or hex value <body alink=?> Sets color of active links (while mouse-clicking) Text Tags <pre> </pre> Creates preformatted text <h1> </h1> --> <h6> </h6> Creates headlines -- H1=largest, H6=smallest <b> </b> Creates bold text (should use <strong> instead) <i> </i> Creates italicized text (should use <em> instead) <tt> </tt> Creates typewriter-style text <code> </code> Used to define source code, usually monospace <cite> </cite> Creates a citation, usually processed in italics <address> </address> Creates address section, usually processed in italics <em> </em> Emphasizes a word (usually processed in italics) <strong> </strong> Emphasizes a word (usually processed in bold) <font size=?> </font> Sets size of font - 1 to 7 (should use CSS instead) <font color=?> </font> Sets font color (should use CSS instead) <font face=?> </font> Defines the font used (should use CSS instead) Links <a href="URL">clickable text</a> Creates a hyperlink to a Uniform Resource Locator <a href="mailto:EMAIL_ADDRESS">clickable text</a> Creates a hyperlink to an email address <a name="NAME"> Creates a target location within a document <a href="#NAME">clickable text</a> Creates a link to that target location page 1 of 2 Formatting <p> </p> Creates a new paragraph <br> AInserts a line break (carriage return) <blockquote> </blockquote> Puts content in a quote - indents text from both sides <div> </div> Used to format block content with CSS <span> </span> Used to format inline content with CSS Lists <ul> </ul> Creates an unordered list <ol start=?> </ol> Creates an ordered list (start=xx, where xx is a counting number) <li> </li> Encompasses each list item <dl> </dl> Creates a definition list <dt> Precedes each defintion term <dd> Precedes each defintion Graphical elements <hr> Inserts a horizontal rule <hr size=?> Sets size (height) of horizontal rule <hr width=?> Sets width of rule (as a % or absolute pixel length) <hr noshade> Creates a horizontal rule without a shadow <img src="URL" /> Adds image; it is a separate file located at the URL <img src="URL" align=?> Aligns image left/right/center/bottom/top/middle (use CSS) <img src="URL" border=?> Sets size of border surrounding image (use CSS) <img src="URL" height=?> Sets height of image, in pixels <img src="URL" width=?> Sets width of image, in pixels <img src="URL" alt=?> Sets the alternate text for browsers that can't process images (required by the ADA) HTML Cheatsheet page 2 of 2 Forms <form> </form> Defines a form <select multiple name=? size=?> </select> Creates a scrolling menu. Size sets the number of menu items visible before user needs to scroll. <select name=?> </select> Creates a pulldown menu <option> Sets off each menu item <textarea name=? cols="x" rows="y"></textarea> Creates a text box area. Columns set the width; rows set the height. <input type="checkbox" name=? value=?> Creates a checkbox. <input type="checkbox" name=? value=? checked> Creates a checkbox which is pre-checked. <input type="radio" name=? value=?> Creates a radio button. <input type="radio" name=? value=? checked> Creates a radio button which is pre-checked. <input type="text" name=? size=?> Creates a one-line text area. Size sets length, in characters. <input type="submit" value=?> Creates a submit button. Value sets the text in the submit button. <input type="image" name=? src=? border=? alt=?> Creates a submit button using an image. <input type="reset"> Creates a reset button HTML5 input tag attributes (not all browsers support; visit http://caniuse.com for details) Tables (use only for data layout - use CSS for page layout) <table> </table> Creates a table <tr> </tr> Sets off each row in a table <td> </td> Sets off each cell in a row <th> </th> Sets off the table header (a normal cell with bold, centered text) Table attributes (only use for email newsletters) <table border=?> Sets the width of the border around table cells <table cellspacing=?> Sets amount of space between table cells <table cellpadding=?> Sets amount of space between a cell's border and its contents <table width=?> Sets width of the table in pixels or as a percentage <tr align=?> Sets alignment for cells within the row (left/center/right) <td align=?> Sets alignment for cells (left/center/right) <tr valign=?> Sets vertical alignment for cells within the row (top/middle/bottom) <td valign=?> Sets vertical alignment for cell (top/middle/bottom) <td rowspan=?> Sets number of rows a cell should span (default=1) <td colspan=?> Sets number of columns a cell should span <td nowrap> Prevents lines within a cell from being broken to fit <input type="email" name=?> Sets a single-line textbox for email addresses <input type="url" name=?> Sets a single-line textbox for URLs <input type="number" name=?> Sets a single-line textbox for a number <input type="range" name=?> Sets a single-line text box for a range of numbers <input type="date/month/week/time" name=?> Sets a single-line text box with a calendar showing the date/month/week/time <input type="search" name=?> Sets a single-line text box for searching <input type="color" name=?> Sets a single-line text box for picking a color Objects Lists Document Outline <!DOCTYPE> Version of (X)HTML <ol> Ordered list <object> Object <html> HTML document <ul> Unordered list <param /> Parameter <head> Page information <li> List item <body> Page contents <dl> Definition list <dt> Definition term <dd> Term description Comments <!-- Comment Text --> Page Information Forms <form> Form <fieldset> Collection of fields Empty Elements <area /> <img /> <base /> <input /> <br /> <link /> <col /> <meta /> <hr /> <param /> <base /> Base URL <legend> Form legend <meta /> Meta data <label> Input label <title> Title <input /> Form input class style <link /> Relevant resource <select> Drop-down box id title <style> Style resource <optgroup> Group of options Script resource <option> Drop-down options Note: Core Attributes may not be used <script> <textarea> Large text input <button> Button Document Structure <h[1-6]> Heading <div> Page section <span> Inline section <p> Paragraph <br /> Line break <hr /> Horizontal rule Links <a href=""> Page link <a href="mailto:"> Email link <a name="name"> Anchor <a href="#name"> Link to anchor <strong> Strong emphasis <em> Emphasis <blockquote> Long quotation <q> Short quotation <abbr> Abbreviation <acronym> Acronym <address> Address <pre> Pre-formatted text <dfn> Definition <code> Code <cite> Citation <del> Deleted text <ins> Inserted text <sub> Subscript <sup> Superscript <bdo> Text direction in base, head, html, meta, param, script, style or title elements. Language Attributes Tables dir <table> Table <caption> Caption <thead> Table header <tbody> Table body <tfoot> Table footer <colgroup> Column group <col /> Column <tr> Table row <th> Header cell <td> Table cell Images and Image Maps Text Markup Core Attributes <img /> Image <map> Image Map <area /> Area of Image Map Common Character Entities lang Note: Language Attributes may not be used in base, br, frame, frameset, hr, iframe, param or script elements. Keyboard Attributes accesskey tabindex Window Events onLoad onUnload Form Events onBlur onReset onChange onSelect onFocus onSubmit &#34; " Quotation mark &#38; & Ampersand &#60; < Less than onKeydown &#62; > Greater than onKeypress &#64; @ "At" symbol &#128; € Euro &#149; • Small bullet &#153; ™ Trademark onClick onMouseout &#163; £ Pound onDblclick onMouseover Non-breaking space onMousedown onMouseup Copyright symbol onMousemove &#160; &#169; © Available free from www.ILoveJackDaniels.com Keyboard Events onKeyup Mouse Events Understanding the Workflow of Version Control presented by Tower - the best Git client for Mac and Windows The Basics 1 Work on an Existing Project Start a New Project $ git clone <remote-url> $ git init The “git clone” command is used to download a copy of an existing repository from a remote server. When this is done, you have a full-featured version of the project on your local computer – including its complete history of changes. Executing the “git init” command in the root folder of your new project creates a new and empty Git repository. You’re ready to start getting your files under version control! 2 File Status Work on Your Files Files that aren’t yet under version control are called “untracked”… ? Modify, rename and delete files or add new ones. Do all of this in your favorite editor / IDE / file browser – there‘s nothing to watch out for in this step! …while files that your version control system already knows about are “tracked” files. A tracked file can either be “unmodified” (meaning it wasn’t changed since the last commit)... m ...or “modified” (meaning it has local changes since it was last committed). 3 $ git status # # Changes not staged for commit: # modified: about.html # deleted: robots.txt # # Untracked files: # login.html # no changes added to commit Keep the Overview $ git status The “git status” command tells you what happened since the last commit: which files did you change? Did you create any new ones or delete old ones? 4 $ git add about.html # # Changes to be committed: # modified: about.html # # Changes not staged for commit: # deleted: robots.txt # # Untracked files: # login.html Add Files to the “Staging Area” $ git add <filename> Only because a file was changed doesn’t mean it will be part of the next commit! Instead, you have to explicitly decide which changes you want to include. To do this, you add them to the so-called “Staging Area” with the “git add” command. 5 Commit all Staged Changes $ git commit -m "message" $ git commit -m "Updated about page" A commit wraps up all the changes you previously staged with the “git add” command. To record this set of changes in Git’s database, you execute the “git commit” command with a short and informative message. [master 9d3f32b] Updated about page 1 file changed, 29 insertions(+) 6 Keep the Overview $ git status # # Changes not staged for commit: # deleted: robots.txt # # Untracked files: # login.html # no changes added to commit $ git status Running the “git status” command right after a commit proves to you: only the changes that you added to the Staging Area were committed. All other changes have been left as local changes: you can continue to work with them and commit or discard them later. 7 Inspect the Commit History $ git log $ git log commit 9d3f32ba002110ee0022fe6d2c5308 Author: Tobias Günther <tg@fournova.c Date: Mon Jul 8 09:56:33 2013 +0200 The “git log” command lists all the commits that were saved in chronological order. This allows you to see which changes were made in detail and helps you comprehend how the project evolved. Updated about page Branching & Merging 1 Understanding Branches BUGFIX #32 C4 C1 C3 C5 C7 FEATURE B C2 C6 We often have to work on multiple things in parallel: feature X, bugfix #32, feature Y… This makes it all too easy to lose track of where each change belongs. Therefore, it’s essential to keep these contexts separate from each other. Start a New Feature $ git branch <new-branch-name> Whenever you start a new feature, a new experiment or a new bugfix, you should create a new branch. In Git, this is extremely fast and easy: just call “git branch <new-branch-name>” and you have a new, separate context. Grouping related changes in their own context has multiple benefits: your coworkers can better understand what happened because they only have to look at code that really concerns them. And you can stay relaxed, because when you mess up, you mess up only this context. Don’t be shy about creating new branches: it costs you nothing. Branches do just this: they provide a context that keeps your work and your changes separate from any other context. 2 HEAD Branch C6 Switch Contexts C1 $ git checkout <new-branch-name> C4 C2 To start working on a different context, you need to tell Git that you want to switch to it. You do this by “checking out” the branch with the “git checkout” command. C3 feature-b master C5 feature-a C7 HEAD At each point in time, you can only work in one context – the context of the currently checked out branch (which is also called the “HEAD” branch in Git). Every commit you make – until you switch branches again – will be recorded in this branch and kept separate from your other contexts. Your project’s working directory contains the files that correspond to this branch. When you check out a different branch (make it “HEAD”), Git replaces the files in your working directory with the ones that match this branch. 3 Integrate Changes $ git merge <branch-to-integrate> When your new feature is ready, you might want to integrate it into another branch (e.g. your production or testing branch). First, switch to the branch that is supposed to receive these changes. Then, call the “git merge” command with the name of the branch you want to integrate. Sharing Work via Remote Repositories 1 Track a Remote Branch $ git checkout --track <remote/branch> If there’s an interesting remote branch that you want to work on, you can easily get your own local copy. Use the “git checkout” command and tell it which remote branch you want your new local branch to base off. 2 Publish a Local Branch $ git push -u <remote> <local-branch> To share one of your local branches with your teammates, you need to publish it on a remote server with the “git push” command. Local & Remote Repositories MODIFY, ADD & DELETE FILES Stay Up-To-Date About Remote Changes $ git fetch <remote> When collaborating with others on a project, you’ll want to stay informed about their changes. The “git fetch” command downloads new changes from a remote repository – but doesn’t integrate them into your local working copy. It only informs you about what happened on the remote, leaving the decision on what to integrate to you. 3 LOCAL COMPUTER LOCAL REPOSITORY REMOTE SERVER SHARE WORK COLLABORATE REMOTE REPOSITORY VIEW HISTORY ADD & DELETE BRANCHES As Git is a so-called “decentralized” version control system, a remote repository is optional. In fact, everything we did until now happened on your local machine, in your local repository – no internet/network connection was necessary. However, if you want to collaborate with others, you need a remote repository on a server. You don’t have to share all of your work though: you can decide for each of your local branches if you want to share it or not. Integrate Remote Changes $ git pull To integrate new changes from the remote repository, you simply call “git pull”. This will update your current HEAD branch with new data from its counterpart branch on the remote. The changes will be directly merged into your local working copy. 4 Upload Local Changes to the Remote Server $ git push To upload the local changes you made in your current HEAD branch, all you have to do is call “git push”. The best Git Client for Mac & Windows 30-day free trial available at www.git-tower.com Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference Java Comments: Syntax for a standalone application in Java: class <classname> { public static void main(String args[]) { statements; ————————; ————————; } } Delimiters // Use Used for commenting a single line /* ————— */ Used for commenting a block of code /** —————*/ Used for commenting a block of code. Used by the Javadoc tool for generating Java documentation. Primitive datatypes in Java: Steps to run the above application: 1. Type the program in the DOS editor or notepad. Save the file with a .java extension. 2. The file name should be the same as the class, which has the main method. 3. To compile the program, using javac compiler, type the following on the command line: Syntax: javac <filename.java> Example: javac abc.java 4. After compilation, run the program using the Java interpreter. Syntax: java <filaname> (without the .java extension) Example: java abc 5. The program output will be displayed on the command line. DataType Size byte (Signed integer) 8 bits 0 -128 +127 short (Signed integer) 16 bits 0 -32,768 +32,767 int (Signed integer) 32 bits 0 -2,147,483,648 +2,147,483,647 0 -9, 223, 372,036,854, 775,808, +9,223,372,036, 854, 775, 807 long (Signed Integer) 64 bits 1 © 1999, Pinnacle Software Solutions Inc. Default Java Programming Guide - Quick Reference Min Value Max Value © 1999, Pinnacle Software Solutions Inc. 3 Java Programming Guide - Quick Reference Java reserved words: abstract boolean Break Byte case try continue Catch char class default do double else extends Const while final finally float if implements import instanceof int for goto interface long native package private protected public return new synchronized short static this throw throws transient null switch super void volatile float (IEEE 754 floating-point) 32 bits 0.0 1.4E-45 3.4028235E38 double (IEEE 754 floating-point) 64 bits 0.0 4.9E-324 1.7976931348623157E308 char (Unicode character) boolean Java naming conventions: 16 bits \u0000 \u0000 \uFFFF 1 bit false Variable Names: Can start with a letter, ‘$’ (dollar symbol), or ‘_’ (underscore); cannot start with a number; cannot be a reserved word. Variable Declaration: <datatype> <variable name> Example: int num1; Method Names: Verbs or verb phrases with first letter in lowercase, and the first letter of subsequent words capitalized; cannot be reserved words. Example: setColor() Variable Initialization: <datatype> <variable name> = value Example: double num2 = 3.1419; Class And Interface Names: Descriptive names that begin with a capital letter, by convention; cannot be a reserved word. Escape sequences: Literal \n \t \b \r Constant Names: They are in capitals. Example: Font.BOLD, Font.ITALIC © 1999, Pinnacle Software Solutions Inc. 2 Represents New line Horizontal tab Backspace Carriage return © 1999, Pinnacle Software Solutions Inc. 4 Java Programming Guide - Quick Reference \f \\ \” \ddd \xdd \udddd Java Programming Guide - Quick Reference 5. Switch statement Syntax: switch(variable) { case(value1): statements; break; case(value2): statements; break; default: statements; break; } Form feed Backslash Double quote Octal character Hexadecimal character Unicode character Arrays: An array which can be of any datatype, is created in two steps – array declaration and memory allocation. Array declaration <datatype> [] <arr ```````````ayname>; Examples int[] myarray1; double[] myarray2; Memory Allocation The new keyword allocates memory for an array. Syntax <arrayname> = new <array type> [<number of elements>]; Examples myarray1 = new int[10]; Myarray2 = new double[15]; Class Declaration: A class must be declared using the keyword class followed by the class name. Syntax class <classname> { ———— Body of the class A typical class declaration is as follows: <modifier> class <classname> extends <superclass name> implements <interface name> { —————Member variable declarations; —————Method declarations and definitions } Multi-dimensional arrays: Syntax: <datatype> <arrayname> [] [] = new <datatype> [number of rows][number of columns]; Example: int mdarray[][] = new int[4][5]; © 1999, Pinnacle Software Solutions Inc. 5 Java Programming Guide - Quick Reference 7 Java Programming Guide - Quick Reference Flow Control: Member variable declarations: 1. If……..else statements Syntax: if(condition) { statements; } else { statements; } <access specifier> <static/final/transient/ volatile> <datatype> <variable name> Example public final int num1; Method declarations: <access specifier> <static/final> <return type> <method name> <arguments list> { Method body; } Example public static void main(String args[]) { } 2. For loop Syntax: for(initialization; condition; increment) { statements; } Interface declaration: Create an interface. Save the file with a.java extension, and with the same name as the interface. Interface methods do not have any implementation and are abstract by default. 3. While loop Syntax: while(condition) { statements; } Syntax interface <interface name> { void abc(); void xyz(); } 4. Do….While loop Syntax: do { statements; } while(condition); © 1999, Pinnacle Software Solutions Inc. © 1999, Pinnacle Software Solutions Inc. Using an interface: A class implements an interface with the implements keyword. 6 © 1999, Pinnacle Software Solutions Inc. 8 Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference Syntax class <classname> extends <superclass name> implements <interface name> { class body; —————————; } final Class Cannot be subclassed. Method Cannot be overridden. Variable Value cannot be changed (Constant) native Method Implemented in a language other than Java like C,C++, assembly etc. Methods do not have bodies. static Method Class method. It cannot refer to nonstatic variables and methods of the class. Static methods are implicitly final and invoked through the class name. Variable Class variable. It has only one copy regardless of how many instances are created. Accessed only through the class name. Method A class which has a synchronized method automatically acts as a lock. Only one synchronized method can run for each class. Creating A Package: 1. 2. 3. 4. 5. 6. 7. Identify the hierarchy in which the .class files have to be organized. Create a directory corresponding to every package, with names similar to the packages. Include the package statement as the first statement in the program. Declare the various classes. Save the file with a .java extension. Compile the program which will create a .class file in the same directory. Execute the .class file. Packages and Access Protection: Accessed Public Protected Package Private From the same class ? Yes Yes Yes Yes From a non subclass in the same package ? Yes Yes Yes No synchronized 9 © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. 11 Java Programming Guide - Quick Reference List of exceptions in Java(part of java.lang package): From a non subclass outside the package? From a subclass in the same package? From a subclass outside the package ? Essential exception classes include Yes No Yes Yes Yes Yes No Yes No No Exception ArithmeticException Caused by exceptional conditions like divide by zero ArrayIndexOfBounds Exception Thrown when an array is accessed beyond its bounds No ArrayStoreException Thrown when an incompatible type is stored in an array ClassCastException Thrown when there is an invalid cast IllegalArgument Exception Thrown when an inappropriate argument is passed to a method IllegalMonitorState Exception Illegal monitor operations such as waiting on an unlocked thread No Attribute modifiers in Java: Modifier abstract Acts on Class Description Contains abstract methods.Cannot be instantiated. Description Interface All interfaces are implicitly abstract. The modifier is optional. IllegalThreadState Exception Thrown when a requested operation is incompatible with the current thread state. Method Method without a body. Signature is followed by a semicolon. The class must also be abstract. IndexOutOfBounds Exception Thrown to indicate that an index is out of range. NegativeArraySize Exception Thrown when an array is created with negative size. © 1999, Pinnacle Software Solutions Inc. 10 © 1999, Pinnacle Software Solutions Inc. 12 Java Programming Guide - Quick Reference NullPointerException Java Programming Guide - Quick Reference Invalid use of a null reference. setPriority() Changes the priority of the thread Returns a reference to the currently executing thread NumberFormatException Invalid conversion of a string to a number. currentThread() SecurityException Thrown when security is violated. activeCount() ClassNotFound Exception Thrown when a class is not found. Returns the number of active threads in a thread group Exception Handling Syntax: CloneNotSupported Exception Attempt to clone an object that does not implement the Cloneable interface. IllegalAccess Exception Thrown when a method does not have access to a class. try { //code to be tried for errors } catch(ExceptionType1 obj1) { Instantiation Exception Thrown when an attempt is made to instantiate an abstract class or an interface. //Exception handler for ExceptionType1 } catch(ExceptionType2 obj2) { InterruptedException Thrown when a second thread interrupts a waiting, sleeping, or paused thread. //Exception handler for ExceptionType2 } finally{ //code to be executed before try block ends. This executes whether or not an // exception occurs in the try block. } The java.lang.Thread class I/O classes in Java (part of the java.io package): The Thread class creates individual threads. To create a thread either (i) extend the Thread class or (ii) implement the Runnable interface. In both cases, the run() method defines operations I/O class name © 1999, Pinnacle Software Solutions Inc. 13 Java Programming Guide - Quick Reference Description BufferedInputStream Provides the ability to buffer the © 1999, Pinnacle Software Solutions Inc. 15 Java Programming Guide - Quick Reference performed by the thread. Methods of the Thread class: BufferedOutputStream Methods Description run() Must be overridden by Runnable object; contains code that the thread should perform Causes the run method to execute and start the thread start() sleep() BufferedReader BufferedWriter Causes the currently executing thread to wait for a specified time before allowing other threads to execute interrupt() Interrupts the current thread Yield() Yields the CPU to other runnable threads DataInputStream DataOutputStream File getName() Returns the current thread’s name getPriority() Returns the thread’s priority as an integer isAlive() Tests if the thread is alive; returns a Boolean value join() Waits for specified number of milliseconds for a thread to die setName() Changes the name of the thread FileInputStream FileOutputStream ObjectInputStream ObjectOutputStream PrintStream RandomAccessFile © 1999, Pinnacle Software Solutions Inc. 14 input. Supports mark() and reset() methods. Provides the ability to write bytes to the underlying output stream without making a call to the underlying system. Reads text from a character input stream Writes text to character output stream Allows an application to read primitive datatypes from an underlying input stream Allows an application to write primitive datatypes to an output stream Represents disk files and directories Reads bytes from a file in a file system Writes bytes to a file Reads bytes i.e. deserializes objects using the readObject() method Writes bytes i.e. serializes objects using the writeObject()method Provides the ability to print different data values in an efficient manner Supports reading and writing to a random access file © 1999, Pinnacle Software Solutions Inc. 16 Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference StringReader Character stream that reads from a string StringWriter Character stream that writes to a StringBuffer that is later converted to a String The java.io.InputStream class: The InputStream class is at the top of the input stream hierarchy. This is an abstract class which cannot be instantiated. Hence, subclasses like the DataInputStream class are used for input purposes. Methods of the InputStream class: Method available() Description Returns the number of bytes that can be read close() Closes the input stream and releases associated system resources mark() Marks the current position in the input stream mark Supported() read() Returns the name of the file and directory denoted by the path name isDirectory() Tests whether the file represented by the pathname is a directory lastModified() Returns the time when the file was last modified l length() Returns the length of the file represented by the pathname listFiles() Returns an array of files in the directory represented by the pathname setReadOnly() Marks the file or directory so that only read operations can be performed renameTo() Renames the file represented by the pathname delete() Deletes the file or directory represented by the pathname canRead() Checks whether the application can read from the specified file canWrite() Checks whether an application can write to a specified file getName() Creating applets: 1. Returns true if mark() and reset() methods are supported by the input stream 2. 3. Abstract method which reads the next byte of data from the input stream 4. read(byte b[]) Reads bytes from the input stream and stores them in the buffer array © 1999, Pinnacle Software Solutions Inc. 17 Java Programming Guide - Quick Reference skip() The java.io.OutputStream class: The OutputStream class which is at the top of the output stream hierarchy, is also an abstract class, which cannot be instantiated. Hence, subclasses like DataOutputStream and PrintStream are used for output purposes. Methods of the OutputStream class: Description close() Closes the output stream, and releases associated system resources write(int b) Writes a byte to the output stream write(byte b[]) Writes bytes from the byte array to the output stream © 1999, Pinnacle Software Solutions Inc. 19 Java Programming Guide - Quick Reference Skips a specified number of bytes from the input stream Method Write the source code and save it with a .java extension Compile the program Create an HTML file and embed the .class file with the <applet> tag into it. To execute the applet, open the HTML file in the browser or use the appletviewer utility, whch is part of the Java Development Kit. The <applet> tag: Code, width, and height are mandatory attributes of the <applet> tag. Optional attributes include codebase, alt,name, align, vspace, and hspace. The code attribute takes the name of the class file as its value. Syntax: <applet code = “abc.class” height=300 width=300> value= value1 > <param name=parameterName1 value= value2 > <param name=parameterName2 </applet> Using the Appletviewer: Appletviewer.exe is an application found in the BIN folder as part of the JDK. Once an HTML file containing the class file is created (eg. abc.html), type in the command line: Appletviewer abc.html java.applet.Applet class: flush() Methods of the java.applet.Applet class: Flushes the ouput stream, and writes buffered output bytes java.io.File class: The File class abstracts information about files and directories. Method Description init() Invoked by the browser or the applet viewer to inform that the applet has been loaded Invoked by the browser or the applet viewer to inform that applet execution has started Invoked by the browser or the applet viewer to inform that applet execution has stopped start() Methods of the File class: stop() Method Description exists() Checks whether a specified file exists © 1999, Pinnacle Software Solutions Inc. 18 © 1999, Pinnacle Software Solutions Inc. 20 Java Programming Guide - Quick Reference destroy() getAppletContext() getImage() getDocumentBase() getCodeBase() getParameter() showStatus() Java Programming Guide - Quick Reference Invoked by the browser or the appletviewer to inform that the applet has been reclaimed by the Garbage Collector Determines the applet context or the environment in which it runs Returns an Image object that can be drawn on the applet window setBackground() setForeground() SetSize() setLocation() setBounds() Returns the URL of the HTML page that loads the applet Returns the URL of the applet’s class file Returns the value of a named applet parameter as a string Displays the argument string on the applet’s status addFocusListener() addMouseListener() addKeyListener() getGraphics() java.awt.Graphics class: The Graphics class is an abstract class that contains all the essential drawing methods like drawLine(), drawOval(), drawRect() and so on. A Graphics reference is passed as an argument to the paint() method that belongs to the java.awt.Component class. Methods of the Graphics class: Method drawLine() Description Draws a line between (x1,y1) and (x2,y2) passed as parameters drawRect()/fillRect() Draws a rectangle of specified width and height at a specified © 1999, Pinnacle Software Solutions Inc. 21 Java Programming Guide - Quick Reference update(Graphics g) Sets the background color of the component Sets the foreground color of the component Resizes the component Moves the component to a new location Moves the component to specified location and resizes it to the specified size Registers a FocusListener object to receive focus events from the component Registers a MouseListener object to receive mouse events from the component Registers a KeyListener object to receive key events from the component Returns the graphics context of this component Updates the component. Calls the paint() method to redraw the component. AWT Components: Many AWT classes like Button, Checkbox, Label, TextField etc. are subclasses of the java.awt.Component class. Containers like Frame and Panel are also subclasses of components, but can additionally hold other components. © 1999, Pinnacle Software Solutions Inc. 23 Java Programming Guide - Quick Reference Label: location drawOval()/fillOval() Draws a circle or an ellipse that fills within a rectangle of specified coordinates drawString() Draws the text given as a specified string drawImage() Draws the specified image onto the screen drawPolygon() /fillPolygon() Draws a closed polygon defined by arrays of x and y coordinates setColor() setFont() Sets the specified color of the graphics context Constructors · Label() - Creates an empty label · Label(String s) - Creates a label with left justified text string · Label (String s, int alignment) - Creates a label with the specified text and specified aligment. Possible values for alignment could be Label.RIGHT, Label.LEFT, or Label.CENTER Methods of the Label class: Method Description getAlignment() Returns an integer representing the current alignment of the Label. 0 for left, 1 for center, and 2 for right alignment. Sets the alignment of the Label to the specified one Returns the label’s text as a string Sets the label’s text with the specified string Sets the specified font of the graphics context setAlignment() java.awt.Component class: The Component class is an abstract class that is a superclass of all AWT components. A component has a graphical representation that a user can interact with. For instance, Button, Checkbox, TextField, and TextArea. getText() setText() Methods of the Component class: Button: Method Description Constructors paint(Graphics g) Paints the component. The Graphics context g is used for painting. Button() - Creates a button without a label Button(String s) - Creates a button with the specified label © 1999, Pinnacle Software Solutions Inc. 22 © 1999, Pinnacle Software Solutions Inc. 24 Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference Methods of the Button class: Method addActionListener() getActionCommand() Choice() - Creates a new choice menu, and presents a popup menu of choices. Description Registers an ActionListener object to receive action events from the button Methods of the Choice class: Returns the command name of the action event fired by the button. Returns the button label if the command name is null. GetLabel() Returns the button’s label SetLabel() Sets the button’s label to the specified string Method Description add() Adds an item to a choice menu addItem() Adds an item to a choice menu addItemListener() Registers an ItemListener object to receive item events from the Choice object getItem() Returns the item at the specified index as a string getItemCount() Returns the number of items in the choice menu getSelectedIndex() Returns the index number of the currently selected item getSelectedItem() Returns the currently selected item as a string insert() Inserts a specified item at a specified index position remove() Removes an item from the choice menu at the specified index Checkbox: Constructors · · Checkbox() - Creates a checkbox without any label Checkbox(String s) - Creates a checkbox with a specified label Checkbox(String s, boolean state) - Creates a checkbox with a specified label, and sets the specified state Checkbox(String s, boolean state, CheckboxGroup cbg) - Creates a checkbox with a specified label and specified state, belonging to a specified checkbox group · · © 1999, Pinnacle Software Solutions Inc. 25 Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. 27 Java Programming Guide - Quick Reference Methods of the Checkbox class: TextField: Method Description Constructors addItemListener() Registers an ItemListener object to receive item events from the checkbox getCheckboxGroup() Returns the checkbox’s group · TextField() - Creates a new text field · TextField(int cols) - Creates a text field with the specified number of columns · TextField(String s) – Creates a text field initialized with a specified string · TextField(String s, int cols) - Creates a text field initialized with a specified string that is wide enough to hold a specified number of columns getLabel() Returns the checkbox’s label getState() Determines if the checkbox is checked or unchecked setLabel() setState() Methods of the TextField class: Sets the label of the check box with the specified string Method Description isEditable() Returns a boolean value indicating whether or not a text field is editable setEditable() Passing True enables text to be edited, while False disables editing. The default is True. addActionListener() Registers an ActionListener object to receive action events from a text field getEchoChar() Returns the character used for echoing getColumns() Returns the number of columns in a text field Sets the specified checkbox state Creating Radio Buttons (Mutually exclusive checkboxes): · · First create a CheckboxGroup instance – CheckboxGroup cbg = new CheckboxGroup(); While creating the checkboxes, pass the checkbox group object as an argument to the constructor - Checkbox (String s, boolean state, CheckboxGroup cbg) Choice: Constructors © 1999, Pinnacle Software Solutions Inc. 26 © 1999, Pinnacle Software Solutions Inc. 28 Java Programming Guide - Quick Reference setEchoChar() Sets the echo character for a text field Returns the text contained in the text field Sets the text for a text field Java Programming Guide - Quick Reference Methods of the List class: Method Description add() Adds an item to the end of the scrolling list addItemListener() Registers an ItemListener object to receive Item events from a scrolling list · TextArea() - Creates a new text area · TextArea(int rows, int cols) - Creates a new empty text area with specified rows and columns · TextArea(String s) – Creates a new text area with the specified string · TextArea(String s, int rows, int cols) - Creates a new text area with the specified string and specified rows and columns. · TextArea(String s, int rows, int cols, int scrollbars) - Creates a text area with the specified text, and rows, columns, and scrollbar visibility as specified. deselect() Deselects the item at the specified index position getItem() Returns the item at the specified index position getItemCount() Returns the number of items in the list getSelectedIndex() Returns the index position of the selected item Methods of the TextArea class: getSelectedItem() Returns the selected item on the scrolling list isMultipleMode() Determines if the scrolling list allows multiple selection remove() Removes a list item from a specified position setMultipleMode() Sets a flag to enable or disable multiple selection getText() setText() TextArea: Constructors Method Description getText() Returns the text contained in the text area as a string setText() Sets the specified text in the text area getRows() Returns the number of rows in the © 1999, Pinnacle Software Solutions Inc. © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference Scrollbar: Constructors getColumns() text area Returns the number of columns in the text area selectAll() Selects all the text in the text area setEditable() A True value passed as an argument enables editing of the text area, while False disables editing. It is True by default. · Scrollbar() - Creates a new vertical scroll bar · Scrollbar(int orientation) - Creates a new scroll bar with a particular orientation, which is specified as Scrollbar.HORIZONTAL or Scrollbar.VERTICAL · Scrollbar(int orientation, int value, int visible, int minimum, int maximum)- Creates a new scroll bar with the specified orientation, initial value, thumb size, minimum and maximum values Methods of the Scrollbar class: List: Method Description Constructors addAdjustmentListener() Registers an adjustmentListener object to receive adjustment events from a scroll bar Returns the block increment of a scrollbar as an integer. Returns the maximum value of a scrollbar as an integer Returns the minimum value of a scrollbar as an integer Returns the orientation of a scrollbar as an integer Returns the current value of a scrollbar as an integer · List() - Creates a new scrolling list · List(int rows) - Creates a new scrolling list with a specified number of visible lines · List(int rows, boolean multiple) - Creates a scrolling list to display a specified number of rows. A True value for Multiple allows multiple selection, while a False value allows only one item to be selected. getBlockIncrement() getMaximum() getMinimum() getOrientation() getValue() © 1999, Pinnacle Software Solutions Inc. © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference setOrientation() setValue() setMinimum() setMaximum() Java Programming Guide - Quick Reference Sets the orientation of a scrollbar Sets the current value of a scrollbar Sets the minimum value of a scrollbar Sets the maximum value of a scrollbar Interface method Description actionPerformed() Invoked whenever an ActionEvent object is generated (button is clicked) Frame: TextListener interface: Implemented by a class to handle text events. Whenever the text value of a component changes, an interface method called textValueChanged is invoked, which must be overridden in the implementing class. Constructors Interface method Description · Frame() - Creates a new frame without any title · Frame(String s) - Creates a new frame with the specified title textValueChanged() Invoked whenever a Text Event object is generated (text value changes) Menus: AdjustmentListener interface: Implemented by a class that handles adjustment events. The method adjustmentValueChanged(), overridden by the implementing class is invoked everytime an AdjustmentEvent object occurs (when a scrollbar is adjusted). · Can be added only to a frame · A MenuBar instance is first created as: MenuBar mb = new MenuBar(); · The MenuBar instance is added to a frame using the setMenuBar() method of the Frame class as follows: setMenuBar(mb); · Individual menus are created (instances of the Menu class) and added to the menu bar with the add() method Interface method adjustmentValueChanged() Dialog: Direct subclass of java.awt.Window, which accepts user input. Description Invoked whenever an AdjustmentEvent object is generated (when a scrollbar thumb is adjusted) ItemListener interface: Implemented to handle state change events. The method itemStateChanged()must be overridden by the implementing class. © 1999, Pinnacle Software Solutions Inc. 33 Java Programming Guide - Quick Reference Constructors · Dialog(Frame parent, boolean modal) – Creates a new initially invisible Dialog attached to the frame object parent. The second argument specifies whether the dialog box is Modal or Non-modal. · Dialog (Frame parent, String s, boolean modal) – Same as the above. The second argument specifies the title of the dialog box. © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference Method Description itemStateChanged() Invoked whenever an ItemEvent object is generated (a checkbox is checked, an item is selected from a choice menu, or an item is selected from a list) FileDialog: Direct subclass of Dialog, which displays a dialog window for file selection. FocusListener interface: Implemented to receive notifications whenever a component gains or loses focus. The two methods to be overridden are focusGained() and focusLost(). The corresponding adapter class is FocusAdapter. Constructors Method Description · FileDialog(Frame f, String s) - Creates a new dialog for loading files(file open dialog) attached to the frame with the specified title · FileDialog(Frame f, String s, int i) - Creates a file dialog box with the specified title. The third argument specifies whether the dialog is for loading a file or saving a file. The value of i can be either FileDialog.LOAD or FileDialog.SAVE focusGained() Invoked whenever a component gains keyboard focus Invoked whenever a component loses keyboard focus AWT Event Listener interfaces: For every AWT event class there is a corresponding event-listener interface, which is a part of the java.awt.event package and provides the eventhandling methods. ActionListener interface: Implemented by a class that handles an action event. The method actionPerformed() must be overridden by the implementing class. © 1999, Pinnacle Software Solutions Inc. 35 focusLost() KeyListener interface: Implemented to handle key events. Each of the three methods – keyPressed(), keyReleased(), keyTyped() – receives a KeyEvent object when a key event is generated. Method Description KeyPressed() Invoked whenever a key is pressed keyReleased() Invoked whenever a key is released © 1999, Pinnacle Software Solutions Inc. 36 Java Programming Guide - Quick Reference keyTyped() Java Programming Guide - Quick Reference Invoked whenever a key is typed MouseListener interface: Implemented by a class handling mouse events. It comprises of five methods invoked when a MouseEvent object is generated. Its corresponding adapter class is the MouseAdapter class. Method Description mouseClicked() Invoked when mouse is clicked on a component mouseEntered() Invoked when mouse enters a component mouseExited() Invoked when mouse exits a component mousePressed() Invoked when mouse button is pressed on a component mouseReleased() Invoked when mouse button is released on a component Invoked when the window is no longer the active window i.e. the window can no longer receive keyboard events windowIconified() Invoked when a normal window is minimized windowDeiconified() Invoked when a minimized window is changed to normal state java.sql.Driver interface: class. Implemented by every driver Methods of the Driver interface: MouseMotionListener interface: Implemented by a class for receiving mouse-motion events. Consists of two methods – mouseDragged() and mouseMoved(), which is invoked when a MouseEvent object is generated. MouseMotionAdapter is its corresponding adapter class. © 1999, Pinnacle Software Solutions Inc. windowDeactivated() 37 Java Programming Guide - Quick Reference Method Description acceptsURL() Returns a Boolean value indicating whether the driver can open a connection to the specified URL connect() Tries to make a database connection to the specified URL getMajorVersion() Returns the driver’s major version number getMinorVersion() Returns the driver’s minor version number © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference jdbcCompliant() JDBC compliant driver Method 39 Tests whether the driver is a genuine Description mouseDragged() Invoked when the mouse is pressed on a component and dragged java.sql.Connection interface: Represents a session with a specific database. SQL statements are executed within a session and the results are returned. mouseMoved() Invoked when mouse is moved over a component Methods of the Connection interface: WindowListener interface: Implemented by a class to receive window events. It consists of seven different methods to handle the different kinds of window events, which are invoked when a WindowEvent object is generated. Its corresponding adapter class is the WindowAdapter class. Method Description windowOpened() Invoked when the window is made visible for the first time windowClosing() Invoked when the user attempts to close the window from the Windows system menu windowClosed() Invoked when the window has been closed as a result of calling the dispose() method windowActivated() Invoked when the window is made active i.e. the window can receive keyboard events © 1999, Pinnacle Software Solutions Inc. 39 Method Description Close() Immediately releases the database and JDBC resources commit() Makes all changes since the last commit/rollback permanent, and releases the database locks held by the connection createStatement() Creates and returns a Statement object. It is used for sending SQL statements to be executed on the database getMetaData() Returns a DatabaseMetaData object that represents metadata about the database isReadOnly() Checks whether the connection is a read-only connection prepareCall() Creates and returns a Callable Statement object, © 1999, Pinnacle Software Solutions Inc. 4 Java Programming Guide - Quick Reference prepareCall() prepareStatement() rollback() setAutoCommit() Java Programming Guide - Quick Reference Creates and returns a CallableStatement object (used for calling database stored procedures) Creates and returns a PreparedStatement object (used for sending precompiled SQL statements to the database) Discards all the changes made since the last commit/rollback and releases database locks held by the connection Enables or disables the auto commit feature. It is disabled by default java.sql.DriverManager class: Responsible for managing a set of JDBC drivers. It attempts to locate and load the JDBC driver specified by the getConnection() method. Methods of the DriverManager class: Method Description getConnection() Attempts to establish a database connection with the specified database URL, and returns a Connection object getLoginTimeout() Returns the maximum number of seconds a driver can wait when attempting to connect to the database © 1999, Pinnacle Software Solutions Inc. © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference Java Programming Guide - Quick Reference registerDriver() Registers the specified driver with the DriverManager setLoginTimeout() Sets the maximum number of seconds a driver can wait when attempting to connect to the database getDrivers() Returns an enumeration of all the drivers installed on the system getDriver() Returns a Driver object that supports connection through a specified URL © 1999, Pinnacle Software Solutions Inc. © 1999, Pinnacle Software Solutions Inc. RubyForBeginners Cheat Sheet by laurennicoleroth via cheatography.com/26292/cs/7316/ Ruby Variables local variable ERB local_variable ERB Conditionals Embedded Ruby for making if/else dynamic HTML templates if input == admin_password instance variable @instance_variable class variable @@class_variable erb Sinatra looks in "views" folder for global variable $global_variable :hello hello.erb file Show <% if @tweets %> <% @tweets @tweets.each do |tweet| %> password." <p><%= tweet %></p> <% end %> end Ruby Data Types String "Sequence of characters." or 'Sequence of admin_logged_in = true else puts "Sorry, wrong <% end %> Instance Any instance variables you declare Variables in your routes, will be accessible in these erb files characters.' Useful Ruby Methods split Breaks a string into an array. join Takes an array and joins into a Symbol :a_symbol, (identifier) :another_symbol, :name Ruby Expressions Integer 42, 100, 1002, -256 seen_it = "seen Save string to upcase Makes characters capital letters. Float again" variable 1.1, 3.1415926, 5.5, - reverse Reverse characters in a string. (floating 128.6 num = 3 Save integer to sample Randomly choose element. map Do the same thing to every +, -, *, /, % other_num = 5 point) Numeric string. variable Save another integer Comparison element. to another variable Methods ==, !=, >, >=, <, <= Operators answer = (num + Save result of other_num) * 6 adding/multiplying. Cmd+Click (Mac) or Open links in new Ctrl+Click tabs. ruby-doc.org ("The Ruby coding best puts "Dogs say # Ruby Docs") practices. "woof!" {dog_speak}" Stack Overflow Oops. Research your or puts "Dogs say " + Return Last line of a ruby Value method/block/expression in IRB Boolean true or false dog_speak = nil counts as false in Ruby, everything counts as true Array (0 letters = ["a", "b", indexed) "c"] letters[2 #returns "c" Research String Interpolation dog_speak error. Guides and blog posts Has someone done this before? ] letters[1 ["a", "monkey", "c"] ] = "monkey" By laurennicoleroth cheatography.com/laurennicoleroth/ Published 25th February, 2016. Sponsored by Readability-Score.com Last updated 25th February, 2016. Measure your website readability! Page 1 of 3. https://readability-score.com RubyForBeginners Cheat Sheet by laurennicoleroth via cheatography.com/26292/cs/7316/ Sinatra Sinatra Routing Array Methods Framework for building a web Add to end of array: letters << Remove person.delete(:sex) # server written in Ruby "elephant" or value by returns "female" Action taken in response to letters.push("elephant") request Path text and slashes after domain http://localh Sinatra looks for get '/hello' ost:4567/he push << Shovel operator. Push to end of array. unshift Add element to beginning of array: letters.unshift("zebra") llo get '/hello' do #code to return a pop shift response to the browser end String get '/hello' Response Greeting Method def Accepts Name create_greeting(nam e) letters.pop return "Welcome, # Remove from start of array. {name}" letters.shift end Call a method with arguments. Call Greeting create_greeting("La (argum Some methods require no Method uren") "Hello, friendly web letters traveler!" .pop arguments. #returns 'Welcome, Method without arguments. Hashes Lauren" Upcase On Call create_greeting("La To Greeting uren").upcase Method Instantiate person = {:name => Arguments Input given to methods. erb :hello a Hash "Lauren", :age => 89, Parameters Define what can be end rockets) Response Get tweets Methods .method ents) get '/hello' do key. Remove from end of array. end HTML File Hashes (cont) get '/' do route @tweets = (hash method without explicit "female"} "return" (shortcut) person[:name] # returns erb :index key. "Lauren" route Returning last line of "Lauren", age: 89, sex: value by '/' Implicit Return a Hash Access Get server to run code in get '/' Output from a function person = {name: { |tweet| tweet.text } Redirect Return value Instantiate $client.user_timeline.map end passed to a method. :sex => "female"} Update person[:age] = 12 value by key. Command Line Ruby Download, install, and use ruby gems software packages on your system $ Get Ruby Version ruby Insert key, person[:gender] = "cis value pair. female" -v $ Load up interactive Ruby irb By laurennicoleroth cheatography.com/laurennicoleroth/ Published 25th February, 2016. Sponsored by Readability-Score.com Last updated 25th February, 2016. Measure your website readability! Page 2 of 3. https://readability-score.com RubyForBeginners Cheat Sheet by laurennicoleroth via cheatography.com/26292/cs/7316/ Command Line (cont) $ gem install Loops Install sinatra gem times sinatra Twitter API (cont) 10.times do puts "Hello!" $ gem install Install twitter gem twitter $ ruby Tell Ruby interpreter to server.rb run code. Ctrl+C Stop server from end times Server each puts "#{counter}" do |config| end config.consumer_key = "YOUR_CONSUMER_KEY" letters = ["a", "b", config.consumer_secret = "c"] "YOUR_CONSUMER_SECRET" requests made by the letters.each do |letter| (client) browser puts "Letter #{letter}" "YOUR_ACCESS_TOKEN" end config.access_token_secret clients and servers map config.access_token = = "YOUR_ACCESS_SECRET" capital_letters = end letters.map do |letter| GET, POST, PUT, PATCH, DELETE letter.upcase Get Request Tweets(data) end timeline from Twitter API POST variable Twitter::REST::Client.new communication between GET global $client = protocol enabling HTTP Verbs $client counter has IP address, processes HTTP require twitter Twitter loop with running. Web and HTTP 10.times do |counter| Set up Submit Tweet(data) to block letters.each { |letter| style Send $client.update("omg I am puts "Upcase # tweet tweeting from the command Twitter API https: scheme twitter.com domain lauren_n_roth/stat path $client.user_timeline user {letter.upcase}!" } elegant capitals = letters.map { map |letter| letter.upcase } method line. So cool!") us/6999964284295‐ 61856 Params hash Twitter API params[:tweet] Download bit.ly/dbc-twitter-sinatra files Sign Up apps.twitter.com To Use Twitter API Create 1. Create new App 2. Create New App Access Tokens 3. Ensure permissions are read/write By laurennicoleroth cheatography.com/laurennicoleroth/ Published 25th February, 2016. Sponsored by Readability-Score.com Last updated 25th February, 2016. Measure your website readability! Page 3 of 3. https://readability-score.com Arrays array_intersect array_merge array_pop array_push array_reverse array_walk count in_array Date and Time date mktime strtotime time Filesystem clearstatcache copy fclose fgets file filemtime filesize file_exists fopen fread fwrite is_dir is_file readfile ^ Start of string Y 4 digit year 2005 $ End of string y 2 digit year 05 . Any single character F Long month January (a|b) a or b M Short month Jan (...) Group section m Month (leading zeros) 01 to 12 [abc] Item in range (a or b or c) n Month 1 to 12 [^abc] Not in range (not a or b or c) D Short day name Mon \s White space l Long day name Monday a? Zero or one of a d Day (leading zeros) 01 to 31 a* Zero or more of a j Day 1 to 31 a+ One or more of a a{3} Exactly 3 of a h 12 Hour (leading zeros) 01 to 12 a{3,} 3 or more of a g 12 Hour 1 to 12 a{3,6} Between 3 and 6 of a H 24 Hour (leading zeros) 00 to 23 \ Escape character G 24 Hour 0 to 23 i Minutes (leading zeros) 00 to 59 s Seconds (leading zeros) 00 to 59 w Day of week 0 to 6 z Day of year W Week of year t Days in month [:punct:] Any punctuation symbol [:space:] Any space character [:blank:] Space or tab 1 0 to 365 1 to 53 2 28 to 31 i Case-insensitive Headers header headers_sent setcookie s Period matches newline a ^ and $ match lines A Ungreedy matching B Swatch Internet Time 000 to 999 e Evaluate replacement S Ordinal Suffix st, nd, td, th Mail mail x Pattern over several lines GMT Numbers ceil floor number_format round Miscellaneous define eval exit Network fsockopen PHP Options ini_get ini_restore ini_set phpinfo Execution exec m U array_push ( array, element ) in_array ( needle, haystack ) explode ( separator, string ) split ( pattern, string ) preg_split ( pattern, string ) ereg ( pattern, string ) strpos ( haystack, needle ) am or pm AM or PM T Timezone of machine Z Timezone offset (seconds) O Difference to GMT (hours) +0200 I Daylight savings 1 or 0 L Leap year 1 or 0 U Seconds since Epoch c ISO 8601 (PHP 5) r RFC 2822 3 1. date("w"): 0 is Sunday, 6 is Saturday. str_replace ( search, replace, string ) 2. Week that overlaps two years belongs to year that contains most days of that week. Hence week number for 1st January r Read r+ Read and write, prepend w Write, truncate w+ Read and write, truncate a Write, append a+ Read and write, append of a given year can return 53rd week if week belongs to previous year. date("W", mktime(0, 0, 0, 12, 28, $year)) always gives correct number of weeks in $year. 3. The Epoch was the 1st January 1970. Regex ereg eregi ereg_replace eregi_replace split spliti preg_match preg_match_all preg_replace preg_split Sessions session_destroy session_id session_start Strings addslashes crypt echo explode implode md5 nl2br sprintf strip_tags stripslashes stristr strpos strrev strstr strtolower strtoupper str_replace substr trim URLs rawurldecode rawurlencode urldecode urlencode Variables empty is_array is_int is_null is_numeric is_object isset serialize unserialize SuperGlobals $_ENV $_GET $_POST $_COOKIE $_SESSION $_SERVER $_FILES $_REQUEST $GLOBALS Available free from www.ILoveJackDaniels.com 010010100101011010101101001010101001011101011010 Data Types integer, float, boolean, string, array, object, resource, NULL Super Globals $GLOBALS (Access all global variables in script) $_SERVER (Access web server variables) $_GET (Values passed to script through URL) $_POST (Values passed to script through HTTP Post) $_COOKIE (Values passed by user cookie) $_FILES (Values ( passed by HTTP Post File Uploads) $_ENV (Values passed to script via the environment) $_REQUEST (Values passed by URL, HTTP Post, or user Cookies) $_SESSION (Values passed through user's session) Variable Declarations $variablename = <value>; $anothervariable =& $variablename; (Assign by Reference) Declare Array $arrayname = array(); Initialize Array $arrayname = array(<value1>, <value2>, <value3>); $arrayname = array(<key> => <value>, <key> => <value>); (Define Keys) $multiarray = array(<key> => array(<value1>,<value2>)); (Multi-dimensional) If Else if (<condition 1>) { <statement 1>; } elseif (<condition 2>) { <statement 2>; } else { <statement 3>; } Common Array Functions sort(<array>); (Sort array assigns new keys) asort(<array>); (Sort array maintain keys) rsort(<array>); (Sort array in reverse, new keys) arsort(<array>); (Sort array in reverse, maintain keys) count(<array>); (Count elements) count(<array>,COUNT_RECURSIVE); (Count multidimensional array) array_push(<array>,<value>); (Push item onto end of array) array_pop(<array>); (Pop item off end of array) Inline If (Ternary) <condition> ? true : false; For Loop for (<initialize>;<condition>;<update>) { <statements>; } Comments // Comment text /* Multi-line comment text */ # Comment text Arithmetic Operators + (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus) Relational Operators == (Equal), === (Equal with type comparison), != (Not equal), <> (Not equal), !== (Not Equal with type comparison), < (Less than), > (Greater than), <= (Less than or equal to), >= (Greater than or equal to) Logical Operators ! (logical NOT), && (logical AND), || (logical OR), xor (logical XOR) Assignment Operators = (Assign), += (Addition), -= (Subtraction), *= (Multiplication), /= (Division), .= (Concatenation), %= (Modulus), &= (And), |= (Or), ^= (Exclusive Or), <<= (Left Shift), >>= (Right Shift) String Concatenation . (Period) String Manipulation substr(<string>,<start>,[<length>]); strlen(<string>); trim(<string>); ltrim(<string>); // Trim left rtrim(<string>); // Trim right strtolower(<string>); strtoupper(<string>); str_replace(<search>,<replace>,<string>,[<count>]); strpos(<string>, <search>); strcmp(<string1>,<string2>); (Binary safe string comparison) strcasecmp(<string1>,<string2>); (Binary safe case-insensitive comparison) explode(<delim>,<string>,[<limit>]); (Break string into array) implode(<delim>,<array>); (Join array into string separated by delim) Cookies setcookie (<cookiename>, [<value>],[<expire_time_in_secs_since_epoch>]); $_COOKIE['cookiename']; (Returns value of cookie) Sessions session_start(); (Create session) $_SESSION['key_name'] = value; (Set session variable) $variablename = $_SESSION['key_name']; (Retrieve value from session variable) session_destroy(); (Destroy session) Error Handling try { <statements that may cause error>; } catch (<Exception Class> $exception_name) { <statements to execute when error is caught>; } For Each Loop foreach (<array> as [<value> |<key> => <value>]) { <statements>; [break]; [continue]; } While Loop while (<condition>) { <statements>; } Do-While Loop do { <statements>; } while (<condition>); Switch switch (<expression>) { case <literal or type>: <statements>; [break;] case <literal or type>: <statements>; [break;] default: <statements>; } Function Structure function <function_name>([<parameters>]) { <statements>; [return <value>;] } Class Structure class <class_name> [<extends base_class>] { [var | <modifiers*>] [<class member variables>]; [<modifiers*>] function <function_name>([<parameters>]) { <statements>; } } * Modifiers <public | pr ivate | static> are implemented in PHP5 Declare and Use Class $variable = new class_name(); $variable->function_name(); class_name::function_name(); (Static call) Download More Reference Sheets & Get Programming Help @ http://www.DreamInCode.net Edited By: hotsnoj, Martyr2 Published: October 18, 2007 sys Variables String Methods Datetime Methods capitalize() * lstrip() today() fromordinal(ordinal) builtin_module_names Linked C modules center(width) partition(sep) now(timezoneinfo) combine(date, time) byteorder Native byte order count(sub, start, end) replace(old, new) utcnow() strptime(date, format) check_interval Signal check frequency decode() rfind(sub, start ,end) fromtimestamp(timestamp) utcfromtimestamp(timestamp) argv Command line args exec_prefix Root directory encode() rindex(sub, start, end) executable Name of executable endswith(sub) rjust(width) exitfunc Exit function name expandtabs() rpartition(sep) modules Loaded modules find(sub, start, end) rsplit(sep) path Search path index(sub, start, end) rstrip() replace() utcoffset() platform Current platform isalnum() * split(sep) isoformat() dst() stdin, stdout, stderr File objects for I/O isalpha() * splitlines() __str__() tzname() version_info Python version info isdigit() * startswith(sub) strftime(format) winver Version number islower() * strip() isspace() * swapcase() * istitle() * title() * sys.argv for $ python foo.py bar -c qux --h Time Methods Date Formatting (strftime and strptime) isupper() * translate(table) %a Abbreviated weekday (Sun) foo.py join() upper() * %A Weekday (Sunday) sys.argv[1] bar ljust(width) zfill(width) sys.argv[2] -c lower() * sys.argv[0] sys.argv[3] qux sys.argv[4] --h %b Abbreviated month name (Jan) %B Month name (January) %c Date and time Note Methods marked * are locale dependant for 8-bit strings. %d Day (leading zeros) (01 to 31) %H 24 hour (leading zeros) (00 to 23) %I 12 hour (leading zeros) (01 to 12) os Variables %j List Methods Day of year (001 to 366) altsep Alternative sep curdir Current dir string append(item) pop(position) defpath Default search path count(item) remove(item) %p AM or PM devnull Path of null device extend(list) reverse() %S Second (00 to 61 4) extsep Extension separator index(item) sort() %U Week number linesep Line separator insert(position, item) name Name of OS %W Week number pardir Parent dir string %x Date pathsep Patch separator sep Path separator Note Registered OS names: “posix”, “nt”, “mac”, “os2”, “ce”, “java”, “riscos” Class Special Methods %m Month (01 to 12) %M Minute (00 to 59) %w Weekday File Methods 2 1 (00 to 53) (0 to 6) 3 (00 to 53) %X Time close() readlines(size) %y Year without century (00 to 99) flush() seek(offset) %Y Year (2008) fileno() tell() %Z Time zone (GMT) isatty() truncate(size) %% A literal "%" character (%) next() write(string) read(size) writelines(list) 1. readline(size) Sunday as start of week. All days in a new year preceding the first Sunday are considered to be in week 0. __new__(cls) __lt__(self, other) __init__(self, args) __le__(self, other) __del__(self) __gt__(self, other) __repr__(self) __ge__(self, other) len(a) 6 __str__(self) Indexes and Slices (of a=[0,1,2,3,4,5]) 2. 0 is Sunday, 6 is Saturday. 3. Monday as start of week. All days in a __eq__(self, other) a[0] 0 __cmp__(self, other) __ne__(self, other) a[5] 5 new year preceding the first Monday __index__(self) a[-1] 5 are considered to be in week 0. __hash__(self) a[-2] 4 __getattr__(self, name) a[1:] [1,2,3,4,5] __getattribute__(self, name) a[:5] [0,1,2,3,4] account of leap and double-leap __setattr__(self, name, attr) a[:-2] [0,1,2,3] seconds. __delattr__(self, name) a[1:3] [1,2] __call__(self, args, kwargs) a[1:-1] [1,2,3,4] b=a[:] Shallow copy of a __nonzero__(self) 4. This is not a mistake. Range takes Available free from AddedBytes.com DEFAULT DIRECTORY STRUCTURE rails_root app apis controllers application.rb helpers application_helper.rb models Methods Strings capitalize! center chomp! chop! concat count crypt delete! downcase! dump each each_byte empty? gsub! hash hex include? index intern length ljust, rjust next! oct replace reverse! rindex scan slice! split squeeze! strip! sub! sum swapcase! tr! tr_s! unpack upcase! upto Regex escape last_match new quote casefold? kcode match source Time asctime ctime day gmt? gmtime hour isdst localtime mday min mon month sec strftime tv_sec tv_usec usec utc utc? wday yday year zone views layouts components config environments development.rb production.rb test.rb database.yml environment.rb routes.rb db doc lib log development.log Methods PRE-DEFINED VARIABLES $! Exception information $& String of last match $` String left of last match $' String right of last match $+ Last group of last match $N Nth group of last match $= Case insensitive flag $/ Input record separator $\ Output record separator $, Output field separator $. Current line number of last file read $> Default output for print $_ Last input line of string $0 Name of script $* Command line arguments $stderr Standard error output $stdin Standard input $stdout Standard output $-a True if -a is set. $-d Status of -d switch $-l True if -l is set $-p True if -p is set $-v Verbose Flag production.log server.log test.log public images javascripts controls.js dragdrop.js effects.js prototype.js stylesheets .htaccess 404.html 500.html dispatch.cgi dispatch.fcgi dispatch.rb favicon.ico index.html script test fixtures functional mocks development test unit test_helper.rb vendor METHODS NOTE ! - Denotes where a tailing ! may be ! - used. A colourless ! denotes that the ! - ! is compulsory. RESERVED WORDS =begin elsif rescue =end end retry BEGIN ensure return END false self alias for super and if then begin in true break module undef case next unless class nil until def not when defined? or while do redo yield else REGULAR EXPRESSIONS SYNTAX ^ Start of string $ End of string . Any single character (a|b) a or b (...) Group section [abc] Item in range (a or b or c) [^abc] Not in range (not a or b or c) a? Zero or one of a a* Zero or more of a a+ One or more of a a{3} Exactly 3 of a a{3,} 3 or more of a Arrays assoc at clear collect! compact! concat delete delete_at delete_if each each_index empty? eql? fill first flatten! include? index indexes join last length nitems pack pop push rassoc reject! replace reverse! reverse_each rindex shift slice! sort! uniq! unshift Validation condition_block? create! evaluate_condition validate validate_on_create validate_on_update validates_acceptance_of validates_associated validates_confirmation_of validates_each validates_exclusion_of validates_format_of validates_inclusion_of validates_length_of validates_numericality_of validates_presence_of validates_size_of validates_uniqueness_of Enumerable Mixin collect each_with_index entries find find_all grep include? max min reject sort Between 3 and 6 of a !(pattern) "Not" prefix. Apply rule when Available free from ILoveJackDaniels.com URL does not match pattern. Ruby on Rails Logo used with permission. a{3,6} http://steve-parker.org/sh/sh.shtml v1.1 – 7 Aug 2007 UNIX / Linux Shell Cheat Sheet File Manipulation Test Operators Variable Substitution > file create (overwrite) file if [ “$x” -lt “$y” ]; then ${V:-def} $V, or “def” if unset >> file >file 2>&1 append to file both output and errors to file fi ${V:=def} ${V:?err} $V (set to “def” if unset) $V, or “err” if unset < file a|b read from file pipe output from 'a' as input to 'b' Numeric Tests Conditional Execution lt gt less than greater than c1 || c2 c1 && c2 read text eq ne equal to not equal Common utilities and switches echo “Line is $f” done < file file line by line ge le greater or equal less or equal $ grep foo myfile afoo find Common Constructs while read f do # do something run c1; if it fails, run c2 run c1; if it works, run c2 ls -lSr ls -ltr ls -lh list files, biggest last list files, newest last human-readable filesizes File Tests nt newer than du -sk * sort -n directory sizes (slow) sort numerically (not alpha) foo foobar matching lines d f is a directory is a file ps -ef wget URL list my commands download URL $ cut -d: -f5 /etc/passwd get field r w readable writeable time cmd touch file stopwatch on `cmd` create file with delimiter x executable read x cmd | \ read “x” from keyboard cmd output to stdout and String Tests = equal to tee file.txt nice cmd also to file.txt run cmd with low priority z n Networking Dilbert foo=`ls` get output of command case $foo in zero length not zero length a) echo “foo is A” case is a good way to avoid Logical Tests ifconfig -a netstat -r list all network interfaces show routers ;; b) echo “foo is B” iterating through many if/elif/elif/elif && || ! ssh u@host scp file.txt \ u@host: log in to host as user “u” copy file.txt to host as user “u” ;; *) logical AND logical OR logical NOT constructs. echo “foo is not A or B” ;; esac Argument Variables General Admin $0 $1 program name 1st argument less file alias l='ls -l' display file, page by page create “l” as alias for “ls -l” $2 ... 2nd argument ... tar cf t.tar \ list_of_files create a tar archive t.tar from the listed dirs/files doubleit() { expr $1 \* 2 function declaration $9 $* 9th argument all arguments cal 3 1973 df -h display a calendar (Mar 73) show disk mounts } doubleit 3 and calling syntax $# No. of arguments truss -p PID show syscalls of PID # returns 6 Files: Contents / Attributes A for loop for i in * do iterates through its input (which echo “File is $i” done is subject to globbing) find . -size 10k -print files over 10Kb find . -name “*.txt” -print find /foo -type d -ls find text files ls all directories three=`expr 1 + 2` under /foo simple maths echo "scale = 5 ; 5121 / 1024” | bc egrep “(foo|bar)” file better maths find “foo” or “bar” in file Useful Variables $IFS $? Internal File Separator return code from last program awk '{ print $5 }' file print the 5th word of each line $SHELL LANG what shell is running this script? Language; C is US English sed s/foo/bar/g file replace “foo” in file with “bar” A full PDF and online tutorial is available at http://steve-parker.org/sh/sh.shtml SQL Facts SQL stands for Structured Query Language SQL is pronounced “sequel” SQL is declarative language SQL is used to access & manipulate data in databases Top SQL DBs are MS SQL Server, Oracle, DB2, and MySQL Database Definitions RDBMS (Relational Database Management System) – Software that stores and manipulates data arranged in relational database tables. Table – A set of data arranged in columns and rows. The columns represent characteristics of stored data and the rows represent actual data entries. How to select data from a table SQL Commands Categories Data Query Language (DQL) SELECT - Retrieve data from table(s) Data Manipulation Language (DML) INSERT - Insert data into db table UPDATE - Update data in db table DELETE - Delete data from table Data Definition Language (DDL) CREATE - Create db object (table, view, etc.) ALTER - Modify db object (table, view, etc.) DROP - Delete db object (table, view, etc.) Data Control Language (DCL) GRANT - Assign privilege REVOKE - remove privilege How to insert data in a table SELECT <Column List> FROM <Table Name> WHERE <Search Condition> Example: SELECT FirstName, LastName, OrderDate FROM Orders WHERE OrderDate > '10/10/2010' INSERT INTO <Table Name> (<Column List>) VALUES (<Values>) Example: INSERT INTO Orders (FirstName, LastName, OrderDate) VALUES ('John', 'Smith', '10/10/2010') How to update data in a table How to delete data from a table UPDATE <Table Name> SET <Column1> = <Value1>, <Column2> = <Value2>, … WHERE <Search Condition> Example: UPDATE Orders SET FirstName = 'John', LastName = 'Who' WHERE LastName='Wo' DELETE FROM <Table Name> WHERE <Search Condition> Example: DELETE FROM Orders WHERE OrderDate < '10/10/2010' How to group data and use aggregates SELECT <Column List>, <Aggregate Function>(<Column Name>) FROM <Table Name> WHERE <Search Condition> GROUP BY <Column List> Example: SELECT LastName, SUM(OrderValue) FROM Orders WHERE OrderDate > '10/10/2010' GROUP BY LastName How to order data SELECT <Column List> FROM <Table Name> WHERE <Search Condition> ORDER BY <Column List> Example: SELECT FirstName, LastName, OrderDate FROM Orders WHERE OrderDate > '10/10/2010' ORDER BY OrderDate How to select data from more than one table SELECT <Column List> FROM <Table1> JOIN <Table2> ON <Table1>.<Column1> = <Table2>.<Column1> Example: SELECT Orders.LastName, Countries.CountryName FROM Orders JOIN Countries ON Orders.CountryID = Countries.ID CREATE TABLE <Table Name> ( Column1 DataType, Column2 DataType, Column3 DataType, …. ) Using UNION SELECT <Column List> FROM <Table1> UNION SELECT <Column List> FROM <Table2> Example: SELECT FirstName, LastName FROM Orders2010 UNION SELECT FirstName, LastName FROM Orders2011 CREATE TABLE CREATE TABLE Orders ( FirstName CHAR(100), LastName CHAR(100), OrderDate DATE, OrderValue Currency ) © http://www.SQL-Tutorial.net Cheat Sheet The most powerful Git client macOS Edition General ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ N T ⇧ ⇧ ⇧ R Open new window Open new tab O Show „Quick Open“ dialog A Show „Quick Actions“ dialog D Open external Diff tool Refresh / reload data Working Copy ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⇧ M ⇧ Merge R Rebase ⌘ ⌘ B ⇧ ⌘ ⌘ ⌘ Creating Branches & Tags ⇧ B Check out revision C Activate commit dialog RETURN SPACEBAR ⌘ Merging & Rebasing ⇧ ⇧ E Stage/unstage or Quicklook selected file (see Preferences) Stage all current changes ⇧ ⌥ ⇧ Confirm commit dialog S E Unstage all current changes Save to Stash ⇧ ⌥ S Apply Stash ⇧ BACKSPACE Discard local changes in selected file Create new branch T Create new tag Commit History + Remote Actions ⌘ Moving Between Views ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ CTRL CTRL 1 2 3 0 S R Show Services Show Repositories Show Working Copy ⌘ ⌘ ⌘ ⇧ ⇧ ⇧ F P U CTRL ⌘ C Show Stashes ⌘ Show HEAD branch ⌘ CTRL Show History Fetch CTRL Pull Push HEAD G Show / hide commit tree graph Copy SHA-1 hashes of selected commits to clipboard → Expand all diffs in changeset ← Collapse all diffs in changeset Download Tower for free at www.git-tower.com Tips & Tricks The most powerful Git client macOS Edition Drag & Drop Chunk & Line Staging Much of the „hard Git work“ can be performed easily in Tower - simply via drag & drop! Tower allows you to determine the exact changes you want to add to a commit - down to the level of chunks and even individual lines. Create, Pull, Push Branches: Drag a branch in the sidebar - and either drop it onto the Branches section header (to create a new branch) or drop it onto another branch (to merge, rebase, pull, or push). Select a changed file in the Working Copy list. In the diff view on the right, you can then select the exact chunks & lines you want to add to the next commit. Create Branches & Tags: Drag commits from the History views and drop them onto the Tags or Branches sections in the sidebar: this will create a new tag/branch based on the dragged commit. Cherry-Pick: Commits can also be dropped onto the Working Copy in the sidebar. This will cherry-pick the dropped commit. Apply Stashes: Drag one of the changed files in a Stash and drop it onto the Working Copy in the sidebar to only apply this very change. Commit Without the Mouse Crafting and confirming a commit can be done without taking your hands off the keyboard. In the Working Copy view, make sure that a changed file is selected: hit the Spacebar to stage/unstage an item use the up & down arrows on your keyboard to inspect other files hit ⌘ + ⇧ + C to focus the Commit area Default Cloning Directory In Tower‘s preferences dialog, you can configure a default directory for cloned repositories. Once configured, Tower will clone new repositories directly into this directory. after having entered a message, confirm the commit by hitting ⌘ + Return Quick Open To open or find a repository, you don‘t have to take your hands off the keyboard. Simply hit ⌘ + ⇧ + O to show Tower‘s Open Quickly window. Check Out Quickly In Tower, you can choose your favorite way to check out a branch: By default, the last opened repositories are shown. Simply start typing the name of a repository to begin searching. by double-clicking the branch in the sidebar by right-clicking the branch in the sidebar and selecting „Check Out“ by right-clicking the Working Copy item in the sidebar and selecting a branch in the „Check Out“ submenu by clicking the current branch‘s name above the list of changed files in the Working Copy view Learn More Our documentation has more tips, tricks, and keyboard shortcuts for you: Tower Help Tips & Tricks Keyboard Shortcuts Download Tower for free at www.git-tower.com Cheat Sheet The most powerful Git client General CTRL Working Copy N CTRL Open new window O CTRL Show „Quick Open“ dialog D F5 Open external Diff tool Refresh / reload data M CTRL CTRL ⇧ CTRL ⇧ CTRL Merge R Rebase B C RETURN SPACEBAR CTRL ⇧ Merging & Rebasing CTRL Windows Edition CTRL S CTRL ⇧ DELETE CTRL B ⇧ Activate commit dialog Confirm commit dialog Stage/unstage or Quicklook selected filesee Preferences) A Stage all current changes Save to Stash S Apply Stash Discard local changes in selected file Creating Branches & Tags CTRL Check out revision Create new branch T Create new tag Commit History + Remote Actions CTRL Moving Between Views ALT ALT CTRL CTRL CTRL CTRL S Show Services R 1 2 3 0 Show Repositories Show Working Copy Show History Show Stashes Show HEAD branch CTRL CTRL CTRL CTRL CTRL CTRL F P U G C Fetch Pull Push HEAD Show / hide commit tree graph Copy SHA-1 hashes of selected commits to clipboard → Expand all diffs in changeset ← Collapse all diffs in changeset Download Tower for free at www.git-tower.com Tips & Tricks The most powerful Git client Windows Edition Drag & Drop Chunk & Line Staging Much of the „hard Git work“ can be performed easily in Tower - simply via drag & drop! Tower allows you to determine the exact changes you want to add to a commit - down to the level of chunks and even individual lines. Create, Pull, Push Branches: Drag a branch in the sidebar - and either drop it onto the Branches section header (to create a new branch) or drop it onto another branch (to merge, rebase, pull, or push). Select a changed file in the Working Copy list. In the diff view on the right, you can then select the exact chunks & lines you want to add to the next commit. Create Branches & Tags: Drag commits from the History views and drop them onto the Tags or Branches sections in the sidebar: this will create a new tag/branch based on the dragged commit. Cherry-Pick: Commits can also be dropped onto the Working Copy in the sidebar. This will cherry-pick the dropped commit. Default Cloning Directory In Tower‘s preferences dialog, you can configure a default directory for cloned repositories. Once configured, Tower will clone new repositories directly into this directory. Combined with the Service Manager, cloning your repos from GitHub / Bitbucket / GitLab / other hosting services literally becomes a matter of a single click. Commit Without the Mouse Crafting and confirming a commit can be done without taking your hands off the keyboard. In the Working Copy view, make sure that a changed file is selected: hit the Spacebar to stage/unstage an item use the up & down arrows on your keyboard to inspect other files hit CTRL + ⇧ + C to focus the Commit area after having entered a message, confirm the commit by hitting CTRL + Return Quick Open To open or find a repository, you don‘t have to take your hands off the keyboard. Simply hit CTRL + O to show Tower‘s Open Quickly window. Check Out Quickly In Tower, you can choose your favorite way to check out a branch: By default, the last opened repositories are shown. Simply start typing the name of a repository to begin searching. by double-clicking the branch in the sidebar by right-clicking the branch in the sidebar and selecting „Check Out“ by right-clicking the Working Copy item in the sidebar and selecting a branch in the „Check Out“ submenu by clicking the current branch‘s name above the list of changed files in the Working Copy view Learn More Our documentation has more tips, tricks, and keyboard shortcuts for you: Tower Help Tips & Tricks Keyboard Shortcuts Download Tower for free at www.git-tower.com Build Better Software Over 100.000 developers and designers are more productive with TOWER - the most powerful Git client for Mac and Windows The new version gives you easy access to the full power of Git with an extensive set of new features including Pull Requests and Interactive Rebase. Try it Free for 30 Days www.git-tower.com Tower is loved by some of the best software and design teams in the world. Esteban Torres Engineer, SoundCloud Hector Simpson UI/UX Designer, Heroku Koen Bok CEO, Framer “The new Tower adds a lot of great features that help me go on with my day faster; like the ability to create pull requests directly from the tool.” “Tower is a vital tool in my workflow. It makes the more advanced things in Git intuitive and completely effortless.” „Tower is a pleasure to use while it retains the full power of Git. I enjoy using it every day for both design and code work.“ Download and try Tower for free at www.git-tower.com MAKE YOUR WEBSITE FASTER A cheat sheet presented by Tower - the best Git client for Mac and Windows REDUCING HTTP REQUESTS WORKING WITH IMAGES GET RID OF IMAGES CHECK FOR 404 ERRORS 404 errors are quick to get. Check your pages with your browser’s “Dev Tools” to make sure all of your requests find their target! CHECK FOR (UNNECESSARY) REDIRECTS Can you reduce the number of image files by: • using CSS? • using WebFonts? • eliminating images that you don’t need at all? Redirects are costly because they cause HTTP requests. Make sure you’re only redirecting when absolutely necessary! USE THE RIGHT IMAGE FORMAT Make sure your images are saved in the format that best suits the use case: CONCATENATE CSS & JAVASCRIPT Combining multiple resources in one output file saves expensive HTTP requests. Make sure you don’t deliver too many CSS and JavaScript files! • SVG is best suited for geometric shapes • JPG is ideal for photos & screen shots • PNG allows for transparency & maximum quality INCLUDE RESPONSIVE IMAGES COMBINE IMAGES IN SPRITE FILES Instead of delivering each graphic asset in its own file, you can bundle them in a single file. “Image Sprites” help reduce HTTP requests and are ideal for smaller graphic files like icons and logos. Different devices, with different screen sizes and pixel densities, demand for different versions of an image. Modern techniques allow you to deliver the optimal image while using as little bandwidth as possible. OPTIMIZE IMAGES Learn more about how to “Reduce HTTP Requests” Saving an image from Photoshop, Illustrator, or other design tools is not the end of the story. In most cases, you still have lots of room for optimization. Make sure your image assets use the best compression algorithms and the smallest file sizes! Learn more about “Working with Images” We make Tower The best Git client for Mac & Windows. We help over 100,000 users in companies like Apple, Google, Amazon, Twitter, and Facebook to easily & productively work with the Git version control system. Try it 30 days for free! MAKE YOUR WEBSITE FASTER A cheat sheet presented by Tower - the best Git client for Mac and Windows DELIVERING FILES FASTER OPTIMIZING CSS & JS CONFIGURE HTTP CACHING CSS & JAVASCRIPT IN EXTERNAL FILES Do you allow your files to be cached by the user’s browser? A lot of optimization potential is at your fingertips when using “HTTP Caching” effectively. Keeping CSS and JavaScript in (preferably few) external files allows the browser to cache them. Take advantage of this! MINIFY CSS & JAVASCRIPT ENABLE GZIP COMPRESSION Delivering your files with GZIP compression is easy to implement - and yet very effective. Make sure your web server delivers your files the right way. Make sure your CSS and JavaScript is delivered with as little “air” as possible: white space, comments, etc. are not necessary for the browser to understand your code. Minification helps ship the leanest file possible. SET UP A CDN OPTIMIZE CSS LOADING The geographical distance between a server and a visitor’s computer matters. Consider using a Content Delivery Network to always serve your files from as close as possible. Learn more about “Delivering Files Faster” Including CSS in your HTML pages can be done the “right” or the “wrong” way. Make sure: • CSS is included right at the top • @import is not used in your CSS • only CSS that is really necessary is delivered OPTIMIZE JAVASCRIPT LOADING The way you include JavaScript in your pages might slow them down. Make sure you: • load JavaScript libraries from Google’s Hosted Libraries CDN • load them with the “async” attribute or at least only at the bottom of your HTML • don’t load third-party libraries multiple times! Learn more about “Optimizing CSS & JavaScript” We make Tower The best Git client for Mac & Windows. We help over 100,000 users in companies like Apple, Google, Amazon, Twitter, and Facebook to easily & productively work with the Git version control system. Try it 30 days for free! Understanding the Workflow of Version Control presented by Tower - the best Git client for Mac and Windows The Basics 1 Work on an Existing Project Start a New Project $ git clone <remote-url> $ git init The “git clone” command is used to download a copy of an existing repository from a remote server. When this is done, you have a full-featured version of the project on your local computer – including its complete history of changes. Executing the “git init” command in the root folder of your new project creates a new and empty Git repository. You’re ready to start getting your files under version control! 2 File Status Work on Your Files Files that aren’t yet under version control are called “untracked”… ? Modify, rename and delete files or add new ones. Do all of this in your favorite editor / IDE / file browser – there‘s nothing to watch out for in this step! …while files that your version control system already knows about are “tracked” files. A tracked file can either be “unmodified” (meaning it wasn’t changed since the last commit)... m ...or “modified” (meaning it has local changes since it was last committed). 3 $ git status # # Changes not staged for commit: # modified: about.html # deleted: robots.txt # # Untracked files: # login.html # no changes added to commit Keep the Overview $ git status The “git status” command tells you what happened since the last commit: which files did you change? Did you create any new ones or delete old ones? 4 $ git add about.html # # Changes to be committed: # modified: about.html # # Changes not staged for commit: # deleted: robots.txt # # Untracked files: # login.html Add Files to the “Staging Area” $ git add <filename> Only because a file was changed doesn’t mean it will be part of the next commit! Instead, you have to explicitly decide which changes you want to include. To do this, you add them to the so-called “Staging Area” with the “git add” command. 5 Commit all Staged Changes $ git commit -m "message" $ git commit -m "Updated about page" A commit wraps up all the changes you previously staged with the “git add” command. To record this set of changes in Git’s database, you execute the “git commit” command with a short and informative message. [master 9d3f32b] Updated about page 1 file changed, 29 insertions(+) 6 Keep the Overview $ git status # # Changes not staged for commit: # deleted: robots.txt # # Untracked files: # login.html # no changes added to commit $ git status Running the “git status” command right after a commit proves to you: only the changes that you added to the Staging Area were committed. All other changes have been left as local changes: you can continue to work with them and commit or discard them later. 7 Inspect the Commit History $ git log $ git log commit 9d3f32ba002110ee0022fe6d2c5308 Author: Tobias Günther <tg@fournova.c Date: Mon Jul 8 09:56:33 2013 +0200 The “git log” command lists all the commits that were saved in chronological order. This allows you to see which changes were made in detail and helps you comprehend how the project evolved. Updated about page Branching & Merging 1 Understanding Branches BUGFIX #32 C4 C1 C3 C5 C7 FEATURE B C2 C6 We often have to work on multiple things in parallel: feature X, bugfix #32, feature Y… This makes it all too easy to lose track of where each change belongs. Therefore, it’s essential to keep these contexts separate from each other. Start a New Feature $ git branch <new-branch-name> Whenever you start a new feature, a new experiment or a new bugfix, you should create a new branch. In Git, this is extremely fast and easy: just call “git branch <new-branch-name>” and you have a new, separate context. Grouping related changes in their own context has multiple benefits: your coworkers can better understand what happened because they only have to look at code that really concerns them. And you can stay relaxed, because when you mess up, you mess up only this context. Don’t be shy about creating new branches: it costs you nothing. Branches do just this: they provide a context that keeps your work and your changes separate from any other context. 2 HEAD Branch C6 Switch Contexts C1 $ git checkout <new-branch-name> C4 C2 To start working on a different context, you need to tell Git that you want to switch to it. You do this by “checking out” the branch with the “git checkout” command. C3 feature-b master C5 feature-a C7 HEAD At each point in time, you can only work in one context – the context of the currently checked out branch (which is also called the “HEAD” branch in Git). Every commit you make – until you switch branches again – will be recorded in this branch and kept separate from your other contexts. Your project’s working directory contains the files that correspond to this branch. When you check out a different branch (make it “HEAD”), Git replaces the files in your working directory with the ones that match this branch. 3 Integrate Changes $ git merge <branch-to-integrate> When your new feature is ready, you might want to integrate it into another branch (e.g. your production or testing branch). First, switch to the branch that is supposed to receive these changes. Then, call the “git merge” command with the name of the branch you want to integrate. Sharing Work via Remote Repositories 1 Track a Remote Branch $ git checkout --track <remote/branch> If there’s an interesting remote branch that you want to work on, you can easily get your own local copy. Use the “git checkout” command and tell it which remote branch you want your new local branch to base off. 2 Publish a Local Branch $ git push -u <remote> <local-branch> To share one of your local branches with your teammates, you need to publish it on a remote server with the “git push” command. Local & Remote Repositories MODIFY, ADD & DELETE FILES Stay Up-To-Date About Remote Changes $ git fetch <remote> When collaborating with others on a project, you’ll want to stay informed about their changes. The “git fetch” command downloads new changes from a remote repository – but doesn’t integrate them into your local working copy. It only informs you about what happened on the remote, leaving the decision on what to integrate to you. 3 LOCAL COMPUTER LOCAL REPOSITORY REMOTE SERVER SHARE WORK COLLABORATE REMOTE REPOSITORY VIEW HISTORY ADD & DELETE BRANCHES As Git is a so-called “decentralized” version control system, a remote repository is optional. In fact, everything we did until now happened on your local machine, in your local repository – no internet/network connection was necessary. However, if you want to collaborate with others, you need a remote repository on a server. You don’t have to share all of your work though: you can decide for each of your local branches if you want to share it or not. Integrate Remote Changes $ git pull To integrate new changes from the remote repository, you simply call “git pull”. This will update your current HEAD branch with new data from its counterpart branch on the remote. The changes will be directly merged into your local working copy. 4 Upload Local Changes to the Remote Server $ git push To upload the local changes you made in your current HEAD branch, all you have to do is call “git push”. The best Git Client for Mac & Windows 30-day free trial available at www.git-tower.com XCODE CHEAT SHEET presented by Tower - the best Git client for Mac and Windows NAVIGATION SEARCH ⌘ Find in File F Find & Replace in File ⌘ ⌥ F Find in Project ⌘ ⇧ F ⌥ ⇧ F Find & Replace in Project ⌘ ⌘ Open Quickly O ⌘ ⌘ Next Counterpart ⌃ J UP Previous Counterpart ⌘ ⌃ DOWN Next Recent File ⌘ ⌃ RIGHT ⌘ New Tab ⌘ T Go to Line Previous Tab ⌘ } Fold Section Next Tab ⌘ { Unfold Section NAVIGATOR ⌘ ⌘ ⌘ 0 1–8 Toggle Debug Area ⌘ ⌃ E Indent Selection ⌘ ] i Comment / Uncomment ⌘ / ⌥ ⌥ L LEFT RIGHT Move Line Up ⌘ ⌥ [ Move Line Down ⌘ ⌥ ] ⌘ ⌥ 0 UTILITIES ⌘ ⇧ ⌘ Next Issue Y Show / Hide ' Switch Tabs …open in Assistant Editor Toggle Breakpoints ⌘ Y Clear Console ⌘ K ⌥ click DOCUMENTATION ⇧ 0 Documentation for for Selection ⌘ ⌥ ⌃ / 30-day free trial available at www.git-tower.com Edit All in Scope ⌃ " ⌘ SPACE Fix Indentation \ Show Documentation ⌃ click ⌘ ⇧ Help for Clicked Symbol Documentation for Clicked Symbol ⌥ RETURN ⌘ ⌘ …open in New Window double click ⌘ Toggle Completions [ Add Breakpoint click RETURN ⌘ Previous Issue ⌥ ⌥ Outdent Selection When Clicking a File in Navigator… …decide where to open Hide Assistant Editor DEBUGGING Show / Hide ⌘ LEFT ⌘ ⌘ Show Assistant Editor ⌃ Definition of Symbol Switch Tabs ⇧ Move Focus to Editor Previous Recent File TABS EDITING ⌥ ⌘ ⌥ BUILD & RUN Build ⌘ B Run ⌘ R Stop click double click 1–9 Analyze ⌘ Test Clean ⌘ ⌘ . ⇧ B ⌘ U ⇧ K The best Git Client for Mac & Windows XCODE TIPS & TRICKS presented by Tower - the best Git client for Mac and Windows 1. DECIDE WHERE TO OPEN A FILE 4. TABS In Xcode, you can open a file in various ways: in the standard Tabs are well-known from almost every IDE and text editor. editor, in a new or existing assistant editor, in a new or existing However, three things make tabs in Xcode especially powerful: tab, or in a new window. Here’s how you can decide about this: — When clicking on a file in the Navigator, hold down ⌥ ⇧ ⌥ tab could contain just two editor panes, while another one could — When clicking on a symbol in an editor pane, hold down ⌘ a) Each tab can be configured individually. For example, one contain the project navigator, a single editor pane, and the ⇧ utilities area. You can therefore configure tabs that are A pop-over will appear and let you choose where exactly you optimized for different use cases (like coding, debugging, want the file to be displayed. interface builder tasks, etc). b) Tabs persist in a workspace. When reopening a project, 2. OPEN QUICKLY Xcode restores its tabs — including their unique structure. You shouldn’t waste your time digging for a file in your folder This makes it worthwhile to take some time to configure hierarchy. Instead, you can use Xcode’s “Open Quickly” dialog your “perfect” setup. by pressing ⌘ ⇧ O . Simply start typing any part of a file’s name — it doesn’t even have to be consecutive letters: c) By double-clicking a tab, you can assign it a name. Named tabs can then be used in “Behaviors” (see #5). “mwinco” will find your ”MainWindowController” class. 5. BEHAVIORS As if that wouldn‘t be cool enough, this dialog also lets you decide where exactly to open the file: hold down ⌘ ⌥ ⇧ while double-clicking the file to bring up the pop-over from #1. With “Behaviors”, you can tell Xcode how to react when certain events happen. For example, you could have the console view shown whenever your app starts running, or you could have a 3. CUSTOM CODE SNIPPETS new tab opened whenever you start a search. Whenever you find yourself typing the same bits of code mul- This becomes even more powerful when combined with named tiple times, you should create a code snippet. To do that, first tabs. For example, whenever your app pauses, you can have make sure that the “Code Snippet Library” pane is displayed Xcode open your named tab “Debug” — a tab that you configu- by pressing ⌘ red exactly how you want it to look (maybe with an assistant ⌥ ⌃ 2 . Now go back to your editor pane and start typing what will soon be a custom snippet — and remember to insert placeholders for values you have to fill out when invoking it (e.g. editor and the debugger shown, but the project navigator hidden). Behaviors can be configured in Xcode’s preferences window. “<#token#>”). KEYBOARD SYMBOLS Then highlight and drag that code to the library pane. Apart from naming it, you should also define a “Completion Shortcut”: when you type these letters later, Xcode will offer to substitute them with your custom snippet. ⌘ Command key ⌥ Option (alt) key ⌃ Control key ⇧ Shift key VERSION CONTROL Go beyond Xcode‘s basic version control support and combine it with Tower — the most powerful Git client for Mac. Try it free for 30 days. 30-day free trial available at www.git-tower.com The best Git Client for Mac & Windows