Welcome to Python xD!  You did a great job on it ^^

Here are my suggestions

Don‘t code everything all in one function

there are two parts in your one_round

place new piece on board
check if there is a winner or game over

so it is better to divide to 2 functions, or more, it is best that one function just do one thing

Clean up lots if else in it

For example:

if row == "a":
      row = 0
elif row =="b":
      row = 1
elif row == "c":
      row = 2

You can use dictionary instead, board_row = {"a" : 0, "b": 1, "c": 2} or code like row = ord(row) - ord("a")

if player == "p1":
    p = "Player 1"
elif player == "p2":
    p = "Player 2"

AND

if player == "p1":
    x = 'X'
elif player == "p2":
    x = 'O'

Can be replaced by

player_info = {"p1": ["Player 1", "X"], "p2": ["Player 2", "O"]}
...
p, x = player_info[player]

Check win

You did this in a quit straight forward code, so it is a bit long, also in python it is best to just with 79 chars in one line.

You can list all position of lines and use a for loop to check if there is a winner(if the current player is the winner)

positions = (((0,0),(0,1),(0,2)), ((1,0),(1,1),(1,2)), ...)

for p in positions:
    if len(set([board[x][y] for x, y in p])) == 1:
        ...
        # then we have a winner, and the winner can only be the current player

Or just check the lines around current piece position

directions = (((0,1),(0,-1)), ((1,0),(-1,0)), ((1,1),(1,-1)), ((-1,1),(-1,-1)))

for d in directions:
    for x, y in d:
        line = set()
        current_row, current_col = row, col
        while 0 <= current_row < 3 and 0 <= current_col < 3:
            line.add(board[current_row][current_col])
            current_row += x
            current_col += y
        if len(line) == 1:
            # Win

check if it is a draw just need if all('-' not in b for b in board)

Other

del board[row][col]
board[row].insert(col, x)

You just need do board[row][col] = x


Here are my comments:

Functionality:

Remove the superfluous start parameter.
Remove all needlessly complex (and slow) pointer arithmetic.
Use the standard wcslen() function from wchar.h
Position 0 is a valid array index, replace it with an invalid one if value not found.

Performance:

Only call the strlen function once.
Minimize the code inside the if/else statement.

Readability and style:

str isn't modified by the function, so make it const (const correctness).
Rewrite the loop to a conventional one.
Only return once from a function.
Replace all "magic numbers" with constants or enums.

-

#include <stddef.h>
#include <wchar.h>
#include <stdio.h>

typedef enum
{
  DIR_POS,
  DIR_NEG
} dir_t;

#define NOT_FOUND -1

int myInstr (const wchar_t*  str,
             wchar_t         c,
             dir_t           dir)
{
  int start;
  int end;
  int step;
  int length;
  int i;
  int result = NOT_FOUND;

  length = wcslen(str);

  if(dir == DIR_POS)
  {
    start = 0;
    end   = length;
    step  = 1;
  }
  else /* if (dir == DIR_NEG) */
  {
    start = length - 1;
    end   = -1;
    step  = -1;
  }

  for(i=start; i!=end; i+=step)
  {
    if(str[i] == c)
    {
      result = i;
      break;
    }
  }

  return result;
}

int main()
{
  wchar_t str [] = L"1234567890";

  printf("%d\n", myInstr(str, '3', DIR_POS)); // prints 2
  printf("%d\n", myInstr(str, '6', DIR_NEG)); // prints 5
  printf("%d\n", myInstr(str, 'X', DIR_POS)); // prints -1
}


Game of life C++ implementation memory access bug

Stop doing manually memory management (this is not C).
Organism** plain;

