recentpopularlog in

kme : idiom   104

« earlier  
What is the !! (not not) operator in JavaScript? - Stack Overflow
An easy way to describe it is: Boolean(5) === !!5; Same casting, fewer characters
devel  javascript  boolean  idiom  syntax  newbie  dammitbrain 
september 2019 by kme
bash - REOPEN: Perform arithmetic expansion inside parameter expansion? - Unix & Linux Stack Exchange
Again with the 'set' trick for testing script arguments interactively:
<code class="language-bash">set 6 7; echo $(($1*$2))</code>
bash  parameterexpansion  arithmeticexpansion  shellscripting  parameters  positionalarguments  idiom  tipsandtricks 
june 2019 by kme
Dry Run « The Word Detective | http://www.word-detective.com/
Beginning in the late 19th century, fire departments in the US began conducting practice sessions where engines were dispatched and hoses deployed, but water was not pumped, thus making the exercises literally “dry” runs. Public exhibitions and competitions between departments also typically centered on such “dry runs.” Conversely, a real run to a “working fire” where water was pumped was known as a “wet run.” In his posting to the ADS list, Doug Wilson found instances of this use of “dry run” dating back to 1893. Just when the term came into more general use meaning “practice session” is uncertain, but it seems to have been after “dry run” was widely used in the US Armed Services during World War II.
english  language  idiom  colloqualism  solution 
may 2019 by kme
Primer on Python Decorators – Real Python | https://realpython.com/
<code class="language-python">
def repeat(_func=None, *, num_times=2):
def decorator_repeat(func):
@functools.wraps(func)
def wrapper_repeat(*args, **kwargs):
for _ in range(num_times):
value = func(*args, **kwargs)
return value
return wrapper_repeat

if _func is None:
return decorator_repeat
else:
return decorator_repeat(_func)
</code>
python  newbie  language  idiom  decorators  solution 
november 2018 by kme
The Grammarphobia Blog: Far be it from me … | https://www.grammarphobia.com/
A: The correct expression is, as you say, “far be it from me.” The Oxford English Dictionary says the phrase is “a form of deprecation” equal to “God forbid that (I, etc.).”
grammar  solution  english  idiom  colloquialism 
may 2018 by kme
transform hash key from string into symbol - Ruby Forum | https://www.ruby-forum.com/
This was handy, but I found a different way by just iterating over the array and returning another (two-element) array inside a 'map' or a 'each_key' or something, then passing this to the Hash#[] constructor.

<code class="language-ruby">class Hash
def symbolize_keys
replace(inject({}) { |h,(k,v)| h[k.to_sym] = v; h })
end
end</code>
ruby  arrays  hashes  map  fp  idiom  newbie  syntax  solution 
may 2018 by kme
syntax - What do the different brackets in Ruby mean? - Stack Overflow | https://stackoverflow.com/
[] can be overridden as a custom method, and is generally used to fetch things from hashes (the standard library sets up [] as a method on hashes which is the same as fetch)
There is also a convention that it is used as a class method in the same way you might use a static Create method in C# or Java. e.g.
<code class="language-ruby">
a = {1 => 2} # create a hash for example
puts a[1] # same as a.fetch(1), will print 2

Hash[1,2,3,4] # this is a custom class method which creates a new hash</code>
ruby  syntax  brackets  braces  idiom  arrays  hashes  annoyance  solution 
may 2018 by kme
"sneaky suspicion" v "sneaking suspicion" - Google Groups | https://groups.google.com/
A "sneaking suspicion" is one that you arrive at in tiny increments...a "sneaky suspicion", if there is such a thing, is suspecting that someone is being sneaky....r
english  idiom  solution 
april 2018 by kme
python - More Pythonic Way to Run a Process X Times - Stack Overflow


Which is more pythonic?

While loop:

<code class="language-python">
count = 0
while count < 50:
print "Some thing"
count = count + 1
</code>

For loop:

