connect_to_db();
in PHP. it knows if im in a development or production environment, knows the proper username and password, and connects.
Very basic i know, and im sure everyone has written a similar function, but super useful.
If I'm not mistaken, that has the same semantics as the standard one line event definition, i.e.:
public event EventHandler MyEvent;
// Inside the class, MyEvent is bound to a multicast delegate.
// Outside the class, MyEvent is bound to an auto-generated add/remove mechanism.
// So MyEvent can only be set to null or invoked from inside the class.
I also see this post explaining the presence of the -webkit-background-clip (http://tumble.sneak.co.nz/post/928998513/fixing-the-backgrou...), but I don't see that behavior in Safari 5. Potentially fixed? If not, I would certainly add that to my boilerplate.
I wrote this simple Python function to create random strings from various character sets. I wish every NES game that had a password-based save used 'alpha_numeric_hardtoconfuse_lowercase'. There's no telling how many times I've mixed up 1, I, i, and l, pending on the crappy font being used. Same goes with hand-written Windows activation keys.
# encoding: utf-8
import random
CHARACTER_SETS = {
'alpha': 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', # 52
'alpha_lowercase': 'abcdefghijklmnopqrstuvwxyz', # 26
'alpha_uppercase': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', # 26
'alpha_numeric': 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', # 62
'alpha_numeric_lowercase': 'abcdefghijklmnopqrstuvwxyz0123456789', # 36
'alpha_numeric_uppercase': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', # 36
'alpha_hardtoconfuse': 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ', # 47 --- Omits: i, l, o, I, O
'alpha_hardtoconfuse_lowercase': 'abcdefghjkmnpqrstuvwxyz', # 23 --- Omits: i, l, o
'alpha_hardtoconfuse_uppercase': 'ABCDEFGHJKLMNPQRSTUVWXYZ', # 24 --- Omits: I, O
'alpha_numeric_hardtoconfuse': 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789', # 55 --- Omits: i, l, o, I, O, 0, 1
'alpha_numeric_hardtoconfuse_lowercase': 'abcdefghjkmnpqrstuvwxyz23456789', # 31 --- Omits: i, l, o, 0, 1
'alpha_numeric_hardtoconfuse_uppercase': 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789', # 32 --- Omits: I, O, 0, 1
'alpha_consonants': 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ', # 42 --- Omits: a, e, i, o, u, A, E, I, O, U
'alpha_consonants_lowercase': 'bcdfghjklmnpqrstvwxyz', # 21 --- Omits: a, e, i, o, u
'alpha_consonants_uppercase': 'BCDFGHJKLMNPQRSTVWXYZ', # 21 --- Omits: A, E, I, O, U
'alpha_numeric_consonants': 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ0123456789', # 52 --- Omits: a, e, i, o, u, A, E, I, O, U
'alpha_numeric_consonants_lowercase': 'bcdfghjklmnpqrstvwxyz0123456789', # 31 --- Omits: a, e, i, o, u
'alpha_numeric_consonants_uppercase': 'BCDFGHJKLMNPQRSTVWXYZ0123456789', # 31 --- Omits: A, E, I, O, U
'alpha_consonants_hardtoconfuse': 'bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ', # 41 --- Omits: a, e, i, l, o, u, A, E, I, O, U
'alpha_consonants_hardtoconfuse_lowercase': 'bcdfghjkmnpqrstvwxyz', # 20 --- Omits: a, e, i, l, o, u
'alpha_consonants_hardtoconfuse_uppercase': 'BCDFGHJKLMNPQRSTVWXYZ', # 21 --- Omits: A, E, I, O, U
'alpha_numeric_consonants_hardtoconfuse': 'bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ23456789', # 49 --- Omits: a, e, i, l, o, u, A, E, I, O, U, 0, 1
'alpha_numeric_consonants_hardtoconfuse_lowercase': 'bcdfghjkmnpqrstvwxyz23456789', # 28 --- Omits: a, e, i, l,...
def history(num=100)
h = Readline::HISTORY.to_a
start = [0,h.size-num-1].max
h.zip((0..h.size).to_a)[start...h.size].each do |cmd,i|
puts " #{(i).to_s.rjust(4)} #{cmd}"
end
end
I keep it in my .irbrc file, really useful to avoid stepping through command history to find previous commands.
Possibly the most critical code in my application:
#Non-destructive. Returns the input array/list in randomized order. Uses approximately O(n) time and O(n) space.
def self.shuffle_array(array)
shallow_copy = array.map {|a| a}
shallow_copy.size.downto(1) {|n| shallow_copy.push(shallow_copy.delete_at(rand(n)))
shallow_copy
end
I know nothing about Ruby, but it's possible if a language implements an array as a linked list so the tail elements don't actually move. (At any rate, I hardly think we're worried about a modern computer workload of at most 25^2 string operations.)
A little bit of python that makes it easier to do shell-style scripting.
def call(cmd):
args = shlex.split(str(cmd))
p = Popen(args, stdout=PIPE, stderr=PIPE)
text = p.stdout.read()
if not text:
text = p.stderr.read()
return text
I don't have the exact example here, but I have a PHP function which takes a (newly deprecated) mysql result, and returns an array of rows as associative arrays with the keys lowercased.
I particularly like an alternate version I wrote of that which returns an associative array keyed by a given database field instead of a regular linear array. I don't need it as much, though.
(If this is still active on Monday, I'll post my real code)
I wrote a C#/.NET function (extension method) called `Becomes` that I use as a replacement for the various `TryParse` methods.
Example:
let n be an int
n.Becomes("2") //returns 2
n.Becomes("sdfsd") //returns n
0.Becomes("12") returns 12
0.Becomes("sdssdf") returns 0
Non-contrived example:
var person = Person.Get(0.Becomes(Request.QueryString["id"]));
Basically, given the expression
n.Becomes(SOME_STRING)
if `SOME_STRING` can be parsed as whatever the type of `n` is then it returns the the parsed result, else it returns (the value of) `n`.
More technically, `Becomes` returns a `ParseAttemptResult<T>` that is implicitly convertible to `T`. It also has `true` and `false` operators so that it can be used in an expression expecting a `Boolean` (e.g. `if` and the ternary operator`?:`).
In multiple languages (perl, haskell), I find myself writing a function that runs a system command and returns False (or sometimes, throws an exception) if it failed nonzero.
Also, in haskell I use these frequently to have monadic versions of some common flow control functions (some nonstandard libraries have similar functions to these but it's easier to write my own):
whenM c a = c >>= flip when a
unlessM c a = c >>= flip unless a
(>>?) = whenM
(>>!) = unlessM
-- low fixity allows eg, foo bar >>! error $ "failed " ++ meep
infixr 0 >>?
infixr 0 >>!
I did the same; I had a simple "def()" and "undef()" function pair, which shrank the code base a tiny bit and made it terribly easy to understand what conditions I was testing for.
Unfortunately, I recently profiled my code and found that those functions were being called an absurd number of times during a moderately complicated page load, so they're gone now. :-(
Yeah. Although, in modern browsers, the overhead is really trivial.
I just tried timing it in modern Chrome. The overhead of calling a function like isDefined(), versus typeof x !== 'undefined', seems trivial. On my machine, after 100,000 calls there's a difference of 50ms.
Still, I concede that there are some situations where it would matter, if you were driving an animation. And in older browsers it might matter a lot even in other circumstances.
I completely agree with you, but I would use "foo === undefined" for locals and "this/window.foo === undefined" for globals.
You can also test for "== null", if you don't care for null values.
Of course due to a bug in the old (v3) spec, you could redefine the builtin undefined as well as some other builtins like NaN and Infinity, but you shouldn't really be doing that and the spec at least is now fixed.
In the meanwhile, to fight that, this is a commonly used pattern for browsers:
(function(window,undefined) {
Maybe I don't understand your use case, but it seems to me your function is masking some other problems. You say you're new to JS, so here's a little unsolicited advice...
If you find yourself retyping the same jQuery selectors over and over, or that the structure changes a lot, then you should be encapsulating that somehow into some other function or object. Instead you're writing a do-it-all function that takes more strokes to type than the original jQuery selectors!
I haven't seen the structure in question, but when I see a class called something very generic like "node", I suspect something else is wrong. If the class isn't specific and at least somewhat meaningful to a person, then you might be solving the problem at the wrong level, using classes when a rethink of the structure might be better.
Also... lack of semicolons is bad style. Lack of braces for if clauses is bad style. Fix it, you'll thank me later. :)
> you should be encapsulating that somehow into some other function or object
Hmm, I believe that's what I'm doing here. This pattern is nice because it's small, simple and easily applied anywhere.
> when I see a class called something very generic like "node"
This is for http://taskranger.com Node is a node in the tree. Might make more sense knowing that.
> lack of semicolons is bad style. Lack of braces for if clauses is bad style.
I'm aware of the consensus, but I'm pretty sure it's wrong :) Semicolons and unnecessary braces create noise and take up space. This subtly harms readability. I've been doing this for about a year and have had no problems.
"Also... lack of semicolons is bad style. Lack of braces for if clauses is bad style. Fix it, you'll thank me later. :)"
Although a popular opinion, it's still just an opinion -- one I strongly disagree with. Almost all semicolon problems in javascript are not caused by not using them, they're caused by not understanding when they will be inserted. The infamous example:
function func(param, param2) {
var meh = 0, gah = 0;
<some more logic here>;
return
{ meh: meh
, gah: gah
};
}
Note: using a semicolon did not save you from returning undefined.
My point is that whether you use or don't use semicolons is not the problem. Not understanding when and how they're inserted is the problem.
I also find that people who do not use semicolons have a much better understanding of the few situations where they are actually needed to avoid errors.
I make lowerTrim and upperTrim functions in any language I work in - change the case and trim the string. Makes things pretty easy.
// PHP example
function lowerTrim($t) {
return strtolower(trim($t));
}
I also have matchLeft and matchRight which take two strings and return true if both strings are non-blank and the shorter matches the longer string's prefix/suffix.
My most-used function during debug-phase is pR:
// especially useful when dealing with PHP arrays/objects
function pR($a)
{
echo '<pre>';
print_r($a);
exit;
}
"src". Takes the name of a variable (usually a function) and searches my source directory for definitions of that variable. The way it recognizes definitions is fairly ad-hoc (it recognizes "def", "mac", "defmemo", and a few others; it doesn't attempt to recognize forms like "(let x 2 (def ...))").
arc> src.src
From: /Users/waterhouse/Dropbox/arc3.1/a
(mac src (name (o strict t))
`(src-fn ',name
',strict))
Found 1 results in 1 different files.
"aps". Apropos; derived from the Common Lisp function. Returns all bound variable names of which the supplied argument is a substring.
93 comments
[ 2.5 ms ] story [ 172 ms ] threadIn SCSS I use a very simple mixin for rounded corners, something I use frequently when designing sites.
Then in the class just add:I also see this post explaining the presence of the -webkit-background-clip (http://tumble.sneak.co.nz/post/928998513/fixing-the-backgrou...), but I don't see that behavior in Safari 5. Potentially fixed? If not, I would certainly add that to my boilerplate.
Mathematica code. Sets the CWD for file operations for a notebook to the same directory the current file is in. This is not default for Mac OSX.
I particularly like an alternate version I wrote of that which returns an associative array keyed by a given database field instead of a regular linear array. I don't need it as much, though.
(If this is still active on Monday, I'll post my real code)
Example:
Non-contrived example: Basically, given the expression if `SOME_STRING` can be parsed as whatever the type of `n` is then it returns the the parsed result, else it returns (the value of) `n`.More technically, `Becomes` returns a `ParseAttemptResult<T>` that is implicitly convertible to `T`. It also has `true` and `false` operators so that it can be used in an expression expecting a `Boolean` (e.g. `if` and the ternary operator`?:`).
Github Repo: https://github.com/noblethrasher/Parser-Helpers/blob/master/...
Also, in haskell I use these frequently to have monadic versions of some common flow control functions (some nonstandard libraries have similar functions to these but it's easier to write my own):
Unfortunately, I recently profiled my code and found that those functions were being called an absurd number of times during a moderately complicated page load, so they're gone now. :-(
I just tried timing it in modern Chrome. The overhead of calling a function like isDefined(), versus typeof x !== 'undefined', seems trivial. On my machine, after 100,000 calls there's a difference of 50ms.
Still, I concede that there are some situations where it would matter, if you were driving an animation. And in older browsers it might matter a lot even in other circumstances.
Of course due to a bug in the old (v3) spec, you could redefine the builtin undefined as well as some other builtins like NaN and Infinity, but you shouldn't really be doing that and the spec at least is now fixed.
In the meanwhile, to fight that, this is a commonly used pattern for browsers: (function(window,undefined) {
// code //
})(this);
That way if I change the html structure I don't have to to change a million jquery selectors, I can just change the from function in one place.
(I'm still somewhat new to Javascript, so this may be a well-known pattern.)If you find yourself retyping the same jQuery selectors over and over, or that the structure changes a lot, then you should be encapsulating that somehow into some other function or object. Instead you're writing a do-it-all function that takes more strokes to type than the original jQuery selectors!
I haven't seen the structure in question, but when I see a class called something very generic like "node", I suspect something else is wrong. If the class isn't specific and at least somewhat meaningful to a person, then you might be solving the problem at the wrong level, using classes when a rethink of the structure might be better.
Also... lack of semicolons is bad style. Lack of braces for if clauses is bad style. Fix it, you'll thank me later. :)
Hmm, I believe that's what I'm doing here. This pattern is nice because it's small, simple and easily applied anywhere.
> when I see a class called something very generic like "node"
This is for http://taskranger.com Node is a node in the tree. Might make more sense knowing that.
> lack of semicolons is bad style. Lack of braces for if clauses is bad style.
I'm aware of the consensus, but I'm pretty sure it's wrong :) Semicolons and unnecessary braces create noise and take up space. This subtly harms readability. I've been doing this for about a year and have had no problems.
I do appreciate the suggestions, though.
Although a popular opinion, it's still just an opinion -- one I strongly disagree with. Almost all semicolon problems in javascript are not caused by not using them, they're caused by not understanding when they will be inserted. The infamous example:
Note: using a semicolon did not save you from returning undefined.My point is that whether you use or don't use semicolons is not the problem. Not understanding when and how they're inserted is the problem.
I also find that people who do not use semicolons have a much better understanding of the few situations where they are actually needed to avoid errors.
My most-used function during debug-phase is pR: