The interface is badly designed:

Are you allowed to pass nullptr here?
Is the object taking ownership of the pointer?

CTextureManager(SDL_Renderer *pRenderer);

Are you allowed to change the renderer?
Are you allowed to replace it with nullptr?
Is the ownership being passed to the CTextureManager object?

void SetRenderer(SDL_Renderer *pRenderer);

Passing name and filename by value. This is causing a copy. This is inefficient and not required. Pass by const reference.
The returned value:
Is it allowed to be nullptr?
Who owns the pointer?

CTexture *LoadFromFile(std::string name, std::string filename);

Another pass by value.
What does the return value indicate?

bool UnLoad(std::string name);

Pass by value again.
Who owns the returned object?

CTexture *GetTexture(std::string name);

You are storing pointers.

    std::map<std::string, CTexture *> m_mapTexture;
    SDL_Renderer *m_pRenderer;

Which means your class is doing both resource management and business logic. A class should do one or the other (search for Separation of Concerns). Split your resource management into its own class. Then use this inside your texture manager.

Ownership semantics.

Your Major problem is you are not correctly indicating the ownership semantics of the objects.

Ownership is all about who is responsible for deleting a dynamically allocated object and is one of the core principles of C++ (the one that raises C++ above C in terms of memory management). If you don't define these semantics well in the interface then people have to actually dig into the implementation to understand how the ownership is working so that they can correctly write their code.

If people are digging into your code to understand the ownership semantics they are now depending on implementation details of your code. This makes your code very brittle to any future changes and tightly couples any code using your class.

Return by reference to indicate that ownership is not being transferred.
Pass by reference to indicate that you are not accepting ownership.
Use smart pointers to pass unique/shared ownership objects around.
Never pass by pointer across a public interface

its fine to use internally but it should not be part of your public interface to other code.

Prefer to use the constructors initialization list.

TextureManager::CTextureManager(SDL_Renderer *pRenderer)
{
    m_pRenderer = pRenderer;
}

// When you have members that have constructors.
// These will be called before the body of the constructor is
// entered.
//
// By initializing in the body of the code you
// are first constructing the object into the default state
// the updating that state. It is better to call the constructor
// directly with the appropriate parameters.
//
// Also reference must be done in the initialization list.
// So prefer to do all initialization in the initialization list
// for consistency.
TextureManager::CTextureManager(SDL_Renderer *pRenderer)
    : m_pRenderer(pRenderer)
{}

Destructor

You destructor is not virtual.

CTextureManager::~CTextureManager()

This means you are not expecting to have any sub types of the object. Which is fine. But you should keep it in mind.

ERROR

    if (m_pFont != nullptr)
    {
        TTF_CloseFont(m_pFont);
    }

m_pFont is not a member of the class. So I expect this would not compile.

Clear All

    for (std::map<std::string, CTexture *>::iterator it = m_mapTexture.begin(); it != m_mapTexture.end(); ++it)

   // Prefer to use `auto` for types you don't care about.
   // Also prefer to use the std::begin() and std::end() rather than
   // calling the methods directly. This will allow you to change the
   // container type in the future without having to change the code.
    for (auto it = std::begin(m_mapTexture); it != std::end(m_mapTexture); ++it)

   // Even better would be to use the new range based for
   for(auto& value: m_mapTexture)

   // Or potentially an algorithm:
   std::for_each(td::begin(m_mapTexture), std::end(m_mapTexture), /* ACTION */);

Don't see any need to set this to nullptr:

        (it->second) = nullptr;

When you are finished you clear the container. So the values no longer exist.

GetTexture

On std::map the operator[] will insert a value into the container if it does not exist. I don't think that is what you actually want.

    return m_mapTexture[name];

UnLoad

Again with the insert.

    CTexture *pTempTexture = m_mapTexture[name];

Don't see the need for this test.

    if (!pTempTexture)
        return false;

Deleting a nullptr is fine.

    delete pTempTexture;

This does nothing useful (as it is about to go out of scope).

    pTempTexture = nullptr;

Since you inserted the name you may want to always delete it (even if the pointer is null).

    m_mapTexture.erase(name);

Just return the pointer here:

    return true;

The pointer will get converted to the correct bool. If you found nothing then it will be false. If you found something it will be true.

LoadFromFile

So your object is always a CTexture never anything derived from it.

        pTexture = new CTexture();

Since your texture is a single type I don't see the need to store pointers in the container. Just store the object directly.

Seems like the only reason for the texture manager to have a renderer is to make this call. Seems strange. Why not pass the renderer into the LoadFromFile() method?

        pTexture->SetRenderer(m_pRenderer);

You have just dynamically allocated and placed into your structure a CTecture. You may return a nullptr now. But a call to GetTexture() is going to return the previously created texture object (that failed to load). On a load failure you may want to remove this object from the structure.

    if (!pTexture->LoadFromFile(filename))
        return nullptr;

This is how I would do it:

// I am guessing a bit because I have not read the SDL documentation.
struct SLDTextureDeleter
{
    void operator()(SDL_Texture* p){SDL_DestroyTexture(p);}
};
class CTextureManager;
class CTexture
{
        // Constructor is private so it can only be used by CTextureManager
        friend class CTextureManager;
        CTexture(std::string const& filename, CRenderer& renderer)
        {
            // Create Texture and load from File.
            // Failure to load leaves the texture pointer as nullptr.
            // The TextureManager tests this by calling ok() to validate
            // that the texture was loaded correctly.

        }
        bool ok() const {return texture.get();}
    public:
        // Allow texture moving
        CTexture(CTexture&& move)
            : texture(std::move(move.texture))
        {}
        CTexture& operator=(CTexture&& move)
        {
            using std::swap;
            swap(texture, move.texture);
        }
        // But disable Copy (as it is manager by CTextureManager)
        CTexture(CTexture const&)            = delete;
        CTexture& operator=(CTexture const&) = delete;
    private:
        std::auto_ptr<SDL_Texture, SLDTextureDeleter>   texture;
};
class CTextureManager
{
  public:
    bool      loadFromFile(std::string const& name, std::string const& filename, CRenderer& renderer);
    bool      hasTexture(std::string const& name) const;
    CTexture& getTexture(std::string const& name) const;

    void clearAll();
    void unLoad(std::string const& name);

  private:
    std::map<std::string, CTexture> mapTextures;
};

bool CTextureManager::loadFromFile(std::string const& name, std::string const& filename, CRenderer& renderer)
{
    CTexture  tmp(filename, renderer);
    bool result = tmp.ok();
    if (result)
    {
        mapTextures.emplace(name, std::move(tmp));
    }
    return result;
}
bool CTextureManager::hasTexture(std::string const& name) const
{
    auto find =   mapTextures.find(name);
    return find != mapTextures.end();
}
CTexture& CTextureManager::getTexture(std::string const& name) const;
{
    // Note: UB if loadFromFile() failed to return true.
    //          or if hasTexture() returned false.
    //          user is supposed to check before use.
    auto find =   mapTextures.find(name);
    return find->second;
}

void CTextureManager::clearAll()
{
    mapTextures.clear();
}
void CTextureManager::unLoad(std::string const& name)
{
    mapTextures.erase(name);
}


Editing  values through a textbox with jquery

First: Rename your variables etc. to English. This is probably why you have not received an answer for one of the most common topics in CR.

Bad Relative Traversal

This is bad practice:

var serieNrBox = $(this).parent().parent().nextAll().last().find("select");
//...
var serieNrBox = $(this).parent().parent().next().find("select");
//...
var serieNr = $(this).parent().parent().prev().find("input");

If you traverse the document tree like this you will need to do shotgun surgery each time anything changes in the DOM. For example, think what would have to change in the above code, if you (or the next developer who maintains this) has to add another select in the same cell as the current select.

Do not traverse DOM to like this to find an element. Give each element you need to find a class name and find relative to the container.

Better Organization

I understand you do this to support multiple product tbodys. You can instead do a:

$("#BestelRegels").find(".BestelRegel").each(function(index, orderRule) {
    //You can locate things relative to orderRule now...

which follows the logical organization of the document.

Unnecessary each

each function bodies with a single function call to $(this) is unnecessary:

$(".SerieNr select").each(function () {
    $(this).change(function () {

is equivalent to:

$(".SerieNr select").change(function () {

Applying these you get:

function alreadyExists(serieNrBox, serienr) {
    return serieNrBox.children().is(function () {
        return $(this).val() === serienr;
    });
}

$("#BestelRegels").find(".BestelRegel").each(function(index, orderRule) {

   // give these elements unique (within tbody) class names instead
   var serieNrBox = $("select", orderRule);
   var txtSerieNr = $(".SerieNr input", orderRule);
   var txtNumberReceived = $(".AantalOntvangen input", orderRule);

    txtNumberReceived.keyup(function (event) {
        var aantal = $(this).val();

        // resize it
        serieNrBox.prop("size", aantal);

        // append new options until it matches the size
        while (serieNrBox.children().length < aantal) {
            serieNrBox.append($("<option></option>"));
        }

        // select the first option
        serieNrBox.children().first().prop("selected", true);
    });

    txtSerieNr.keydown(function (event) {
        if (event.which !== 9 && event.which !== 13) return;

        var serienr = $(this).val();

        // the s/n has to be unique
        if (alreadyExists(serieNrBox, serienr)) return;

        // update the selected, or next empty, option
        var selected = $("option:selected", serieNrBox);

        selected.text(serienr);
        selected.val(serienr);

        var emptyOptions = serieNrBox.find("option")
            .filter(function () {
            return !this.value || $.trim(this.value).length === 0;
        });

        (selected.val().length > 0
            ? emptyOptions
            : emptyOptions.next())
                .first()
                .prop("selected", true);

        $(this).val("").focus();
    });

    serieNrBox.change(function () {
        // update the textbox
        var selected = $("option:selected", this);
        txtSerieNr.val(selected.val()).focus().select();
    });
});

Notes:

References to parent and children are gone (except for
serieNrBox.children() which is quite safe).
keydown handler is simplified.
You can check if any element in a selection satisfies some condition
using is.


How about using the ternary operator and assigning the result to the variable?

def index
  @users = params[:search].nil? ? nil : User
           .search { fulltext params[:search] }.results
           .paginate(page: params[:page], per_page: 10)
end


Best way to handle the error in async node

Check out promises. They are not (yet) available natively in Node.js, but you can use Q library.

Promises allow you to make your control flow explicit with methods like catch and finally instead of hiding it in callbacks.

Also you won't need async with promises.

Q provides a convenience method to “convert” a function that accepts a callback to a promise-returning function.

I don't understand what fnOne or fnTwo is your code (seemingly objects and not functions), so I can't really translate your example, but it would look similar to this:

var Q = require('q');

// Convert our functions to promise-returning functions
var getOne = Q.nbind(fnOne.GetOne, fnOne),
    getTwo = Q.nbind(fnTwo.two, fnTwo) ;

getOne(req, res)
  .then(function (result) {
    return getTwo(result);
  })
  .then(function (result) {
    // do something useful with final result
  })
  .catch(function (err) {
    console.error("Three was an error", err);
    res.send("Error in serving request.");
  })
  .done();


Specification

Palindrome

From wikipedia:

  A palindrome is a word, number, phrase, or other sequence of
  characters which reads the same backward as forward, such as madam or
  racecar or the number 10801. Sentence-length palindromes may be
  written when allowances are made for adjustments to capital letters,
  punctuation, and word dividers, such as "A man, a plan, a canal,
  Panama!", "Was it a car or a cat I saw?" or "No 'x' in Nixon".

We can argue that your specification is stricter/simpler than that of wikipedia.

Unicode compliance

Your algorithm checks characters, not actual glyphs. This is OK for most applications that use ASCII, ANSI or other encodings that represent characters with 16 bits as limit. But for extended unicode, combining characters and other diacritics, your algorithm is flawed.

Design

Guard arguments

You provide a public method, so argument checks are in place.

if (text == null) throw new ArgumentNullException(nameof(text));

While (true) loops

Many consider while (true) bad practice, because it can lead to infinite loops in missing edge cases. Specially when code gets more complex, this is the case. Consider refactoring the loop to use a boolean. However, since this is a trivial and simple algorithm, I understand why you have done it like this.

Unnecessary variables

Since the variables a and b are only used once, there is no need to create variables.

char a = text[min];
char b = text[max];

if (a != b) {
    return false;
}

Shorter:

if (text[min] != text[max]) {
    return false;
}

Lack of variables

Consider creating variables for objects you require on multiple occasions.

lblInput.Foreground = Brushes.ForestGreen;
lblResult.Foreground = Brushes.ForestGreen;
lblTitel.Foreground = Brushes.ForestGreen;

public Brush ForegroundColor { get; } = Brushes.ForestGreen;

lblInput.Foreground = ForegroundColor;
lblResult.Foreground = ForegroundColor;
lblTitel.Foreground = ForegroundColor;

Normalize user input

You could argue that whitespace at the start or end of the input is mostly unintentional, so you should trim it. This depends on your guidelines for best practices concerning user experience.

  string text = InputText.Text;

 var text = InputText.Text.Trim();

Formatted strings

Formatted strings are cleaner and better optimized than concatenating strings.

  OutputText.Text = text + (isPalindrome ? " is a palindrome" : " is NOT a palindrome");

OutputText.Text = $"text is{(isPalindrome ? " " : " NOT ")}a palindrome";

Unoptimized code flow

This code clears the output after checking for a palindrome. You should put this before the check, and only calculate the palindrome if any non-empty input is provided.

if(InputText.Text == string.Empty)
            OutputText.Clear();

WPF design

For a trivial UI, using the code-behind of a control is fine. Consider using M-V-VM when you decide to extend the design and make it more complex.


You should use namespace-qualified keywords instead of strings in the fileKind function:

(defn fileKind [filename]
  (let [f (File. filename)]
    (cond
      (.isFile f)      ::file
      (.isDirectory f) ::directory
      (.exists f)      ::other
      :else            ::non-existent)))

... which would require the following change in the -main function:

(= (lib/fileKind input) :lib/file)


Xamarin image download and resizing for Android

WebClient.DownloadData is a blocking method; you should use DownloadDataTaskAsync. Network I/O is almost certainly the slowest part of the whole operation, so it's important that we're not blocking here. You might also want to consider using the newer HttpClient instead of WebClient.

The third parameter of DecodeByteArrayAsync is the length of the array, but you're passing it imagesBytes.Length - 1. I think you want to pass it imageBytes.Length instead.

There's no need to set imageBytes to null.

I don't really like that LoadScaledDownBitmapForDisplayAsync modifies the options parameter. Since the method is private it's not that important, but it is, to me, surprising behaviour. To avoid this, I would consider merging GetBitmapOptionsOfImageAsync and LoadScaledDownBitmapForDisplayAsync into one method, e.g:

public static async Task<Bitmap> DecodeByteArrayAsync(byte[] imageBytes, int requiredWidth, int requiredHeight)
{
    var options = new Options { InJustDecodeBounds = true };
    await BitmapFactory.DecodeByteArrayAsync(imageBytes, 0, imageBytes.Length, options);

    options.InSampleSize = CalculateInSampleSize(options, requiredWidth, requiredHeight);
    options.InJustDecodeBounds = false;

    return await BitmapFactory.DecodeByteArrayAsync(imageBytes, 0, imageBytes.Length, options);
}


Python program to find the topic with the most meeting time dedicated to it

This can be radically simplified (and made much more legible) in a variety of ways.

First off, the you use 5 lines of code to compute the duration of a meeting, including checking in advance if that duration will be 0 (if M[i][2] != M[i][3]). You don't care if the duration is 0 (s += 0 leaves s unchanged), and the rest of that logic just ensures that you get a positive difference even if the order of those values is backwards. Technically, the definition of a "meeting" that you give doesn't allow those values to be backwards, so it should be safe to simply subtract the start from the end time; however, even if you want to ensure you end up with a positive value, you can just use abs (absolute value):

def period(M,c):
    s = 0
    for i in range(len(M)):
        if c in M[i]:
            s += abs(M[i][3] - M[i][2])
    return s

Next, don't iterate over the indices of a list when you can just iterate over the list. Why do you care about i? You don't, you only want the value M[i], which is much more cheaply and clearly obtained by simply looping on M:

def period(M,c):
    s = 0
    for meeting in M:
        if c in meeting:
            s += abs(meeting[3] - meeting[2])
    return s

Also, you check if c in m, but that's not really what you mean: you actually want to know if the topic c is the topic that meeting m is about. While we're at it, let's also unpack exactly what a meeting is expected to be, rather than use arbitrary integer indices into a list:

def period(M,c):
    s = 0
    for _, _, start, fin, topic in M:
        if c == topic:
            s += abs(fin - start)
    return s

That's become much more clear now that we've given every value a name (rather than just a number) and been explicit about what we're doing.

Alright, let's tackle the main function now. You iterate over every meeting, and compare it to every other meeting, but this isn't strictly necessary. It also risks doing repeated work (e.g., if you have one REALLY long meeting about 'A' and a thousand tiny ones about 'B', you'll compute the total meeting durations for 'B' a thousand times, and actually do the same with 'A'). Let's first figure out all unique topics, and that way we'll be sure to not re-do any work:

def common_argument(M):
    all_topics = {topic for _, _, _, _, topic in M}
    element = all_topics.pop()
    for other_topic in all_topics:
        if period(M, element) < period(M, other_topic):
            element = other_topic
    return element

Well, that still doesn't prevent us from not duplicating work... let's make sure that we only compute the period of each topic once:

def common_argument(M):
    topic_duration = {topic: period(M, topic) for _, _, _, _, topic in M}
    element, element_duration = ...  # What to put here?
    for other_topic, other_duration in topic_duration.items():
        if element_duration < other_duration:
            element = other_topic
    return element

Alright, we're now only compute each duration once. But the rest of that function is just asking "What is the max topic, sorted by duration?" And, in Python, there's a much easier way to ask that:

def common_argument(M):
    topic_duration = {topic: period(M, topic) for _, _, _, _, topic in M}
    return max(topic_duration, key=topic_duration.get)

The function topic_duration.get takes a topic and returns its duration, and iterating over topic_duration yields each unique topic once, so this will give us exactly what we want.

The one thing we could still improve is that we're iterating over M once for each topic, yielding a runtime of O(N*T) where N = len(M) and T is the number of unique topics. There's no reason for that, we could easily loop over the array just once. That would look more like the following:

from collections import defaultdict

def common_argument(M):
    topic_duration = defaultdict(int)
    for _, _, start, fin, topic in M:
        topic_duration[topic] += abs(fin - start)

    return max(topic_duration, key=topic_duration.get)

And voila, we've collapsed all of the same logic into effectively 4 lines of code, and reduced computational complexity significantly.


Python includes logging in the standard library; rather than write your own, why not use it? You can specify an output file, and handle different levels of logging according to the situation.

Per the style guide, the identifiers of constants like freedns_domains should be UPPERCASE_WITH_UNDERSCORES. Also, any import statements should be at the top of the script.

Your docstring isn't quite formatted correctly, it should look like:

def log(message):
    """Appends a string to the logfile (hardcoded as log.txt).

    :param message: The message to be appended. Linebreaks are your responsibility.

    """

Also, I think that the Google style with sphinx-napoleon is much more readable, but YMMV.

Rather than have virtually the whole script running at the top level of the file, it is conventional to encapsulate it into a single entry point function (sometimes called main) then call it like:

if __name__ == '__main__':
    main()

This makes it much easier to reuse the functionality you've developed by importing it elsewhere without actually running anything.

Rather than using + to concatenate strings, I would generally use str.format, e.g.:

"\n\n" + str(now) + ": Script executing,"

would become:

"\n\n{!s}: Script executing,".format(now)

Improvements are a bit outside the usual scope of CR.SE, but as you've asked:

Yes, reading in the appropriate domains from a file would be a good idea. You could use e.g. a regular expression to validate them, or just try: to access them and deal with any exceptions.
Adding a command line interface (see e.g. argparse) would potentially make this more useful.


Routing Java objects using conditional consumers

Again, I strongly recommend you stick to the methods and systems already provided in the Streams API. In this case, the ability to observe-without-changing the stream is given with the Stream.peek() method and the ability to conditionally remove a value from the stream is given with the Stream.filter() method. Using these two methods with a simple helper class, you can get the functionality you desire. Consider your existing "use case":

Predicate<Integer> p1 = (Integer i) -> {
    System.out.println("call p1");
    return i < 5;
};
Predicate<Integer> p2 = (Integer i) -> {
    System.out.println("call p2");
    return i > 5;
};
Consumer<Integer> c1 = i -> System.out.println("less");
Consumer<Integer> c2 = i -> System.out.println("more");

Router<Integer> routerMatchAll = RouterMatchAll.of(p1, c1)
        .chain(p2, c2);
IntStream.range(0, 10).boxed().forEach(routerMatchAll.toConsumer());
System.out.println(">>>>>>>>>>>>>>>>>>>>>>");
Router<Integer> routerMatchOnce = RouterMatchOnce.of(p1, c1).chain(p2,
        c2);
IntStream.range(0, 10).boxed().forEach(routerMatchOnce.toConsumer());

How about a system where you would implement the first stream:

Router<Integer> routerMatchAll = RouterMatchAll.of(p1, c1)
        .chain(p2, c2);
IntStream.range(0, 10).boxed().forEach(routerMatchAll.toConsumer());

as:

    IntStream.range(0, 10).boxed()
        .peek(new ConditionalTee<>(p1, c1))
        .forEach(new ConditionalTee<>(p2, c2));

Note how you use peek() to ensure all values pass through to the forEach()?

The second implementation is currently:

Router<Integer> routerMatchOnce = RouterMatchOnce.of(p1, c1).chain(p2,
        c2);
IntStream.range(0, 10).boxed().forEach(routerMatchOnce.toConsumer());

but I would instead suggest:

    IntStream.range(0, 10).boxed()
        .filter(new ConditionalTee<>(p1, c1))
        .forEach(new ConditionalTee<>(p2, c2));

Note how we call filter() instead of peek()?

Now, what is ConditionalTee? It is a simple class that takes a predicate, and a Consumer, and it calls the consumer with the value, if the value passes, and it returns false if the predicate passes (which means the value will be filtered in a filter call). It is more comments than code, and it's really simple:

public class ConditionalTee<T> implements Predicate<T>, Consumer<T> {

    private final Predicate<? super T> predicate;
    private final Consumer<? super T> consumer;

    public ConditionalTee(
          Predicate<? super T> condition, Consumer<? super T> consumer) {
        this.predicate = condition;
        this.consumer = consumer;
    }

    @Override
    public void accept(T t) {
        test(t);
    }

    @Override
    public boolean test(T t) {
        // NOTE: inverted boolean.
        // this will be called from a Stream.filter()
        // need to return true if the value should stay on the stream
        // false if it should be removed from the stream.
        // We want to keep it on the stream if we are not siphoning it off
        //     (return true).
        // We want to remove from the stream if we are siphoning the value off
        //     (return false).
        if (!predicate.test(t)) {
            return true;
        }
        consumer.accept(t);
        return false;
    }
}

See it all running here, in ideone.


Ideal FP/Scala way to vaildate rectangular list

In Scala, never use null unless some API requires it of you; use Option instead. If you have to interface with an API that returns null, convert the result into an Option. As long as you do that, you can ignore null checks, for they'll always be errors: you got a null from some code that shouldn't be producing it, or you forgot to convert some return value to Option, or else you didn't even know you had to.
Use exists or forall -- forall seems better suited, but either will do with the proper conditionals. Also, do not use first -- use head. Yeah, it looks weird, but head/tail is idiomatic, and faster.
There's a require function that is used for parameter validation. Either require(validateRectangular) or require(validateRectangular, "all rows must have same length") will do.

And, yes, validateRectangular was a good start, and for new comers to FP it is not obvious to implement something that will stop at the first incorrect size in functional style -- at least on a strict language like Scala. You'd either throw an exception or use recursion.


Remove Duplicates From Linked List In Place - Java

Classes not designed for extension should be made final. Variables which should not change after initial assignment should also be made final. In addition to documenting design intent, they make it easier to read the code because you know they won't change.

As @IEatBagels said, removing curly braces is not a reasonable design goal. Code readability should be maximized. In particular, even optional curly braces are desirable in almost all cases, both because they enhance readability and because they avoid an obnoxious bug when you need to add a second statement and forget to add the curly braces.

In idiomatic java, underscores are only used in the names of constants. Prefer the use of camelCase.

For readability, it's preferable to use full, descriptive variable names rather than abbreviations.

In non-trivial code, you'd often want to encapsulate the variables in Node. This lets you change the types of those variables without breaking the contract of Node.

If you build your test list slightly differently, you don't need all those new variables. Even better would be to use a method to create the list for you.

A toString implementation on Node might be nice. Then you can just print the node directly, rather than asking for the value.

An arguably superior approach would use a HashSet<Character> rather than nested iterations of the list. You cut the runtime significantly at the cost of some memory. If you're not allowed to use a HashSet, an array of size 26 mapped to the letters of the alphabet would also work (assuming the input is constrained to all lowercase letters).

If you made all these changes, your code might look more like:

void removeDuplicatesInPlace(final Node head) {
    final Set<Character> listValues = new HashSet<>();
    Node current = head;
    listValues.add(current.val);

    while (current.next != null) {
        if (!listValues.add(current.next.val)) {
            current.next = current.next.next;
        } else {
            current = current.next;
        }
    }
}

class Node {
    final char val;
    Node next;

    Node(char val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return Character.toString(val);
    }
}

public void removeDuplicatesInPlace() {
    final Node head = new Node('a');
    Node current = head;

    current.next = new Node('a');
    current = current.next;

    current.next = new Node('b');
    current = current.next;

    current.next = new Node('c');
    current = current.next;

    current.next = new Node('b');
    current = current.next;

    current.next = new Node('b');
    current = current.next;

    current.next = new Node('c');
    current = current.next;

    current.next = new Node('c');
    current = current.next;

    // a -> a -> b -> c -> b -> b -> c -> c
    this.removeDuplicatesInPlace(head);
    // a -> b -> c

    current = head;
    while (current != null) {
        System.out.print(current + " -> ");
        current = current.next;
    }
}

private static Node buildList(final char... values) {
    final Node head = new Node(values[0]);
    Node current = head;

    for (int i = 1; i < values.length; i++) {
        current.next = new Node(values[i]);
        current = current.next;
    }

    return head;
}


Clean up repeated file.writes, if/elses when adding keys to a dict

You can make the HTML a multi-line string with formatting templates (see this SO question for discussion on indentation, I've kept it simple):

def print_html(car, html_file):
    html = '''
{0[price]}

{0[year]} {0[trim]}

     ...

'''

Then your writing becomes a single line:

    html_file.write(html.format(car))

Note that this doesn't strip; you should do that when the data go into the dictionary.

There is a lot of duplication in get_car. Also, you do the find twice, which will slow you down. Try something like:

def get_car(listing):
   car = dict()
   data = {'year': ('span', 'atcui-truncate ymm'),
           ...}

   for key in data:
       element, class_ = data[key]
       result = listing.find(element, class_=class_)
       car[key] = '' if result is None else result.get_text().strip()

   return car

Finally, you aren't always following the style guide, e.g. lining up operators:

### Declarations

home = os.environ['HOME']
filename = home + '/results.html'
results_file = open(filename, 'w')


Node, Link, Node, Link, Node: Linking Nodes into a LinkedList

Methods & Naming

You're building a collection so, implicitly, you're building a contract with your user that your class will act like a collection, that you'll stick to a protocol for collections objects.

If you wan't to grasp a little more on what I’m trying to say, you can read this article.

So, even though I agree with @Dair that size would be “saffer” as _size (but hey, we’re all responsible adults around here), I strongly disagree with the size property. You should implement it as a __len__ method and use it like:

stuff = LinkedList()
length = len(stuff)

Some other methods can have more common names too:

add \$->\$ apppend;
add_at \$->\$ insert or __setitem__:

__setitem__ will allow you to do stuff[3] = 'some value' and then insert is just a call to self[index] = value.

You will need to change the signature to def __setitem__(self, key, value).
remove \$->\$ pop (or maybe __delitem__); remove is prefered to remove by value instead of by index.
get \$->\$ __getitem__: it will allow you to do the_value = stuff[3]; you should also remove get_node as there is little to no interest in exposing your internals to the user.

Methods that are missing

You could implement an __iter__ method that will allow you to do:

stuff = LinkedList()
# populate stuff
for elem in stuff: # will use __iter__, or fail back to __len__ + __getitem__ if not available
    do_something(elem)

It will also help you shorten __getitem__. You can use something along the lines of:

def __iter__(self):
    node = self.first
    while node is not None: # No self.size involved, yay
        yield node.value
        node = node.after

You can also implement the __reversed__ iterator using the same logic (and use it in __getitem__ too.

Using a parameter to __init__ that default to None would also be usefull to build a LinkedList out of any iterable:

def __init__(self, other=None):
    self._size = 0
    self.first = None
    self.last = None

    if other is not None:
        for element in other:
            self.append(element)

It is then easy to create stuff = LinkedList([1,2,8,12]).

And finally, you should consider adding a __str__ or __repr__ method so you can print(stuff). Use __iter__ to simplify it.


class Node:

It is "strange" to have a Node with no value.  Consider removing the default value=None.

You never create a Node with an explicit "left" or "right" branch.  Consider removing these extra parameters from the constructor, and just assigning them to None.

Private members should be prefixed by an underscore.  Since no external entity should access the value, or the left or right branches, these should be renamed.

class Node:
   def __init__(self, value):
      self._value = value
      self._left = None
      self._right = None

Node is actually an internal detail of BST, so perhaps nest it as an inner class:

class BST:

   class _Node:
      def __init__(self, value):
        self._value = value
        self._left = None
        self._right = None

Again, a node with no value is "strange".  It is much more common to represent an empty tree with as root=None, rather than root=Node(None).

   def __init__(self):
      self._root = None

Your put() method calls _put(), which can call _put(), which can call _put() and so on.  In short, it is recursive.  There is no need to be recursive; you never need to return a value from a sub-call.  You are using tail-recursion, so the compiler/interpreter might simply jump back to the top of the function, instead of creating additional stack-frames.  Except python doesn't do tail recursion, and you could get a stack overflow!

Instead, you can simply do the loop yourself:

   def put(self, value):

      new_node = BST._Node(value)

      if self._root:
         node = self._root

         while node:
            prev = node
            node = node._left if value < node._value else node._right

         if value < prev._value:
            prev._left = new_node
         else:
            prev._right = new_node

      else:
         self._root = new_node

Ditto for contains().  Don't rely on tail-recursion, just create the loop yourself.

   def contains(self, value):
      node = self._root

      while node:
        if node._value == value:
           return True
        node = node._left  if  value < node._value  else  node._right

      return False

In-order traversal: building lists is so passé.  Generators can be much more efficient.  Starting with Python 3.3, we also get the cool new yield from syntax, to make them easier:

   def inorder(self):

      def _inorder(node):

         if node._left:
            yield from _inorder(node._left)

         yield node._value

         if node._right:
            yield from _inorder(node._right)

     if self._root:
         yield from _inorder(self._root)

If you want to return a list, and not the generator, you could simply pass the generator to the list() function.

   def inorder_list(self):
       return list(self.inorder())

Avoid polluting the global namespace.  I prefer my tests in a separate "xxxx_test.py" file, but for a single file solution, you can put the required imports and test classes in the if __name__ == '__main__': block:

if __name__ == '__main__':

   import unittest, random

   class TestBST(unittest.TestCase):

      def test_random_lists(self):

         """Test a bunch of lists of various sizes, randomly"""

         for length in range(20):

            bst = BST()
            lst = [ random.randint(1, 100) for _ in range(length) ]

            with self.subTest(lst=lst):

               for val in lst:
                  bst.put(val)

               lst.sort()

               self.assertEqual( bst.inorder_list(), lst)

   unittest.main()

Finally, documentation!  Use """docstrings"""

Run help(BST) and look at the output.  Is everything documented?  Are there any unnecessary (ie, private) classes or methods exposed to the outside world?


Basic Javascript algorithm for time implementation (morning, afternoon, etc.)

The first question has to be: What is the point of this? Do you really want to (only) write the results into the console in a real application?

Other than that, it is a bit pointless to pre-calculate the conditions in variables in this case, because they are only used once and they are exclusive to each other.


You claim that this code works.  However, since you haven't really specified exactly what the intended behaviour is, I can't verify whether it does what it's supposed to do.  There are some very strong code smells that lead me to suspect that this code is completely broken, or at least doing something silly.

Non-idiomatic loop limits: The idiomatic way to write a loop that does something 14 times, especially when counting from 0, is

for (int i = 0; i < 14; i++) {
    …
}

This tip would be merely a nitpick, except that I suspect you have a bug in setup(): is pin 7 supposed to be in INPUT or OUTPUT mode?
Apparent mismatch of code and comments:  In setup(), you wrote:

//setup digital pins as inputs pin 3 - 13
for (int i = 2; i <= 7; i++) {

What is the relationship between 3-13 and 2-7?  The comment is either erroneous or fails to fully explain the code.
Misuse of String.concat():  dataString, being a String, is immutable.  Therefore, dataString.concat(i) is a no-op, and dataString.concat("," + String(digitalRead(i)) + "/") is a convoluted way of just calling digitalRead(i) and discarding the result.  The final outcome is that Serial.println(dataString) is equivalent to Serial.println("").

In addition, I see some code hygiene issues, such as inconsistent indentation and using Input instead of input for a variable name.


Bug

No, it is not correct:

self.right.set_height

set_height is not run due to the lack of parenthesis, hence the height is not correctly set.

Swapping

In many places such as for example:

    temp = self
    self = self.right
    self.right = temp
    self.right.set_height
    self.set_height

You are swapping values in an obfuscated manner, just use the built-in a, b = b, a syntax:

>>> a, b = 1, 2
>>> a, b = b, a
>>> a, b
(2, 1)

Naming

Universally, names of classes are written in PascalCase, and you should really stick to it, even if the compiler does not enforce it:

binary_tree -> BinaryTree

getters

Getters are highly frowned upon in Python. Values are generally accessed directly.

If you really do not want the user to access values directly you may make them "private" by prefixing __ and letting a @property return them.

Decide for your nil values

None is the standard nil (nothing) value in Python but in get_right_height you return -1 if the value isNone. If so just make the default -1 and remove the getter as suggested above.

Repetition Repetition

You repeat b.add 6 times, use a loop to avoid such waste.

There must be a way to avoid repetition in the below code-blocks, the problem is that you have duplicate functions for left and right, maybe a single rotate function could help you here.

        '''Adding to left subtree'''
        if self.left is None:
            self.left = Node(data)
        else:
            self.left.add_node(data)
            if ( self.get_left_height() - self.get_right_height() == 2):
                ''' Then we need to balance a subtree'''
                print("Rebalancing after inserting", data)
                if (data < self.left.data):
                    self.rotate_left()
                else:
                    self.double_rotate_left()

        '''Adding to right subtree'''
        if self.right is None:
            self.right = Node(data)
        else:
            self.right.add_node(data)
            if ( self.get_right_height() - self.get_left_height() == 2):
                ''' Then we need to balance a subtree'''
                print("Rebalancing after inserting", data)
                if (data < self.right.data):
                    self.rotate_right()
                else:
                    self.double_rotate_right()


Registration and Login System for Application

Security

Yes, you are storing passwords safely. But your code is still incredibly insecure, as you are completely open to SQL injection.

You should use prepared statements, always, for all variable data.

[I also don't see any protection against CSRF; If you don't have it, you should add it, even for login forms; A user may for example force-login a victim into a fake account, and - if the victim does not pay attention - the attacker can thus see actions the victim takes on the site (which may potentially be interesting on a social platform and would definitely violate the privacy of your users)]

Misc

There are a lot of small mistakes and oddities in your code which makes it harder to read and maintain than necessary. Here's a small list, although I may have missed some.

Your indentation is off, making your code hard to read.
You mix mysql_ and mysqli_ functions, which will not work.
Do not use mysql_ functions; they are deprecated and will be removed in PHP7.
You have statements after you die (eg mysql_close();), which doesn't make sense.
Why die? There are few reasons to do it (one would be after a redirect), but in your cases it doesn't really make sense.
You have some duplication which you should remove (eg the One or both of the fields are empty error parts; You also have a lot more die(json_encode($response)); than you need).
I would use a lot more functions. It makes code more readable (because logical blocks now have a name) and more reusable and testable.
Why do you have POST values that you don't use (eg age, id)?
You define your db info more than once, which makes your code hard to maintain. It also makes hiding your db password harder.
You first access POST, and only afterwards ask if POST is empty or not (and you only actually check this in your login code, not your registration code).


Checking whether various form fields are filled in

You could solve this by constructing your Queryname dynamically:

var queryName = "Query";
if ( sEmail ) queryName += "Email";
if ( sBDay  ) queryName += "BDay";
if ( sPhone ) queryName += "Phone";

if ( queryName == "Query" ) queryName = "QueryNameOnly";

Outputs.SetProperty( queryName,"Y" );

But for this you would have to be a little more strict with your Parameter-Names not changing between BDay and BithDate and no Specialcase for ALL


Advice 1

In your insertionSort you can remove the last statement (return).

Advice 2

Making your insertion sort generic is easy:

template<typename RandIt>
void insertion_sort(RandIt begin, RandIt end)
{
    for (auto i = begin + 1; i != end; ++i)
    {
        auto key = *i;
        auto j = i - 1;

        while (j >= begin and *j > key)
        {
            *(j + 1) = *j;
            --j;
        }

        *(j + 1) = key;
    }
}

template<typename Container>
void insertion_sort(Container& cont)
{
    insertion_sort(std::begin(cont), std::end(cont));
}

Advice 3

Making your print function generic is not hard either:

template<typename RandIt>
void print(RandIt begin, RandIt end)
{
    using value_type = typename std::iterator_traits<RandIt>::value_type;
    std::copy(begin, end, std::ostream_iterator<value_type>(std::cout, ", "));
    std::cout << std::endl;
}

template<typename Container>
void print(const Container& container)
{
    print(std::begin(container), std::end(container));
}

Hope that helps.


Load bitmap object data into array of byte values

module imagesearch =

All types should use PascalCase, this includes modules. So the correct name would be ImageSearch.

type BitmapSearchClass() =

That's a weird name, names of classes shouldn't end with Class. And why is it a class in the first place? If it contains only static members, it should probably be a module.

static member loadBitmapIntoArray (pBitmap:Bitmap) =

Public methods should also use PascalCase (LoadBitmapIntoArray).

pBitmap:Bitmap
let tBitmapRectangle = …

Prefixing each parameter with p and each local variable with t seems like a weird kind of Hungarian notation. Please don't do that, it doesn't serve any purpose.

Rectangle(0, 0, pBitmap.Width, pBitmap.Height)

A shorter way to write this would be:

Rectangle(Point.Empty, pBitmap.Size)

let tLockMode = ImageLockMode.ReadOnly
let tImageFormat = PixelFormat.Format24bppRgb

let tBitmapData = pBitmap.LockBits(tBitmapRectangle, tLockMode, tImageFormat)

Why are these variables? Since you never use them again, and since naming them doesn't add any useful information, you can just write them directly in the function call:

let tBitmapData = pBitmap.LockBits(tBitmapRectangle, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb)

let tImageRGBValues : byte array = Array.zeroCreate tImageByteLength

Another way to specify the type is to add type parameter to zeroCreate:

let tImageRGBValues = Array.zeroCreate<byte> tImageByteLength

do Marshal.Copy(tImageRGBValues, 0, tIntPtr, tImageByteLength)

do pBitmap.UnlockBits(tBitmapData)

You don't need to write do here. (Actually, I was surprised you can write do here.)


You could eta-contract the definition in two places: \acc x -> acc ++ x is the eta-expanded version of (++) and concat' ys = (...) ys is the eta-expanded version of concat' = (...). So that would take you to:

concat' :: [[a]] -> [a]
concat' = foldl (++) []

Now, in that case it turns out that it's better to use foldr rather than foldl and there is a good write-up about concat on the haskell wiki.


Asserting our preconditions

Your class requires T to either be an integral type or a floating point type. If it's not, you'll get a compile error at point of use on operator() instead of at point of declaration. Let's fix that:

static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value, "!");

Unnecessary Complexity

We are conditionally selecting a distribution type based on whether or not T is integral or floating point. Once we assert that it's one or the other, we can simply use std::conditional:

using dist_type = std::conditional_t<
                      std::is_integral<T>::value,
                      std::uniform_int_distribution<T>,
                      std::uniform_real_distribution<T>>;

And just use that:

T operator()(T min, T max)
{
    dist_type uniformDistribution(min, max);
    return uniformDistribution(mRandomEngine);
}

This is a lot more direct. No extra template arguments. Also auto on return type is best reserved for those cases where you need it. This is a random engine generating Ts, so it really had better return a T.

Single-value?

Consider the difference between our distributions. uniform_int_distribution is closed:

  Produces random integer values i, uniformly distributed on the closed interval [a, b]

but uniform_real_distribution is open:

  Produces random floating-point values i, uniformly distributed on the interval [a, b)

This suggests one of two potential implementations

Pass this difference onto your users. They should be aware that for floating point Ts, it will be open on the top end.
Make your implementation always open on top end of the distribution.

Right now, we're half and half. It's fairly unexpected that:

Random<int> r;
r(1, 6); // can return 6
r(0, 6); // can return 6
r(6);    // cannot return 6

I'd recommend option (1):

T operator()(T max) {
    return (*this)(0, max);
}

Prefer Braces

Where you have:

: mRandomEngine(std::random_device()())

Prefer to brace-initialize the random_device:

: mRandomEngine(std::random_device{}())


Jest unit test that handles a wrapped Promise

I think the test is ok. Remember what you're testing is this

const signIn = (
  username,
  password,
  successCallback,
  errorCallback,
) => {
  Auth.signIn(username, password)
    .then(user => successCallback(user))
    .catch(err => errorCallback(err));
};

and NOT Auth. Here Auth is just a dependency so you will stub its functionality. Considering that its interface is Promise-based, you need to test both cases - therefore having a test that verifies your expected (promise solved) and the one with the error is correct.

There are some changes I would add, though. For instance, rather than creating my own successCallback and errorCallback I would use mock functions, that would allow me to have further information

const successCallback = jest.fn();
const rejectCallback = jest.fn();

and I can check there if they were called or not and verify their arguments.

expect(successCallback).toHaveBeenCalledWith(mockUser);
expect(rejectCallback).not.toHaveBeenCalled();

and the other way around for the other test.

Then, I would take advantage of async/await for the tests, so we don't need to ensure that ugly done function is called. Basically, we declare the arrow function of the test as async, we await the promise calls and just by having the arrow function to be finished ensures our tests have passed.

An example of these changes would be something like this

it('invokes the success callback on success', async () => {
    jest
      .spyOn(Auth, 'signIn')
      .mockImplementation(() => Promise.resolve(mockUser));
    const successCallback = jest.fn();
    const rejectCallback = jest.fn();
    await signIn('jon', 'snow', successCallback, rejectCallback)
    expect(Auth.signIn).toHaveBeenCalledWith('jon', 'snow');
    expect(successCallback).toHaveBeenCalledWith(mockUser);
    expect(rejectCallback).not.toHaveBeenCalled();
  });

Another step would be that we have strings all over our tests, such as "jon" and "snow". If we already have a mocked user we could reference them from there by using mockUser.username, mockUser.password

That leaves us with the tests looking like this

it('invokes the success callback on success', async () => {
    jest
      .spyOn(Auth, 'signIn')
      .mockImplementation(() => Promise.resolve(mockUser));
    const successCallback = jest.fn();
    const rejectCallback = jest.fn();
    await signIn(mockUser.username, mockUser.password, successCallback, rejectCallback)
    expect(Auth.signIn).toHaveBeenCalledWith(mockUser.username, mockUser.password);
    expect(successCallback).toHaveBeenCalledWith(mockUser);
    expect(rejectCallback).not.toHaveBeenCalled();
  });

  it('invokes the error callback on err', async () => {
    jest
      .spyOn(Auth, 'signIn')
      .mockImplementation(() => Promise.reject(mockUser));

    const successCallback = jest.fn();
    const rejectCallback = jest.fn();
    await signIn(mockUser.username, mockUser.password, successCallback, rejectCallback);
    expect(Auth.signIn).toHaveBeenCalledWith(mockUser.username, mockUser.password);
    expect(rejectCallback).toHaveBeenCalledWith(mockUser);
    expect(successCallback).not.toHaveBeenCalled();
  });

As you can see they are pretty similar, so we could somewhat extract that functionality to a method with the common assertions.

We could create a function like this

const assertSignIn = async (mockedResponse, shouldBeCalledCallback, shouldNotBeCalledCallback) => {
        jest
            .spyOn(Auth, 'signIn')
            .mockImplementation(() => mockedResponse);
        const successCallback = jest.fn();
        const rejectCallback = jest.fn();
        await signIn(mockUser.username, mockUser.password, successCallback, rejectCallback)
        expect(Auth.signIn).toHaveBeenCalledWith(mockUser.username, mockUser.password);
        expect(shouldBeCalledCallback).toHaveBeenCalledWith(mockUser);
        expect(shouldNotBeCalledCallback).not.toHaveBeenCalled();
  };

and then call it properly from each test

it('invokes the success callback on success', async () => {
    const successCallback = jest.fn();
    const rejectCallback = jest.fn();
    await assertSignIn(Promise.resolve(mockUser), successCallback, rejectCallback);
  });

  it('invokes the error callback on err', async () => {
    const successCallback = jest.fn();
    const rejectCallback = jest.fn();
    await assertSignIn(Promise.reject(mockUser), rejectCallback, successCallback);
  });

Although both last parameters are mock function, the difference is conceptual - by declaring them outside you can ensure by reading the tests in which the successCallback should be executed and in which should not.


Count lines of scala code (omitting empty lines) in a directory, traversing any subdirectories

Instead of collecting all the source files in one sweep, and all the sub-directories in another sweep, you could move the foldLeft() to the top level and deal with each element as it is encountered.

def traverse(dir :File) :Int =
  dir.listFiles().foldLeft(0){ case (sum,file) =>
    if (file.isDirectory)
      sum + traverse(file)
    else if (file.getName.endsWith(".scala"))
      sum + io.Source.fromFile(file).getLines().count(_.nonEmpty)
    else
      sum
  }


I don't quite understand why you'd use a ref here.

public void insertData(ref Node node, int data)
{
    if (node == null)
    {
        node = new Node(data);

    }
    else if (node.number < data)
    {
        insertData(ref node.rightLeaf, data);
    }

    else if (node.number > data)
    {
        insertData(ref node.leftLeaf, data);
    }
}

Why not just return the node?

public Node insertData(Node node, int data)
{
    if (node == null)
    {
        return new Node(data);

    }

    if (node.number < data)
    {
        return insertData(node.rightLeaf, data);
    }

    if (node.number > data)
    {
        return insertData(node.leftLeaf, data);
    }
}

Your capitalization is consistent, but slightly confusing and non-standard. For example, both your private fields and public methods are camelCase.

   public void insert(int d)
    {
        if (isEmpty())
        {
            root = new Node(d);
        }

This would be perfectly fine if you distinguished the field by using the this keyword or an underscore to make it look different from your methods.

    public void insert(int d)
    {
        if (isEmpty())
        {
            _root = new Node(d);
        }

Or

    public void insert(int d)
    {
        if (isEmpty())
        {
            this.root = new Node(d);
        }

But like I said, it's non-standard. The standard is to use PascalCase for methods, camelCase for local vars, and _underscoredCamelCase for private fields.

    public void Insert(int d)
    {
        if (IsEmpty())
        {
            _root = new Node(d);
        }


Personally I would change

public void Push(T value)
{
    var newNode = new StorageNode(value);
    if (head != null)
    {
        newNode.Next = head;
    }
    head = newNode;
    ++Count;
}

into

public void Push(T value)
{
    var newNode = new StorageNode(value);
    newNode.Next = head;
    head = newNode;
    ++Count;
}

because I find the control not really useful. I mean, if the head is null then nothing happens, newNode.Next remains null.

Better yet (in my opinion), if you add a constructor:

public StorageNode(T value, StorageNode next)
{
    Value = value;
    Next = next;
}

the Push method can be written as:

public void Push(T value)
{
    head = new StorageNode(value, head);
    ++Count;
}


Big Nerd Ranch Bronze Challenge: Disallow Alphabetic Characters

Two problems in your code

You check if the replacement string contains at least one allowed
character, so that pasting  "1A" into the text field would be accepted.
Instead you should check if the string contains no invalid character:

if string.rangeOfCharacterFromSet(
    NSCharacterSet(charactersInString: "-0123456789.").invertedSet) != nil {
    return false
}

(I prefer a comparison != nil over an optional binding to the
unused variable _ in this situation.) Note that this makes the initial
check for a non-empty string obsolete.

In order to prevent two decimal separators (such as "1.2.3"), you check if both
the existing string and the replacement string contain a period. But
this prevents the replacement of – for example – "1.2" by "3.4" with
copy/paste. To handle that correctly, you have to build the
new string and check that:

if let existingString = textField.text as NSString? {
    let newString = existingString.stringByReplacingCharactersInRange(range, withString: string)
    // check if `newString` contains more than one dot `.`
    // ...
}

Possible improvements

The decimal separator is not always the
dot character ".". In Germany for example (and many other countries),
floating point numbers are written as "12,34" with a comma as separator, and that would be denied with your code.

You could determine the correct localized decimal separator at
runtime:

let separator = NSNumberFormatter().decimalSeparator

and use that instead of the hard-coded period. But that still does not
cover all invalid input, such as "12-34-56".

There is a better (and simpler) solution: Check if the new string
after replacement can successfully be converted to a number, using
a NSNumberFormatter. That will recognize valid numbers according to
the user's locale correctly:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    // Get current string as `NSString`
    guard let existingString = textField.text as NSString? else { return false }
    // Perform replacement:
    let newString = existingString.stringByReplacingCharactersInRange(range, withString: string)
    // Check for empty result ...
    if newString.isEmpty {
        return true
    }
    // ... or valid number:
    let fmt = NSNumberFormatter()
    fmt.numberStyle = .DecimalStyle
    return fmt.numberFromString(newString) != nil
}

Since creating a number formatter is "expensive" (compare
NSFormatter - NSHipster), you
can improve that further by creating the formatter only once – for example as a static property.


Looking this over a second time, I see a few more problems, one of which was my mistake.

I believe that InsertEmployee is a bad name, since the number of employees inserted depends on the input parameter. A better name is InsertEmployees. Similarly, newEmployeeRecord is a bad name since it's also about an arbitrary set of employees, but it's extraneous anyway.

I notice that this code throws an exception if any of the Convert.To*() fails, maybe due to the CEO making $3 billion a year, or employeee IDs changing to have 10 digits. you mention wanting to avoid the type conversion, was this the main idea or was it speed?

I had missed the line about EmployeeRecords. What is it? It's not defined anywhere in the code provided; we can determine from context (though we shouldn't have to) that it is IEnumerable<Employee> or a derived class and that it's either a global, or a member of the same class that InsertEmployee() is, and that no matter what its protection status is, it's available to anyone who can call InsertEmployee(), which is everybody. Which brings up two questions: (a) why does it need to be returned from InsertEmployee() if it's accessible everyhwere that InsertEmployee() is? Just make it public. (b) Why wouldn't InsertEmployees just .Add the Employees directly to it?

public void InsertEmployees(dynamic employees)
{
    foreach (dynamic employee in employees)
    {
        EmployeeRecords.Add(new Employee
        {
            EmployeeId = Convert.ToInt32(employee.EmployeeId)
            ,
            EmployeeName = Convert.ToString(employee.EmployeeName)
            ,
            Age = Convert.ToInt32(employee.Age)
            ,
            Salary = Convert.ToInt32(employee.Salary)
            ,
            DepartmentId = Convert.ToInt32(employee.DepartmentId)
        });
    }
}

But let's get to the real underlying issue, why this whole code stinks. Several commenters hinted at the absurdity of using dynamic here. It's clear that you know the database schema; thus there's no reason to be using dynamic. .NET has good language features for working with database natively and in a strongly typed manner; it's called LINQ-to-SQL. Use it; you'll do less grunt work and have better code. Please see https://msdn.microsoft.com/en-us/library/bb386976%28v=vs.110%29.aspx

Old answer (incorrect, given that I missed what the function was returning):

Since you're returning an IEnumerable<>, you can simplify things greatly by using yield return to give elements back one at a time, rather than creating a temporary List and then throwing it away:

    public IEnumerable<Employee> InsertEmployee(dynamic employees)
    {
        foreach (dynamic employee in employees)
        {
            yield return new Employee
                {
                    EmployeeId = Convert.ToInt32(employee.EmployeeId)
                    ,
                    EmployeeName = Convert.ToString(employee.EmployeeName)
                    ,
                    Age = Convert.ToInt32(employee.Age)
                    ,
                    Salary = Convert.ToInt32(employee.Salary)
                    ,
                    DepartmentId = Convert.ToInt32(employee.DepartmentId)
                }
            );
        }
    }


Determine children within edge and return a list of tuple pairs

Run hlint tool on your source to help you with getting rid of redundant brackets, $ and other minor suggestions.

In neighbors your using of guard in list monad can be changed to filter function:

neighbors :: Pair Int -> Int -> BiMorph Int -> Neighbors
neighbors p e (BiMorph f g) = map dropP $ filter ff $ concat [cartesianPairs f p, cartesianPairs g p, cartesianDoubles f g p] where
    ff (Pair x' y') = x' <= e && y' <= e

You can also hardcode the list into cartesianPairs as it's short:

cartesianPairs :: Func -> Pair Int -> [Pair Int]
cartesianPairs f p =
    [f <$> Pair x y <*> p | (x, y) <- [(1,0), (0,1), (1,1)]]

You can even use pairs directly:

cartesianPairs :: Func -> Pair Int -> [Pair Int]
cartesianPairs f p =
    [f <$> pair <*> p | pair <- [Pair 1 0, Pair 0 1, Pair 1 1]]

I also have an impression that cartesianPairs can be further simplified but I couldn't find anything that has clear meaning. Here are two attempts:

cartesianPairs f p =
     (<*> p) <$> (fmap . fmap) f [Pair 1 0, Pair 0 1, Pair 1 1]

cartesianPairs f p =
     (<*> p) . fmap f <$> [Pair 1 0, Pair 0 1, Pair 1 1]

cartesianDoubles can be shrinked the same way if you want:

cartesianDoubles f g (Pair x y) = [Pair (ff x) (gg y), Pair (gg x) (ff y)] where
    ff x = f x 1
    gg x = g x 1

cartesianDoubles f g p = [Pair ff gg <*> p, Pair gg ff <*> p] where
    ff x = f x 1
    gg x = g x 1

cartesianDoubles f g p = (<*> p) <$> [Pair ff gg, Pair gg ff] where
    ff x = f x 1
    gg x = g x 1

Yet another improvement. You can notice that there are versions of cartesianDoubles and cartesianPairs sharing the same (<*> p) <$> part:

cartesianPairs f p =
    (<*> p) <$> (fmap . fmap) f [Pair 1 0, Pair 0 1, Pair 1 1]

cartesianDoubles f g p = (<*> p) <$> [Pair ff gg, Pair gg ff] where
    ff x = f x 1
    gg x = g x 1

Then notice that <$> in (<*> p) <$> is for Functor [] instance, so it's just plain map, and map has a property of commuting withconcat:map f . concat == concat . map f`.

So you can move the common fragment out:

cartesianPairs f p =
    (fmap . fmap) f [Pair 1 0, Pair 0 1, Pair 1 1]

cartesianDoubles f g p = [Pair ff gg, Pair gg ff] where
    ff x = f x 1
    gg x = g x 1

neighbors :: Pair Int -> Int -> BiMorph Int -> Neighbors
neighbors p e (BiMorph f g) = map dropP $ filter ff $ map (<*> p) $ concat [cartesianPairs f p, cartesianPairs g p, cartesianDoubles f g p] where
    ff (Pair x' y') = x' <= e && y' <= e

Now p argument is not used:

cartesianPairs f =
    (fmap . fmap) f [Pair 1 0, Pair 0 1, Pair 1 1]

cartesianDoubles f g = [Pair ff gg, Pair gg ff] where
    ff x = f x 1
    gg x = g x 1

neighbors :: Pair Int -> Int -> BiMorph Int -> Neighbors
neighbors p e (BiMorph f g) = map dropP $ filter ff $ map (<*> p) $ concat [cartesianPairs f, cartesianPairs g, cartesianDoubles f g] where
    ff (Pair x' y') = x' <= e && y' <= e

If you want, you can convert neighbors to use list comprehensions:

neighbors :: Pair Int -> Int -> BiMorph Int -> Neighbors
neighbors p e (BiMorph f g) =
    [ dropP xx
    | x <- concat [cartesianPairs f, cartesianPairs g, cartesianDoubles f g]
    , let xx @ (Pair x' y') = x <*> p
    , x' <= e && y' <= e ]

Or even

neighbors :: Pair Int -> Int -> BiMorph Int -> Neighbors
neighbors p e (BiMorph f g) =
    [ dropP xx
    | xx @ (Pair x' y') <- (<*> p) <$>
        concat [cartesianPairs f, cartesianPairs g, cartesianDoubles f g]
    , x' <= e && y' <= e ]

But I find it less clear.


Triangulate the divisors and divide the triangulars

Can it be made even faster?

Sure.

Fact number one. An n'th triangular number is \$\frac{n(n+1)}{2}\$

Fact number two. A number of divisors (aka \$\sigma(n)\$) is multiplicative, that is \$\sigma(m*n) = \sigma(m)*\sigma(n)\$ for coprime m and n.

Fact number three. \$n\$ and \$n + 1\$ are coprime.

Which means you don't have to factorize (fairly large) triangular numbers. Instead, you only need to factorize \$n\$ and \$n+1\$; in fact, since one of them is even, and contributes as a number twice that small, at most one number needs to be factorized at each iteration. You need to memoize factorizations though.

And of course a precomputed prime numbers table may help.


Walking all zeros is indeed suboptimal. A good first optimization is to preferentially walk on the zeros that bring you closer to the end point.

To do this, at each step calculate the pythagorean distance between the x,y coords of the array entry you're considering walking to, and the x,y coords of the array entry containing -3. This will be the cost of walking to that square. Store all calculated costs so you don't have to recalculate them.

Then, continue to preferentially choose lowest-cost next squares until you reach the end or a dead end. In cases of dead ends, simply go back and choose the next lowest-cost square that has yet to be traversed. To do this, you will need to keep some notion of path hierarchy, i.e. which steps lead to which next potential steps. A custom node type will do this for you.

If you've made it this far, then congratulations! You have a rudimentary A* path-finding algorithm. For a helpful guide to implementing this algorithm I recommend this resource.

There are further enhancements to A* efficiency, such as the Jump Point Search algorithm, which is best for more open spaces.


Clean code attempt on codechef.com FCTRL

Code Review

int requestNumInts();
bool validateInputSize(const int totalNumInts);
std::vector<int>* createVector(int totalNumInputs);
void loadVector(std::vector<int>* numbersEntered);
void printNumTrailingZeros(const std::vector<int>* numbersEntered);
int findTrailingZeros(int numberToCalculateZeros);

Personally I like to align the function names (this makes it easier to read). This is purely personal. Some like it some don't.

int               requestNumInts();
bool              validateInputSize(const int totalNumInts);
std::vector<int>* createVector(int totalNumInputs);
void              loadVector(std::vector<int>* numbersEntered);
void              printNumTrailingZeros(const std::vector<int>* numbersEntered);
int               findTrailingZeros(int numberToCalculateZeros);

Now that I have lined it up two things sprint to mind.

You are returning a vector by pointer (that's not good as there is no ownership semantics (who deletes it)). You should probably return by value. The optimizer will remove any copying and it prevents memory leaks. You can then pass the vector by reference to prevent copying in other situations.
You seem to be writing C code. If you implements this inside an object then a lot of you parameters don't need to be passed they are part of the object that is being manipulated.

Nice:

    std::ios::sync_with_stdio(false);

Pointer. Boo. Bad.

    std::vector<int>* numbers;

It is rare to see RAW pointers in C++ code. Pointers are usually wrapped inside smart pointers. But in this case you don't even need a pointer just use a normal std::vector as an object in place.

    std::vector<int> numbers = createVector(requestNumInts());

Using a delete is risky.

    delete numbers;

It is hard to tell if numbers was dynamically allocated! You actually have to go and look that up in the function createVector(). So if you change createVector() you also need to go through your code and find every place that calls createVector() to make sure they also use it correctly. Also its not exception safe. If an exception propagates through your code then you leak memory.

The main() function is special. If you don't specify a return then the compiler generates a return 0; for you. If your code can do nothing else apart from exit successfully then leave the return 0; out to indicate that there are no failure states. If there are error exit states then return 0; is an indication that the reader of the code should look for exit failures attempts.

Here:

int requestNumInts() {
    int totalNumInts = 0;
    while(!validateInputSize(totalNumInts))
    {
        std::cin >> totalNumInts;
    }
    return totalNumInts;
}

The first attempt will always fail. So why not use a do {} while() loop. This is designed for this situation. You always execute the code before doing the test.

Avoid if conditions that return true/false.

bool validateInputSize(const int totalNumInts) {
    const int MAX_NUMBER_OF_INPUTS = 1000000000;
    const int MIN_NUMBER_OF_INPUTS = 1;
    if(totalNumInts >= MIN_NUMBER_OF_INPUTS && totalNumInts <= MAX_NUMBER_OF_INPUTS) {
        return true;
    }
    else {
        return false;
    }
}

The above can be written as:
Much more readable.

    return (totalNumInts >= MIN_NUMBER_OF_INPUTS)
        && (totalNumInts <= MAX_NUMBER_OF_INPUTS);

Don't create the vector with new.

std::vector<int>* createVector(int totalNumInts) {
    std::vector<int>* numbers = new std::vector<int>(totalNumInts);
    return numbers;
}

RVO and NRVO will remove the copy that happens when you return by value. Also with C++11 and move semantics this makes this even more efficient. So never do this.

Also this whole function can be replaced with just a simple declaration in main.
Much simpler and more readable.

std::vector<int>   numbers(requestNumInts());

Good try:

void loadVector(std::vector<int>* numbersEntered) {
    for(unsigned int count = 0; count < numbersEntered->size(); ++count) {
        std::cin >> (*numbersEntered)[count];
    }
}

Couple of different ways to do this:

// Use the new foreach keyword
for(auto& val: numbers)
{
    std::cin >> val;
}

// Using iterators.
for(auto loop = numbers.begin(); loop != numbers.end(); ++loop)
{
    std::cint >>  (*loop);
}

// Or we can use the old classic C++03 std::transform
std::transform(std::begin(numbers), std::end(numbers),
               std::istream_iterator<int>(std::cin),
               std::begin(numbers),
               [](int& /*val1*/, int& val2){ return val2;});

Again nice effort with the printing.

void printNumTrailingZeros(const std::vector<int>* numbersEntered) {
    for(unsigned int count = 0; count < numbersEntered->size(); ++count) {
        std::cout << findTrailingZeros((*numbersEntered)[count]) << std::endl;
    }
}

Again some other options:

// Use the new foreach keyword
for(auto& val: numbers)
{
    std::cout << findTrailingZeros(val) << "\n";
}

// Using iterators
for(auto loop = numbers.begin(); loop != numbers.end(); ++loop)
{
    std::cout << findTrailingZeros(*loop) << "\n";
}

// Or we can use the old classic C++03 std::for_each
std::for_each(std::begin(numbers), std::end(numbers),
              [](int val){ std::cout << findTrailingZeros(val) << "\n";});

Also note the use of "\n" rather than std::endl. The std::endl adds a "\n" to the stream but then also calls flush. This is hardly ever what you actually want to do. Let the stream flush itself it makes it much more efficient to do so.

In your loops get used to use iterators to loop over containers. They are much more versatile and apply to all containers. Also you can pass them to functions very easily and they allow you to specify sub-ranges very trivially (event the foreach uses iterators underneath).

How I would do it.

First note that the output does not depend on previous values. You could cache them for speedy look-up but that seems overkill for such a simple algorithm. So there is no need to store the data in a vector.

 #include <iostream>

 int main()
 {
     std::ios::sync_with_stdio(false);

     int count;
     std::cin >> count;

     for(int loop=0; loop < count; ++count)
     {
          int value;
          std::cin >> value;

          std::cout << LeadingZero(value) << "\n";
     }
 }


Merging two multidimensional associative arrays

There is an alternative to your implementation. If you can change the position of the name element to the array key:

$defaults = array(
    'foo' => array(
        "level" => 5,
        "meta" => array(
            "value" => 1
        )
    ),
    'bar' => array(
        "level" => 6
    )
);

$custom = array(
    'qux' => array(
        "date" => "2016-01-01"
    ),
    'tux' => array(
        "date" => "2016-01-31"
    ),
    'foo' => array(
        "date" => "2015-01-01",
        "meta" => array(
            "value" => 5,
            "something" => "hello world"
        )
    )
);

You can utilize the native PHP function: array_replace_recursive

Using this function will provide you with the same resulting structure as you have shown with the exception of having the names as array keys. If this is an issue to you, you can duplicate the name once more into an array element.

The reason this specific/unique key is required is to only merge elements related to each other.

This little snippet should translate your array into the required structure:

/**
 * Translates an array element into an unique key for the element.
 *
 * (The name is just an example)
 */
function uniqify(array $array, string $key): array
{
    foreach($array as $index => $value)
    {
        $array[$value[$key]] = $value;
        unset($array[$index]);
    }
    return $array;
}

You could then so something like this:

$merged = array_replace_recursive(
    uniqify($defaults, 'name'),
    uniqify($custom,   'name')
);

Hope this can help, happy coding!


As @aled1027 suggests, partition' is just a fancy form of filter.  Therefore, it would be useful to study how filter can be implemented without ++.

filter' :: (a -> Bool) -> [a] -> [a]
filter' _ [] = []
filter' f (x:xs)
  | f x       = x:rest
  | otherwise = rest
  where rest = filter' f xs

The key to avoiding ++, I think, is to force yourself to write x: first, then figure out how to fill in everything surrounding it.  The next logical step would be to write

  | f x = x:filter' f xs

… and the rest should follow naturally.

Here's what I came up with for partition' (hover for spoiler):

  partition' :: (a -> Bool) -> [a] -> ([a], [a])
partition' _ [] = ([], [])
partition' f (x:xs)
  | f x       = ((x:accepted), rejected)
  | otherwise = (accepted, (x:rejected))
  where (accepted, rejected) = partition' f xs


Finding all non-empty directories and their files on an SFTP server with Paramiko

There is nothing obviously wrong with your implementation that could explain a slow behaviour. The slowest part here being the use of listdir_attr, you might want to check with other means if its speed matches what your network has to offer.
That being said, there are a few changes you can do to improve a bit on your end:

use an helper function so files will not be both a return value and modified in place;
use paramiko simulation of a working directory to remove the need for os.path;
use list-comprehension to remove the need for defaultdict.

I'm also wondering whether you really want to list everything that is not a directory or only regular files (i.e. no symlinks, no block devives, etc.) You can change the proposed list-comprehension accordingly.
Proposed improvements
def _sftp_helper(sftp, files):
    stats = sftp.listdir_attr('.')
    files[sftp.getcwd()] = [attr.filename for attr in stats if stat.S_ISREG(attr.st_mode)]

    for attr in stats:
        if stat.S_ISDIR(attr.st_mode):  # If the file is a directory, recurse it
            sftp.chdir(attr.filename)
            _sftp_helper(sftp, files)
            sftp.chdir('..')

def filelist_recursive(sftp):
    files = {}
    _sftp_helper(sftp, files)
    return files

You can adapt easily to include back the optional path parameter into filelist_recursive.


Efficient communication across multiple processors for finite elements

The answer was staring me right in the face, I just wasn't paying attention, apparently. Instead of sending one integer and one real*8 at a time, I should have been sending all of them at once, as:

do n=0,numProcs-1
    if( my_id .eq. n ) then
        do i=0,numProcs-1
            if( i .ne. my_id ) then
                currProc=i
                call MPI_RECV( numNeeded,1,MPI_INTEGER,i,my_id*2, &
                               MPI_COMM_WORLD,status,ierr )

                allocate( currNeeded(numNeeded) )
                allocate( volsNeeded(numNeeded) )

                call MPI_RECV( currNeeded,numNeeded,MPI_INTEGER,currProc,my_id*2+1, &
                               MPI_COMM_WORLD,status,ierr )

                do j=1,numNeeded
                    volsNeeded(j)=myElements(elementGlobalToLocal(currNeeded(j)))%xsj
                enddo

                call MPI_SEND( volsNeeded,numNeeded,MPI_REAL8,currProc,my_id, &
                               MPI_COMM_WORLD,status,ierr )

                deallocate( currNeeded )
                deallocate( volsNeeded )
            endif
        enddo
    else
        call MPI_SEND( numElementsNeeded(n+1),1,MPI_INTEGER,n,n*2, &
                       MPI_COMM_WORLD,status,ierr )

        call MPI_SEND( elementsNeeded(n+1, 1:numElementsNeeded(n+1)), &
                       numElementsNeeded(n+1),MPI_INTEGER,n,n*2+1, &
                       MPI_COMM_WORLD,status,ierr )

        call MPI_RECV( myExternalXsj(currReceived:currReceived+numElementsNeeded(n+1)), &
                       numElementsNeeded(n+1),MPI_REAL8,n,n,MPI_COMM_WORLD,status,ierr )

        do j=1,numElementsNeeded(n+1)
            elementGlobalToLocal(elementsNeeded(n+1, j))=currReceived
            currReceived=currReceived+1
        enddo
    endif
enddo

Reducing the MPI call times drastically reduces the time spent in communication from (on 8 cores) roughly 269 seconds to roughly 13 seconds, a speedup by a factor of more than 20. This still doesn't change the problem of low scalability, though perhaps using non-blocking send/receive operations (with a barrier after the end of the loop to ensure all messages are received/sent) will do that.


A couple of general points:

You shouldn't be using properties to set an error message like that. The error message is associated with the action you attempted on the object- in this case the delete- not the object itself. After the error has been handled, it doesn't make any sense for the property to continue holding that error message. It also potentially adds unnecessary concurrency woes.

You could fix that by wrapping up the bool you're returning and the message into a class, like DbActionResult. Or you could make the message an out parameter. But this still isn't a great solution because you have a leaking of concerns between your layers. Why should the data layer directly dictate what's being displayed in the UI like that? Better options would be either:

Return some kind of status code from the data layer, and have the UI display a message based on that code. If you don't need any more information in the UI than just whether or not it passed, a bool would be sufficient. If you want to log the exact exception details for debugging, that can be done with some kind of logging framework

OR

Don't catch the exception at all. Or if you do catch it to do some kind of handling/logging, rethrow it. That way you can access it directly in the UI layer if necessary, but the UI decides how to handle turning that exception into a message to display to the user, rather than the data layer doing it.

Also, this may have just been because it was an example, but OrtundUser is a bad name for a class. A User is a User, it shouldn't be a UserWhichIsPersistedInAParticularWay. That violates the Single Responsibility Principle, as it now has to take responsibility not only for what it's actually supposed to do- represent a user- but also do at least some management of its own persistence. You also have a similar problem with your actual User class, though it's not reflected in the name. By putting the Delete method on the user, it now has to be concerned not only with what it actually is, but with how to persist itself

This is related to the actual meat of the question. Your first step should be to separate your User class out into User and UserRepository like so:

public class User
{
    public int userid { get; set; }
}

public class UserRepository
{
    public bool Delete(User user)
    {
        //Delete logic goes here
    }
}

That's not a full example, but it'll be refined later. Hopefully you can see how this has now separated out different responsibilities into their own classes.

From your mention of DbContext in a comment, I assume you're using Entity Framework. EF actually already provides you with a class that will serve the purpose UserRepository here, which is DbSet<User>. You should be able to get that from your OrtundData. That class will handle operations like Delete for you. So in fact the only class from the above example that you actually need is the User class.

(As a side note, this is an implementation of what's called the 'repository pattern'. If you look this up, you'll see it's often recommended that even when using Entity Framework, you add your own repository class on top- UserRepository in the above example. I wouldn't worry about that at the moment, it adds another layer of abstraction which can be valuable in some cases, but don't do it without understanding why. It's more important to get the basics in place.)

So finally coming to whether User and OrtundUser are redundant. Yes, they are. Once you remove the persistence logic from both of them as described above, you're left with nothing but a property bag which is identical for both of them. You should delete OrtundUser, and push User down into your data layer.

In fact, in large solution you could push futher- have a "Core" project referenced by both the UI and Data projects which contains your domain objects like User. Data would then reference Core, and UI would reference both Data and Core. In your case, actually structuring your solution like this is likely to be unnecessary, but it's a good way to think about it conceptually.

So, finally, with all of the above applied your code might look something like this (again this is omitting some details like construction, just leaving you with the key bits):

// Website/Admin/Users.aspx.cs
private DbSet<User> _userRepository;
private SomeSortOfLogger _logger;

protected void btnDelete_Click(object sender, EventArgs e)
{
    User us = new User(Convert.ToInt32(Session["ActionUserID"]));

    try
    {
       _userRepository.Delete(us);
       lblResult.Text = "User record was successfully deleted.";
    }
    catch(Exception e)
    {
        _logger.Log(e);
        lblResult.Text = "There was an error, see log for details";
    }
}

// DataProject/User.cs
public int userid { get; protected set; }

public User(int UserID)
{
    userid = UserID;
}

There's likely still scope for improvement- e.g. adding a better way of doing exception/error handling and logging, dependency injection. But those would be beyond the scope of this question.


Since your script has no content to return, a status code of 204 No Content would be more desirable than 200 Success.  For that, you should echo "Status: 204 No Content" (RFC 3875 Sec 6.3.3).  Also consider returning using status code 405 Method Not Allowed for anything other than a POST request.

$TMPOUT is a misnomer.  The file is not temporary at all — $TMPOUT.1 contains the final output of your script.

If your goal is to redirect the input to a file, discarding the first four lines, the last line, and the trailing newline of the penultimate line, you don't need to execute any external commands.  Bash is fully capable of doing all of the work itself.  The script isn't pretty, but I still find it easier to understand than copying the data back and forth, extracting lines here and there each time.

#!/bin/bash

case "$REQUEST_METHOD" in
  POST)
    (
        # Discard first four lines
        read && read && read && read &&

        # Read and echo, buffering two lines
        read line1 &&
        read line2 &&
        while read nextline ; do
            echo "$line1"
            line1="$line2"
            line2="$nextline"
        done

        # Echo penultimate line with no trailing newline.
        echo -n "$line1"

        # Discard last line ($line2)
    ) > hello

    echo 'Status: 204 No Content'
    echo
    ;;

  *)
    echo 'Status: 405 Method Not Allowed'
    echo
esac


You should definitely be releasing both btMonitoredDevices and btPairedDevices in the dealloc. But it appears that this is your appDelegate so it matters little outside of correctness. I'd do it anyhow.

You shouldn't need the retain on btMonitoredDevices since you're calling alloc on it. So you already have a retain count of one on it. By calling retain on it you actually have a retain count of two.

So to sum up make sure you're releasing both in your dealloc and get rid of the [btMonitedDecices retain]; and you should be good.


First, don't use the conditional operator as an if statement.  Either encode the conditional as part of the initialization of minSize, or use an if statement instead of the conditional.  In this case, though, a better solution is to make use of the standard min function:

int minSize = std::min(path1Expnded.size(), path2Expnded.size());

But we can redo your code to eliminate this part.

The sort you've coded and the one you describe (how I am interpreting your description, anyway) are different, as your code only looks at the number of subfolders if one path is in a subfolder of the folder that has the file in the other path.

Your problem description ("files closer to the root directory sorted first"), sounds like all the paths with fewer folders should be before longer ones, in which case the number of stems should be the first thing compared.  Then a direct comparison on the full paths if they have the same folder count.

What you've coded up will put files in a folder before subfolders of that folder.  Your current implementation does a lot of memory allocations and frees, mainly with strings and vector resizes.  You can simplify this a lot by first comparing the two parent_paths.  If they are different, return the result of this comparison (the path to a file will be shorter than the path for a subfolder in the folder with the file, so it'll be earlier).  Otherwise the two paths are the same, and return the result of comparing the filenames.


Is this implementation of signed URLs reasonably secure?

It looks like a rather straightforward use of HMAC. So I would presume it is safe from that perspective.

A note about terminology. Personally I would talk about an authentication tag or simply HMAC value because people often associate signatures with asymmetric algorithms such as RSA. The same goes for "private key"; I'd use secret key for symmetric keys as in your code.

Some remarks:

the regular expression is used twice, it seems more logical to match the entire GET request and make sure it ends with the group with the signature in it (even if that just means using .*);
to remove one way of attacks, I'd make sure that there aren't two authentication tags in the GET request;
to remove another, I'd include a sequence number or time stamp so that replay attacks are not possible;
hexadecimals are not very efficient, I'd use a base64url encoder, it's made for it;
the groups count check is unnecessary, either the regex matches or it doesn't.

One idea is to have a method split the URI and the signature, you don't need the authentication tag after verification after all - you could for instance use a tuple with the verification status and the URL without signature (as optional value), or use a yucky output parameter. Check your coding standards before doing either of these though.


Find the minimum number of operations (concat, add and subtract) for the numbers 1-9 to equal 100

Nesting

Using nested functions is not a bad practice per se, but all depends on the concrete case. Often they are used to enrich the parameters, to share with locally scoped values, or to hide the def from other members of the same object.

In many cases, they are just equivalent of functions with private visibility. But when too much nesting appears, I'd suggest to flatten the things for the sake of readability.

In this example I don't see any special reason to make the function nested. It does not use any of the values available to gchq. Keeping it nested would not be a mistake, but the flat approach seems cleaner:

def gchq2(): Unit = solve("0", 1, concat)

private def solve(total: String,
                  currentValue: Int,
                  f: (String, Int) => String) = ???

Moreover, other referenced functions (plus, minus...) are flat, so all of the pieces are well kept at same level.

Other Considerations

Returned values. The Int return type from gchq() seems suspicious. I hope to understand the meaning (1 for successful result, 0 for no solution found), but the returned values are hugely falsified. solve() will return an Int only from the last call of solve(newtotal, currentValue + 1, plus), the others will remain hidden. Since the solutions are output into the console, I'd suggest to return nothing from solve:

private def solve(total: String, currentValue: Int, f: (String, Int) => String): Unit = ???

Conditinals. There are two checks for currentValue == 9. One should be enough:

if (currentValue == 9) {
  if (evaluate(newtotal.split("\\s").toList) == 100) {
    ...
  }
}
else {
  ...
}

It introduces one more case of nested ifs, but is fully justified here: this is the end condition of the calls sequence, while else adds more recursion.

Naming. Names like gchq or f are awful and should be changed to more meaningful.


Bash/zsh function that cd to the root of git tree

Great

100% pass on shellcheck which means you're doing great with quoting everything that could be potentially problematic.
scoping variables
using [[ conditional for the if
nice explanation of what it is doing and why

Could be better

a sh-bang line at the top is a good idea for scripts, even if this would usually just be sourced during your login scripts.
Your inner function is defined with different syntax than your outer function.
You can scope and define a variable in one line.  For example: local super_root="$(git rev-parse --show-superproject-working-tree)".  This makes sure you don't fail to define a local variable or fail to scope a new variable.  And it cuts out a line of code in each case.
Reusing git_root for a variable name and the function name is confusing.  I initially wondered why you were trying to scope the function after you had just defined it.
use [[ conditional for conditional in the last line.


DateTimePrecise - current DateTime with millisecond precision

If you don't need a precise DateTime, only differences, then don't use DateTime at all. I think you should work only with TimeSpans.

This will avoid confusion, because with your class, it looks like DateTimePrecise
.CurDateTime() is better than DateTime.Now, even when used once. If you only used TimeSpans, this wouldn't be a problem.


Let me offer the following rewrite of your program and then let's walk through it:

names = {'Addition' : '+',
         'Subtraction' : '-',
         'Division' : '/',
         'Exponentation': '**',
         'Radicalization': '**(1/'
        }

print("Operations that you can use:")
for op in names:
    print(op, names[op])

ops = {
       '+' : (lambda x, y: x + y),
       '-' : (lambda x, y: x - y),
       '*' : (lambda x, y: x * y),
       '/' : (lambda x, y: x / y),
       '**' : (lambda x, y: x ** y),
       '**(1/' : (lambda x, y: x ** 1.0 / y),
       'na' : (lambda x, y: 'Unknown binary operator')
      }

ce = 0
while ce != 1:
    x = float(input("First Value: "))
    y = input("Operation: ")
    z = float(input("Second Value: "))

    op = ops.get(y, 'na')
    print(ops[op](x, z))

    print("Continue or Exit?")
    ce = int(input("    0    or   1  : "))

It seems unnecessary to define x, y and z to be None so we just define them inside the main loop.
The ops dictionary stores a symbol of the operator and the actual implementation in a lambda function. It also stores a special 'na' value to represent any unknown operator; this is useful in the main loop where we return that key if we don't find what the user gave us as input.
The key difference and main idea here is a data-driven solution. That is, notice how we've put the supported operators into data structures. This way it's easier to make changes and to maintain the program, e.g., when you add a new binary operator, you don't have to touch the logic of your calculator, just add a new element into your data structure.
There's no explicit if-elif chain anymore, yay! Such chains are often annoying to write and it's always a potential code smell. No matter how experienced you are, it's one of those things where it's easy to make a human error and write something you didn't mean to, but it can be tough to discover the bug.


I've bumped the number to 100000 and profiled. It seems that modulo operation is the most expensive here:

ROUTINE ======================== main.isPerfectNumber in /tmp/so/main.go
    31.72s     31.72s (flat, cum)   100% of Total
         .          .     19:   if num == 1 {
         .          .     20:       return false
         .          .     21:   }
         .          .     22:
         .          .     23:   c := num - 1
     2.35s      2.35s     24:   for i := 2; i <= num/2; i++ {
    29.37s     29.37s     25:       if num%i == 0 {
         .          .     26:           c -= i
         .          .     27:       }
         .          .     28:   }
         .          .     29:
         .          .     30:   return c == 0

It seems that C compilers are able to optimize modulo here, while the Go compiler cannot. I'd suggest opening an issue about it on the Go bug tracker. If C can do that, Go should as well.


Your code is interesting, in the sense that it appears to have been pulled from about 4 different text books all related to Java about 4 versions ago.... actually, make it Java 1.3.

It is consistent code, but everything is just.... old.

In some sense of order, the following strike me most:

multicatch
try with resources
don't catch Exception
don't just print the exception's toString, print the full stack.
Brace on same line
don't *-import.
don't pre-declare variables... declare at use-time.
redundant comments

On the other hand, your variable names are great, and the basic concept is sound.

Here's my version of your code:

import java.io.FileReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class ReadNum {
    public static void main(String[] args) {
        try (Scanner inFile = new Scanner(new FileReader("sample.txt"))) {

            int num1 = inFile.nextInt();
            int num2 = inFile.nextInt();

            int sum = num1 + num2;

            System.out.println("sum " + sum);
        } catch (IOException | InputMismatchException ex) {
            ex.printStackTrace();
        }
    }
}