<code class="language-python">
for i in range(50):
print "Some thing"
</code>

Edit: not duplicate because this has answers to determine which is clearer, vs. how to run a range without 'i' -- even though that ended up being the most elegant
python  idiom  solution 
november 2017 by kme
Accessing the index in Python 'for' loops - Stack Overflow
Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic.

The better option is to use the built-in function enumerate(), available in both Python 2 and 3:

for idx, val in enumerate(ints):
print(idx, val)
python  loops  pythonic  idiom  solution 
june 2017 by kme
How to get the nth element of a python list or a default if not available - Stack Overflow
x[index] if len(x) > index else default

to support negative indices we can use:

x[index] if -len(l) <= index < len(l) else default
python  arrays  idiom  solution 
april 2017 by kme
Yak Shaving
You see, yak shaving is what you are doing when you're doing some
stupid, fiddly little task that bears no obvious relationship to what
you're supposed to be working on, but yet a chain of twelve causal
relations links what you're doing to the original meta-task.


"I was working on my thesis and realized I needed a reference. I'd
seen a post on comp.arch recently that cited a paper, so I fired up
gnus. While I was searching the for the post, I came across another
post whose MIME encoding screwed up my ancient version of gnus, so I
stopped and downloaded the latest version of gnus.


"Unfortunately, the new version of gnus didn't work with emacs 18, so
I downloaded and built emacs 20. Of course, then I had to install
updated versions of a half-dozen other packages to keep other users
from hurting me. When I finally tried to use the new gnus, it kept
crapping out on my old configuration. And that's why I'm deep in the
gnus info pages and my .emacs file -- and yet it's all part of working
on my thesis."
hacker  culture  language  idiom  dependencyhell 
january 2017 by kme
python - Import a module from a relative path - Stack Overflow
import os, sys, inspect
# realpath() will make your script run, even if you symlink it :)
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)

# use this if you want to include modules from a subfolder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)

# Info:
# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
# __file__ fails if script is called in different ways on Windows
# __file__ fails if someone does os.chdir() before
# sys.argv[0] also fails because it doesn't not always contains the path


This also works, but it's fragile:

You could also add the sub directory to your python path so that it imports as a normal script.

import sys
sys.path.append( <path to dirFoo> )
import Bar
python  imports  classpath  idiom  maybesolution 
july 2016 by kme
Can anyone explain python's relative imports? - Stack Overflow
The solution was to put the "runner" script *next to* the top-level package directory, because even if you put it *in* the package directory, as soon as you run it directly (as an argument to the interpreter), it forgets that it's in a package. and you get an error like "Attempted relative import beyond toplevel package".

So if, for instance, you had a 'pkg/start.py' and you ran it like:

python pkg/start.py

__name__ inside that script would be '__main__' and sys.argv[0] is just the script name ('pkg/start.py', probably), and Python would have no other information from the environment with which to work out "relative" imports like "from .. import settings" or "from .sub import relative".
You are importing from package "sub". start.py is not itself in a package even if there is a __init__.py present.

You would need to start your program from one directory over parent.py:

./start.py

./pkg/__init__.py
./pkg/parent.py
./pkg/sub/__init__.py
./pkg/sub/relative.py

With start.py:

import pkg.sub.relative

Now pkg is the top level package and your relative import should work.
python  imports  annoyance  idiom  newbie  reference  fuckina  solution 
july 2016 by kme
The bee's knees - meaning and origin.
Nor is there any connection with another earlier phrase, 'a bee's knee'. In the 18th century this was used as a synonym for smallness, but has since disappeared from the language, replaced more recently by the less polite 'gnat's bollock':

Mrs. Townley Ward - Letters, June 1797 in N. & Q. "It cannot be as big as a bee's knee."

