Pattern-less function names.  For Queue.h, rather see function named  obviously make sense together like Queue_Init(), Queue_GetSize() than queueInit(), getQueueSize(), etc.
Comments with # preprocessing may not be portable

// #endif /* QUEUE_H_INCLUDED */
#endif

There is no need for a head and tail.  Alternative, only store tail and have the tail point to the head of the list.  End of list detected when p->next == tail->next.  This makes your head node one field smaller.  Important if code uses lots of queues.
Unclear why code uses int for the queue size type.  A signed type is not needed (could use unsigned) and on a system where size_t could be much wider than int, a queue size like size_t is more prudent.  Robust code would check for a queue exceed the max value of size in enqueue().
Good use of size_t for memSize.  Good error checking for malloc().  Good to have test case.  IMO, a commented sample usage in the *.h file is nice. ; the *.h being the public interface to your good code.
Pedantic: Robust would check for memSize==0 in queueInit() as that negates the correctness of the malloc() checks which should be if(newNode->data == NULL && q->memSize > 0).
A little documentation goes a long way.  suggest a line or two of comment preceding each function declaration in Queue.h.
Functions like queuePeek(Queue *q, void *data) that do not alter *q should be declared queuePeek(const Queue *q, void *data).  This self documents the unchanging nature of q in the function to users and allows some optimizations a compiler may not otherwise employ.  It is a check on the implementation of the function too.
For completeness, suggest q->memSize = 0 in clearQueue().
Change #include order.  Put "Queue.h" first as a check that Queue.h does not depend on the 3 <*.h> include files - unless that .h file is coded in Queue.h.

#include "Queue.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// #include "Queue.h"

Indicate failure.  If void dequeue(Queue *q, void *data) does not have anything in the queue to copy to data, there is no indication of that here.  Perhaps return true/false indicating success.  Same for queuePeek().
For debugging,  zero filling memory before free() I have found useful.  Errant code tends to fail faster with a 0 pointer/data than with its original data still potentially intact.  Faster failing code is easier to debug. YMMV.
Opinion:  Storing the queue size is of dubious value, unless of course that is the reason for the queue type - one with a quick size report.  Alternative, drop the size field and calculate when needed.  More often, I have found the need for bool Queue_IsEmpty(const Queue *q) sufficient than needing a quick size and prefer to drop the ever present size field.


Shell script to copy video files to another folder

Function

The command

is_video_file $extension = 1

just passes the arguments $extension , = and 1 to the function is_video_file.

To check if the return value of is_video_file is 1, do the following:

is_video_file "$extension"

if [ $? = 1 ]; then ...

However, making a function return 1 usually indicates an error; the return value 0 indicates success.

If you swap 1 and 0 in the definition of is_video_file, you can use

if is_video_file "$extension"; then ...

Further problems

Every time you do not know the value of a variable with certainty, you should surround it with double quotes.

Most of your variables are unquoted, while the strings are quoted. The latter is unnecessary.

For example, you wrote

[ $ext = "m4v" ]

which might fail if $ext contains unanticipated characters.

The commands

[ "$ext" = "m4v" ]

and

[ "$ext" = m4v ]

will both work fine.

Suggestions

There is not need to restore the IFS and the end of the script. Modifying the IFS will only affect the script itself.
Setting IFS=$'\n' gives a false sense of security. It's still necessary to quote all variables if their values are unknown.


Constructing NewsArticle objects from a database table

Coding Issues

In NewsArticle, the names of the attributes begin with uppercase letters (Id, Title, Story, Pubdate). This violates common Java field naming conventions.
Database column names are usually case insensitive. Depending on the underlying DBMS, the instructions like col.getKey().equals("id") may fail, because the searched value could have been stored under e.g. ID key when being read in DbTable. Either it should be normalized by applying toLowerCase() there, or it should be checked with equalsIgnoreCase() in NewsArticle constructor.
Looping over the entire row map in NewsArticle constructor is unnecessary. The fields may be initialized with e.g. id = (String) row.get("id"); and there is no need to use local variables id, title etc.
In DbTable: Class colClass var is not typed (raw type), which is not good. This variable is useless, because colValue is an Object and can be directly initialized with queryResults.getObject(arg), without casting.

Design Issues: Critical!

There are some very important issues concerning DbTable class.

Loading the contents of an entire table using tblData Set is very dangerous. First of all, if the table is rather huge (imagine just several dozens of thousands of rows), this object will squatter the memory and probably consume too much of it uselessly. It also duplicates the data supposed to be stored in the DB and produces too much overhead on each DbTable object creation by reading all the data. However, reading just the metadata of table columns and their types could have been useful for your problem.
prpStmt and queryResults objects are created, but never closed. Initializing them inside a try-with-resources block will solve the issue.
throws Exception, especially in a constructor, looks very ugly. Either replace it with a more concrete exception type or (even better) find a way to avoid the throws clause for the constructor.
There are no validity checks for Connection and String arguments. What will happen, for example, if one of them or both are null?

These remarks do not answer your initial question about the type safety of the solution. It's too early to answer it before fixing many of the critical issues.


Checking whether four text fields are all empty

you could just say