There is no reason to have an array of pointers. You could just have an array of object (thus you don't need to manage the individual cells).
Organism*  plain;
....
plain = new Organism[width * height]; // Allocates and calls default constructor.
                                      // You will still need to loop over
                                      // them to reset them to an initial good
                                      // state (but you will not have) to
                                      // manage the memory for individual cells.

Because the cells are no longer pointers you will need to replace -> with . (a dot). But other than than no difference.
Part 2 of memory management
Take this a step further. You don't need to manually manage the memory for the array of plain. We have classes that do that for you.
std::vector<Organism>  plain;        // initially this holds zero elements
...

plain.reserve(width * height);       // Let the object know you are going to
                                     // add a lot of cells so it can pre-allocate space.

for (int i = 0; i < (width * height); i++) {
    state = rand() % 100 < chance;
    plain.emplace_back(state);       // add a new element to the end.
    // If you are using C++03 you may not have emplace_back()
    // So use the regular push_back instead (it does the same thing).
    //    plain.push_back(Organism(state));
}

You can access plain (a std::vector<>) with operator [] like you would an array. So no other code needs to change (you just need any new or delete calls). So you have no memory management calls and thus no headaches with leaks.
Now a nice bit is you can replace plain[x] with plain.at(x) and it checks to make sure you access to the array is in bounds (and will throw an exception if not). This may help you track down your error.
Initialize srand() one
You should only initializre the random number generator once in a program.
srand(time(nullptr));

So it is best to do this in main(). In your application you are doing this once for each game object. This may not seem like a big thing. But of your code get's re-used by another application that does not realize you are doing this. You mess up other people's code.
You should also note. This old random number generator is considered pretty bad. You should probably start looking at the new ones provided by C++11. They are much better and can be used in ways that don't interact (so you don't screw over other people's random numbers).
Move Platform specific code to its own function.
Sleep(500);
system("cls");

You should probably put this in its own function. So when people come to port your code to another platform they just need to provide an alternative implementation to a couple of specific functions and the rest of the code can stay the same.


Thing that makes me more perplex is error-handling.

First of all you're catching all exceptions, it may hide subtle bugs unrelated to web request itself (for example wrong parameters you supply in your own code, StackoverflowException, OutOfMemoryException and so on).
You're swallowing exceptions, you just log them and return null (which is little bit counter-sense because it nullify any benefit of exceptions itself).
You do not give any chance to caller to handle exceptions (you're not doing anything useful, they may do), for example retry after a short amount of time (in case network error is transitory) or even to have any meaningful information about error.

IMO if you're writing library reusable code you shouldn't, it may be acceptable if this is an helper method to avoid repetitive code (but in this case some decent error handling is mandatory). Take, at least, a look at System.Net.WebException: The remote name could not be resolved.

After that, starting from top, I have some perplexity about method argument. It's a string and it has two drawbacks:

User may pass any unknown method and you won't know. Server may respond with an error 501 (according to RFC 2616 section 5.1.1, superseded by RFC 5789) but you will even get 400, 404 or probably 405 out there in the big real world...
User has always to type an error-prone string, no compile-time checks: errors will be detected at run-time (what if she types OPTONS instead of OPTIONS?)

Moreover you're handling strings in the wrong way:

You have method.ToUpper() just in case but there should not be a just in case in production code! Throw an error if you want user to use uppercase text or smoothly handle case errors. According to RFC 2616 (again in section 5.1.1) HTTP method is case sensitive (even if some servers don't care).
If a Turkish user enters options your code will fail because ToUpper() (again it's culture aware) will convert it to OPTİONS (note dotted uppercase İ instead of I).
You're comparing strings with == and it's current culture aware (same as above, it's not safe) and it's not case-insensitive (then what's the point of previous ToUpper()?)

What I'd do? Simply avoid strings in favor of an enum:

public enum HttpMethod
{
    Get,
    Post,
    Put,
}

Then you can convert that to string:

request.Method = HttpMethodToString(method);
if ((method == HttpMethod.Put || method == HttpMethod.Post) && postData != null)

Where HttpMethodToString() may (unless you want to use different names and enum items decorated with attributes) simply be:

static string HttpMethodToString(HttpMethod method)
{
    return method.ToString().ToUpperInvariant();
}

Even better: use already existing System.Web.Http.HttpMethod class and directly use it as string:

request.Method = method.ToString();
if ((method == HttpMethod.Put || method == HttpMethod.Post) && postData != null)

Now let's go to request itself.

HttpWebResponse implements IDisposable then it must be properly disposed, enclose it inside an using statement.

You're assuming that HTTP response is encoded as UTF-8 (StreamReader default) but it's not always true (I don't see anywhere code to add Accept-Charset HTTP header) then your code will fail if server will respond with any other encoding but UTF-8 or - and you're lucky with ISO 8859-1).

Read HttpWebResponse.CharacterSet, create the right Encoding with Encoding.GetEncoding() and give it to StreamReader constructor.

Your function is now doing three things:

Prepares the request.
Gets the response.
Parses response.

It is doing those things inside just one function called CreateRequest, little bit too much (IMO) and with a misleading name! I'd split this function into two/three smaller functions:

public static T ReadJsonFrom<T>(string url, HttpMethod method, string payload) {
    var request = CreateRequest(url, method, payload);
    var response = ReadResponseAsString(request);

    return JsonConvert.DeserializeObject<T>(response);
}

To fill those function is a trivial exercise. Now to understand how it works you need to read just three lines of code and you can put your error-handling code in one specific point: you may, for example, apply a retry pattern to read the response in ReadResponseAsString() but CreateRequest() may fail immediately.


GetBorderedText(string Input, int AbsoluteLength, bool splitLines = true, int Offset = -4)

You are very inconsistent with naming parameters. Some of them are in PascalCase while only one has the correct camelCase. This makes your code look strange and unprofessional.

if (Input.Length > AbsoluteLength + Offset && splitLines)

Conditions like this are better stored in a variable that describes what its purpose is and split into two. Consider this:

var wrapRequired = input.Length > absoluteLength + offset;
if (wrapRequired && canWrap)

input.Split(' ').ToList()

You don't need to call ToList, it's already an array and can be enumerated.

foreach (string s in words)

If your collection is called words then name the item word and not s. It's very confusing when one looks at the code and wonders what that s is.

lineConstruction.Length + word.Length + 1 >= absoluteLength + offset

The same here. You should name this condition propertly and especially the magic 1.

Other than this

you should use StringBuilder for concatenating strings in loops because it's not only faster but also easier to use.
make the border as prefix & suffix parameters instead of hardcoding them (or leftBorder & rightBorder).
use variables with stronger names and use more of them so that they document your code.

As an example of how you can apply all these suggestions here's the new code with one new method for adding the border.

public static string CreateBorderedText(string input, int maxLength, bool canWrap = true, string prefix = "+ ", string suffix = " +")
{
    const string wordSeparator = " ";

    var lines = new List<string>();
    var lineBuilder = new StringBuilder();
    var borderLength = prefix.Length + suffix.Length;
    var contentLength = maxLength - borderLength;

    var wrapRequired = input.Length > contentLength;
    if (wrapRequired && canWrap)
    {
        var words = input.Split(' ');
        foreach (var word in words)
        {
            var projectedLength = lineBuilder.Length + word.Length + wordSeparator.Length + borderLength;
            var wrap = projectedLength >= maxLength;
            if (wrap)
            {
                PadRight(lineBuilder, contentLength);
                AddBorder(lineBuilder, prefix, suffix);

                lines.Add(lineBuilder.ToString());
                lineBuilder.Clear();
            }

            lineBuilder.Append(word).Append(wordSeparator);
        }
    }
    else
    {
        lineBuilder.Append(input);
    }

    PadRight(lineBuilder, contentLength);
    AddBorder(lineBuilder, prefix, suffix);
    lines.Add(lineBuilder.ToString());

    return string.Join(Environment.NewLine, lines);
}

and the two helpers

private static void AddBorder(StringBuilder lineBuilder, string prefix, string suffix)
{
    lineBuilder
        .Insert(0, prefix)
        .Append(suffix);
}

private static void PadRight(StringBuilder lineBuilder, int targetLength)
{
    lineBuilder.Append(' ', targetLength - lineBuilder.Length);
}


The first thing I'd do is to create your Entry objects on demand, rather than in Entries#initialize:

class Entries
  include Enumerable
  ...
  def initialize(body)
    @body = body
  end
  ...
  def each(&block)
    @body.each do |entry|
      block.call(Entry.new(entry))
    end
  end
end

As for dynamically creating methods for each attribute, I'd be wary of doing that. Without knowing your JSON API schema, there could be two possibilities going on:

Each Entry always has the same attributes, so you are spending processing time and memory dynamically generating the same methods every time.
Each Entry may have wildly differing attributes – in which case your clients won't know at runtime which methods each entry object actually responds to, and will have to use some checks of their own, e.g., #respond_to? in order for their code to work reliably.

In either case, you really want your clients to know that each Entry object they receive will have the same attributes at all times. I'd be inclined to explicitly define each attribute method, e.g.:

class Entry
  attr_reader :attributes
  ...
  def title
    attributes[:title]
  end
end

This gives you the option of how to deal with missing attributes in the API. For example, if an array field, such as authors, is missing, you could choose to return an empty array instead:

def authors
  attributes.fetch(:authors, [])
end

I know the non-metaprogramming way can seem like a more boring way of doing things, but even though your entry.rb source code will be much longer, everything will be much clearer and easier to maintain and debug.

And at the end of the day, your gem's users will end up with an interface which is much more predictable – and the methods you include will be more easily documentable through YARD or any other automated documentation tool.


While the general code quality is good, the contract should be formalized by adding "use strict";
Even though var is used, everything is still in the global namespace, thereby polluting it and risking name collisions. Moving things into a namespace also means some other parts of the code can/should be re-arranged.
There's ideally no need to manually specify both the number, and how many digits there are after the ..
I honestly fail to understand the problem the function solves, so it's unclear to me if var decimalBeforeRepeatLength = 2 can also be derived automatically from the input, or if it needs to be a separate input parameter.
There's no radix parameter to parseInt(). Without it, the "correct" behaviour is not guaranteed, so you really should specify it. See Mozilla's documentation for details.
It's unclear to me why parseInt() is used, why not just Math.floor()?
Separating the output from the functionality would be a nice improvement.
improperFractionToMixedNumber isn't included in the actual code you posted, so I can't really comment on that, nor test that the code gets the same results before and after my changes.
Since i is hardcoded to 0, most of the original simplifyFraction() can actually be removed all together, but I'm guessing making i a parameter would be the solution instead.
Why does simplifyFraction() return i when it's an unmodified input parameter?
With some of the changes I've done, a few variables should probably have their names changed. I'll leave that as an exercise to the reader.

Code below incorporating the above changes. I've removed all original comments and added my own, to make it easier to spot the differences.

// Isolate variables and functions from the global scope.
// The namespace should of course not actually be named 'namespace'.
var simplifyFraction = function(decimal, decimalBeforeRepeatLength) {
   // Improve the code quality with strict mode.
  "use strict";

  // Figure out decimal length automatically.
  var indexOfDot = decimal.toString().indexOf('.');
  var decimalLength = decimal.toString().length - indexOfDot - 1;

  var power1 = Math.pow(10, decimalLength);
  var power2 = Math.pow(10, decimalBeforeRepeatLength);
  var finalPower = power1 - power2;
  var decimal1 = decimal * power1;
  // Explicitly set a radix of '10' to avoid unpredicatable results.
  var decimal2 = parseInt(decimal * power2, 10);
  // Preferred option.
  decimal2 = Math.floor(decimal * power2);
  var finalDecimal = decimal1 - decimal2;
  var i = 0;

  var greatestCommonDivisor = function(a, b) {
    if (b === 0) {
        return a;
    }

    return greatestCommonDivisor(b, (a % b));
  };

  var gcd = greatestCommonDivisor(finalDecimal, finalPower);

  // Since simplifyFraction() is now what we use for namespacing, it's not
  // kept as a function in here.
  if (Math.abs(i) > 0 && finalDecimal >= finalPower) {
    if (i < 0) {
      finalDecimal *= -1;
    }

    var temp = improperFractionToMixedNumber(finalDecimal, finalPower);

    return [temp[0] + i, temp[1] / gcd, temp[2] / gcd];
  }

  return [i, finalDecimal / gcd, finalPower / gcd];
};

// The function no longer forces a certain outout. We get back the answer and treat it anyway we want.
//
var answer = simplifyFraction(21.8335745857, 2);


You can just use Python's slice notation. It allows you to pass steps, which allows you to do this with ease.

I also think it's fairly easy to understand.

def zigzag(values):
    half = len(values) // 2
    new = [None] * len(values)

    new[0::2] = values[:-half]
    new[1::2] = values[-half:][::-1]
    return new

>>> zigzag([1, 2, 3, 4])
[1, 4, 2, 3]
>>> zigzag([1, 2, 3, 4, 5])
[1, 5, 2, 4, 3]


You can move the range values first to the array before doing your loops.
You can try below:

Dim tbArray, fcArray, gcArray ' Variant type
Dim elr As Long, flr As Long, glr As Long, i As Long
Dim T

With Sheets("YourSheetName") ' always be explicit when working with objects
    elr = .Range("E" & .Rows.Count).End(xlUp).Row
    flr = .Range("F" & .Rows.Count).End(xlUp).Row
    'glr = .Range("G" & .Rows.Count).End(xlUp).Row
    tbArray = .Range("F2:J" & elr) ' pass Range values, arr becomes 2D array
    fcArray = .Range("F2:F" & flr) ' creates horizontal 2D array but regardless
    gcArray = .Range("G2:G" & flr) ' this will be used for matching only

    For i = LBound(tbArray, 1) To UBound(tbArray, 1)
        If Len(tbArray(i, 1)) = 0 Then ' you can use tbArray(i, 1) = "", just preference
            For Each T In Split(tbArray(i, 5), " ")
                If Not IsError(Application.Match(T, fcArray, 0)) Then
                    tbArray(i, 1) = T ' corresponds to F
                ElseIf Not IsError(Application.Match(T, gcArray, 0)) Then
                    tbArray(i, 2) = T ' corresponds to G
                End If
            Next
        End If
    Next
    .Range("F2:J" & elr) = tbArray ' return the array to range
End With

This is compiled but not tested. We took advantage of using the Match Function.
You based your last rows to Columns E, F and G respectively so I just mimicked that.
No idea on how much data it can handle, but a 10K wouldn't hurt I guess.


has extra blank 's and I have no idea why. please help me get them out

You should close the option tag. Change

$opt7.="<option value='$var'>$m $name<option>";

to

$opt7.="<option value='$var'>$m $name</option>";


You are hitting the time limit as you are supposed to only find the k-th permutation, but you are generating all permutations instead. Look at this discussion. You will probably have to replace the term (numberOfCharacters!) with (numberOfCharacters!/countO!/countZ!) as explained here.


Optimize KnockoutJs Pagination Computed Function

Let's take a look at that first line of the PageDirection function:

var self = this;

This is a common practice to keep a reference to the this object within the closure. A different way to do this would be to bind the context of the closure using Function.bind()
this.disabled = function (currentPage, lastPage) {
    return this.value() > lastPage || this.value() < 1 || this.value() == null;
}.bind(this);

However, there appears to be no need to bind the context

function PageDirection(data) {
    this.display = data.display;
    this.value = data.value;
    this.disabled = function (currentPage, lastPage) {
        console.log('this.value: ', this.value(), ' > lastPage: ', this.value() > lastPage);
        return this.value() > lastPage || this.value() < 1 || this.value() == null;
    };
}

const pd1 = new PageDirection({value: _ => 16, display: 'BMW'});
console.log('pd1 disabled: ', pd1.disabled(1, 10));

Though maybe the KO code invokes that method differently, in which case the function may need to be bound.
Another option would be to use an ES6 arrow function expression, which doesn't have its own this binding:
this.disabled = (currentPage, lastPage) =>
                this.value() > lastPage || this.value() < 1 || this.value() == null;

To be honest, the logic in the observable looks a bit overly-complex. I didn't fully study it and grok it but I would look to see if some of the logic can be simplified - for example:

} else {
    if (pageIndex > 4) {

Unless it is the case that the subsequent logic wouldn't work you might consider if that can be converted to:
} else if (pageIndex > 4) {

Which could decrease the sub-sequent indentation levels.


Cleaning up repeated calls to NSMakeRange()

I see a couple of ways to clean this up.

First of all, you mention not wanting to use #define, but let's not forget about #undef.  You could define a macro as the first line of this method and undefine it as the last line of the method.

For example:

- (NSString *)cleanPath:(NSString *)originalPath inRoot:(NSString *)rootPath {
   #define _STRING_RANGE(string) (NSMakeRange(0,[string length]))
   // code
   #undef _STRING_RANGE
}

Now, this macro definition exists only within this method. You don't necessarily save a whole lot of characters, but autocomplete will be a lot nicer, and you don't have to explicitly tell the macro to start at 0 and go to the end...you've predefined that in the macro.

You can also just write your own C-Style function.  That's all NSMakeRange is after all.

NSRange stringRange(NSString *string) {
    return NSMakeRange(0,[string length]);
}

And while defining a function is fine and dandy, now it can be seen by at least everything in the file.  This is Objective-C, so we can use blocks.  We can create a block within the method, and now the block, much like the #define macro that we #undef exists only within the method:

- (NSString *)cleanPath:(NSString *)originalPath inRoot:(NSString *)rootPath {
    NSRange (^stringRange)(NSString *) = (^NSString *string) {
        return NSMakeRange(0,[string length]);
    }
    // code...
}

Here we've define a block called stringRange, that returns a NSRange and takes a single argument of type NSString *.  This is exactly the same as the function we wrote in option two, and it's even called in the exact same way too.

stringRange(myString)

There a couple of important differences between a regular C-style function and a block though.  Scope and memory.

With this block example, the block's scope is limited only to this method.  It also exists in memory on the stack and only until this method returns (or until the end of an @autoreleasepool it was created in, whichever comes first).


function for PDO queries and return result - tested - any tips?

First of all, it's a very good thing that you came to the idea of such a function. Sadly, but out of many people asking questions on Stack Overflow, only a handful ever come to such an idea. It means you're a natural born programmer, with an eye for the sub-optimal code and the desire to make it better.
The regular routine with prepared statements is not that optimal indeed, you need two function calls instead of one. Some drivers already have such a function to execute the prepared query in one go, pg_query_params() for example. But for PDO we have to create one of our own.
The function
However, the code for such a function should be much, much simper. Basically it's just three lines
function db_query_pdo( PDO $pd, $q, $ar )
{
    $stmt = $pd->prepare($q);
    $stmt->execute($ar);
    return $stmt;
}

surprisingly, that's all you really need. The rest is either harmful, superfluous or can be achieved by other means.
$query='SELECT * FROM `users` WHERE u_id=:uid OR u_id=:uid2';
$vals=[
    'uid' => $id,
    'uid2' => $id2
];

$res = db_query_pdo($pdo_cnctn,$query,$vals)->fetchAll();
if($res)
{
    var_dump($res);
}
else
{
    echo 'Not Found';
}

See, the calling code is almost the same, but the function became
a) much cleaner
b) much more versatile, as you can chain any PDOStatement method to it, not limited to the return value of fetchAll()
Say, you've got a delete query and want to know whether it deleted any rows? No problemo!
if (db_query_pdo($pdo_cnctn,"DELETE FROM t WHERE id=?",[1])->rowCount()) {
    echo "deleted";
}

or you want a fetchAll() but with different modifier:
$ids = db_query_pdo($pdo_cnctn,"SELECT id FROM t WHERE id<?",[10] )->fetchAll(PDO::FETCH_COLUMN);

or you want to get a single value
$exists = db_query_pdo($pdo_cnctn,"SELECT 1 FROM t WHERE email=?",[$email] )->fetchColumn();

etc., etc., etc.
The error reporting
To be honest, all that try catch business in your function is completely off the track. Especially that commented out section, "uncomment this lines if needed in future". Seriously? Are you really going to comment these lines back and forth? That's not how a good program should be written. It shouldn't require anything like this.
Besides, this approach is based on the two wrong notions which, sadly, are extremely popular among PHP folks:

"an error must be thrown only in some circumstances". That's but a grave delusion. A programmer desperately needs the error message no matter that. An error must be thrown every time, no exceptions. As a matter of fact, in the production environment the error message is much more important than in the dev. Without the error message a programmer will never have an idea what's going wrong
"a database function should decide what to do with its errors". This is a funny one. There is nothing special in the database interactions. But for some reason PHP users diligently wrap their database functions in a distinct handling code. At the same time completely neglecting every single other line in the code. It just makes no sense. A database error is no different from a filesystem error. And as you don't wrap every include in a distinct try catch, you should never do it for a db function either.

All the error handling business should occur elsewhere. You can read more about error reporting basics from my article.


Check the security of my image upload script

Your script has one underlying assumption that invalidates the whole set of security checks: That the value of $files_array['name'] is safe - it is not. This value is user supplied, and can very easily be spoofed to pass malicious data into your server that would get through all your security checks.

Neither $_FILES['control']['name'] nor $_FILES['control']['type'] are safe and you should not use either value for anything, ever.

In order to make your image uploads as safe as possible you must do all of the following:

Verify that the data you are working with is an uploaded file (move_uploaded_file() / is_uploaded_file() will take care of this for you)
Create the file name used to store the file on the file system entirely dynamically. You cannot use user input in any way to generate this. If your application requires that you store the original file name, you should keep this association in an external data store such as a database.
Verify that the image really is an image. The GD extension can verify the headers for you (use the getimagesize() function).
Copy the pixel data out of the image into a new one. Again, GD can do this for you (imagecopyresampled()). It is important to do this - it is possible to hide malicious code inside something with headers that make it appear to be a valid image. Resampling the image will destroy such malicious code.
I recommend that if you store the image on the file system, store it outside the document root and proxy the retrieval process with a script, so it cannot be directly accessed via the web server. The above measures should mitigate the implied security risk here, but better safe than sorry ;-)
Never include/require a file uploaded by a user. If you want to provide a file download, always use filesystem functions. readfile() is often the most appropriate choice.

Unfortunately, in order to comply with all these requirements you are basically going to need to throw your code out and start again.

If you want something for reference, this Gist contains something that's not a million miles away from the code I use in my real-life applications, and contains a basic usage example.


Project Euler 40: Champernownes's Constant

This probably plenty fast enough, but a brute force method strikes me as a very inefficient approach. I can think of a way that should be faster and more efficient, and avoids you constructing a million-character string.

Here are some suggestions/hints:

You calculate the same constant string each time, despite the fact that it’s always going to be the same. Do you really need to construct it every time? (Or at all?)
For every value of k you add to constant, you know how long it is. Do you actually need to add it to the string if you’re not going to look at it? Or could you just decrement that from the number of digits left before you get to the digit you want?
How many one-digit numbers are in the string? And two-digit numbers? And so on.

My actual solution in spoiler text:

   We can show that there are always \$ 9 \times 10^{n-1} \$ numbers which have \$n\$ digits, so by computing the sum
 \$ 9 + 90 + 900 + \dotsb \$
 until we go over the target value, we can work out how many digits the number we land in has (say \$ N \$). You can then jump back to the start of the \$ N \$-digit numbers and count up from there. You don't even need to be constructing the string; you can just use lengths to work out where we end up.

Oh, and one style comment:

Quoting from PEP 8 on imports:

  Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

Don’t put them inside your product definition. The way that Python caches module imports means that it won’t be a performance hit, but it does make it harder to find your module dependencies in a large file. I realise that this isn’t much of an issue in short snippets like this, but it’s a good habit to put your import statements in the standard location.


Calculating ordered differences between elements in vector

Array is not a Vector
JavaScript does not have vectors, it uses  Array and  Object that can both behave like vectors (grows and shrinks).

Arrays can also be sparse [hash map] or dense [flat sequential array].

Objects are sparse.

Objects do not have a length property

As you have not defined what you mean by vector one must make an assumption in regard to what the variable vector will contain and the general rule for arrays is that they are dense with numeric 0 based indexes.
My assumption that it is an array is based on the following

Is vector an Array?
The question's examples show arrays [5, 10, 20, 50, 100] and Objects do not (may not) have a length property.

Is vector a dense array?
The line  = vector.length; would return the last index of a sparse array. eg a = []; a[100] = 1; console.log(a.length); outputs 101 but has only 1 item. Your code would fail if you passed a sparse array.

Once we have established that the input is a standard array we can begin to optimize the function
Too complex
The first part of the function is overly complex and mostly redundant.
Sort
Array.sort is required but can be simplified as follows
.sort((a,b) => vector[a] - vector[b])

Tracking sorted position
There is no need to track the sort position by creating an object for each item. The sort position is already available in the indices array by index. Eg indices[0] gives the sort position for the first item.
Thus the need to call Array.map and create {i,d} for each item is not needed, however if it were required it could be better
Better the map
Properties names are very poor and the map function is also too complex. the line

.map((d, i) => { const k = indices[i]; const v = vector[k]; return { i: indices[i] , value: vector[indices[i]] }; });

could be be simplified to
.map(pos => ({pos , value: vector[pos]}));

Avoid duplicated processing
You create the array indices using Array.keys . const indices = [...Array(l).keys()] to get an ordered list of indexes, then lower down you create the array const deltas = new Array(l);
Note that the both lines are based on identical arrays. If you create deltas  first and use it to get the keys you can remove one of the created arrays.
  const deltas = new Array(l);
  const indices = [...deltas.keys()];

Calculate deltas and return
There are a lot of changes before we get to the meat of the function so all the rest of your original code can be replaced while considering the following...
Changes

The for loop can be replaced with the simpler while loop.
There is no need to create yet another object for each value. Once you have used the sorted positions they can be ignored.
The final sort and map operations are not required.
The first entry in the resulting array deltasmay not be at position 0 so the arraydeltas` must be pre-assigned space to avoid creating a sparse array.

BTW: Always delimit code blocks, eg for(i = 0; i < 10; i++) foo += i; is better as for(i = 0; i < 10; i++) { foo+=i; }
Rewrite
Changing the overly long function name remapVectorToIndexSortedDiffs with sortedDiffs
The functions complexity (time and storage) is the same,
however its memory use and performance have been improved significantly.
function sortedDiffs(vector) {
      var i = 0;
      const length = vector.length, deltas = Array(length);
      const idxs = [...deltas.keys()].sort((a, b) => vector[a] - vector[b]);
      deltas[idxs[i]] = vector[idxs[i]];
      while (i++ < length - 1) {
          deltas[idxs[i]] = vector[idxs[i]] - vector[idxs[i - 1]];
      }
      return deltas;
}

or a less verbose version.
function sortedDiffs(vecs) {
      var i = 0;
      const len = vecs.length - 1, res = Array(len + 1);
      const idxs = [...res.keys()].sort((a, b) => vecs[a] - vecs[b]);
      res[idxs[i]] = vecs[idxs[i]];
      while (i++ < len) { res[idxs[i]] = vecs[idxs[i]] - vecs[idxs[i - 1]] }
      return res;
}


Oneliner to extract External IP from IFCONFIG.CO

I don't like the idea of using Invoke-RestMethod here. Normally it would return an object, but here it just returns html as a string, which isn't much use to us. I guess that's because the payload is not XML or JSON, so PowerShell can't turn it into an object for us.

Invoke-WebRequest in contrast will parse the HTML for us, and then we can filter out the element we want:

function WhatsMyIP
{
    $x = Invoke-WebRequest -Uri http://ifconfig.co
    $elt = $x.AllElements | ? { $_.tagName -eq 'CODE' -and $_.class -eq 'ip' }
    $elt.innerText
}

The question mark ? means "where". (It's an alias for Where-Object.) So, what we are doing is we get all the HTML elements on the page, and we filter out all of them except the ones that have a tagName of 'CODE' and a class of 'ip'. (There will only be one of them on this particular page.) We are catching this element: 1.2.3.4.

That's "screen scraping" though, which is a bit crappy. I notice on the web site that they provide JSON if you give them the right URL. Now we can use Invoke-RestMethod:

function WhatsMyIP
{
    $x = Invoke-RestMethod -Uri ifconfig.co/all.json
    $x.'X-Real-Ip'
}

Note that there's no need to use return. Any unconsumed objects will be put in the pipeline. If you don't understand the pipeline, you should read up on it, because it is key to understanding PowerShell.


It's not at all clear to me what the point of this code is: I assume it's running on the server, but I can't see how it would fit into the broader picture of client-server synch. It would probably be better to debug the underlying problem rather than try to hack a workaround.

That aside, the code has one important misunderstanding, one bad practice used twice, and is overcomplicated.

Misunderstanding

    Task waiterTask = Task.Run(async() =>
    {
        while (!File.Exists(path))
        {
            await Task.Delay(10);
        }
    }, cts.Token);

There's no point passing in cts.Token because the task ignores it completely. (Task.Run would test whether the token has been cancelled before calling the action, but if the timeout is happening before the action is called then either the timeout is far too small or there's a much bigger problem to fix with server load).

There isn't actually a Task.Run(Action<CancellationToken>, CancellationToken>) method, so you can either forget CancellationTokenSource and use a different synchronisation method; or pull in either the token or cts directly from the outer scope.

Bad practice

CancellationTokenSource is IDisposable, but neither of the methods which create an instance are disposing it. Since its scope is clearly defined, the best practice would be a using statement.

Overcomplication

Two CancellationTokenSources just to handle a timeout for a single task, when you have full control over the task's source? It seems to me that the KISS approach would be

private static async Task<bool> WaitForFile(string path, TimeSpan timeout)
{
    DateTimeOffset timeoutAt = DateTimeOffset.UtcNow + timeout;
    while (true)
    {
        if (File.Exists(path)) return true;
        if (DateTimeOffset.UtcNow >= timeoutAt) return false;
        await Task.Delay(10);
    }
}

If cancellation is important (it's not in the original code, but it allows me to show how to use CancellationToken correctly, so...),

private static async Task<bool> WaitForFile(string path, TimeSpan timeout, CancellationToken cancellationToken = default(CancellationToken))
{
    DateTimeOffset timeoutAt = DateTimeOffset.UtcNow + timeout;
    while (true)
    {
        if (File.Exists(path)) return true;
        if (DateTimeOffset.UtcNow >= timeoutAt) return false;
        cancellationToken.ThrowIfCancellationRequested();
        await Task.Delay(10);
    }
}

(or, in this case)

private static async Task<bool> WaitForFile(string path, TimeSpan timeout, CancellationToken cancellationToken = default(CancellationToken))
{
    DateTimeOffset timeoutAt = DateTimeOffset.UtcNow + timeout;
    while (true)
    {
        if (File.Exists(path)) return true;
        if (DateTimeOffset.UtcNow >= timeoutAt) return false;
        await Task.Delay(10, cancellationToken);
    }
}


As a general rule of thumb, you should avoid using the global database for such purposes.

For example, in your case, after the predicate completes, counted_states/1 is still asserted, and will influence later invocations of the predicate.

This certainly is not intended, no?

There is a straight-forward solution for this:

First, describe what it means that that a state is reachable from a particular state.
Then, use findall/3 to collect all such reachable states into a list of results.
On that list, simply use length/2 to obtain the number of reachable states.

This works without modifying the global database in any way.


Missing overflow check

One serious flaw that I see in this code is that the user needs to determine the number of parameters to unpack. This is a no go for a function whose output depends on a runtime input. Even worse there is no check that would tell the user that the actual number overflows the number of bits given to be unpacked into.

One possible solution would be to return an std::vector<bool> to fit the whole number.

The other solution would be to retain the current interface but to introduce error notification (by exception or return code).

Unnecessary template parameter

Another thing regarding the unpack function:
It seems that you don't need the Types parameter in the recursion end, so it becomes:

template<typename T>
void unpack(T packed, bool& b1)
{
    b1 = packed & 1;
}

Naming

The function parameter names could be better.
I assume b1 is only appropriate in the top level call of the function. I cannot decide on a better name now, but it should indicate that it is the current bit. Likewise, args should be named remainingBits or something like this.


From a once over:

load_comments should follow lowerCamelCase -> loadComments
Avoid console.log, at least wrap it in something that also takes in to account message severity and filters on that message severity
Personally I would have used either comments or wellFormedComments instead of notNullComments
It seems that if there are no comments, that you should get out, and not do the JSON parsing and the html appending
Where is commentsTmpl defined? Smells like a global variable
It is very confusing to have #target_dom there, I am guessing that it is a subelement of #comments_section, but I would have called it #comments probably?
Even more confusing is that you append the html to #comments_section and not #target_dom

All in all, I would go with something like this:

var CommentView = Backbone.View.extend({
    el: $("#comments_section"),
    render: function() {
        var comments= comments.wellFormedComments();
        if (!comments.length) {
            return
        }
        $("#a_descriptive_id").show();
        var html = commentsTmpl(notNullComments.toJSON());
        $(this.el).append(html);
    },
});


Use $(...) style command substitution instead of the deprecated `...` style. And double-quote variables if they might contain spaces. So instead of this:

usage="Usage: `basename $0` [-v VOL] "

Write like this:

usage="Usage: $(basename "$0") [-v VOL] "

Testing with [ ... ] is deprecated in favor of the more modern and powerful [[ ... ]]. So instead of this:

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then

Write like this:

if [[ $1 = -h || $1 = --help ]]; then

This is equivalent, but notice that it's shorter, and in this form there is no need for those double-quotes. (Strictly speaking, in [ ... ] there was no need to double-quote "-h" and "--help", only "$1", the variable).

But in any case, why not move the handling of -h and --help together with the other options of the script?

while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help)
            echo $usage
            echo "  -h, --help  for help"
            exit;;
        -v)
            shift
            [[ $# -gt 0 ]] && VOL="$1";;
        -*)
            echo "Option not supported: $1" >&2
            echo $usage >&2
            exit 1;;
        *) break;;
    esac
    shift
done

This way it's simpler, and now you can use -h and --help anywhere on the command line, not only as the first argument.

About this bit:

[ -z "$(pidof -x gfaaudioloop)" ] || killall gfaaudioloop

I don't have the pidof command so I can't really test it, but in general it doesn't sound good to put the output of a program into a string just to check with -z if it's empty. Usually there is a more direct way, using the exit code of the program. Here's an example that should come quite close to what you want:

ps xa | grep -q gfaaudioloop && killall gfaaudioloop

Having the exit at the end of a script makes is exit with success. Without it, the exit code of the script will be that of the last command executed. If you correctly check for and handle the exit code of all commands, then you don't need to explicitly exit. Let the script exit normally, using the exit code of the last command executed.


Basic text editor in Python with Tkinter

Style

Python has a guide style called PEP 8. If you have no good reason not to follow it, just follow it. You'll find various tools to check your code (pep8, pep8online.com/, etc) and even to fix it more or less automatically (autopep8).

Here's a list of problems detected :

txt_original.py:13:80: E501 line too long (105 > 79 characters)
txt_original.py:14:80: E501 line too long (105 > 79 characters)
txt_original.py:15:80: E501 line too long (141 > 79 characters)
txt_original.py:17:80: E501 line too long (138 > 79 characters)
txt_original.py:22:43: E231 missing whitespace after ','
txt_original.py:25:8: E713 test for membership should be 'not in'
txt_original.py:30:35: E231 missing whitespace after ','
txt_original.py:33:43: E231 missing whitespace after ','
txt_original.py:35:1: E302 expected 2 blank lines, found 1
txt_original.py:37:37: E231 missing whitespace after ','
txt_original.py:40:8: E713 test for membership should be 'not in'
txt_original.py:43:23: E231 missing whitespace after ','
txt_original.py:44:34: E231 missing whitespace after ','
txt_original.py:45:46: E231 missing whitespace after ','
txt_original.py:45:80: E501 line too long (95 > 79 characters)
txt_original.py:47:1: E302 expected 2 blank lines, found 1
txt_original.py:55:1: E302 expected 2 blank lines, found 1
txt_original.py:61:56: E231 missing whitespace after ','
txt_original.py:61:65: W291 trailing whitespace
txt_original.py:68:42: E231 missing whitespace after ','
txt_original.py:69:37: E231 missing whitespace after ','
txt_original.py:75:21: E231 missing whitespace after ','
txt_original.py:76:14: E251 unexpected spaces around keyword / parameter equals
txt_original.py:76:16: E251 unexpected spaces around keyword / parameter equals
txt_original.py:76:20: E231 missing whitespace after ','
txt_original.py:79:20: E251 unexpected spaces around keyword / parameter equals
txt_original.py:79:22: E251 unexpected spaces around keyword / parameter equals
txt_original.py:79:26: E231 missing whitespace after ','

And here's you code after most of the problems are fixed :

try:
    import tkinter as tk
except:
    import Tkinter as tk

try:
    import tkMessageBox as pop_up
except:
    import tkinter.tkMessageBox as pop_up

import time

EMPTY_TITLE_ERROR_MESSAGE_SAVE = "Please write the name of the file you want to save in the given field."
EMPTY_TITLE_ERROR_MESSAGE_OPEN = "Please write the name of the file you want to open in the given field."
FILE_NOT_FOUND_ERROR_MESSAGE = "No file with the given title was found, remember that this text editor can only read files in its directory."
SAVING_SUCCESS_MESSAGE = "Your text is now stored in the {filename} file"
SIGNATURE_TXT_NOT_FOUND_MESSAGE = "Please be sure that the file you want to open exists and that it is in the same folder of this editor."

def _open():
    if not file_title.get():
        pop_up.showerror("Title is empty.", EMPTY_TITLE_ERROR_MESSAGE_OPEN)
        return 1

    if ".txt" not in file_title.get():
        filename = file_title.get() + ".txt"

    try:
        with open(filename) as f:
            main_text.delete("1.0", tk.END)
            main_text.insert(tk.INSERT, f.read(), "a")
    except IOError:
        pop_up.showerror("File not found.", FILE_NOT_FOUND_ERROR_MESSAGE)

def save():
    if not file_title.get():
        pop_up.showerror("No title.", EMPTY_TITLE_ERROR_MESSAGE_SAVE)
        return 1

    if ".txt" not in file_title.get():
        filename = file_title.get() + ".txt"

    with open(filename, "w+") as f:
        f.write(main_text.get(1.0, tk.END))
    pop_up.showinfo(
        "File saved succesfully.",
        SAVING_SUCCESS_MESSAGE.format(
            filename=filename))

def add_date():
    full_date = time.localtime()
    day = str(full_date.tm_mday)
    month = str(full_date.tm_mon)
    year = str(full_date.tm_year)
    date = "\n" + day + '/' + month + '/' + year
    main_text.insert(tk.INSERT, date, "a")

def add_signature():
    try:
        with open("signature.txt") as f:
            main_text.insert(tk.INSERT, "\n" + f.read(), "a")
    except IOError:
        MESSAGE = SIGNATURE_TXT_NOT_FOUND_MESSAGE
        pop_up.showerror("\"signature.txt\" not found.", MESSAGE)

root = tk.Tk()

menubar = tk.Menu(root)
menubar.add_command(label="Open", command=_open)
menubar.add_command(label="Save", command=save)
menubar.add_command(label="Add signature", command=add_signature)
menubar.add_command(label="Add date", command=add_date)

root.config(menu=menubar)

top = tk.Frame(root)
temp = tk.Label(root, text="Title:")
temp.pack(in_=top, side=tk.LEFT)

file_title = tk.Entry(root)
file_title.pack(in_=top, side=tk.RIGHT)

top.pack()

main_text = tk.Text(root)
main_text.pack()

tk.mainloop()

As I am talking about tools, it is probably worth mentionning that you'll find various other tools to check your code.

pylint finds :

************* Module txt
C: 13, 0: Line too long (105/80) (line-too-long)
C: 14, 0: Line too long (105/80) (line-too-long)
C: 15, 0: Line too long (141/80) (line-too-long)
C: 17, 0: Line too long (138/80) (line-too-long)
C:  1, 0: Missing module docstring (missing-docstring)
W:  3, 0: No exception type(s) specified (bare-except)
F:  4, 4: Unable to import 'Tkinter' (import-error)
W:  8, 0: No exception type(s) specified (bare-except)
F:  7, 4: Unable to import 'tkMessageBox' (import-error)
E:  9, 4: No name 'tkMessageBox' in module 'tkinter' (no-name-in-module)
F:  9, 4: Unable to import 'tkinter.tkMessageBox' (import-error)
C: 20, 0: Missing function docstring (missing-docstring)
C: 29,31: Invalid variable name "f" (invalid-name)
C: 36, 0: Missing function docstring (missing-docstring)
C: 44,33: Invalid variable name "f" (invalid-name)
C: 52, 0: Missing function docstring (missing-docstring)
C: 61, 0: Missing function docstring (missing-docstring)
C: 63,38: Invalid variable name "f" (invalid-name)
C: 66, 8: Invalid variable name "MESSAGE" (invalid-name)
C: 69, 0: Invalid constant name "root" (invalid-name)
C: 71, 0: Invalid constant name "menubar" (invalid-name)
C: 80, 0: Invalid constant name "top" (invalid-name)
C: 81, 0: Invalid constant name "temp" (invalid-name)
C: 84, 0: Invalid constant name "file_title" (invalid-name)
C: 89, 0: Invalid constant name "main_text" (invalid-name)

but there is also pyflakes, pychecker, etc.

Logic around file name

The following logic :

if not ".txt" in file_title.get():
    filename = file_title.get() + ".txt"

seems wrong on many different levels :

It does not follow PEP8 and should be if ".txt" not in file_title.get()
You have the same hardcoded string in multiple places : you are pretty much asking to be biten at some point if you want to change this. What about TXT_EXTENSION = '.txt'.
You are calling file_title.get() for no good reason
You do not define filename if the condition in the if is evaluated to false. Maybe you meant :

TXT_EXTENSION = '.txt'
filename = file_title.get()
if TXT_EXTENSION not in filename:
    filename = filename + TXT_EXTENSION
You are changing "toto.tutu" to "toto.tutu.txt" but "toto.txt.tutu" does not change. If what you are interested in is extension, you should probably be using endswith.

You have the same logic in multiple places : you should probably move it in a function of its own :

def add_txt_extension_if_needed(filename):
    if not filename.endswith(TXT_EXTENSION):
        return filename + TXT_EXTENSION
    return filename

Date format

You can probably find in the documentation how to format a date as a string.

I have to go and I don't know tkinter but I guess other people will have additional relevant comments.


Binary Search Tree implementation with unique pointers

Observations
You pass data by value. This is fine for small data types like int. But imagine that T is some huge object that is very expensive to copy. You should think of passing the data by reference to avoid any intermediate copies. When you get a bit more advanced think about passing by r-value reference to allow you to move the objects.
For your traversal you pass a function pointer. This is a bit limiting. Normally you would templateze the function to allow you to pass any function like object (function pointer/functor/lambda/std::function) etc.
Yes you need recursion when traversing trees. But you don't need it everywhere. There are a couple of places where a simple loop would be sufficient.
I can see why you use std::unique_ptr. But in my view a tree is a container and should manage its own memory. So I would have simply used Node* inside data. The code is not that much harder to write in this context. BUT I don't have any real issue with std::unique_ptr.
Code
Insert by const reference
void insert(T const& data)
{
    _insert(root, data);
}
_insert(std::unique_ptr<node>& curr, T const& data)
{
    if (curr.get() == nullptr) {
        curr.reset(new node(data));
        return;
    }

    auto& next = (data < curr->data) ? curr->left : curr->right;
    _insert(next, data);
}

Insert by r-Value reference
void insert(T&& data)
{
    _insert(root, std::forward<T>(data));
}
_insert(std::unique_ptr<node>& curr, T&& data)
{
    if (curr.get() == nullptr) {
        curr.reset(new node(data));
        return;
    }

    auto& next = (data < curr->data) ? curr->left : curr->right;
    _insert(next, std::forward<T>(data));
}

Emplace into node.
// This calls T constructor only when you construct the node itself.
template<typename... Args>
void emplace(Args const&... args)
{
    _emplace(root, args...));
}
template<typename... Args>
_emplace(std::unique_ptr<node>& curr, Args const&... args)
{
    if (curr.get() == nullptr) {
        curr.reset(new node(args...));
        return;
    }

    auto& next = (data < curr->data) ? curr->left : curr->right;
    _insert(next, args...);
}
template<typename... Args>
node::node(Args const&... args)
    : data(args...)  // Data of type T constructed in place
    , left(nullptr)
    , right(nullptr)
{}

Using a function like object to traverse the tree:
template<typename F>
void traverse(const & action)
{
    _traverse(root, action);
}
template<typename F>
void _traverse(std::unique_ptr<node>& curr, F const& action);

// outside class

template<typename T>
template<typename F>
void Btree<T>::_traverse(std::unique_ptr<node>& curr, F const& action)
{
    if (curr == nullptr)
        return;
    _traverse(curr->left, action);
    action(curr->data);
    _traverse(curr->right, action);
}

int main()
{
     Btree<int>  tree;
     tree.traverse([](int x){std::cout << x << " ";});
}


Okay, your question is very ambiguous, but I'll give it a shot. First, is seems like you're confused about what a closure is. A closure is simply accessing a variable that was not defined inside that function.

For instance, in:

function foo () {
    var bar = 9;
    function bla () {
        return bar;
    }
}

bar can be accessed because of closure. Read this if you still have questions about that.

Now regarding your use case, it seems like what you want is a cache. You don't want to go to the server every time to get the same information, you want the user to get information that has already been requested. That's the use case of a cache.

This is how you create a cache in JavaScript:

var cache = {};

Now you need a way to index your data. Since it seems like you get it from a db, you'll have an ID available, index it by that. So your app will look something like:

$.ajax(....).done(function (data) {
    // Cache your data
    cache[data.id] = data;
});

Now before every db request you can check if the data is in the cache or not. If it is you can use the copy in the cache, if not issue the request to the server.


Yes, No, and Maybe.
Yes
The table has 10 rows, the column is used as a constant argument in a query, and the query optimizer has ways to do index lookups (probes) in a very fast way. So, if the query parser decides to access the menu table by the literal, instead of the id, then the index will likely help. Also, for 10 rows, it will not take much space.
No
Because you use a left-join from items to menu, on the menu.id column, the reality is that the query plan will likely have to process all the records in item before joining to menu so that it can do the outer-join right. This means that all the query access to the menu table should be through the id column, and the menu_title column will be secondary, and the index on the menu_title (if any) will be ignored.
Maybe
Query optimizers can sometimes make dumb, and also very smart choices, and there is a chance that having the index will help, despite my best-guess that it wont. Additionally, there is a chance the optimizer will use the index, even though that will make it slower.
There is no way to know unless you try it.
My suggestion
Create the index, but don't expect it to be used for this query.
A second suggestion is to create the index menu(id, menu_title) because sometimes putting them together in an index helps avoid a data page lookup, but for just 10 rows, it's not going to make much difference.


Find all words that can create a pyramid

SRP

You should start by splitting this class into smaller pieces to satisfy the Single Responsibility Priciple. One class should do only one thing and yours is doing at least two:

it reads and writes files
it finds the pyramid words

This means you should:

Create one module for reading and writing words into a file
Let the second module only find pyramid words

The first module could be the DictionaryFile

class DictionaryFile
{
    public IReadOnlyList<string> LoadDictionary(string filePath)
    {
        // ...
    }

    public void SaveDictionary(IEnumerable<string> words, string fileName)
    {
        // ...
    }
}

Keep the names clear but not too long if this is not necessary.

The second module is the PyramidWordFinder:

class PyramidWordFinder
{
    private readonly HashSet<int> _lengths = new HashSet<int>();

    public PyramidWordFinder(int maxLength)
    {
        var length = 3;
        var i = 1;
        while (length <= maxLength)
        {
            _lengths.Add(length);
            length = ++i + length + 1;
        }
    }

    public bool IsPyramidWord(string value)
    {
        if (!_lengths.Contains(value.Length)) { return false; }

        var groups = value
            .GroupBy(x => x.ToString(), StringComparer.OrdinalIgnoreCase)
            .Select(x => x.Count())
            .OrderBy(x => x);
        return groups.SequenceEqual(Enumerable.Range(1, groups.Length));
    }
}

HashSet

Instead of having a list with predefined lengths, you can calculate them based on the max length and save them in a HashSet<int> for faster lookup which is O(1) in comparison to the list where it's O(n).

LINQ

To determine whether a word is a pyramid you can use LINQ where you first group each letter and sort it in the ascending order. Then you check if the count is increasing by one:

var groups = value
    .GroupBy(x => x.ToString(), StringComparer.OrdinalIgnoreCase)
    .Select(x => x.Count())
    .OrderBy(x => x);
return groups.SequenceEqual(Enumerable.Range(1, groups.Length));

StringComparer

With the StringComparer.OrdinalIgnoreCase you don't need to call ToLower or ToUpper.

IEnumerable

public IList<string> FindPyramidWords(IReadOnlyList<string> wordList)

Don't return a complete list of words if this isn't necessary. Use an iterator instead - by using LINQ or the yield return. What if you wanted just the first three words? You would need to calculate them all anyway. With deferred execution you can stop whereever you want to.

Example

You can now easily find all pyramid words with linq:

var pwf = new PyramidWordFinder(maxLength: 55); // or use constant
var words = new string[] { /* words */ }; // from the file
var pyramidWords = words.Where(pwf.IsPyramidWord).ToList();

I'm aware of the fact that the LINQ solution might not be the fastest one but it's definitely the esiest one. If you don't notice any performance hit then why make it so complex? Premature optimization is the root of all evil.

The point is that you should separate each feature so that you can work on it and test it without affecting the others. If you can focus on one thing at a time you can better optimize it.


Your cache can only be initialised once with the put method (hence your set flag): why not use a constructor instead and get rid of the flag?
If 2 items with the same UUID are identical and you only need to store one of them, using a map would simplify your design a lot
The map gives you an O(1) algorithm for contains and getById instead of O(n) in your code
Since the class is now immutable, you don't need to synchronize the methods any more which should result in much better result in case of heavy concurrency (no lock contention)

Here is what I would propose:

public class StaticCacheImpl<T extends Entity> implements StaticCache<T>
{
    //Assumes that 2 items with the same UUID only need to be stored once
    private final Map<UUID, T> cache = new HashMap<UUID, T>();

    public StaticCacheImpl(List<T> cachedList) {
        for (T t : cachedList) {
            cache.put(t.getUuid(), t);
        }
    }

    @Override
    public boolean isSet() {
        return true;
    }

    @Override
    public void put(List<T> cachedList) {
        throw new IllegalStateException("Cache has already been set");
    }

    @Override
    public List<T> get() {
        return new ArrayList<T> (cache.values()); //defensive copy
    }

    @Override
    public boolean contains(UUID uuid) {
        return cache.containsKey(uuid);
    }

    @Override
    public T getById(UUID uuid){
        return cache.get(uuid);
    }
}

If you can't use a constructor and need the put method to work as in your original design, then the only change I would make is to use a map, but you would still need to synchronize the methods and use the set flag.


In GetIdAndKeys(), you do the default initialization of the out variables just before the default return.  I find it is usually better to initialize these variables at the top of the method because many methods will have multiple early return conditions, as well as a default return value.  Doing the default initialization at the beginning of the method prevents needing to do it in multiple places, and aids in consistency if the specific method does not have this problem.

public static bool GetIdAndKeys(RouteValueDictionary dataTokens, out int id, out Dictionary<string, string> keys)
{
    id = 0;
    keys = null;

    if (dataTokens.Count > 0)
    {
        // re-assign and return
    }

    return false;  // use default values
}


"Fun with Rotation" - Codechef September Challenge

Your outer class name should correspond to the type of program.  There's no point in calling it Main since you already have to have a main() method.  Of course, you'll have to be sure that your .java filename and outer class name are the same.
You have a lot of excess whitespace, and I don't think it's a copy/paste error.  Just get rid of all this whitespace so that it's easier for others to read.

On the other hand, this could use more whitespace:

for(int i=0;i<n;i++)

It's good to separate each operator and operand so that the line is easier to read.  Although keeping them together saves horizontal length, the line itself is already short, and even then there's little reason to cram everything together.

for (int i = 0; i < n; i++)

You're using single-character variable names such as n and s, and it's not at all clear what they mean in this code.  If it were a tiny program, then it may be okay.  But for this program, it's best to use meaningful names so that the code is self-documenting.


Documentation and tests

Before improving your code, is it important to write tests for it to make you you don't break anything.

As you do it, you might want that you need to be a bit clearer about the behavior of your function. Let's see what your functions return with a simple piece of code:

def print_results():
    print("i, primeFactorization(i), reduce(i), isPrime(i)")
    for i in range(15):
        print(i, primeFactorization(i), reduce(i), isPrime(i))

Most results seem ok but why do we sometimes have "1" in the return value for primeFactorisation. In theory, we should have only prime numbers in it.

We could:

write doc to specify what the functions does (return prime factorisation)
write tests for the actual expected behavior
fix the code

Here are various snippets I've written to test the code. In a more serious project, you could use a testing framework.

def test_is_prime():
    primes = [2, 3, 5, 7, 11, 13]
    not_primes = [0, 1, 4, 6, 8, 9, 10, 12, 14, 15, 100, 100000]
    for p in primes:
        assert isPrime(p), p
    for np in not_primes:
        assert not isPrime(np), np

def test_prime_factorization():
    prime_factorisations = {
        2: [2],
        3: [3],
        4: [2, 2],
        5: [5],
        6: [2, 3],
        7: [7],
        8: [2, 2, 2],
        9: [3, 3],
        10: [2, 5],
        11: [11],
        12: [2, 2, 3],
        13: [13],
        14: [2, 7],
    }
    for n, factors in prime_factorisations.items():
        ret = primeFactorization(n)
        assert ret == factors, str(n) + ": " + str(ret) + "!=" + str(factors)

def test_prime_factorization_randomised():
    import random
    n = random.randint(2, 10000)
    ret = primeFactorization(n)
    m = 1
    assert sorted(ret) == ret, "return is not sorted for n:" + str(n)
    for p in ret:
        assert isPrime(p), "factor " + str(p) + " is not prime for n:" + str(n)
        m *= p
    assert m == n, "product of factors does not lead to original value:" + str(n) + ", " + str(m)

if __name__ == '__main__':
    print_results()
    test_is_prime()
    test_prime_factorization()
    for i in range(300):
        test_prime_factorization_randomised()

Now, it feels fuch safer to improve the code.

Also, you could use this to perform benchmarks: compute the operations many times and/or on huge numbers to measure the time it takes.

Style

Python has a style guide called PEP 8. I highly recommend reading it (many times) and trying to apply it as much as possible.

Among other things, the functions names should be in snake_case.

Algorithm

Splitting a problem into smaller problems and writing functions for these is usually a good idea.

Unfortunately, I am not fully convinced that the reduce functions really helps you here.

Let's see how things can be improved anyway.

Small simplifications/optimisations

We could use the divmod builtin to get both the quotient and the remainder of the division.

The ctr variable seems useless. It is used to break after we've incremented it. We could just break directly.

At this stage, we have:

def reduce(n):
    n = abs(n)
    factors_list = []
    for i in range(2,n+1):
        p, q = divmod(n, i)
        if q == 0:
            factors_list.append(i)
            factors_list.append(p)
            break
    return factors_list

Now it is clear that we either add i and p to the list only once or we add nothing as all. We could make this clearer:

def reduce(n):
    n = abs(n)
    for i in range(2,n+1):
        p, q = divmod(n, i)
        if q == 0:
            return [i, p]
    return []

Now, it is clear that the function:

returns [] in the cases 0 and 1
return [n, 1] when n is prime
return [d, n/d] where d is the smallest (prime) divisisors otherwise.

Also, reduce is called more than needed: everytime we do

if isPrime(n):
    ret = reduce(n)

on a prime number, we actually perform reduce twice which is very expensice, in particular for primes as we iterate up to n.

Thus, we could get an optimisation boost by writing:

def primeFactorization(n):
    """Return the prime factorisation of n in sorted order."""
    factors = reduce(n)
    if 1 in factors:
        return [n]
    primeFactors = []
    while True:
        for e in factors:
            new_factors = reduce(e)
            if 1 in new_factors:
                primeFactors.append(e)
                factors.remove(e)
            else:
                factors.extend(new_factors)
                factors.remove(e)
        if len(factors) == 0:
            break
    ret = sorted(primeFactors)
    return ret

Another key hindsight is prime factorisation is that the smallest divisors of n is at most sqrt(n) which limits the range you have to look in.

In your case, we could use this in reduce, change slightly how reduce behaves and write:

def reduce(n):
    """Return [a, b] where a is the smallest divisor of n and n = a * b."""
    n = abs(n)
    for i in range(2, int(math.sqrt(n)) + 1):
        p, q = divmod(n, i)
        if q == 0:
            return [i, p]
    return [n, 1]

def isPrime(n):
    """Return True if n is a prime number, False otherwise."""
    return n > 1 and reduce(n) == [n, 1]

def primeFactorization(n):
    """Return the prime factorisation of n in sorted order."""
    factors = reduce(n)
    if factors == [n, 1]:  # prime
        return [n]
    primeFactors = []
    while True:
        for e in factors:
            new_factors = reduce(e)
            if new_factors == [e, 1]:  # prime
                primeFactors.append(e)
            else:
                factors.extend(new_factors)
            factors.remove(e)
        if len(factors) == 0:
            break
    ret = sorted(primeFactors)
    return ret

which is much faster.

Then, you could get rid of:

    if len(factors) == 0:
        break

by looping with while factors.

Then using, list.pop(), you could get rid of remove (which takes a linear time):

def primeFactorization(n):
    """Return the prime factorisation of n in sorted order."""
    factors = reduce(n)
    if factors == [n, 1]:  # prime
        return [n]
    primeFactors = []
    while factors:
        e = factors.pop()
        new_factors = reduce(e)
        if new_factors == [e, 1]:  # prime
            primeFactors.append(e)
        else:
            factors.extend(new_factors)
    ret = sorted(primeFactors)
    return ret

Then it appears that the initial check is not really required as the logic is already performed inside the loop:

def primeFactorization(n):
    """Return the prime factorisation of n in sorted order."""
    primeFactors = []
    factors = [n]
    while factors:
        e = factors.pop()
        new_factors = reduce(e)
        if new_factors == [e, 1]:  # prime
            primeFactors.append(e)
        else:
            factors.extend(new_factors)
    ret = sorted(primeFactors)
    return ret

We can actually get rid of the sorting by popping the first element of the list, thus generating the factors in order:

def primeFactorization(n):
    """Return the prime factorisation of n in sorted order."""
    primeFactors = []
    factors = [n]
    while factors:
        e = factors.pop(0)
        new_factors = reduce(e)
        if new_factors == [e, 1]:  # prime
            primeFactors.append(e)
        else:
            factors.extend(new_factors)
    return primeFactors

Now, instead of a reduce function, we could write a somehow equivalent but easier to use get_smallest_div function. Taking this chance to rename all functions, the whole code becomes:

import math

def get_smallest_div(n):
    """Return the smallest divisor of n."""
    n = abs(n)
    for i in range(2, int(math.sqrt(n)) + 1):
        p, q = divmod(n, i)
        if q == 0:
            return i
    return n

def is_prime(n):
    """Return True if n is a prime number, False otherwise."""
    return n > 1 and get_smallest_div(n) == n

def get_prime_factors(n):
    """Return the prime factorisation of n in sorted order."""
    prime_factors = []
    factors = [n]
    while factors:
        n = factors.pop(0)
        div = get_smallest_div(n)
        if div == n:  # prime
            prime_factors.append(n)
        else:
            factors.extend([div, n//div])
    return prime_factors

def print_results():
    print("i, get_prime_factors(i), get_smallest_div(i), is_prime(i)")
    for i in range(15):
        print(i, get_prime_factors(i), get_smallest_div(i), is_prime(i))

def test_is_prime():
    primes = [2, 3, 5, 7, 11, 13]
    not_primes = [0, 1, 4, 6, 8, 9, 10, 12, 14, 15, 100, 100000]
    for p in primes:
        assert is_prime(p), p
    for np in not_primes:
        assert not is_prime(np), np

def test_prime_factorization():
    prime_factorisations = {
        2: [2],
        3: [3],
        4: [2, 2],
        5: [5],
        6: [2, 3],
        7: [7],
        8: [2, 2, 2],
        9: [3, 3],
        10: [2, 5],
        11: [11],
        12: [2, 2, 3],
        13: [13],
        14: [2, 7],
    }
    for n, factors in prime_factorisations.items():
        ret = get_prime_factors(n)
        assert ret == factors, str(n) + ": " + str(ret) + "!=" + str(factors)

def test_prime_factorization_randomised():
    import random
    n = random.randint(2, 10000)
    ret = get_prime_factors(n)
    m = 1
    assert sorted(ret) == ret, "return is not sorted for n:" + str(n)
    for p in ret:
        assert is_prime(p), "factor " + str(p) + " is not prime for n:" + str(n)
        m *= p
    assert m == n, "product of factors does not lead to original value:" + str(n) + ", " + str(m)

if __name__ == '__main__':
    start = time.perf_counter()
    import time
    print_results()
    test_is_prime()
    test_prime_factorization()
    for i in range(300):
        test_prime_factorization_randomised()
    print(get_prime_factors(9000000))
    print(get_prime_factors(9000000 * 701 * 701))
    print(time.perf_counter() - start)

My solution for this

If I was to write this from scratch, here is how I'd do it:

def is_prime(n):
    """Return True if n is a prime number, False otherwise."""
    if n < 2:
        return False
    return all(n % i for i in range(2, int(math.sqrt(n)) + 1))

def get_prime_factors(n):
    """Return the prime factorisation of n in sorted order."""
    prime_factors = []
    d = 2
    while d * d <= n:
        while n % d == 0:
            n //= d
            prime_factors.append(d)
        d += 1
    if n > 1:  # to avoid 1 as a factor
        assert d <= n
        prime_factors.append(n)
    return prime_factors


Update MediaWiki settings with dynamic IP address

That's nutty, trying to address a server by a changing IP address. Reconfiguring the wiki to adjust to it is even crazier.

The standard practice for adapting to dynamic IP addresses is to use a dynamic DNS service. Then, everything else works normally.

Pick a hostname, like afuna.noip.com. Run a DDNS client to register your hostname whenever you acquire a DHCP lease, and re-register that hostname periodically thereafter.
Use it to form the URL of your site, e.g. https://afuna.noip.com/.
Configure your MediaWiki setting using that URL once, and you won't need that hacky script anymore.


Lock free consumer producer using memory barrier

It's always difficult, and sometimes impossible, to review a snippet of code without knowing how it is intended to be used. In this case, I can say confidently that this code will do the job. Whether that happens to be the job you want it to do is another thing entirely.

As long as you understand the limitations of the pattern you're using (and assuming g_guard is initialized to 0 properly before either of the functions are called), this will "work".

The limitations are:

SendTestMessage() can only be called once. Not once-per-thread; once for the entire program.
TryReceiveMessage() can be called repeatedly... but only non-concurrently in a single thread.

You didn't say how you intend to use this code, but from your questions, I can deduce that this won't work for you.

It would avoid TryReciveMessage to cosnume same message if called multiple times before new message is written

With this code, it is safe to call SendTestMessage() EXACTLY ONCE, concurrently with TryReceiveMessage() any number of times IN A SINGLE THREAD. So TryReceiveMessage() will not consume the same message more than once... but it can also not consume more than one message in total. There can be no "new message".

Safely synchronizing the guard does not safely synchronize the payload. This code "works" only because the payload is written ONCE, and then read, with the guard making sure the read is absolutely ordered after the write. If you want to write a second time (for a new message): you can't. You'd need a second guard to prevent the second write until after the read is finished. That would turn SendTestMessage() into a blocking call... and then you might as well just use regular synchronization techniques.
It would not add explicit memory fence and hence won't affect performance

"Performance" is always a vague term. There are many different ways for code to be performant.

If your goals are:

You want to minimize inter-thread synchronization costs.
You don't care how long you have to wait to receive the message.

Then this code is about as performant as it can be.

Note that "performance" in this case doesn't mean "fast". After you call SendTestMessage(), you could end up waiting a looong time before TryReceiveMessage() realizes that there's a message ready. If you have other things to do in the receive thread, that's fine I guess. But if all you're doing is a busy-wait spin... this is not the best design for this.
since std::memory_order_relaxed guarantees the ordering, it would get overwritten by SendTestMessage value if new load added after the std::memory_order_acquire is called. So, we will not miss any load.

I assume there's a typo here, and you mean to say: "since std::memory_order_ release guarantees the ordering...." Because std::memory_order_relaxed does literally the opposite of guaranteeing ordering.

But that's just a guess, because I can't make any sense of what you said. I can't even figure out what "it" is that you're concerned about being overwritten: Do you mean g_guard or g_payload? Are you asking about if you try to call SendTestMessage() twice? I can't figure out what you're asking.

Is this the best way to do this? That depends on what "this" is; you didn't say. It's a passable demonstration on how to use thread fences... but it doesn't look like anything that would be useful in a real-world program generally. This setup works for sending exactly one message in the entire lifetime of the program, and receiving it exactly once in a single thread. That's not very useful, generally.

If what you want is a way to set up a producer-consumer operation between threads of any kind - multi-consumer, multi-producer, whatever - there are much better ways to do it, generally.

Relaxed memory ordering is one of the deepest and darkest corners of C++, and you really shouldn't be screwing around with it unless you're an expert. Unless and until you've done everything else possible to speed up your code in a bottleneck, and have confirmed that it is inter-thread synchronization holding you up, you shouldn't even consider touching relaxed memory ordering. And even then, you shouldn't.

I'd say the bottom line of this review is: whatever you're planning to do with this code... don't.


Particles moving around a Perlin Noise field

(1). From the point of style I'd recommend you not to mix the level of details in a function. For example.

Instead of writing something like this:

void setup() {
  background(0);
  size(1000, 500);
  for (int i = 0; i < pAmt; i++) { // this is bad
    p[i] = new Particle(random(width), random(height), i);
  }
}

You should write something like this. The same is applicable for other functions.

void setup() {
  background(0);
  size(1000, 500);
  fillArray(); // there goes the loop and it's load easier to read.
}

(2). As for naming conventions I'd recommend you to use a verb as a first part for the function's name. Code like this looks unusual.

background(0);
size(1000, 500);

(3). You should be consistent with names for your variables. For example in your update() function you can see a mix of full and short names like stride, target, chaos vs accel, vel, pos. It really makes me think a lot more about names than I should.

(4).If you have to call this "normalize()" method a lot after construction of the object I'd recommend to think about adding this method to consturctor for example with the flag called "shouldNormalize".

PVector dir = new PVector(x - pos.x, y - pos.y);
dir.normalize();

vs

PVector dir = new PVector(x - pos.x, y - pos.y, true);
//or make it to normalize the vector by default and pass false when you don't need it
//but I guess that you should normalize it quite often after creation

(5). I would strongly recommend to make Particle class immutable. It would save you from a lot of hacks like this and make your code cleaner:

 void update(float stride, PVector target, float chaos) {
 this.stride = stride;
 ... }


Read an input text file and store the tokens in 2 different arrays

A useful first step for you to take is to separate out 1 item of functionality in to a class. Your method should be broken up in to several classes, but you will get the idea with just one.

This one class, call it DataParser for want of a better name, will be used like this:

DataParser parser = new DataParser();
// set up a loop over the input data
for (String line : inputlines) {
    parser.parseLine(line)
}
char[][] chars = parser.getChars();
double[] doubles = parser.getDoubles();

The advantage of this is that you can separate out your file-reading logic from your parsing logic.

Now, about how we read the file. I recommend something simple that's new in Java 7: Files.readAllLines(Path, Charset).

Path inputpath = Paths.get("hello.txt");
List<String> inputlines = Files.readAllLines(inputpath, StandardCharsets.UTF_8);

OK, we have our input lines that way, and we can string together the two sections:

Path inputpath = Paths.get("hello.txt");
List<String> inputlines = Files.readAllLines(inputpath, StandardCharsets.UTF_8);

DataParser parser = new DataParser();
// set up a loop over the input data
for (String line : inputlines) {
    parser.parseLine(line);
}
char[][] chars = parser.getChars();
double[] doubles = parser.getDoubles();

Now, about that DataParser class.... it should look something like:

public class DataParser {
    private final List<char[]> charlist = new ArrayList<>();
    private final List<Double> doublelist = new ArrayList<>();

    public void parseLine(String line) {
        int charpos = line.indexOf('>');
        if (charpos >= 0) {
            charlist.add(line.substring(0, charpos).toCharArray());
            doublelist.add(Double.parseDouble(line.substring(charpos + 1)));
        } else {
            // the line does not have a >
            // throw an exception?
        }
    }

    public char[][] getChars() {
        return charlist.toArray(new char[charlist.size()][]);
    }

    public double[] getDoubles() {
        double[] ret = new double[doublelist.size()];
        int cnt = 0;
        for (Double d : doublelist) {
            ret[cnt++] = d;
        }
        return ret;
    }

}

This class will 'accumulate' the parsed data, and return it when asked. It needs to do some tricks with both accumulators to get the data out in the right format, but you should be able to figure it out.

Edit Here, I did it for you:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DataParser {
    private final List<char[]> charlist = new ArrayList<>();
    private final List<Double> doublelist = new ArrayList<>();

    public void parseLine(String line) {
        int charpos = line.indexOf('>');
        if (charpos >= 0) {
            charlist.add(line.substring(0, charpos).toCharArray());
            doublelist.add(Double.parseDouble(line.substring(charpos + 1)));
        } else {
            // the line does not have a >
            // throw an exception?
        }
    }

    public char[][] getChars() {
        return charlist.toArray(new char[charlist.size()][]);
    }

    public double[] getDoubles() {
        double[] ret = new double[doublelist.size()];
        int cnt = 0;
        for (Double d : doublelist) {
            ret[cnt++] = d;
        }
        return ret;
    }

    public static void main(String[] args) throws IOException {
        Path inputpath = Paths.get("hello.txt");
        List<String> inputlines = Files.readAllLines(inputpath, StandardCharsets.UTF_8);

        DataParser parser = new DataParser();
        // set up a loop over the input data
        for (String line : inputlines) {
            parser.parseLine(line);
        }
        char[][] chars = parser.getChars();
        double[] doubles = parser.getDoubles();

        System.out.println(Arrays.deepToString(chars));
        System.out.println(Arrays.toString(doubles));
    }

}

Output:

   [[a,  , A,  , b,  , u], [b,  , b,  , X,  , g], [Y,  , z,  , N,  , H]]
   [1.0E-4, 5.0E-4, 3.0E-4]


PHP script that combines data from two CSV files to produce two new files

There are a few things you should take into account.

You never close your files. At the end, use fclose;
Use try {...} catch(){} finally {} and close the file(s) in the finally
Use functions to enhance readability
Do not use die or exit, this kills the script and is bad practise. See this blog post, very valuable
It might be wise to put "magic strings" in a constants file and including this with require - for example your datetime formats, csv columns and so forth. This makes sure that you do not have to edit the script when any of these would change but rather only change the constants.
Comments rot very quickly, any change would leave you with "you have to update the comments too". Don't use comments, in stead use functions that have self explanatory names. i.e. pushCustomerDateToCsvRow(param1, param2,... )


Let's start with weather.js.

Use Node's querystring module to generate the query string from an object instead of concatenating strings. It's easier to read, plus you don't have to deal with escaping.
is appid your API key? You shouldn't put any keys in the code. I suggest you move it out of your code and into an environment variable. That way, it's not part of the history of your version control.
url seems constant (except the query part). You should also move that outside into a variable like you did with location.js. Just combine the url with your constructed query string during calls.
I would suggest you don't construct the text for resolve in the weather module. Have it resolve the data instead. Let the caller decide what it does with the data. It's better that way in the long run, so that you can just chain tools that speak data rather than presentation.

In location.js

Reject with the error object. Let the caller decide what it wants to do with the error. Same as mentioned earlier, it's easier when the caller decides what to do with the data and for functions to just speak in data.

In app.js

You can merge both logic branches together. If you have the location, you can create a pre-resolved promise using the static function Promise.resolve(value). Otherwise, call location(). Then you can have the rest of your logic chain afterwards.

(argv.location ? Promise.resolve(argv.location) : location()).then(function(location){
  return weather(location);
}).then(function(output){
  console.log(output);
}).catch (function(error){
  console.log(error);
});


Could this depth system for a game be improved?

Some remarks to your current map-based implementation:

The idiomatic way of accessing an item in a map and adding it if not present usually goes like this:

if not map.contains(key)
    map[key] = new value

value = map[key]
... modify value

So objectAdd could be shortened:

obj->depth = depth;
// make sure we have an object vector for the given depth
if ( objectMap.find( depth ) == objectMap.end() )
{
    objectMap[ depth ] = new std::vector< object* >;
}

std::vector< object* >* &refVec = objectMap[ depth ];
refVec->push_back( obj );
obj->idDepth = (unsigned)(int)refVec->size() - 1;

In objectRemove it is apparently illegal to pass an object with a non-existent depth. Printing an error message to stdout is not the best way to handle an error like that. You should throw an appropriate exception (fail early is a valuable debugging tool) or allow it by ignoring invalid depths.
It is not imminently clear what objectMove exactly does based on its name and the names of its parameters. It looks like it moves an object to a different depth. So a better name and signature might be:

void depthManager::changeDepth(unsigned int newDepth, object *obj)

In class object the methods getIdDepth() and getDepth do not modify the object state so you should consider making them const (i.e. unsigned int getDepth() const { return this->depth; }).
I'm not 100% convinced of the idDepth property. It basically just reflects the current position of the object in the depth-list and you are writing a fair amount of boiler plate code to keep it that way. This increases the complexity of the class somewhat. I'd revisit the concept and check if I can't get by without it.


When push data to array decide which key need to use

A few thoughts:

First, you might consider whether the name/color property REALLY needs to change as output here.  Why return { color: ... } in some cases and { name: ... } in others?  This tends to indicate that the return data may not sufficiently be describing itself. Even stranger here is the fact that the caller must pass in the hint dataControl "hint" in order to tell the function to modify the return value.  If the calling code is where understanding of "color" vs. "name" exists, then why make this function now have to understand this?  Why can the caller not just mutate a returned { name: ... } object into a { color: ... } one if it is really critical to make this distinction in property name.  Perhaps your object might be well suited to have properties like username, test, value (instead of name or color) and type (to indicate name vs. color).  At least this way to get a consistently formed data objects here (and your if-else goes away).
I am struggling to understand why you are looping through the passed data and setting data1 or data2 value repeatedly when, you are basically overwriting this set value X times (where X is the length of the array).  Why not just build the array once and then set the value?
You really only have two things that are changing when dataControl equals color.  You can just use variables and drop the if-else construct altogether.  In fact generally-speaking, much of you logic can be put into variables, as these values do not change for each iteration over passed data. Using variables here will also simplify your loop such that perhaps all you really need to do is call map on passedData.
Why hard-code your data1 and data2 targets?
It looks like this code has TypeScript type hinting, however no TypeScript tag was applied to this question.  You should either be consistent with your TypeScript usage (putting type hint for BOTH parameters), or not use it it all.

Putting it all together, might yield something like...
const getData = (passedData, dataControl) {
  let propName = 'name';
  let target = 'data2';

  if (dataControl === 'color') {
    propName = 'color';
    target = 'data1';
  }

  const username = this.userForm.value.username;
  const test = this.userForm.value.test;
  const targetEl = this.userForm.controls[target];

  const data = passedData.map((value) => {
    return {
      // if you still REALLY need color vs. name prop
      [propName]: value,
      username,
      test
    };
  });

  targetEl.setValue(data);
}


There is a lot of way, I advice the simple one, use a loop:

enum Error {
    A,
}

fn run() -> Result<(), Error> {
    if rand::random() {
        Ok(())
    } else {
        Err(Error::A)
    }
}

pub fn main() {
    while let Err(_) = run() {
        println!("Hello");
    }
}

However, be sure the program end maybe add a maximum fail counter.


Inside of a function call, avoid echoing.  By hardcoding echoes, you prevent the "silent" usage of the function.  It may be necessary in the future to present the output in more than one format, so use a return inside the function declaration and perform the echo on the function call.

Pay close attention to psr-2's guidelines on control structures.  They will help you (and future developers of your code) to read your code.  Always imagine that the next person to read your code will have a headache, a hatchet, and your home address; don't set them off.

Empty on $_POST is an imprecise way of checking for expected submission data.

strcmp() provides greater specificity than your condition logic requires.   For your logic, just check if the input is identical to the string without a function call.

Condense conditionals within the same block that have the same outcome.  Multiple conditions lead to $passed = 1 so they can be consolidated. I didn't really bother to understand the conditional logic behind $passed = 1 but it should certainly be refined.

Refine your validation check on $_POST['pc'].  You are checking if is_numeric(), that's fine. Then checking if the value that is cast as (int) is an integer -- um, at this point of course it is, it has no choice.  Better yet, why not just make a single check with ctype_digit()?  You might also like to check that the strlen() is valid (only you will know if/how to design this for your region).  If you want to check the quality and length of the postcode value, perhaps it would be more sensible to use preg_match() where you can design robust/flexible validation with a single function call (again, only you can determine this).

$temp_l and $temp_p are poor variable naming choices.  As a new dev to your script, I don't instantly know what they contains (I can venture a guess, but don't ask devs to do this).  Try to practice a more literal naming convention.  Furthermore, try to avoid declaring single-use variables ($temp_l).  Often, fewer variables will lead to fewer typos/mistakes, concise code, and improved readability.  When data needs some explaining, use commenting. *notes: 1. I have read some cases where declaring a variable prior to a foreach loop can improve performance 2. Some devs don't like to see functions fed to a foreach loop, I can respect this and I don't typically do this in my own projects.

There is no use in checking if the return value from explode() is an array.  It returns an array by design, so you can remove that check.  Even if you explode a empty string with PHP_EOL, you will not get a true evaluation from empty(), so that check is pointless to write.  At the end of the day, if you try to use foreach() on an empty array, it simply won't iterate -- no worries.

If you have no intentions of using $i in your foreach loop, don't bother to declare it.  I don't like single-use variables; I super don't like no-use variables.

How to get the substring before the first occurrence of a character without explode()? strstr() with a true third parameter.  Otherwise, explode has to create an array enroute to delivering the string that you need.  My suggested snippet will attempt to extract the substring before the first colon, if there is no colon the full string will be used.

By storing qualifying matches as an array, you can avoid having to trim any trailing delimiters from your output string.  In fact, return the data without delimiters as an array so that you can easily adjust the way that your qualifying values are delimited.

Strictly speaking, having zero qualifying results from a postcode search doesn't mean that there was an "Error", so just have your function calling script accommodate for "Successful" yet "Empty" results.

I can't imagine a benefit from JSON_FORCE_OBJECT.

die() in nearly every scenario should be avoided.

Suggested Code Overhaul:

function sapc_ajax_check() {
    $checker_defaults = get_option('sapc_checker_settings_options');

    if (!isset($_POST['action']) ||  $_POST['action'] !== 'sapc_ajax_check') {
        $errors[] = 'Missing required submission data';
    }
    if (!isset($_POST['pc'])) {
        $errors[] = 'Missing postcode value';
    }
    if (isset($_POST['verify-int']) && $_POST['verify-int'] === 'on' && ctype_digit($_POST['pc'])) {
        $errors[] = 'Invalid postcode value';
    }
    if (isset($errors)) {
        return json_encode(['Error', $errors]);
    }

    $result = [];
    foreach (explode(PHP_EOL, $checker_defaults['postcodes']) as $postcode) {
        $before_colon = strstr($postcode, ':', true);
        $postcode = ($before_colon === false ? $postcode : $before_colon);
        if ($postcode === $_POST['pc'])) {
            $result[] = $postcode;
        }
    }
    return json_encode(['Success', $result]);
}

Much cleaner right?


Don't use threads

You don't need the complexities of threading for this problem. You can use the Tkinter method after to run a function periodically. Threading is necessary if the function you are running takes a long time, but that is not the case here.

You can use a class, but to keep this answer simple I'll only show the function.

Also, note that I use an existing window rather than tkinter.Tk() on each call. There's no need to create a new root window every time you do the check.

def check_clipboard(window):
    temp_value = window.clipboard_get()
    ...

Next, create a function that calls this function every half second:

def run_listener(window, interval):
    check_clipboard(window)
    root.after(interval, run_listener, window, interval)

To start running, simply call run_listener once, and it will continue to run every 500 milliseconds:

run_listener(root, 500)

The logic to stop and pause is roughly the same as what you have now. Create a flag, and then check that flag inside of run_check_periodically.

With this, you can remove the loop from main since tkinter already has an efficient loop:

def main():
    root = tkinter.Tk()
    gui = GUI(root)

    # start the listener
    listen_to_clipboard(root)

    # start the GUI loop
    root.mainloop()