'Bee's knees' began to be used in early 20th century America. Initially, it was just a nonsense expression that denoted something that didn't have any meaningful existence - the kind of thing that a naive apprentice would be sent to the stores to ask for, like a 'sky-hook' or 'striped paint'. That meaning is apparent in a spoof report in the New Zealand newspaper The West Coast Times in August 1906, which listed the cargo carried by the SS Zealandia as 'a quantity of post holes, 3 bags of treacle and 7 cases of bees' knees'. The teasing wasn't restricted to the southern hemisphere. The US author Zane Grey's 1909 story, The Shortstop, has a city slicker teasing a yokel by questioning him about make-believe farm products:

"How's yer ham trees? Wal, dog-gone me! Why, over in Indianer our ham trees is sproutin' powerful. An' how about the bee's knees? Got any bee's knees this Spring?"
language  english  idiom 
april 2016 by kme
Acid test - meaning and origin.
Gold prospectors and dealers need to be able to distinguish gold from base metal. The original acid test was developed in the late 18th century and relied on nitric acid's ability to dissolve other metals more readily than gold. To confirm that a find was gold it was given 'the acid test'. A test sample was used to mark a touchstone and the degree to which it dissolved when the acid was added determined whether it was gold. Various other later tests also used acid and these are all called 'acid tests'.
idiom  english  language 
april 2016 by kme
Break a leg - meaning and origin.
The word 'break' has many meanings - the OED lists 57 distinct uses of it as a verb alone. That gives considerable scope for speculation over what is meant by this phrase. The most common interpretation of 'break' in this context is 'to deviate from a straight line', as in the cricketing term 'off break', to unstraighten the leg by bending at the knee, by bowing or curtseying.

There is a German saying 'Hals und Beinbruch', meaning 'break your neck and leg', which dates back to at least WWII as Luftwaffe slang, and is therefore earlier than any known English version. It may be that this is a corruption of the Hebrew blessing 'hatzlakha u-brakha', meaning 'success and blessing'.
idiom  english  german  language 
april 2016 by kme
Get down to brass tacks - meaning and origin.
\
Of the supposed explanations that don't have literal allusions, we can rule out links with any form of 'brass tax'. There have been taxes on brass at various times, but no one can find any connection with this phrase. 'Getting down to brass tax' appears to be just a misspelling. The expression is also often said to be an example of Cockney rhyming slang, meaning 'facts'. In the strange world of Cockney argot, 'tacks' does indeed rhyme with 'facts' (facks), but that's as far as it goes. Rhyming slang coinages from the 19th century are limited to the UK and Australia. The apparent US origin of the phrase discounts the rhyming slang origin.</blockquote
english  language  idiom  answered 
april 2016 by kme
Going to hell in a handbasket - meaning and origin.
Let's launch 'going to hell in a hovercraft' and see if that flies, so to speak.
idiom  language  english 
april 2016 by kme
regex - How do I perform a Perl substitution on a string while keeping the original? - Stack Overflow
This is the idiom I've always used to get a modified copy of a string without changing the original:

(my $new = $original) =~ s/foo/bar/;

In perl 5.14.0 or later, you can use the new /r non-destructive substitution modifier:

my $new = $old =~ s/foo/bar/r;
perl  regexp  idiom  dammitbrain  solution 
october 2015 by kme
How can I print source line number in Perl? - Stack Overflow
print "File: ", __FILE__, " Line: ", __LINE__, "\n";

or

warn("foo");
perl  idiom  solution  programming  webdevel 
january 2015 by kme
How do I get the full path to a Perl script that is executing? - Stack Overflow
$0 is typically the name of your program, so how about this?

use Cwd 'abs_path';
print abs_path($0);

Seems to me that this should work as abs_path knows if you are using a relative or absolute path

Here's what I came up with for the test I was trying to write:
use Test::More qw(no_plan);
use Cwd qw(abs_path);
use File::Basename;