var checkRow = false;
if(word1 != '' || word2 != '' || word3 != '' || word4 != '') {
    checkRow = true;

or you could concat the single words and check if the length is greater than 0

EDIT:
since some people favored the string-concat solution: actually that was kind of a joke in the sense of https://en.wikipedia.org/wiki/Barometer_question. if the strings are not large it doesn't make much of a difference, but from a performance-point of view that would not be a good solution.


Multiple independent or layered constructors for TicTacToe?

I would vote for the second, i.e. the one with a basic constructor called by others.

But what is important is how to decide. The criteria that come to mind are:

what if you should refactor later?
which is the most clear when using this class?

In your case, you want to offer different constructors for different usages, with default values in some case.

There are two types of refactoring impacting a constructor:

fields change
usage changes

Refactoring fields

If the fields change, then you do not have to update 2 (or more) constructors by hand. You first update the lowest level constructor. You can handle the default setting of this field once. If you use an argument and forget to update other constructors, the compiler will let you know.

While if you picked the first option, you will notice you forgot to update all constructors at execution (or test if you have good tests) time.

Refactoring usage

If the usage change, you want to add a new constructor with different arguments. Then you will call another constructor, and all fields will be set since your constructors were correct at first implementation.

Again, if you picked the first option, you would have to set the fields one by one, and there are chances you would not set a field correctly, the compiler would not help you on that.

Clarity

Now let's consider how clear it looks to a user. If you set correctly the visibility (as you did), no option is particularly preferable. Some javadoc would help though, so that the user does not need to open your file. But when reading your file, unless the javadoc is clear, the second option is more confusing, as one should read the whole code to figure what best to use, and what each constructor does, jumping to another method, ...

There might be other criteria that I missed. But from a basic check, the second option seems easier to maintain and be clear enough if some documentation is added. But based on those two criteria, you might conclude differently (you might find clarity more important than later refactoring)


Hello Functional World: Counting occurrences of each letter

As @Caridorc says, this is functional code, not imperative.  It's basically pretty good.

It would be a good idea to include type annotations — for example, (xs:string).  If you wanted to (and I'm not saying it would be better to do so), you could drop xs as an explicit parameter and change the pipeline into a composition of functions.  Also, you could sort before grouping for a slight simplification.

I find the fold in tuplesToString a bit hard to follow.  In my opinion, using String.concat would be clearer, and it would also eliminate the extra space at the end of the line.

I'd rename both functions to have "counts" in their name.  You can see the coherence in getLetterCounts |> countsToString.

open System

let getLetterCounts:(string -> seq<char * int>) =
    Seq.filter Char.IsLetter >>
    Seq.map Char.ToUpper >>
    Seq.sort >>
    Seq.groupBy id >>
    Seq.map (fun (k, v) -> (k, Seq.length v))

let countsToString (counts:seq<char * int>) =
    [for k, v in counts -> sprintf "[%c, %i];" k v] |> String.concat " "

"Hello World" |> getLetterCounts |> countsToString |> printfn "%s"


My advice here is not to use C++ (directly) for this type of job. There are tools out there to help you parse formatted streams (you have to learn another tool though).

Personally I use flex and bison. BUT I recommend you look around and see if there are more modern version or alternatives.

Flex Rules

This converts a stream of characters into a stream of tokens.

%%
\+              return '+';
\-              return '-';
\*              return '*';
\/              return '/';
\(              return '(';
\)              return ')';
{Number}        return 259;
{WhiteSpace}    /* Ignore */
.               throw std::runtime_error("Invalid Character");
%%

Bison Rules

This converts a stream of tokens and build a parse stack that is processed.

%%
result  :   exp                     {value = $1;}
exp     :   add_exp
add_exp :   mul_exp
        |   add_exp '+' mul_exp     {$$ = $1 + $3;}
        |   add_exp '-' mul_exp     {$$ = $1 - $3;}
mul_exp :  pri_exp
        |   mul_exp '*' pri_exp     {$$ = $1 * $3;}
        |   mul_exp '/' pri_exp     {$$ = $1 / $3;}
pri_exp :   '(' exp ')'             {$$ = $2;}
        |   Number
Number  :   NUMBER                  {$$ = getCurrentNumber();}
%%

The actual files are slightly bigger as there are some boiler plate that you need get everything working together. But this boilerplate is very similar so once you have it no need to worry about it. The languages are very concise and understandable (but that is relative).

A lot of research has already been done on parsing so there is very little need to reinvent the wheel.


Project Euler #45 - Triangular, pentagonal, and hexagonal

This expands my comments on Brythan's answer:

Note: It's written in JavaScript (not C#) since I haven't written C# in years but you should be able to convert it fairly easily.

Answer 1 - Test if successive hexagonal numbers are also triangular and pentagonal

A number \$c\$ is triangular if \$c = t(t + 1)/2\$ (where \$c \in \mathbb{N}\$ and \$t \in \mathbb{N}\$) which can be rewritten as \$0 = t^2 + t -2c\$ and then in terms on \$t\$, using the positive root given by the quadratic formula, as \$t = \frac{-1 + \sqrt{1+8c}}{2}\$.

Similarly, the pentagonal number formula \$c = p(3p-1)/2\$ (where \$c \in \mathbb{N}\$ and \$p \in \mathbb{N}\$) can be rewritten as \$0 = 3p^2 - p - 2c\$ then as \$p = \frac{1 + \sqrt{1+24c}}{6}\$ .

You can then use these to test successive hexagonal numbers to see if the they are also triangular and pentagonal:

function quadraticRoot(a,b,c){
  return ( -b + Math.sqrt( b*b - 4 * a * c ) ) / (2 * a);
}

function isInteger(n){
  return n === Math.round( n );
}

function isTriangularNumber(n){
  return isInteger( quadraticRoot( 1, 1, n*-2) );
}

function isPentagonalNumber(n){
  return isInteger( quadraticRoot( 3,-1, n*-2 ) );
}

function getNextHexagonalNumberWhichIsTriangularAndPentagonal(n){
  var hex;
  while( true ) {
    hex = n * ( 2 * n - 1 );
    if ( isTriangularNumber( hex ) && isPentagonalNumber( hex ) )
    {
      return n;
    }
    ++n;
  }
}

Then:

getNextHexagonalNumberWhichIsTriangularAndPentagonal( 144 );

Gives the answer 27693 as the next hexagonal number that is also triangular and pentagonal.

Answer 2 - Generate successive triangular, pentagonal and hexagonal numbers

function getTriangular(n){
  return n * (n + 1 ) / 2;
}

function getPentagonal(n){
  return n * ( 3 * n - 1 ) / 2;
}

function getHexagonal(n){
  return n * ( 2 * n - 1 );
}

function getNextEqualTriangluarPentagonalHexagonalNumbers(t,p,h){
  var tt = getTriangular(t);
  var pp = getPentagonal(p);
  var hh = getHexagonal(h);
  while ( true ){
    var max = Math.max( tt, pp, hh );
    if ( tt < max ) {
      tt = getTriangular(++t);
    } else if ( pp < max ) {
      pp = getPentagonal(++p);
    } else if ( hh < max ) {
      hh = getHexagonal(++h);
    } else {
      return [t,p,h];
    }
  }
}

Then

getNextEqualTriangluarPentagonalHexagonalNumbers(286,166,144);

Gives the answer [ 55385, 31977, 27693 ] for the next triangular, pentagonal and hexagonal numbers which are identical.


Delete order's details' line without changing page using AJAX

PHP

Variable names, excess variables, logic

When iterating through the rows in showOrderDetails(), the variable $row_index is slightly misleading because that should contain the column name, not an index (typically an integer value):

foreach ($table_row as $row_index => $row_data) { // titulos campos

A better name for that key would be something like $column_name:

foreach ($table_row as $column_name => $column_value) { // titulos campos

But the name $row_index would be appropriate for the key on the outer foreach:

foreach ($res as $row_index => $table_row) {

Then instead of creating an extra variable called $first, you could utilize $row_index and $column_name to conditionally display the rows and cells.

The first one:

if($first){ //HEADERS

could then be updated to:

if($row_index === 0){ //HEADERS

And then the second one, in the nested loop:

if($first){ //TO NOT DISPLAY ID

Could be changed to:

if($column_name === 'id'){ //TO NOT DISPLAY ID

And the second inner loop could be updated as well:

foreach ($table_row as $row_data) { // DATA
      if ($first){
          continue;

Could be rewritten to add the row if the column name is id:

foreach ($table_row as $column_name => $column_value) { // DATA
    if ($column_name === 'id'){
        $idLinea=$column_value;

And then $first could be eliminated entirely.

Alternatively, the condition in the first nested loop could be negated and then the continue could be eliminated:

if($column_name !== 'id'){ //DO NOT DISPLAY ID
    echo "<th>$column_name</th>";
}

See that all together in this playground example (not connected with Javascript/AJAX requests).

JS

The line to look up the element to remove by id attribute:

var fila=document.querySelector('#fila'+idLinea); //We choose the first and unique row which has whatever ID needed.

Could be changed to use document.getElementById()

  var fila=document.getElementById('fila'+idLinea); //We choose the first and unique row which has whatever ID needed.

There are a few discussions about which to use:

this Sitepoint forum
this SO question and its answers (and related posts)

The general consensus is that getElementById() is quicker than querySelector(). For a small page like this it would likely not be noticeable.


As already mentioned in the comments, I don't think there's a strictly better way to create the morse code mapping. There is however a lot we can do to make this code more concise and more pythonic. This looks like Java code that was directly translated into Python and doesn't utilise some of Python's key features.

Morse Code dict
See the comments on your question: We don't need function createDict, which should be called create_dict (PEP 8), we only need a top-level variable:
CHAR_TO_MORSE = {'A': '.-',
                 ...
                 '0': '-----'}

Never iterate over indices in python
In Python this pattern is generally not recommended:
i = 0
while (i < len(words)):
    print(words[i])

You almost never need to iterate over and access elements by their indices. Instead you should directly iterate over the elements of the iterable:
for word in words:
    print(word)

If you do need the index as well you can use built-in enumerate:
for index, word in enumerate(words):
    print(f"{index}: {word}")

words is not a descriptive variable name for a string. If I iterate over a variable named words, I expect to receive words, not single characters. I'd change it to text or message and then change the loop to:
for char in text:
    ...

This makes it immediately clear what is happening.

Exception handling
Do not use bare except. Doing so can make it harder to interrupt programs and it can disguise other problems, since it catches all errors, not just the ones you're expecting. Instead you should only catch KeyError, since that's the only error you're explicitly handling.

words[i] != " "
You perform this check in every loop iteration, although it's not really a special case. This basically only translates " " to "/", the rest of the logic is the same. So you can simply add it to your char to morse mapping:
CHAR_TO_MORSE = {'A': '.-',
                 ...
                 '0': '-----',
                 ' ': '/'}

Calling main()
For most use cases, you should wrap a call to main() from within the script in a if __name__ == “__main__”: condition.
if __name__ == "__main__":
    main()

What does if name == “main”: do?

Complete code
I also applied .upper() directly to the return value of input(...) and moved the Exception clause into the loop to allow for a better error statement to the user.
CHAR_TO_MORSE = {'A': '.-',
                 ...
                 '0': '-----',
                 ' ': '/'}

def main():
    print("This program translates words to morse code", end="\n\n")

    text = input("Enter a word or phrase to be encoded: ").upper()

    for char in text:
        try:
            print(CHAR_TO_MORSE[char], end=" ")
        except KeyError:
            print(f"\nInvalid character found: '{char}' - refer to morse code alphabet")
            break

if __name__ == "__main__":
    main()

join and list comprehensions / generator expressions
If you're not set on printing the morse code up until the invalid character, this is a perfect use case for join together with a list comprehension:
try:
    print(" ".join(CHAR_TO_MORSE[char] for char in text))
except KeyError:
    print(f"\nInvalid character found - refer to morse code alphabet")

What we're using here is actually not a list comprehension, but a generator expression. If you're interested you can read more about Generator Expressions vs List Comprehensions.


Checking host status for clients on server

Some observations:

Regarding the "stratification". It's hard to give practical advice, this is something that comes from experience and personal taste. Some basics to start with: a) write classes/modules with low coupling to achieve real modularization, b) write fairly short methods than do only one thing. c) Keep model-view separations. d) Don't use global variables.
class Domain_check: that's against Ruby practices, a class or module names are named CamelCase: class DomainCheck.
Don't write an explicit return on the last line of a method/block, it's non idiomatic.
Don't assign a variable on this last expression, why would be it different from the method name itself?
Don't call to external commands (ls, grep, awk, ...), Ruby is more than able to perform those tasks, check the standard library.
About this: prefix =  DomainCheck.new.vhost_grab. You are already in the instance, just prefix = vhost_grab.
You are using a class just nominaly, you don't use any of its facilities. You can convert all these methods to classmethods if you store nothing in the instances.
Init empty + iterate with each + push is an anti-pattern in Ruby (and in any language with decent functional capabilities, for that matter). Use Enumerable#map. Also, you use each_index to iterate in a C fashion, use each (or better, map, select, inject, as required, read the Enumerable documentation from start to finish).
Having only a C background your code has a serious problem, it's very, very imperative. Functional programming allows far better abstraction and  clarity, check this wiki page I maintain.
If every method is prefixed with vhost_ there's no point in prefixing anything. Besides, if all the methods start with vhost_, the class should probably be called VirtualHostChecker instead (@Flambino).


Use traverse instead of foldM + accumulate

In a fold, you usually use a function that reduces (or folds) your input into a single result. You, on the other hand, use fold mapEmissions to create a list from an input list. Both lists will have the same number of elements. That's not a fold. That's a map.

So first of all, let's use traverse instead of foldM:

evaluate :: [Input] -> Output
evaluate inputs = evalState (traverse emit inputs) (False, True)

Next, let's figure out how emit should look like:

emit :: Input -> State (Negated, Enabled) Emission
emit input = do
    (negated, enabled) <- get
    let (negated', enabled', emission) = step (negated, enabled, input)
    put (negated', enabled')
    return emission

Almost the same as mapEmission, and we can use emit to implement mapEmission:

mapEmission accum input = (accum ++) <$> emit input

Therefore, we should really replace the foldM by traverse.

Consider already existing interfaces

step can be rewritten with another interface that fits the state interface:

type MMState = (Negated, Enabled) --  Mealy Machine State

step :: Input -> MMState -> (MMState, Emission)
step ToggleNegate  (n, e)     = ((not n, e    ), 0)
step ToggleEnabled (n, e)     = ((    n, not e), 0)
step _             (n, False) = ((n,     False), 0)
step Plus          (n, e)     = ((n,     e    ), if n then -1 else  1)
step Minus         (n, e)     = ((n,     e    ), if n then  1 else -1)

This makes emit even easier:

emit :: Input -> State MMState Emission
emit input = state (step input)

Note that MMState makes it easier to change the other types, as there is less repetition.

It's completely up to you to write step like this, though.

Encapsulate possible errors in the type (if possible)

In toInput consider Maybe Input or Either String Input instead of error:

toInput :: Char -> Either String Input
toInput '+' = pure Plus
toInput '-' = pure Minus
toInput 'n' = pure ToggleNegate
toInput 'e' = pure ToggleEnabled
toInput  c  = Left $ "Unrecognised character: " ++ [c]

Use Int instead of Integer if the values are small

Instead of Integer we should use Int as Emission. Integer can be arbitrarily large, but your output values are either -1, 0 or 1. Int is much more suitable for that.

Other comments

Other than that, well done. You followed good practice by including type signatures, and your code is easy to read and to follow. The only real hurdle was foldM instead of traverse.

However, your single instruction type is called Input, whereas your complete output type is called Output. That naming is somewhat unbalanced.

Overall, we end up with:

import Control.Monad.Trans.State.Lazy

data Input = Plus | Minus | ToggleNegate | ToggleEnabled
type Emission = Int
type Output = [Emission]
type Negated = Bool
type Enabled = Bool
type MMState = (Negated, Enabled) --  Mealy Machine State

toInput :: Char -> Either String Input
toInput '+' = pure Plus
toInput '-' = pure Minus
toInput 'n' = pure ToggleNegate
toInput 'e' = pure ToggleEnabled
toInput  c  = Left $ "Unrecognised character: " ++ [c]

step :: Input -> MMState -> (MMState, Emission)
step ToggleNegate  (n, e)     = ((not n, e),     0)
step ToggleEnabled (n, e)     = ((    n, not e), 0)
step _             (n, False) = ((n,     False), 0)
step Plus          (n, e)     = ((n,     e),     if n then -1 else  1)
step Minus         (n, e)     = ((n,     e),     if n then  1 else -1)

emit :: Input -> State MMState Emission
emit input = state (step input)

evaluate :: [Input] -> Output
evaluate inputs = evalState (traverse emit inputs) (False, True)

By the way, we can now use emit on any traversable, so we could relax evaluate's type to

evaluate :: Traversable t => t Input -> t Emission
evaluate inputs = evalState (traverse emit inputs) (False, True)

But that's up to you.


Is this the right way to read every line?

Too complicated. Just say:

for (std::string line; std::getline(_file, line); )
{
    // process "line"
}

The function std::getline, like most iostreams operations, returns a reference to the stream object itself, which can be evaluated in a boolean context to tell you whether it is still good, i.e. whether the extraction operation succeeded.

Also, the function shouldn't be called "parseLine", but "parseAllLines" or "parseStream".


Arduino project to indicate soil moisture using LEDs

You wrote several for loops without any spaces.
Please don't do that, as it makes the code harder to read.

Instead of

  for(;*colors;colors++) {
    blink(*colors);
  }

you might prefer

  while (*colors) {
    blink(*colors++);
  }

Moving loop() to the bottom of the file would save you
some forward declarations.

Your Serial.print() statements might benefit from the addition
of a debug flag, so there's no need to comment them.

Things like counts and durations won't go negative.
I can't see the signatures for delay() and digitalWrite(),
but it seems like some of your ints might want to be uint.


AutoreleasePool NSString Automatic Reference Counting

Also @autoreleasepool does not look are the objects create outside of it scope, just the object used within. Also if using are there is not need for the @autoreleasepool at all, since the scope variables will be released and nilled at the end of the scope.


Extract and sort all numbers that appear after ',

re.findall() behaves differently depending on whether the regex contains capturing parentheses.  If it doesn't contain capturing parentheses, then it just returns the matching text as a flat list.

So, how can you avoid capturing?  Just rewrite your regex to use a positive lookbehind assertion.

s = "'bhhd',12 'kjubk',2 'bjki',98 'khjbjj',4"
all = re.findall(r"(?<=',)\d+", s)
print(",".join(sorted(all, key=int)))


In general, your code looks fine to me. You could make myTarget and myStabs in BadIdea final. Also, you don't have to create three separate BadIdea objects in main(String[]). Instead, it would suffice to create only one BadIdea from guineaPig and stabCount and pass that object to the threads you start, because the BadIdea objects themselves will never change, only the Counter the point to, and since they all point to the same Counter (which is guineaPig), creating a separate BadIdea for each thread is redundant.

And about that InterruptedException: I can't envision a scenario in which an InterruptedException could ever be thrown in your program, but your comment "i dont care!!" implies that you think by merely swallowing the exception, you let the flow of your program be unaffected by it. However, this is not what would happen if an InterruptedException were actually thrown. If your code actually caught an InterruptedException, then it would no longer wait for t to die, but instead, the for-each loop would move on to the next thread, if there is one. So theoretically, it could happen that, if an InterruptedException is thrown, by the time you call System.out.println(guineaPig.getCounter()), not all 3 threads (or however many you start) are dead yet and the guinea pig is secretly still being tortured.

To prevent this from happening, you could rewrite the code to look something like this:

for (Thread t : threads) {
    while (t.isAlive()) {
        try {
            t.join();
        } catch (InterruptedException e) {
            // i really dont care!!
        }
    }
}


Spotify's "Reversed Binary Numbers" Problem

I do not see any problems inside the given range. I would have used already existing methods:

public static int reverse2(final int n) {
    return Integer.valueOf(new StringBuilder(Integer.toBinaryString(n)).reverse().toString(), 2);
}

Which is probably to best readable version.

If we want to do it by ourself and do not want to create a string and stringbuilder:

With recursion:

public static int reverse3(final int newNumber, final int number) {
    if (number == 0)
        return newNumber;
    return reverse3((newNumber << 1) | (number & 1), number >> 1);
}

Without recursion:

public static int reverse4(int number) {
    int newNumber = 0;
    while (number != 0) {
        newNumber = (newNumber << 1) | (number & 1);
        number >>= 1;
    }
    return newNumber;
}

Hint: I have only considered the given range. I did not think about negative numbers.

You could try to avoid Scanner and use Integer.parseInt inside a try/catch. Who knows what they throw at you at the command line. The nextInt from Scanner does a Integer.parseInt, but it also tries to match tokens.


Am I missing any security loopholes in this php script that reads and outputs directory/file from $_GET variable

As Jason stated checking for ".." is a good idea. If there are only a limited number of path where the pdfs are located on the server, I would even prefer matching against this set.

Nevertheless, you might also want to invert your ifs to get rid of the nesting and use guard conditions.

<?php
    // !!!! comment intention, not what your code is doing

    // Don't allow direct access to the script
    if (strstr($_SERVER['REQUEST_URI'], 'pdffiles.php')) notFound();

    // expected format is "somedir/otherdir/xyz.pdf"
    $path= $_GET['p'];
    if (empty($path)) notFound();

    $root = $_SERVER['DOCUMENT_ROOT'];
    $dir = realpath(dirname($root.'/'.$path));
    if ($dir===FALSE) notFound();
    $file = basename($path);
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    if (strtolower($ext) != "pdf") notFound();

    if ($fh = opendir($dir)) {
        while (false !== ($tfile = readdir($fh))) {
           if ($tfile == "." || $tfile == "..") continue;
           if (strtolower($tfile) != strtolower($file)) continue;

           header("Content-type: application/pdf");
           readfile($dir.'/'.$tfile);
           exit;
        }
    }

    function notFound() {
         // we failed one of our checkpoints, redirect to 404
         header("HTTP/1.1 301 Moved Permanently");
         header("Location: /notfound.html");
         exit();
    }
// ? > !!!! omit this. It's not necessary and you will have no empty line in you php files.

Maybe you want to also have a look at the DirectoryIterator


Count frequency of words in a string returning list of unique words sorted by frequency in descending order

From a once over:

It seems your code is giving the words with fewest occurrences, consider switching b.count and a.count
I am not vehemently against regexes, but if you use them, I would advise 2 lines of comments, one with the intent of the regex, and one with an example of from -> to
Naming, numofwords -> should be numOfWords or since you only use it once you might as well go for numberOfWords and personally I called it cutOff
Not sure why you named the string myString, I would just call it string or s
It seems that sorting the words in advance will require more code to process the words and it is not guaranteed to be faster, I would not do that
From a data structure perspective, I would go for an object, where each word is a property of the object, and the value is the count, this way you can skip the build
If you are going to sort and slice, then perhaps you should FIRST sort and SECOND slice ;)

This would be my approach:

function getFrequency2(string, cutOff) {
  var cleanString = string.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,""),
      words = cleanString.split(' '),
      frequencies = {},
      word, frequency, i;

  for( i=0; i<words.length; i++ ) {
    word = words[i];
    frequencies[word] = frequencies[word] || 0;
    frequencies[word]++;
  }

  words = Object.keys( frequencies );

  return words.sort(function (a,b) { return frequencies[b] -frequencies[a];}).slice(0,cutOff).toString();
}

document.write( getFrequency2( "1 2 1 2 3 1 2 3 1 1 4 test", 3  ) );


Cryptographically secure token generation in C#

What is there to say about it?

The code generates 32 random bytes, fed by a good Cryptographically Secure Random Number Generator, seeded by the operating system. Then it converts to just lowercase hexadecimals.

There is only a very small chance that a CryptographicException is thrown by the random number generator, but if it happens it is currently not caught.


Rails already has a built-in mechanism for doing this with the first_or_initialize method within ActiveRecord::Relation.

As an example, you can perform the following

Service.where(protocol: params[:protocol], port_from: params[:port_from], port_to: params[:port_to]).first_or_initialize

This will try and find a service with the given attributes OR initialize a new object with those attributes set if it can't find it.

Hope this helps.


Order loaded modules by amount of functions

Breaking the problem into tiny, useful functions is a very good way to write Erlang code. So your code is easy to read and gives us a great start in understanding and analyzing it.

The one thing I notice is that, in loaded_modules_with_functions, you map a function over a list and then map a function on the resulting list. This creates an intermediate list which will just be thrown away (GCed.) I'd combine the two operations so there's only one pass through the list. Since the result of this function is the resulting list, I'd use a list comprehension:

loaded_modules_with_functions() ->
  [ extract_functions_from_module(ModName) || {ModName, _} <- code:all_loaded() ].

In extract_functions_from_module, you're making an assumption that the export list is always the second element. Maybe this is the case. Or maybe in your OTP release this is always the case. The next release, however, may break your code if module_info adds more information. You can use the proplists module (in the standard library) to generalize the look-up:

extract_functions_from_module(ModuleName) ->
  {ModuleName, proplists:get_value(exports, ModuleName:module_info(), [])}.

Finally, I'd put a list comprehension at the end of modules_ordered_by_amount_of_functions and inline extract_amount_of_functions.


Use a class, or at least some functions, to make your code more readable and understandable

Very first reaction looking at your code is ....blech. I don't want to read that giant blob.
Why not make a class to bundle a bunch of functions together, such as a function readAndConcatAHT? Actually, many of these for loops are doing the exact same thing for slightly differently named files. Why not do something like a function that takes in a filename and then runs a for loop like so:

def readAndConcatFile(filename, daterange):
    try:
        for date_range in (Timestamp(startdate) + dt.timedelta(n) for n in range(daterange)):
            fcr = pd.read_csv(filename+date_range.strftime('%m_%d_%Y')+ext, parse_dates = ['call_time'])
            data.append(fcr)
    except IOError:
        print('File does not exist:', fcrname+date_range.strftime('%m_%d_%Y')+ext)

This would really clear out your code even if you elected not to write any other functions or a call. I think it's also fairer to your reader and yourself to respect DRY and not make readers check for themselves when you are doing something absolutely repetitive with slightly different function names.

I'll put an extra point to say I think a class would be nice because in your init or some processing function you could string together a bunch of calls to readAndConcatFile to standardize your read/write process for these CSV files. This will, again, make your code more extensible and more readable.

Avoid redundant import statements and stick with standards

Almost everyone uses import pandas as pd. I wouldn't recomend doing it any other way, and it's never a good idea to do a whole scale import *
Don't import glob unless you are actually using it. Where do you use glob after importing it?

Use special features only when you need them

Do you actually need raw strings? I don't see you using your strings in any way that would seem to require them.
Similarly, why use os.chdir when it could be smarter to specify filenames as absolute file names? Here you're again using an option you don't really need and that could have future unintended side effects.

Use more defined constants

It's not a good idea to hard code Timedelta(60 day) like so. You should separately specify DAY_RANGE = 60 as a constant and then use that wherever you'd use 60. That way you can easily change the day range. Alternately, you could make the day range an input parameter to your script so that non-programmer users can also call this script for their desired look-back period.
Similarly, you can save your desired date formats as strings to be treated as constants at the top of your file:
format1 = "'%m_%d_%Y'" and format2 = "'%Y_%m_%d'" Again this makes it easier to see what's going on and also makes it easier to make changes in the future. You can change just one string at the top of your file to change all related formatting, rather than having to change each string. This won't make any given line of code shorter, but it will make it better.

More sophisticated error handling

Error handling is not something I do enough of myself, but I wonder if you can do better here. I'm going to assume that errors in ahtname are related, for example, to errors in fcrname. If that's the case, once you establish that a date range is missing for one kind of file, why not delete that daterange for all further queries in future loops? You could do so easily by simply deleting that member of daterange that causes the IOError. Then you wouldn't get repetitive error messages that are really all telling you the same thing.

What I liked

It's good practice to use generator expressions where you can, so I liked seeing code like for date_range in (Timestamp(startdate) + dt.timedelta(n) for n in range(daterange)):.


We cant review the code if you don't provide it, telling us that it is a bit long will not help. You should provide the full code especially since it is likely that refactoring will be useful between the different cases.

Regardless, here are some observations from what you did provide:

In essence, whatever the user does, you will always call setValue(), once you realize this you can simplify the first if statement

if ($("#up_vote").hasClass("voted") || $("#down_vote").hasClass("voted")) {
  if ($(this).hasClass("voted")) {
    action = "remove_vote";
  } else {
    action = "switch_vote";
  }
} else {
  action = "add_vote";
}
setValue();

And, since you only call setValue() once, you can even take it out of it's function and just put it after the first if statement.
You might even consider replacing the if statement inside setValue with a ternary statement: value = e.target.id === "up_vote" ? 1 : -1;
When posting data, you should use "POST", not "GET"
I feel votes.php should give back the vote counts. Just adding 1 or removing 1 from the last vote count is cheating, and I think users can tell.
Finally, and this is a matter of taste, I would not send +1 or -1 back, I would send the value of e.target.id back, and let the back-end do the conversion.


Why don't you use the exif timestamps of your images and name them accordingly? I use the following code to rename my images. It also extends the timestamp to feature not only the date but also the time:

import os
import glob
from PIL import Image
from PIL.ExifTags import TAGS
import time

def get_exif(fn):
    ret = {}
    i = Image.open(fn)
    info = i._getexif()
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        ret[decoded] = value
    return ret

os.chdir("/path/to/images")

files = glob.glob("*.JPG")

for file in files:
    print(file)
    time = get_exif(file)["DateTimeOriginal"]

    time = time.replace(":", "")
    time = time.replace(" ", "_")
    number = 0
    new_name = time+"_additional_information.jpg"
    if new_name == file:
        print(new_name, "already ok")
        continue
    while os.path.exists(new_name):
        number += 1
        new_name = time+"_"+str(number)+"_additional_information.jpg"
    os.rename(file, new_name)

If you want to use your own code, why don't you just test it on a copy of the data?


Naming

Java method names should not contain underscore characters. It's also preferable to use CamelCase even for abbreviations for readability (e.g. graphJson instead of graphJSON. convertListToCSATGraphJSON is pretty clumsy and could stand to be renamed for simplicity and clarity.

Implementation

I'm going to assume there's a good reason you're hand-rolling this. If not, hibernate has tools to help do this for you.

You have both for loops backwards. The first one should be an enhanced for-loop, and the second should be old-school.

There is absolutely no reason for the second for loop or the switch statement to exist. Just directly set the values by accessing the index number in the Object[] directly.

You may run into trouble later using a List<Object[]>. Generics and arrays do not play nicely together. Changing that is outside the scope of this review.

Small static helper methods can greatly clean up the variable assignments.

If you were to make all these changes, your code might look more like:

public List<CSATGraphJSON> convertListToCSATGraphJSON(final List<Object[]> list) throws ParseException {
    final List<CSATGraphJSON> customers = new ArrayList<CSATGraphJSON>();
    for (final Object[] objects : list) {
        final CSATGraphJSON graphJson = new CSATGraphJSON();
        graphJson.setX(parseString(objects[0]));
        graphJson.setVeryPoor(parseInt(objects[1]));
        graphJson.setPoor(parseInt(objects[2]));
        graphJson.setAverage(parseInt(objects[3]));
        graphJson.setGood(parseInt(objects[4]));
        graphJson.setVeryGood(parseInt(objects[5]));
        graphJson.setTotal(parseInt(objects[6]));
        customers.add(graphJson);
    }

    return customers;
}

private static String parseString(final Object o) {
    if (o == null) {
        return null;
    }
    return o.toString();
}

private static int parseInt(final Object o) {
    if (o == null) {
        return 0;
    }
    return Integer.parseInt(o.toString());
}


F# method to insert, update, or delete events in a dictionary

You have probably found a good solution long time ago, but here is my suggestion:
member this.ProcessEvent(sourceStream: OrderResponse) =
    let handler: (Order -> unit) =
        match sourceStream.Action with
        | Action.Partial
        | Action.Insert -> (fun x -> this.orderState.[x.OrderId] <- this.ConvertFullOrder x)
        | Action.Update -> (fun x -> this.orderState.[x.OrderId] <- this.UpdateOrder x this.orderState.[x.OrderId])
        | Action.Delete -> (fun x -> this.orderState.Remove(x.OrderId) |> ignore)
        | _ -> (fun x -> ())

    sourceStream.Data |> Seq.iter handler

I'm not sure. what type x has, so for the illustration I just call it Order in the handler definition.


It seems that Tile is a key element in your game model.
On the other hand, a field like Tile.hasBeenSearched sounds something technical, not something that belongs to conceptual model.
You probably don't wake up in the morning thinking, "hm, it will be nice to give the Tile class a hasBeenSearched attribute". This field is an implementation detail of the flood-fill algorithm, and I don't think it fits well into Tile. It will be better to use a Set<Tile> searched.
This field could be encapsulated within a FloodFiller class,
that takes tilesForSort and returns a collection of tiles for which the caller can set isPowered to true.
The advantage of this approach will be that you can reuse FloodFiller for other purposes, say, to actually flood your city.

This call is a bit tedious, with the duplicated tile.getPosition():

powerFill(tile.getPosition().x, tile.getPosition().y);

It would be good to create a helper powerFill(tile.getPosition()) that forwards to powerFill(int, int).

The name isNotInsideGrid is a bit clumsy. How about isOutsideGrid ?

Perhaps something like this might work well:

public class FloodFill {
    interface World {
        Set<Position> getEligibleNeighbors(Position position);
    }

    interface Position {
    }

    public static Set<Position> floodFill(World world, Position start) {
        Set<Position> searched = new HashSet<>();
        floodFill(world, searched, start);
        return searched;
    }

    private static void floodFill(World world, Set<Position> searched, Position position) {

        if (searched.contains(position)) {
            return;
        }

        searched.add(position);

        for (Position neighbor : world.getEligibleNeighbors(position)) {
            floodFill(world, searched, neighbor);
        }
    }
}

The idea is:

It is the responsibility of the World implementation to return the valid neighbors of a position that are eligible for filling:

x +- 1, y +- 1, or whatever coordinate system you use
Excluding positions outside of the world's boundary
Excluding positions where zoneType.getLevel() < 1
Any other custom logic you might need

The FloodFill class doesn't need to know anything else about the world, and doesn't need to know what "filling" really means

This gives you the flexibility to reuse the flood fill logic to other purposes, without polluting the rest of your game model with specific knowledge catering to the flood fill process.


Alternate way for comparison call back function?

Comparator

There is no need for your interface.... what's wrong with Comparator? Why do you need to have your own?

The reason you appear to have it is because you need to compare the myTreeItem against another myTreeItem and the generic type is not right for you, but you can solve it easily with wrapping the Comparator in your myTree class when you need to....

So, your code has:

tree1.setCallback(new comparableCallBack<Integer>() {
        public int onCompare(myTreeItem<Integer> item1,
                myTreeItem<Integer> item2) {
            .......
        }
    });

but it should instead have:

tree1.setCallback(new Comparator<Integer>() {
        public int compare(Integer item1, Integer item2) {
            .......
        }
    });

and then, your library should have it's own private Comparator that looks something like:

class TreeComparator <T> implements Comparator<myTreeItem<T>> {

     private final Comparator<T> delegate;
     TreeComparator(Comparator<T> delegate) {
         this.delegate = delegate;
     }
     public int compare(myTreeItem<T> a, myTreeItem<T> b) {
         return delegate.compare(a.getItem(), b.getItem());
     }
}

Code Style

Read the Java Code-style guidelines.

Java class names should start with a capital letter.


Excel's SUMIFS implemented using PANDAS, the Python Data Analysis Library

The usual approach -- if you want all the projects -- would be

>>> df.groupby("PROJECT")["HOURS"].sum()
PROJECT
A001       15
B002        6
C003       11
Name: HOURS, dtype: float64

This only applies the sum on the desired column, as this constructs an intermediate SeriesGroupBy object:

>>> df.groupby("PROJECT")["HOURS"]
<pandas.core.groupby.SeriesGroupBy object at 0xa94f8cc>

If you're only interested in the total hours of a particular project, then I suppose you could do

>>> df.loc[df.PROJECT == "A001", "HOURS"].sum()
15.0

or if you dislike the repetition of df:

>>> df.query("PROJECT == 'A001'")["HOURS"].sum()
15.0

but I find that I almost always want to be able to access more than one sum, so these are pretty rare patterns in my code.

Aside: .ix has fallen out of favour as it has some confusing behaviour.  These days it's recommended to use .loc or .iloc to be explicit.


Looks good, the only thing I'd suggest is that since you don't really
rely on having strings as nodes, you can also generalise your
implementation to arbitrary chains, i.e. Chain Char for this particular
main function.  You'll need to change to a GADT (I think) but
otherwise the code would just need a few minor additional changes.


volatile bool thread_shutdown = false;

This is definitely not correct. volatile is not for thread safety. What you want here is atomic<bool>.

Other than that, I'd say everything else looks technically kosher. The thing is, the semantics of your move operations will be weird now. For example, if I write:

auto func(A a) {}

auto a = A{};
func(std::move(a));

What I expect to happen is that a is cheaply moved into the function argument (and thus, into the function). Instead what happens here is that I've triggered a thread death plus the creation of a whole new thread. So much for moves being cheap - in fact, copying might be cheaper because it would create a new thread, but not destroy the old one.

If you want to define a constructor that steals data from another object, and creates an entirely new thread to use that data in, that's fine. But using the move constructor for that seems unwise. This is probably a job for a tagged constructor:

A() :
    b_ptr{std::make_unique<B>()}
{
    // I wouldn't rely on order of data members to guarantee the thread
    // is started after the data is set.
    t = std::thread{&A::run, this};
}

A(steal_data_t, A&& a)
{
    a.shutdown_thread();
    b_ptr = std::move(a.b_ptr());
    t = std::thread{&A::run, this};
}

A(A&&) noexcept = default; // well, you'd need to handle moving the atomic, I believe

// Usage:
auto a1 = A{};
auto a2 = std::move(a1); // this invalidates a1, as usual
auto a3 = A{steal_data, std::move(a2)}; // this invalidates a2, as expected

You could avoid some repetition with private helper functions.


Choose the right type for method GetById

If you're only going to make the minimal required change

Accommodate the IQueryable requirement in the layer where it is needed, not in your repository layer. That will probably be some object that takes in an entity, wraps it in an IEnumerable, and calls AsQueryable() on it. (Disclaimer: This may or may not work. I haven't tested it.) If you were to do otherwise and change your repo signature to use IQueryable, that would be coupling the repository layer to downstream requirements, which you are correct in wanting to avoid.

A side pet peeve

Please avoid using object in signatures if you're going to use generics in the same class and you don't have a reason to box (I believe DbSet has to use reflection to find the key so it has a boxing requirement, but your code does not require boxing). Use strong typing all the way until you absolutely must cast to object. You'll thank me later.  And make the parameter names expressive:

public TEntity GetById<TKey>(TKey id)
{
    return this.Entities.Find((object)id);
}

Digging deeper

It seems a bit wonky and counterintuitive to have to pass an IQueryable to SingleResult. But come! Join me on a journey in pursuit of greater understanding of this "IQueryable".

An IQueryable is a bit more than just a collection. It functions as a sort of gateway to the data you're after, letting you query that data without having to use its unique language (SQL, or OData queries, what have you). This is accomplished through an associated query provider, which translates the lambda expressions you provide it to the language of your data store.

More importantly, that query provider decides how to compose and manage queries, and that includes utilizing deferred evaluation. The fact that you can pass it a query from your EF context is its way of telling you "I got this bro. This IQueryable has all I need to pull the data from here when I need it." It will then pull the data it needs for the OData query it's building on demand.

If you instead return it an entity, you have eagerly loaded that entity from the DB yourself, when you may not have needed to. Or at the very least, before you needed to.

A Catch-22

Using the generic repository here directly pits the benefits of IQueryable (deferred evaluation, the need for less "intermediary" code) against the reusability of a library that abstracts data access away from queries (is this even being reused?). In order for these two to coexist, some compromises are going to have to be made, compromises that may result in an extremely mediocre "solution."

A simpler appeal

If you look at the way the OData provider functionality is designed, it's evident that it's meant to directly consume EF context queries including in your web app layer. If the DbContext was meant to be shut away inside a library, they would have designed things a lot differently.

To sum up

I would recommend reconsidering the purpose of your generic repository, why you need it, and what it's buying you.


Counting increasing subsequences with a "hacker's" Binary Index Tree

I wouldn't go as far to say that functional programming and Python don't mix, but you should really consider what you're going for while writing it whatever language you are writing in. I would not make your goal:

  How could I have made it more functional?

while writing Python. If you are used to writing in Haskell (for example) you shouldn't expect to always write like that in Python, so I think you should reconsider your ideal.

As for an actual correction to your code:

If you're going to call list on map, you might as well use a list comprehension, change:

seq = list(map(lambda x: bisect_left(seq_sorted, x), seq))

to:

seq = [ bisect_left(seq_sorted, x) for x in seq ]


NewPolish - unconventional translator in Python

Your code is reasonable, but it does get tripped up if the text (input)
contains multiple adjacent spaces or the cleaned text (content) ends up
containing multiple adjacent spaces. It also could be simplified here and
there. Some suggestions to consider: (1) parameterize the function so the user
can control which punctuation characters to remove; (2) since the algorithm is
fundamentally a word-based translation, it makes sense to convert the text to
words early; (3) the check for already-translated text is not robust to
capitalization; and (4) use the no-argument form of split() to avoid the bug
noted above. Here's one way to make those changes:
def new_polish_translator(text, replace = ',.?-'):
    # Remove unwanted punctuation.
    for char in replace:
        text = text.replace(char, '')

    # Convert to words.
    words = text.split()

    # Translate, unless the text is already New Polish.
    prefix = 'ano'
    if all(w.lower().startswith(prefix) for w in words):
        np_words = words
    else:
        np_words = [prefix + w[-1] + w[0:-1] for w in words]

    # Return new text.
    return ' '.join(np_words).capitalize()

As you know already, this problem raises some tricky questions related to how
the algorithm defines a "word". Simply splitting on whitespace and removing a
few common punctuation markers will fail to handle a variety of human language
inputs reasonably. There are other types of punctation (colon, semicolon, dash,
and some weird ones), some words have internal punctuation (apostrophe), some
words contain or even start with digits, some words convey additional meaning
with capitalization, and some texts care about internal whitespace. Consider
this specimen from Ogden Nash, and notice the details of spacing and
punctuation lost during translation:
# English.

The camel has a single hump;
The dromedary, two;
Or else the other way around.
I'm never sure. Are you?

# New Polish.

Anoeth anolcame anosha anoa anoesingl ano;hump anoeth anoydromedar ano;two anoro anoeels anoeth anorothe anoywa anodaroun anomi' anorneve anoesur anoear anouyo

Is there a a practical way to make a translator that preserves more of
those details? One approach is to use a basic tokenizing technique to decompose
the input text into various tokens, some of which will be preserved as-is and
some of which will be word-translated. These tokenizers are easy to build
because they follow a simple pattern: try to match a sequence of regular
expressions; stop on the first match; emit a Token; then re-enter the loop.
In these situations, it helps to define some simple data-objects to represent
search patterns and tokens. A sketch is shown below. It is purposely unfinished
in the sense that it is missing some error handling (eg, checking that the
patterns exhaust the text) and
it doesn't try to preserve the original word capitalization. But those
improvements are fairly easy to add if you are so inclined.
from collections import namedtuple
import re

Pattern = namedtuple('Pattern', 'kind regex')
Token = namedtuple('Token', 'kind text')

def new_polish_translator(text):
    # Define the search patterns.
    patterns = [
        Pattern('whitespace', re.compile('\s+')),
        Pattern('word', re.compile('[A-Za-z]+')),
        Pattern('other', re.compile('\S+')),
    ]

    # Translate only Token(kind=word). Preserve the rest.
    words = []
    for tok in tokenize(text, patterns):
        if tok.kind == 'word':
            w = tok.text
            words.append('ano' + w[-1] + w[0:-1])
        else:
            words.append(tok.text)

    # Return joined text.
    return ''.join(words)

def tokenize(text, patterns):
    pos = 0
    limit = len(text)
    while pos < limit:
        for p in patterns:
            m = p.regex.match(text, pos = pos)
            if m:
                txt = m.group(0)
                pos += len(txt)
                yield Token(p.kind, txt)
                break

Output:
anoeTh anolcame anosha anoa anoesingl anophum;
anoeTh anoydromedar, anootw;
anorO anoeels anoeth anorothe anoywa anodaroun.
anoI'm anorneve anoesur. anoeAr anouyo?


Parse one table out of CSV with multiple titled tables with the Python CSV module

In general this code look very nice and seems to follow style guidelines well. I found your code easy to follow.  You asked for:

  ... suggestions to make the code more compact, idiomatic, and fit for my goals.

I will start with a couple of points for compact and idiomatic, and then add something a bit bigger picture.

Only need one stop iteration:

Your main loop uses this construct twice:

try:
    ....
except StopIteration:
    break

But the net result of these is identical, and the inner one could simply be removed.

Acccessing Dunders is generally uneeded:

In several places your code has something like:

curr = reader.__next__()

The idiomatic way to do this is:

curr = next(reader)

The __next__ (dunder next) method is there because that is how an object publishes its interface for next().  And while you can access this, you probably shouldn't.

In addition your entire loop is using next().  I suggest that this likely indicates your iteration structure could use some reworking.  Looking for a more natural iteration element may allow the code to be simplified.

Use natural record breaks:

Now something a little more substantive.

The data structure has a natural break between records as an empty line.  By noting the presence of this empty line in the parsing logic, the parsing logic can get quite a bit simpler. In your code you need to have:

prev = curr

Which is needed to reach back a line to find the category name.  But that same category was already marked via a blank line before.

I started to recast your code as an example of how to take advantage of that blank line, and found it just as easy to read in the entire file. The example below does not preserve the logic of looking for category heads of:

 ['id', ' book', ' pages']

But is was not super clear why in your requirements this was important.  But adding that back into the code below, or taking the resulting data and then finding that record in said data, could also be done.

Recast Parsing Code:

def read_my_csv(filename):
    category = None
    header = None
    record_data = {}
    table = []

    def make_record():
        return [dict(zip(header, x)) for x in table]

    with open(filename, 'rU') as csv_data:
        reader = csv.reader(csv_data)

        for row in reader:
            if not row:
                if category:
                    record_data[category] = make_record()
                table = []
                category = next(reader)[0]
                header = tuple(x.strip() for x in next(reader))
            else:
                table.append([x.strip() for x in row])

    if category:
        record_data[category] = make_record()
    return record_data

Test Code:

import csv
data = read_my_csv('csvfile.csv')
for item in data.items():
    print(item[0])
    for records in item[1]:
        for record in records.items():
            print('   {}'.format(record))
        print()

Results from recast:

Manhattan Produce Market
   ('id', '1')
   ('fruit', 'orange')
   ('color', 'orange')

   ('id', '2')
   ('fruit', 'apple')
   ('color', 'red')

Books
   ('id', '1')
   ('book', 'Websterâ€™s Dictionary')
   ('pages', '1000')

   ('id', '2')
   ('book', 'Tony the Towtruck')
   ('pages', '20')

   ('id', '3')
   ('book', 'The Twelfth Night')
   ('pages', '144')

Rope
   ('id', '1')
   ('rope', 'hemp')
   ('length', '12-feet')
   ('diameter', '.5')
   ('color', 'green')

   ('id', '2')
   ('rope', 'sisal')
   ('length', '50-feet')
   ('diameter', '.125')
   ('color', 'brown')

Kings County Candy
   ('id', '1')
   ('flavor', 'grape')
   ('color', 'purple')
   ('bigleague', 'yes')

   ('id', '2')
   ('flavor', 'mega mango')
   ('color', 'yellow-orange')
   ('bigleague', 'no')


Find the maximum price change over any 1 to 5 day rolling window

A first pass will see (as Vishesh suggests) collapsing one dimension, and properly unpacking the index tuple:
import numpy as np

# Window size
W = 5

prices = np.arange(1, 10)  # npr.random([1000,1])*1000

max_array = np.zeros(prices.size-W)
for (index,), elem in np.ndenumerate(prices[:-W]):
    local_max = 0
    for i in range(1, W+1):
        price_return = prices[index + i] / elem
        local_max = max(local_max, price_return)
    max_array[index] = local_max
global_max = np.amax(max_array)

I've also replaced your random array with a simple one so that this is repeatable and verifiable. You should make your window size parametric or at least configurable via constant.
Unfortunately, none of the native Numpy options are great. Your best bet is to use Pandas:
import numpy as np
import pandas as pd

# Window size
W = 5

rolled = (
    pd.Series(prices)
    .rolling(window=W)
    .min()
    .to_numpy()
)
max_array = prices[1-W:] / rolled[W-1:-1]

I have tested this to be equivalent. Note that you need to start with a rolling minimum in the denominator to get a maximum numerator.


Implementation of a property and a corresponding animated setter

The alternative is:

public var isEditing: Bool {
    didSet {
        // do whatever you need when the property changes, e.g.
        updateView()
    }
}

// wrap the changing of `isEditing` in some animation

func setEditing(_ editing: Bool, animated: Bool) {
    if animated {
        someAnimation {
            isEditing = editing
        }
    } else {
        isEditing = editing
    }
}

This basically separates the “do what I need when isEditing changes” from the “by the way, animate that” and it eliminates a private backing stored property.

There are cases where you need to do the “exposed computed property with a private backing stored property” approach, but I generally avoid that pattern where I can.


Finding the longest repeated substring in a string

Off-by-one error

You have an off-by-one error in the innermost while loop: for input string "aa", this will not reach length 1, and give empty string as the result, which is incorrect.

I looked at this loop with suspicion, because I noticed that it checks the string bound in the second condition. The more natural code organization is to check the bound first, and then the second condition &&-ed to the first will be safe.

I suggest to rearrange that way, and for that you will need to rethink and verify all the indexes and ranges there. Which can be pretty hard to get right. So at this point, before touching anything, I suggest to add a bunch of Junit tests first, try to cover all the corner cases.

More bugs

I tried a bunch of random examples, and the program gives incorrect results:

"abac" -> "ab"
"abcac" -> "ab"
"abcba" -> "bc"

As I suggested in the previous point,
it will be good to add Junit tests to verify the logic.

Longest repeated substring problem

Quoting from Wikipedia:

  This problem can be solved in linear time and space by building a suffix tree for the string, and finding the deepest internal node in the tree. Depth is measured by the number of characters traversed from the root.

I think you should look into that and abandon your current implementation.


The code is more 'Pythonic' than the majority of the codes I have seen here. Are you sure you are just a beginner in python?

One suggestion is to keep consumerKey, consumerKeySecret, accessToken and accessToken secret in another python file, and import these values from that file.
If you do that then, when you need to send this code to somebody or upload it anywhere, you can do it without worrying about making your consumerKey, consumerKeySecret, accessToken and accessToken values public.

Some of your lines are too long. I recommend you to follow PEP 8 standards while writing the code.

Also keep the naming convention uniform throughout the code.If you are using camelcase, then follow camelcase throughout.

I believe that you can do the following task

for tweet in reversed(tweets):
    latestID = tweet.id_str

like this:

lastID = tweet[0]

Also you are appending the tweets into a file and get_last_id() returns the topmost tweet id. I think that is a bug.

A class for each Tweet would have been better. That will make the code more beautiful.

Here is my implementation: github. You can refer it while converting this into a class.
PS: My code is also not perfect. So I also welcome any comments, tips on my code too.


You can make use ":counter_cache", it finds the number of belonging objects more efficient.

class Book < ApplicationRecord
  belongs_to :author, counter_cache: true
end
class Author < ApplicationRecord
  has_many :books
end

Asking for the value of @author.books.size requires making a call to the database to perform a COUNT(*) query. To avoid this call, you can add a counter cache, with this declaration, Rails will keep the cache value up to date, and then return that value in response to the size method.

Reference : http://guides.rubyonrails.org/association_basics.html


Alternative for checking the existence of a value in PHP

As Hugo Dozois suggested, using isset with the ternary operator is a good way to do this.

If you can assume that the options have not been set to NULL or false and you can change the $ecom variable you can use array_merge or the union operator.

// Merge with your default values here.
$ecom += array('ecom_options_flickr_api'    => '',
               'ecom_options_flickr_secret' => '',
               'ecom_options_freebase_api'  => '',
               'ecom_options_ebay_api'      => '');

// Set the variables.
$flickr_key    = $ecom['ecom_options_flickr_api'];
$flickr_secret = $ecom['ecom_options_flickr_secret'];
$freebase_key  = $ecom['ecom_options_freebase_api'];
$ebay_key      = $ecom['ecom_options_ebay_api'];

If they could be NULL or false you could set them using a short ternary as Hugo Dozois mentioned.  The indexes will now be set thanks to the union so you won't get Notices for undefined indexes.

Other Suggestions

I think your structure would be better represented as a multidimensional array:

$ecom['options'] = array('flickr_api'    => '',
                         'flickr_secret' => 'etc.');
Often intermediary variables such as $flickr_secret etc. are a bad idea IMO.  I prefer to use $ecom['options']['flickr_secret'] in my code.  I find aliases normally just confuse the code.


Use of static factory methods for vectors and matrices library

To put it simply, you're using the wrong language elements to achieve your goals.

The purpose of interfaces is to serve as a contract.
They define a set of actions that implementations must be able to perform.
Although Java 8 made it possible to add static and default methods to an interface (and I'll have to read up on why they did that),
it's best when an interface contains no implementation at all.
Before adding static or default methods,
think twice, and question yourself if there's a better way.

In this example,
it seems quite clear that all those createFrom* methods are in fact utility methods,
that would be best in a utility class.
There's no point putting them anywhere else if they cannot be extended or overridden.
So it would be better to extract these to a Vector2dUtils class or similar.

And why does a Vector2d extend Bufferable and Measurable?
What does that even mean?
It seems like this interface is trying to do too much.
I strongly suspect violations of the single responsibility principle in your implementation.

  the interface class knows about a specific implementation and can only return Vector2f instances, and

Why does an interface know about any implementations at all? It really shouldn't.

  a client expecting a Vector2d implementation class gets a Vector2f instead!

Why would a client expect a specific implementation from a method that returns an interface type? It really shouldn't.

You seem deeply confused. I recommend further reading on the subject:

In Effective Java by Joshua Bloch (in this order):

Item 19: Use interfaces only to define types
Item 17: Design and document for inheritance or else prohibit it
Item 18: Prefer interfaces to abstract classes
Item 16: Favor composition over inheritance

Consider a related pattern used by java.util.Collections (source code), in particular the facilities provided by methods like .emptyList, .unmodifiableList, .synchronizedList
Consider a related pattern used by java.util.EnumSet (source code), especially how its various factory methods create either RegularEnumSet or a JumboEnumSet depending on what is appropriate given the input params, and the client just doesn't need to know whatever is the actual implementation.


Array decomposing recursive function in JavaScript

If you don't need using recursion, this is an alternative where you can get rid of the second param of the function.

const stringToArray = (str) => {
  const result = [];
  let wordArray = str.split(' ');

  while(wordArray.length > 0) {
    result.push(wordArray.join(' '));
    wordArray = wordArray.slice(1);
  }

  return result;
};

const partsArray = stringToArray('Chicago IL 12345 United States');

console.log(partsArray);


Find how many inequalities can be simultaneously satisfied

Avoid using namespace std;

Bringing all names in from a namespace is problematic; namespace std particularly so. See Why is “using namespace std” considered bad practice?.

Don't do everything in main()

Putting all the code into the main() function makes it harder to test parts of the program separately.  If we at least create a function that can read from an arbitrary std::istream, then we're able to do more repeatable testing (by passing suitable std::istringstream objects with our test data in).

Always test that input was successfully read

When we read values from an input stream, we must check that the read was successful before using those values.  A simple way to do that is to set the stream to throw exceptions on failures.

We also need to be more robust when we've read the inequality type, rather than just assuming it will be found in symbols.

Consider using unsigned types

We know that N can't be negative, and the answer is a count of results, which must necessarily be non-negative, too.

Magic numbers

The magic numbers 1..5 used for the different inequalities should be given names.  But there's something better that we can do: we can change their type to be the actual functions:

#include <functional>

///...
{

    using inequality = std::function<bool(float,float)>;

    vector<float> arrayOne(T, 0);
    vector<inequality> arrayTwo(T);
    static const std::map<string, inequality> symbols =
        {
         { ">", std::greater<float>() },
         { ">=", std::greater_equal<float>() },
         { "=", std::equal_to<float>() },
         { "<=", std::less_equal<float>() },
         { "<", std::less<float>() },
        };

Then the big switch becomes much simpler:

    for (auto const& numTwo: arrayTwo){
        passNum += numTwo(*testNum, arrayOne[i]);
        i++;
    }

(I must point out in passing that those names - arrayOne, arrayTwo, numTwo - are really uninformative and unhelpful; you really do need to spend some time thinking of better names if you want to be able to understand your code again later.)

Reconsider the algorithm

Instead of performing all the comparisons on a selection of values (which is O(n²) unless there's many duplicate C values), let's consider what happens to the number of satisfied inequalities as we move X from -∞ to +∞:

each < changes the count by -1 infinitesimally before C
each <= changes the count by -1 infinitesimally after C
>= and > change the count by +1 before or after C, respectively
= changes the count by +1 before and -1 after.

So we can keep an ordered map of those changes:

struct delta
{
    int before;
    int after;

    delta& operator+=(const delta& other)
    {
        before += other.before;
        after  += other.after;
        return *this;
    }
};

Then, just add the appropriate delta values for each inequality:

static const std::map<string, delta> symbol_delta =
    {
     { ">",  {  0,  1 } },
     { ">=", {  1,  0 } },
     { "=",  {  1, -1 } },
     { "<=", {  0, -1 } },
     { "<",  { -1,  0 } },
    };

for (auto i = 0u;  i < lines;  ++i) {
    std::string var;
    std::string symbol;
    double value;

    in >> var >> symbol >> value;
    if (var != "X") {
        throw std::invalid_argument(var);
    }

    auto entry = symbol_delta.find(symbol);
    if (entry == symbol_delta.end()) {
        throw std::invalid_argument(symbol);
    }

    const delta& d = entry->second;
    changes[value] += d;
    if (d.before + d.after < 0) {
        // it's a less-than relation, so true at -∞
        ++count;
    }
}

When that's done, start with a count of the number of inequalities that are true at -∞, (i.e. the total number of < and <= we've seen) and update that count as we walk the map, keeping track of the maximum:

auto max_count = count;
// now, advance to +∞; updating count as we go
for (auto& entry: changes) {
    const delta& d = entry.second;
    count += d.before;
    if (count > max_count) { max_count = count; }
    count += d.after;
    if (count > max_count) { max_count = count; }
}

The complexity of this algorithm is O(n log n), because we're doing a O(log n) insertion into the map n times.

Full working alternative

#include <istream>
#include <map>
#include <string>

struct delta
{
    int before;
    int after;

    delta& operator+=(const delta& other)
    {
        before += other.before;
        after  += other.after;
        return *this;
    }
};

unsigned int max_inequalities(std::istream& in)
{
    // ensure stream '>>' succeeds or throws
    in.exceptions(std::ios_base::badbit | std::ios_base::failbit);

    unsigned int lines;
    in >> lines;

    std::map<double,delta> changes;
    unsigned int count = 0;     // count of satisfied inequalities at -∞

    static const std::map<std::string, delta> deltas =
        {
         { ">",  {  0,  1 } },
         { ">=", {  1,  0 } },
         { "=",  {  1, -1 } },
         { "<=", {  0, -1 } },
         { "<",  { -1,  0 } },
        };

    for (auto i = 0u;  i < lines;  ++i) {
        std::string var_name;
        std::string comparison;
        double value;

        in >> var_name >> comparison >> value;
        if (var_name != "X") {
            throw std::invalid_argument(var_name);
        }

        auto entry = deltas.find(comparison);
        if (entry == deltas.end()) {
            throw std::invalid_argument(comparison);
        }

        const delta& d = entry->second;
        changes[value] += d;
        if (d.before + d.after < 0) {
            // it's a less-than relation, so true at -∞
            ++count;
        }
    }

    auto max_count = count;
    // now, advance to +∞; updating count as we go
    for (auto& entry: changes) {
        const delta& d = entry.second;
        count += d.before;
        if (count > max_count) { max_count = count; }
        count += d.after;
        if (count > max_count) { max_count = count; }
    }

    return max_count;
}

#include <iostream>
#include <sstream>

int main()
{
    auto input = std::istringstream{"4\n"
                                    "X = 1\n"
                                    "X = 2\n"
                                    "X = 3\n"
                                    "X > 0\n"
    };

    std::cout << max_inequalities(input) << '\n';
}


Blocking send and receive algorithm in Go

You have at least one bug.

The closure from your code:

package main

import (
    "fmt"
    "time"
)

func main() {
    for i := 0; i < 7; i++ {
        go func() {
            x := i
            fmt.Printf("Sending successful. i=%v\n", x)
        }()
    }
    time.Sleep(4 * time.Second)
}

Output:

$ go run closure.go
Sending successful. i=7
Sending successful. i=7
Sending successful. i=7
Sending successful. i=7
Sending successful. i=7
Sending successful. i=7
Sending successful. i=7
$

The x := i statement is in the wrong place. It should be:

package main

import (
    "fmt"
    "time"
)

func main() {
    for i := 0; i < 7; i++ {
        x := i
        go func() {
            fmt.Printf("Sending successful. i=%v\n", x)
        }()
    }
    time.Sleep(4 * time.Second)
}

Output:

$ go run closure.go
Sending successful. i=4
Sending successful. i=5
Sending successful. i=1
Sending successful. i=3
Sending successful. i=2
Sending successful. i=0
Sending successful. i=6
$

Reference:

Go: Frequently Asked Questions (FAQ)

What happens with closures running as
goroutines?


Archiving content in SharePoint libraries

Well, one is redundant, Dispose() on the site object is done for you automatically in the context of using. To be idiomatic in C#, you should do the following:

using (var site = new SPSite(connectionString))
using (SPWeb web = site.OpenWeb()) // open the site
{
        try
        {
            Console.WriteLine("[{0}] Opened site: {1}", DateTime.Now.ToShortTimeString(), web);
            Console.WriteLine("[{0}] Web Relative URL is: {1}", DateTime.Now.ToShortTimeString(), web.ServerRelativeUrl);

            // Get your source and destination libraries
            var source = web.GetList(web.ServerRelativeUrl + @"/Approval%20History%20%20Sales1");
            var destination = web.GetList(web.ServerRelativeUrl + @"/Approval%20History%20%20Sales");

            Console.WriteLine("[{0}] Source set to: {1}", DateTime.Now.ToShortTimeString(), source);
            Console.WriteLine("[{0}] Destination set to: {1}", DateTime.Now.ToShortTimeString(), destination);

            // Get the collection of items to move, use source.GetItems(SPQuery) if you want a subset
            SPListItemCollection items = source.Items;

            // Get the root folder of the destination we'll use this to add the files
            SPFolder folder = web.GetFolder(destination.RootFolder.Url);

            Console.WriteLine("[{0}] Moving {1} files from {2} to {3} - please wait...", DateTime.Now.ToShortTimeString(),
                              items.Count, source, destination);

            // Now to move the files and the metadata
            foreach (SPListItem item in items)
            {
                //Get the file associated with the item
                SPFile file = item.File;

                // Create a new file in the destination library with the same properties
                SPFile newFile = folder.Files.Add(folder.Url + "/" + file.Name, file.OpenBinary(), file.Properties, true);

                // Optionally copy across the created/modified metadata
                SPListItem newItem = newFile.Item;
                newItem["Editor"] = item["Editor"];
                newItem["Modified"] = item["Modified"];
                newItem["Modified By"] = item["Modified By"];
                newItem["Author"] = item["Author"];
                newItem["Created"] = item["Created"];
                newItem["Created By"] = item["Created By"];

                // UpdateOverwriteVersion() will preserve the metadata added above.
                newItem.UpdateOverwriteVersion();

                // Delete the original version of the file
                // todo: make local backup before deleting?
                file.Delete();
                fileCount++;
            }

            Console.WriteLine("[{0}] Completed moving {1} files to {2}", DateTime.Now.ToShortTimeString(), fileCount,
                              destination);
        }
        catch (System.IO.FileNotFoundException)
        {
            Console.WriteLine("[{0}] Unable to set a location. Please check that paths for source and destination libraries are correct and relative to the site collection.", DateTime.Now.ToShortTimeString());
        }
}


Some of the logic is nicely encapsulated in functions sendx and recvx, but then main disappoints with its lump of code. It would be better to leave main in charge of parsing and validating the command line arguments, and extract the rest to functions with descriptive names.

In main the assert(argc == 3) should come before the first memset: no need to initialize memory if you might not use it.

In sendx, the variable i is used for two purposes: loop variable for reading input, and input size. If you extract the input reading to a function that returns the number of characters read, then in sendx you can store that in a variable with a descriptive name, and the logic of the main responsibility of this method will become clearer.


Assemblies and naming

Assemblies are units of deployment -- you should put this code in the assembly it's being used in; don't over-think it. Use namespaces, not assemblies, for logical partitioning of code, and don't create a new assembly just because some code may be used elsewhere. Wait until it is used elsewhere.

However

However, I would question the usefulness of such a function.

You catch an Exception, which is generally not recommended -- what happens if it's an OutOfMemoryException? But you're forced to catch an Exception as you have no way of knowing which exceptions could be thrown.

You throw an Exception, forcing callers in turn to catch an Exception. And only the last exception is kept around (in the inner exception) -- what if some exceptions require special handling, or logging? All the information contained in them is lost. As @CodesInChaos commented, an AggregateException would be better.

What if it's being called on the UI thread, and it wouldn't make sense to call Thread.Sleep between retries?

The problem with this method is that it tries to be too general. Retry logic will often have very specific requirements that can't be abstracted away into one function. For instance, say I'm getting exceptions that contain HTTP status codes. If I'm getting 503 Service Unavailable, I may want to try again with exponential back-off. But if it's a 400 Bad Request, there is something wrong with my code and I should log it without retrying.


Is my login function secure ? how to improve it?

I answered you on SO but I'll repeat it here too.

Please read the CakePHP Documentation, preferably from the start because you really are getting a lot wrong here.

There is no need to addslashes() everything, (or anything ever)
CakePHP has it's own AuthComponent, so no need to roll your own
It also has a validation engine, so no need to validate anything here
You're also passing some Request object to the method? I don't even want to ask...

This action should basically be about 6 lines long. TL;DR: Read the CakePHP Authentication docs, and start again.


Am I using "global" right?

It would be better to not use global at all,
by wrapping this in a class,
with state and list as attributes,
so an instance could reference them with self.state, for example.

  How did I do?

state is used as a boolean.
So it should be a boolean value,
set to False instead of 0 and True instead of 1 values.

list is not a good name for a variable,
as it shadows a built-in with the same name.

A quick tip: you can write ["x", "x", "x", "x", "x", "x", "x"] simpler as ["x"] * 7.
In any case, duplicating "x" in multiple places (first when you initialize list, and then later in linearProbing), is not great.
It would be better to put the value "x" in a variable, say FREESPOT = "x",
and reuse that everywhere.


Filtering a List based on a Suffix and avoid duplicates

First off, since you're looking for strings that end with _imp, x.endswith("_imp") is probably more reliable than "imp" in x.
Second, since we only want to remove _imp when it's a suffix, and since we know how long it is, we can use string slicing to remove the last 4 characters. That means we don't accidentally turn x_impabc_imp into xabc instead of x_impabc or something. Assuming that's not what we want to do. Maybe it is, maybe it isn't, maybe we'll never get an input like that so it won't matter either way, I have no idea.
I'm also thinking it might be nice to pass the suffix as a parameter. Maybe it might change at some point in the future. Maybe another part of the program uses a different suffix in a similar way. Doesn't hurt to be prepared.
In general, though, your approach is good. You find the _imp ones, you figure out what they are replacing, you remove the ones that have been replaced.
The neat thing is, you can do the first two steps all at once in a single pass through the input list. For example, you can do this:
def imputed_handler(my_list, suffix="_imp"):
    my_set = set(my_list)
    cleaned_imp = set(item[:-len(suffix)] for item in my_set if item.endswith(suffix))

    return list(my_set - cleaned_imp)

Though a loop might be clearer at that point:
def imputed_handler(my_list, suffix="_imp"):
    my_set = set(my_list)

    for item in my_list:
        if item.endswith(suffix):
            my_set.discard(item[:-len(suffix)])

    return list(my_set)


config.properties, Static Classes and Reflection

Do you have an actual, measured performance issue with accessing the properties file every time? If not, you're just introducing complexity to no end. What happens if the application crashes? All your updated properties are gone.

If you do have an actual, measured performance issue, consider keeping an in-memory copy of the properties. When one changes, update the in-memory version and spawn a low-priority thread to handle the write to the file. If you do, then you have to worry about the order those threads run in.

Definitely don't use Strings. If you're going to enumerate all your properties, use an enum. If you do, you shouldn't need reflection .. just walk down the values() of the enum.


Code Smell in Unit Testing Serialized Classes

I think the bigger issue is that you have an operation with side-effect in the property setter SerialPortConnection,  which means that if your unit test fails, it will not be clear whether it is due to a problem with deserialisation or with the operation.

I would suggest moving the operation (i.e. writing "R" to the port) in a separate Initialize method that you can test individually.


If you have setter methods (setName, setFullName) in your class, then your constructor should call the setter methods.

setName(personJsonObject.getString("name"));

If you don't have setter methods in your class (your class is immutable), then your constructor should perform the evaluation.

this.name = personJsonObject.getString("name");

You should only pass to a method what it needs.  In this case, your setName method takes a String as a parameter, which is what the method needs.  If your method needs 3 or more values from the personJsonObject (arbitrary rule of mine), then you would pass the personJsonObject to the method.


There are two things I would like to point out here.

There is no need to do the cast on the putColumn call. The method signature is: public <T> void putColumn(Column<T> type, T instance) { so we know that instance is of type T already, and it is being stored in an Object value in a Map. There is no reason to force the cast before storing it.
The Column's cast method would be better done using a Class<T> instance. Consider the 'standard' pattern of requiring a class instance in the constructor of the Column. For example:

class Column<T> {

    private final Class<T> valClass;
    public Column(Class<T> valClass) {
        this.valClass = valClass;
    }

    public T cast(Object obj) {
        return obj == null ? null : valClass.cast(obj);
    }
}

this has the benefit of not requiring the SuppressWarnings. It also ends up being helpful for other reasons too.

The class would be used as:

Column<String> col = new Column(String.class);

Apart from that, things will be the same.


var before = ace.edit("beforeSQL", {
  showPrintMargin: false,
  fontSize: '14px',
  theme: "ace/theme/sqlserver",
  mode: "ace/mode/sql"
}),
execute = ace.edit("executeSQL", {
  showPrintMargin: false,
  fontSize: '14px',
  theme: "ace/theme/sqlserver",
  mode: "ace/mode/sql"
}),
after = ace.edit("afterSQL", {
  showPrintMargin: false,
  fontSize: '14px',
  theme: "ace/theme/sqlserver",
  mode: "ace/mode/sql"
});

There's a lot of repetition here in terms of the options you're using. You could avoid repeating yourself by creating an object to hold defaults. For example:

const defaults = {
  showPrintMargin: false,
  fontSize: '14px',
  theme: "ace/theme/sqlserver",
  mode: "ace/mode/sql"
}

var before = ace.edit("beforeSQL", {...defaults})
var execute = ace.edit("executeSQL", {...defaults})
var after = ace.edit("afterSQL", {...defaults})

To avoid repeating yourself when adding an event listener you could do something like this:

[before, execute, after].forEach(obj => {
  obj.session.on('change', toggleSubmit);
})


I have a strong suspicion that this is an XY Problem, or at the very least, that you're using the wrong abstraction and/or data structure for representing data, using numbers as keywords somehow doesn't seem right. Anyway, I think the requested functionality can be implemented in an alternate, simpler way:

; obtain all values for a given keyword
(define (key-values lst kwd)
  (cond ((null? lst) '())
        ((equal? (first lst) kwd)
         (cons (second lst) (key-values (cddr lst) kwd)))
        (else (key-values (cddr lst) kwd))))

; interleave elements from two lists
(define (interleave lst1 lst2)
  (cond ((null? lst1) lst2)
        ((null? lst2) lst1)
        (else (cons (first lst1) (interleave lst2 (rest lst1))))))

; create all layers according to the defined structure
(define (joiner name lst1 lst2)
  (let loop ((lst (interleave lst1 lst2)))
    (if (null? (cddr lst))
        '()
        (cons (list name (first lst) (second lst) (third lst) (fourth lst))
              (loop (cddr lst))))))

; main function, receives a list of values and a list of keywords
(define (get-values lst kwds)
  (let ((name (first (key-values lst (first kwds))))
        (xs   (key-values lst (second kwds)))
        (ys   (key-values lst (third kwds))))
    (joiner name xs ys)))

For example:

(define test-list '(8 "layer-name" 10 30 20 30 10 40 20 40 10 50 20 50))
(define keywords '(8 10 20))
(get-values test-list keywords)
=> '(("layer-name" 30 30 40 40) ("layer-name" 40 40 50 50))


Follow up - Decide whether a triangle is isosceles or not

Law of Excluded Middle

Something is either an isosceles triangle or it isn't. (This is a consequence of Law of Excluded Middle). Given this knowledge, as an exercise, what should you be able to eliminate from this code:

    if side1 == side2:
        print("This is an isosceles triangle!")
    elif side1 == side3:
        print("This is an isosceles triangle!")
    elif side2 == side3:
        print("This is an isosceles triangle!")
    elif side1 != side2 and side1 != side3:
        print("This is not an isosceles triangle!")
    elif side2 != side1 and side2 != side3:
        print("This is not an isosceles triangle!")
    elif side3 != side1 and side3 != side2:
        print("This is not an isosceles triangle!")

Don't sleep on me.

There really is no reason to write:

time.sleep(2.5)
side1 = askSideLength("first")
time.sleep(0.25)
side2 = askSideLength("second")
time.sleep(0.25)
side3 = askSideLength("third")
time.sleep(1)

The prompt will wait for the user to input the data, don't make the user wait.

Naming conventions

askSideLength for example should be converted to ask_side_length. We don't use the camelCase for functions and variables in Python. Instead we use snake_case.


mapM for both keys and values of Data.Map

There is keys library which implements

mapWithKeyM_ :: (FoldableWithKey t, Monad m) => (Key t -> a -> m b) -> t a -> m ()

and related functions for Data.Map.

There is also Data.Traversable.mapM, but it only maps over values. Mapping over both keys and values is not a mapM operation because there is Ord constraint.

If you still consider implementing your function yourself, it can be written like this:

import qualified Data.Map as M
import Control.Monad

mapMmap :: (Ord a2, Monad m) =>
   (a1 -> m a2) -> (b1 -> m b2) -> M.Map a1 b1 -> m (M.Map a2 b2)
mapMmap kf vf = liftM M.fromList . mapM fs . M.assocs
    where
    fs (k, v) = liftM2 (,) (kf k) (vf v)


Merges given list of integer entries acccordingly

I'm just going to review creating_resulting_list.

def creating_resulting_list(length_line):
    """
    Function that create a resulting_list with equal number of \
    zeros as length of line
    """
    from itertools import repeat
    return list(repeat(0, length_line))

#BEGIN Test
#print creating_resulting_list(2) == [0, 0]
#print creating_resulting_list(0) == []
#END Test

There's no need to use backslashes at the ends of lines inside a triple-quoted string.
The name creating_resulting_list doesn't help the reader understand what it does. What is a "resulting list" anyway? What this function does is to create a list of zeros. So a better name would be zeros_list or just zeros (see for example numpy.zeros, which is similar).
The argument is called length_line. But this is too specific: nothing in this function cares about lines. By avoiding dependencies like this, you can make code more self-contained and easier to understand in isolation. So I would call this argument just length.
Since the import statement is inside this function, it gets run every time the function is called. If you moved this statement to the top level of your module, then it would be run only once.
The test cases should be made automatically runnable, using the unittest or doctest modules. I'll show below how to do it using the latter.
The sequence documentation says:

  s * n or n * s    equivalent to adding s to itself n times

so you don't need itertools.repeat, you can just multiply.

Revised code with doctests:

def zeros(length):
    """Create and return a list of zeros with the given length.

    >>> zeros(2)
    [0, 0]
    >>> zeros(0)
    []

    """
    return [0] * length

The doctests can be run using python -m doctest program.py.


BoundLess Grid, grid with unknown and infinite dimension

An example of some alternatives that you could use, there may be things there that you prefer.

/*
  A grid which can have any bounds and be checked against.
  create: let grid = new BoundlessGrid();
  set: grid( 0,0, "start point" )
  get: let myVal = grid(0,0);
  delete y:  delete grid()[0][0];
  delete x: delete grid()[0];
  iterate: grid().forEach( (x,y,grid)=> {... } );
*/
function* generateValues(object) {
  for (let value in object) {
    yield value;
  }
}

class BoundlessGrid {
  constructor() {
    this.grid = Object.create(null, {
      forEach: {
        value: callback => {
          for (let x of generateValues(this)) {
            for (let y of generateValues(Reflect.get(this, x))) {
              callback(x, y, this);
            }
          }
        },
        enumerable: false,
        writable: false
      }
    });
    this.deleteProperty = Reflect.deleteProperty.bind(null, this.grid);
    // return a function that abstracts the object into
    // something that has friendlier shorthand syntax
    return (x, y, val) => this.handler(x, y, val);
  }

  has(x) {
    return Reflect.has(this.grid, x);
  }

  set(x, y, val) {
    if (!this.has(x)) {
      const deleteProperty = this.deleteProperty;
      // automatically removes the x grid axis when
      // the last y point is deleted from that x
      Reflect.set(this.grid, x, Reflect.construct(Proxy, [Object.create(null), {
        deleteProperty(yAxis, y) {
          Reflect.deleteProperty(yAxis, y);
          if (Object.keys(yAxis).length === 0) {
            deleteProperty(x);
          }
        }
      }]));
    }
    Reflect.set(Reflect.get(this.grid, x), y, val);
  }

  get(x, y) {
    if (this.has(x)) {
      return Reflect.get(Reflect.get(this.grid, x), y);
    }
  }

  // Single function that delegates to others
  // by determining inputs
  handler(x, y, val) {
    if (x === undefined) {
      return this.grid;
    }
    return val === undefined ? this.get(x, y) : this.set(x, y, val);
  }
}

const grid = Reflect.construct(BoundlessGrid, []);
grid(5, 4, "test1");
grid(5, 3, "test2");
grid().forEach((x, y, g) => console.log(`loop: val of ${x} and ${y}`, g[x][y]));
delete grid()[5][4];
console.log("First deleted key at 5x 4y:", grid(5, 4));
console.log("Value at 5x 3y:", grid(5, 3));
console.log("array of 5x", grid()[5]);
delete grid()[5][3];
console.log("second deleted key exists?", grid(5, 3) !== undefined);
console.log("array 5x defined?", grid()[5]);