recentpopularlog in

kme : syntax   144

« 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 
23 days ago by kme
BashFAQ/024 (Why can't I pipe data to read?) - Greg's Wiki
So when you try to pipe into 'readarray', the variable you're trying to 'readarray' *into* is created in the context of the subshell, and then deleted when the subshell terminates.
The reason for this potentially surprising behaviour, as described above, is that each SubShell introduces a new variable context and environment. The while loop above is executed in a new subshell with its own copy of the variable linecount created with the initial value of '0' taken from the parent shell. This copy then is used for counting. When the while loop is finished, the subshell copy is discarded, and the original variable linecount of the parent (whose value hasn't changed) is used in the echo command.
bash  looping  whileloop  forloop  arrays  mapfile  readarray  syntax  newbie  pitfall  dammitbrain 
7 weeks ago by kme
linux - Bash arrays and negative subscripts, yes or no? - Stack Overflow
This is *way* easier than stuff I was trying to do before. The reason this doesn't show up in the help for "Arrays" in the bash manual is because it's a type of "Shell Parameter Expansion" that just happens to behave the way it does when the subscripted thing is an array.
If you just want the last element
<code class="language-bash">$ echo ${muh[*]: -1}

If you want next to last element
<code class="language-bash">$ echo ${muh[*]: -2:1}
bash  shellscripting  arrays  subscripting  syntax  fuckina  solution 
june 2019 by kme
arrays - Perl: if ( element in list ) - Stack Overflow
Here is an example which works with any searched (scalar) value, including undef:
<code class="language-perl">use List::MoreUtils qw(any);

my $value = 'test'; # or any other scalar
my @array = (1, 2, undef, 'test', 5, 6);

no warnings 'uninitialized';

if ( any { $_ eq $value } @array ) {
print "$value present\n"
perl  listmembership  lists  syntax  newbie  dammitbrain  likepython  solution 
june 2019 by kme
How to view all the content in an awk array? - Unix & Linux Stack Exchange
You can loop over the array's keys and extract the corresponding values:
<code class="language-bash">awk '{my_dict[$1] = $2} END { for (key in my_dict) { print my_dict[key] } }' zen</code>

To get output similar to that you'd get with a Python dictionary, you can print the key as well:
<code class="language-bash">awk '{my_dict[$1] = $2} END { for (key in my_dict) { print key ": " my_dict[key] } }' zen

This works regardless of the key type.
awk  array  syntax  associativearray  solution  dammitbrain 
may 2019 by kme
command line - sed weirdness, unmatched { - Super User |
The 'e' GNU extension (execute process) also falls into this category: it must have a newline right after it; try using the ANSI-C quoting ($'string') feature of Bash to substitute in a literal newline.
sed  shellscripting  solution  syntax 
may 2019 by kme
How to change the default target of `make`? - SysTutorials |
See also:
Way 1. Set the .DEFAULT_GOAL special variable to ‘default’.
<code class="language-makefile">
.DEFAULT_GOAL := default

# other targets ...

@ echo default target

Way 2. clear the .DEFAULT_GOAL special variable before the ‘default’ target so that ‘default’ turns to the first target after .DEFAULT_GOAL is not set.
<code class="language-makefile">
# other targets ...

# no target starting with '.' should be here
# between .DEFAULT_GOAL and 'default'
@ echo default target
make  makefile  syntax  solution 
april 2019 by kme
use of alternation "|" in sed's regex - Super User |
<code style="language-bash">echo "blia blib bou blf" | sed 's/bl\(ia\|f\)//g'</code>
For anyone else confused by this answer \| only works in gnu sed (gsed on os x) not vanilla sed (sed on os x). – Andrew Hancox Apr 4 '12 at 14:54
sed  shellscripting  textprocessing  syntax  newbie  dammitbrain  linuxonly  solution 
march 2019 by kme
How can I join elements of an array in Bash? - Stack Overflow |
Other, more complicated solutions (multiple-letter separators) require 'printf' and have their own problems.

<code class="language-bash">
IFS=, eval 'joined="${foo[*]}"'
bash  arrays  shellscripting  syntax  solution  likepython 
march 2019 by kme
EmacsWiki: Regular Expression Help |
GNU Emacs (and GNU find) regexps *do* support alternates, but you have to escape *both* the parens and the pipe symbol.
emacs  gnu  gnufind  regexp  syntax  solution 
february 2019 by kme
makefile - How do I get $(error ...) to work conditionally in GNU Make? - Stack Overflow |
This looks like it should, but doesn't actually work (for me, or apparently the OP):

<code class="language-makefile">
ifeq ($(shell test -d /foobar; echo $$?),1) $(error Not a directory) endif
make  makefile  conditional  syntax  devel  sortof  solution  needshelp 
february 2019 by kme
introspection - How do I list available methods on a given object or package in Perl? - Stack Overflow |
<code class="language-perl">
my @methods = Class::Inspector->methods( 'Foo::Class', 'full', 'public' );
perl  newbie  syntax  introspection  oop  solution 
february 2019 by kme
How do I tell what type of value is in a Perl variable? - Stack Overflow |

Perl provides the ref() function so that you can check the reference type before dereferencing a reference...

By using the ref() function you can protect program code that dereferences variables from producing errors when the wrong type of reference is used...
perl  devel  newbie  introspection  syntax  solution 
february 2019 by kme
Vim documentation: eval |
Expand the value of an environment variable into the current buffer:

<code>Ctrl-R, =, expand($LANG)</code>
vim  syntax  function  registers  reference  environmentvariables  solution 
february 2019 by kme
In AWK, is it possible to specify "ranges" of fields? - Stack Overflow |
The answer is "no"; AWK does not support ranges of subscripts like Perl or Python slices.
unix  shellscripting  awk  syntax  newbie  workaround  solution 
january 2019 by kme
Checking if an array key exists - Tcl example |
<code class="language-tcl">
if {[info exists capital($where)]}
tcl  syntax  arrays 
january 2019 by kme
Ternary operation - Wikipedia |
Solution for Tcl via

<code class="language-tcl">
set x 5
set y [expr $x == 5 ? 10 : 15]
syntax  programming  dammitbrain  solution 
january 2019 by kme
Combine XPATH predicate with position - Stack Overflow |
Solution: use parentheses for grouping, *then* subscript the results. Still not clear why the OP's methods don't work, though.
xpath  webdevel  syntax  solution 
december 2018 by kme
What are your thoughts on sigils? : perl |
Larry Wall notes in an interview that «On a syntactic level, in the particular case of Perl, I placed variable names in a separate namespace from reserved words. That's one of the reasons there are funny characters on the front of variable names -- dollar signs and so forth. That allowed me to add new reserved words without breaking old programs.». Furthermore, first order lists allow for cleaner code sometimes. So I think sigils are great, but naturally inexperienced people often complain that they add clutter or make the code "unreadable" or "messy".

And I find that sigils give my code more visual rhythm and makes it easier to read

This, right here.

I don't need a fancy IDE or somehow encoding the type of the thing into the name of the thing to know what it is. Or, at least, the type of thing that the author wanted the interpreter to treat it as.

Having spent the last couple years in node/javascript land, too often it's a "oh, shit, it's a function?" is too common.
perl  language  design  perl5  syntax  thisvsthat  forthecomments  sigils 
september 2018 by kme
Python import statement semantics - Stack Overflow
<code class="language-python">import lxml.html as LH
doc = LH.parse('http://somesite')
lxml.html is a module. When you import lxml, the html module is not imported into the lxml namespace. This is a developer's decision. Some packages automatically import some modules, some don't. In this case, you have to do it yourself with import lxml.html.

import lxml.html as LH imports the html module and binds it to the name LH in the current module's namespace. So you can access the parse function with LH.parse.

python  lxml  imports  syntax  annoyance  solution 
june 2018 by kme
jinja string match - Google Groups |
In a test pillar:
<code class="language-jinja">
{% if 'node3' in grains["id"] %}
test: yayaya matches node3
{% else %}
test: nonono
{% endif %}
flask  jinja  templates  syntax  webdevel  webdesign  solution 
june 2018 by kme
python - Add another tuple to a tuple of tuples - Stack Overflow |
I thought that argument unpacking might work here, like 'a = (1,2,3)' and 'b = (0, *a)', but yeah, no it's called "argument" unpacking for a reason, and creating tuples isn't a function call. It might work with namedtuples though!

<code class="language-python"
# build another tuple-of-tuples out of another_choice,
# then concatenate:

final_choices = (another_choice,) + my_choices</code>
python  tuples  lists  concatenation  syntax  newbie  solution 
may 2018 by kme
Transclusion - MediaWiki |
Sample: {{Special:Newpages/3}} gives 3 new pages.

URL parameters can be given like template parameters, e. g. {{Special:RecentChanges|namespace=10|limit=5}}.
mediawiki  templates  transclusion  wikitext  syntax  newbie  reference 
may 2018 by kme
transform hash key from string into symbol - Ruby Forum |
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 })
ruby  arrays  hashes  map  fp  idiom  newbie  syntax  solution 
may 2018 by kme
ruby - Difference Between map and each - Stack Overflow |

each simply iterates over the given enumerable, running the block for each value. It discards the return value of the block, and each simply returns the original object it was called on:
<code class="language-ruby">[1, 2, 3].each do |i|
i + 1
end # => [1, 2, 3]

This is simply a nicer, more universal way of doing a traditional iterating for loop, and each is much preferred over for loops in Ruby (in fact, I don't think I've ever used a for loop in Ruby).

map, however, iterates over each element, using the return value of the block to populate a new array at each respective index and return that new array:
<code class="language-ruby">[1, 2, 3].map do |i|
i + 1
end # => [2, 3, 4]</code>

So it "maps" each element to a new one using the block given, hence the name "map". Note that neither each nor map themselves modify the original collection.
ruby  arrays  fp  map  syntax  newbie  reference  solution 
may 2018 by kme
syntax - What do the different brackets in Ruby mean? - Stack Overflow |
[] 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
How to prevent overwritting Python Built-in Function by accident? - Stack Overflow |
You can't. You could use linters (e.g. pylint) which will check for this kind of thing, but Python allows you to reuse anything except a keyword ( or None.
You can't prevent it, Python is built on the notion of "we're all consenting adults" so you are free to do what you want. It is possible to delete the override but you'd have to know that you shadowed that function in the first place.
python  language  syntax  newbie  pitfall  annoyance  explained 
april 2018 by kme
How do I determine the size of an object in Python? - Stack Overflow |
The Pympler package's asizeof module can do this.

Use as follows:
<code class="language-python">
from pympler import asizeof

Unlike sys.getsizeof, it works for your self-created objects. It even works with numpy.
python  syntax  sizeof  solution 
march 2018 by kme
How can I represent an 'Enum' in Python? - Stack Overflow |
You can also easily support automatic enumeration with something like this:
<code class="language-python">def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)</code>

and used like so:
<code class="language-python">
>>> Numbers = enum('ZERO', 'ONE', 'TWO')
>>> Numbers.ZERO
>>> Numbers.ONE
python  syntax  enum  shim  solution 
march 2018 by kme
python - Are Mixin class __init__ functions not automatically called? - Stack Overflow |
<code class="language-python">class MixedClass2(SomeMixin, MyClass):

>>> m = MixedClass2()
mixin before
mixin after</code>

The pattern @Ignacio is talking about is called cooperative multiple inheritance, and it's great. But if a base class isn't interested in cooperating, make it the second base, and your mixin the first. The mixin's __init__() (and anything else it defines) will be checked before the base class, following Python's MRO.

But also note:
Have the base class invoke super().__init__() even though it is a subclass of object. That way all the __init__() methods will be run.
<code class="language-python">
class BaseClassOne(object):
def __init__(self, *args, **kwargs):
super(BaseClassOne, self).__init__(*args, **kwargs)
print (" base ")
python  inheritance  mixins  multipleinheritance  syntax  oop  solution 
march 2018 by kme
introspection - Getting the class name of an instance in Python - Stack Overflow |
Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.
<code class="language-python">>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
python  class  oop  syntax  solution 
march 2018 by kme
html - Testing text() nodes vs string values in XPath - Stack Overflow |
XPath text() = is different than XPath . =

(Matching text nodes is different than matching string values)

The following XPaths are not the same...
<code class="language-xpath">//span[text() = 'Office Hours']</code>

Says: Select the span elements that have an immediate child text node equal to 'Office Hours`.

<code class="language-xpath">//span[. = 'Office Hours']</code>

Says: Select the span elements whose string value is equal to 'Office Hours`.
xpath  xml  syntax  textcontent  thisvsthat  patternmatching  newbie  webdevel  reference  explained 
february 2018 by kme
mysql - Insert auto increment primary key to existing table - Stack Overflow |
This is interesting, but I don't know how it could work:

You can add a new Primary Key column to an existing table, which can have sequence numbers, using command:
<code class="language-sql">ALTER TABLE mydb.mytable ADD pk_columnName INT IDENTITY
dba  mysql  sql  newbie  syntax  primarykey  altertable  solution 
february 2018 by kme
MySQL Count distinct values from one column - Stack Overflow |
Have you tried
<code class="language-sql">SELECT COUNT(DISTINCT B) FROM mytable WHERE C = 2;</code>
dba  sql  syntax  mysql  dammitbrain  newbie  solution 
february 2018 by kme
mysql command for showing current configuration variables - Stack Overflow |
What you are looking for is this:
<code class="language-sql">SHOW VARIABLES;</code>

You can modify it further like any query:
<code class="language-sql">SHOW VARIABLES LIKE '%max%';</code>
dba  mysql  sql  syntax  newbie  dammitbrain  solution 
january 2018 by kme
sql - How to get the next auto-increment id in mysql - Stack Overflow |
Two solutions, but only the second works if you just TRUNCATEd the table:

<code class="language-sql">SELECT LAST_INSERT_ID()</code>

<code class="language-sql">
FROM information_schema.tables
WHERE table_name = 'table_name'
AND table_schema = DATABASE( ) ;

-- or if you do not wish to use information_schema you can use this

dba  mysql  sql  syntax  newbie  solution 
january 2018 by kme
mysql - How to truncate a foreign key constrained table? - Stack Overflow |
<code class="language-sql">SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE table1;
TRUNCATE table2;


This will handily reset the AUTO_INCREMENT as well, while maintaining the table structure and comments.
mysql  dba  sql  syntax  newbie  solution 
january 2018 by kme
php - SQL Update query based on another table's field - Stack Overflow |
In MySQL, you can use join with update. This is how I interpret your question:

<code class="language-sql">update t1_users u join
t2_settings s
on u.uid = s.value and = 'beta_givebeta'
set t1.beta = 'yes';</code>
sql  mysql  syntax  maybesolution 
january 2018 by kme
mysql - SQL set values of one column equal to values of another column in the same table - Stack Overflow |
Sounds like you're working in just one table so something like this:
<code class="language-sql">
update your_table
set B = A
where B is null</code>
mysql  sql  newbie  syntax  solution 
january 2018 by kme
MySQL :: MySQL 5.7 Reference Manual :: 23.2.1 Stored Routine Syntax |
An alternative summary of functions versus procedures:

Inputs: Takes a list of arguments, all are inputs.
Could also get input from running a query?

Outputs: Produces a single return value -- see RETURN clause. Can be any valid MySQL data type.

(Can that return value be a result set? Other docs say that "functions cannot return a result set", but this probably means "cannot return a result set direct to the client", which is something _procedures_ can do. So far as I can tell, functions cannot return a cursor, which would be a related concept.)

Calling method: Can be used where a built-in function like ABS() might be used, such as in an assignment, expression, or where a field value is expected.

Inputs: Takes a list of arguments. Procedure definition specifies whether these arguments are for input and/or output, via IN, OUT or INOUT.

Could also get input from running a query.

Outputs: Unlike a Function, does not produce a return value per se. However, can send values back to caller via OUT or INOUT arguments.

Also, procedures can contain a bare SELECT statement, which sends a result set to the client. A procedure can contain multiple such SELECT statements, if other details enable the client to receive multiple result sets.
mysql  dba  sql  syntax  explained  solution  forthecomments 
january 2018 by kme
mysql - Using a stored procedure as subquery - Stack Overflow |
The gist: functions return a value; procedures can return values (for INOUT parameters) or results set(s) if there's a bare SELECT within them.
dba  mysql  sql  storedroutines  functions  procedures  syntax  newbie 
january 2018 by kme
Writing optional parameters within stored procedures in MySQL? - Stack Overflow |
Optional Parameters are not yet supported on MySQL. I'm suggesting that you pass null value in your parameter and inside your stored procedure has an IF statement.
<code class="language-sql">
(IN param VARCHAR(25))
-- statements ;
ELSE commands
-- statements ;
DELIMITER ;</code>
dba  sql  mysql  syntax  workaround  solution 
january 2018 by kme
MySQL - create table by using another table |
<code class="language-sql">
SELECT * FROM other_table;

-- if you need to empty its contents, then:
3. Create a new table based on one or more existing tables, and at the same time create extra new column(s).

The query below is similar to the one shown above, but in the create table statement, it has specified a new column to be created with data type, not null constraint, and auto_increment attribute. In the new table product_sold_by_order2, all the columns in the SELECT statement are appended to the right side of the extra new column ID. This gives us the flexibility to add extra new columns without having to write and run another ALTER table query after the new table is created.

<code class="language-sql">
create table product_sold_by_order2(ID int not null auto_increment, PRIMARY KEY (ID))
select distinct y.OrderID,
round(y.UnitPrice * y.Quantity * (1 - y.Discount), 2) as TotalSales
from Products x
inner join Order_Details y on x.ProductID = y.ProductID
order by y.OrderID;
sql  mysql  dba  syntax  solution 
january 2018 by kme
sql - How to reset AUTO_INCREMENT in MySQL? - Stack Overflow |
You can reset the counter with:
<code class="language-sql">

dba  syntax  newbie  mysql  solution 
january 2018 by kme
python - 'too many values to unpack', iterating over a dict. key=>string, value=>list - Stack Overflow |
I ran into this problem with Flask-Admin ( and the issue was some breaking change in some API in SQLAlchemy 1.2.0 that returned a 3-element instead of a two-element tuple.
python  errormessage  dictionary  syntax  maybesolution 
january 2018 by kme
Passing FieldName as Parameter in MySQL Stored Procedure - Stack Overflow |
You can use prepared statements, for example -

<code class="language-sql">
CREATE `VSK_Comments_UpdateAction`(IN FieldName varchar(30),IN FieldValue tinyint,CID bigint)
SET @query = CONCAT('Update comments Set ', FieldName, '=? WHERE commentid=?');
PREPARE stmt FROM @query;
SET @FieldValue = FieldValue;
EXECUTE stmt USING @FieldValue, @CID;
sql  mysql  procedure  syntax  dba  solution 
december 2017 by kme
Add a new element to an array without specifying the index in Bash - Stack Overflow |
Yes there is:
<code class="language-bash">

Bash Reference Manual:

In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the += operator can be used to append to or add to the variable's previous value.

Note that this only works with sequential indices, though...
it's important to note whether the array starts at zero and is sequential. Since you can make assignments to and unset non-contiguous indices ${#array[@]} is not always the next item at the end of the array.
<code class="language-bash">
$ array=(a b c d e f g h)
$ array[42]="i"
$ unset array[2]
$ unset array[3]
$ declare -p array # dump the array so we can see what it contains
declare -a array='([0]="a" [1]="b" [4]="e" [5]="f" [6]="g" [7]="h" [42]="i")'
$ echo ${#array[@]}
$ echo ${array[${#array[@]}]}

Here's how to get the last index:
<code class="language-bash">
$ end=(${!array[@]}) # put all the indices in an array
$ end=${end[@]: -1} # get the last one
$ echo $end

That illustrates how to get the last element of an array. You'll often see this:
<code class="language-bash">
$ echo ${array[${#array[@]} - 1]}

As you can see, because we're dealing with a sparse array, this isn't the last element. This works on both sparse and contiguous arrays, though:
<code class="language-bash">
$ echo ${array[@]: -1}
bash  array  subscript  syntax  newbie  solution  dammitbrain 
december 2017 by kme
« earlier      
per page:    204080120160

Copy this bookmark:

to read