## TEST ## Does the module load?
BEGIN {
my $modpath = dirname(abs_path($0)) . '/..';
unshift @INC, $modpath;
use_ok('ConfigParser');
}
perl  scripting  devel  idiom  solution 
october 2014 by kme
PHP: Examples - Manual
$errortype = array (
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parsing Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
E_STRICT => 'Runtime Notice',
E_RECOVERABLE_ERROR => 'Catchable Fatal Error'
);
php  errorhandling  idiom  devel  webdevel  reference 
october 2014 by kme
Multi-Line JavaScript Strings
I think this is quite controversial. Other than issue with minifiers, ‘backslashes’ can cause error if there is any white space after it. I often write multiline string as arrays and join, this way IMO is quite readable.

var multiStr = [
"This is the first line",
"This is the second line",
"This is more..."
].join("\n");
javascript  continuationcharacter  multilinestrings  idiom  styleguide  programming  webdevel  devel  reference 
october 2014 by kme
Here documents, or how to create multi-line strings in Perl
The lack of indentation of the end-mark can be solved by using one that already includes enough leading white-spaces: (I am using 4 real spaces here, as the tabs don't work well in the article, but they could work in real code. If you are in the indent-by-tab camp.)

my $message = <<" END_MESSAGE";
...
END_MESSAGE

The extra indentation of the actual text can be removed using a substitution at the assignment.

(my $message = <<" END_MESSAGE") =~ s/^ {8}//gm;
...
END_MESSAGE

In the substitution we replace 8 leading spaces by the empty string. We use two modifiers: /m changes the behavior of ^ from matching at the beginning of the string to match at the beginning of line. /g tells the substitution to work globally, that is to repeat the substitution as many times as it can.

Together these two flag will get the substitution to remove 8 leading spaces from every line in the variable on the left-hand side of =~. On the left-hand side we had to put the assignment in parentheses because the precedence of the assignment operator (=) is lower than the precedence of the regex =~. Without the parentheses, perl would first try to run the regex substitution on the here-document itself resulting in a compile-time error:
perl  idiom  webdevel  devel  heredoc  syntax  solution 
october 2014 by kme
Tek-Tips: Perl - check if directory exists
$dir = 'c:/mike/tmp/';

unless(-d $dir){
mkdir $dir or die;
}
perl  idiom  programming  reference  solution  filesystem  io  sysadmin 
october 2014 by kme
filehandle - Read file into variable in Perl - Stack Overflow
my $content;
open(my $fh, '<', $filename) or die "cannot open file $filename";
{
local $/;
$content = <$fh>;
}
close($fh);
perl  idiom  programming  fileio  intputoutput  solution  devel  webdevel 
september 2014 by kme
How do I check If a Class already exists in Ruby - Stack Overflow
if defined?(MyClassName) == 'constant' && MyClassName.class == Class
puts "its a class"
end
ruby  programming  language  idiom  solution 
july 2014 by kme
Pass Variables by Reference in Javascript - Stack Overflow
There is no "pass by reference" available in JavaScript. You can pass an object (which is to say, you can pass-by-value a reference to an object) and then have a function modify the object contents:

function alterObject(obj) {
obj.foo = "hello world";
}

var myObj = { foo: "goodbye" };

alterObject(myObj);

alert(myObj.foo); // "hello world" instead of "goodbye"
javascript  idiom  programming  newbie  question  passbyreference  solution 
july 2014 by kme
Parkinson's law of triviality - Wikipedia, the free encyclopedia
Parkinson's law of triviality, also known as bikeshedding or the bicycle-shed example, is C. Northcote Parkinson's 1957 argument that organizations give disproportionate weight to trivial issues. Parkinson demonstrated this by contrasting the triviality of the cost of building a bike shed to an atomic reactor. The law has been applied to software development[1] and other activities.
idiom  management  business  somebodyslaw 
june 2014 by kme
Parkinson's law - Wikipedia, the free encyclopedia
Parkinson's law is the adage that "work expands so as to fill the time available for its completion".
management  idiom  somebodyslaw 
june 2014 by kme
« earlier      
per page:    204080120160

Copy this bookmark:





to read